Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Proper way to handle reversed Depth

Discussion in 'Shaders' started by CaffeinatedCoolaid, Jan 23, 2023.

  1. CaffeinatedCoolaid

    CaffeinatedCoolaid

    Joined:
    May 10, 2021
    Posts:
    59
    I am a little confused on proper handling of sampling the depth. I have seen examples of manually handling reversed depth, examples of calling built in functions that do not check if hardware is reverse depth, but also while skewering through Core and URP packages code I see references to the the zparams being flipped if the hardware is reverse depth. So what are the correct ways to sample depth in BRIP/URP/HDRP that guarantee the depth value is going to be consistent across hardware?
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,236
    What exactly are you attempting to do? Because the nature of reversed Z, and the fact it's not available on some API targets, means there is no way for it to be consistent across hardware. Which is why there are checks for the reversed Z in the first place, so different code can run depending on which kind of depth is in use.
     
  3. CaffeinatedCoolaid

    CaffeinatedCoolaid

    Joined:
    May 10, 2021
    Posts:
    59
    Specifically I'm reading from URP depth texture to determine if the screen position is sky or not to mask out a post effect.
    Code (CSharp):
    1. result = lerp( skyPost, opaquePost, ceil(depth));
    What I am unsure is if the written depth texture is already checked and going to be in the same distance format or if I need to be checking as well in my code.

    Also if I do or don't does that apply to both BRIP and HDRP depth sample methods?
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,236
    The BIRP, URP and HDRP will be in the same “format”, though the functions to read the depth buffer may be different between the BIRP and the two SRPs. If you’re getting the raw depth, then it’ll depend on if Unity is using reversed Z or not for if the skybox is nearly 0.0 or nearly 1.0.

    If you convert that to the linear 0-1 depth, it’ll always be nearly 1.0.

    Or if you convert the raw depth to linear eye depth, it’ll be nearly the far clip plane.
     
    CaffeinatedCoolaid likes this.
  5. CaffeinatedCoolaid

    CaffeinatedCoolaid

    Joined:
    May 10, 2021
    Posts:
    59
    Awesome that is exactly what I needed thank you!