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

Calculating Depth

Discussion in 'Shaders' started by MaT227, Jan 4, 2015.

  1. MaT227

    MaT227

    Joined:
    Jul 3, 2012
    Posts:
    628
    I am trying to retrieve depth it seems that there's two way to do it, manually and using the _CameraDepthNormalsTexture.

    Using _CameraDepthNormalsTexture, I can't simply get any result.

    Using the manual way I am having nice results but I am still facing some difficulties.
    Code (CSharp):
    1. o.depth = -mul(UNITY_MATRIX_MV, v.vertex).z * _ProjectionParams.w;
    With this formula, I have a nice result but it is link with the Camera clipping planes which is a bit annoying.
    Code (CSharp):
    1. o.depth = 1.0 / (_ProjectionParams.x * -mul(UNITY_MATRIX_MV, v.vertex).z + _ProjectionParams.y);
    With this forumula, the depth is no more related to the camera clipping planes but to the camera position... which is worse.

    Is there a better way to retrieve depth ?
    Thanks a lot !
     
  2. MaT227

    MaT227

    Joined:
    Jul 3, 2012
    Posts:
    628
    Any idea ?
     
  3. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    That might be because you're using the forward rendering path. Only the deferred path fills _CameraDepthNormalsTexture.

    I'd say you could just do this:
    Code (csharp):
    1. o.depth = mul(UNITY_MATRIX_MV, v.vertex).z * _ProjectionParams.x;
    The w component is 1/farClip, so yes, then it's linked with the far clipping plane. The x component just inverts if needed.

    Another approach is to just take distance instead of depth.
    Code (csharp):
    1. o.depth = distance(mul(_Object2World, v.vertex), _WorldSpaceCameraPos);
     
  4. MaT227

    MaT227

    Joined:
    Jul 3, 2012
    Posts:
    628