Search Unity

Depth Buffer and RenderTextures

Discussion in 'General Graphics' started by Nekativ, Jul 29, 2017.

  1. Nekativ

    Nekativ

    Joined:
    Jun 30, 2017
    Posts:
    9
    So you create a RenderTexture with a depth format. Then you create a typical RenderTexture.

    Then you set your camera target buffers to the render texture you just created and render.

    Code (CSharp):
    1.  
    2.  
    3. RenderTexture depthTexture = new RenderTexture(1024,1024, 24, RenderTextureFormat.Depth);
    4. RenderTexture renderTexture = new RenderTexture(1024,1024, 0);
    5.  
    6. camera1.depthTextureMode = DepthTextureMode.Depth;
    7.  
    8. camera1.SetTargetBuffers(renderTexture.colorBuffer, depthTexture.depthBuffer);
    9.  
    10. camera.Render()
    11.  
    12.  
    My understanding is that "depthTexture" now holds the camera1's depth at the time rendering.

    How do you go about accessing the depth data in depthTexture inside of a fragment shader?

    I have seen the somewhat documented examples of accessing _CameraDepthTexture and _LastCameraDepthTexture, but that is the depth from the current and last frames rendered by any camera, not the depth information in "depthTexture".

    I have also seen examples of outputting the camera's depth in one of the color channels of a RenderTexture using a replacement shader, but this would mean two rendering operations, one for depth to a separate RenderTexture and one for color the other RenderTexture. With this method you would pass the RenderTexture with the depth information to the fragment shader and use a standard sampler2D to access the depth information like you would a color. However you would now have to do two renders instead of one which is wasteful.
     
    Last edited: Jul 29, 2017
  2. Nekativ

    Nekativ

    Joined:
    Jun 30, 2017
    Posts:
    9
    Bump.

    I will replace this bump with the best assessment of what I can dig up soon if nobody knows anything about my initial question (so the next guy can who is googling this problem can get a reasonable answer).
     
  3. ilya_ca

    ilya_ca

    Joined:
    Nov 19, 2011
    Posts:
    274
    This is actually quite trivial, simply call SetTexture() on the material you're using to manually pass the depth texture:

    Code (CSharp):
    1. material.SetTexture("_DepthTex", depthTexture);
    To sample the texture inside of the surface shader do:
    Code (CSharp):
    1. float depthValue = tex2Dproj(_DepthTex, UNITY_PROJ_COORD(IN.screenPos)).r;
     
    vsugrob likes this.
  4. CurryGewuerzKetchup

    CurryGewuerzKetchup

    Joined:
    Dec 19, 2018
    Posts:
    3
    Do the values have a unit? Is it for example depending on the camera settings to get meter?