Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question How to properly render a depth texture, using command buffers and a custom shader?

Discussion in 'Shaders' started by Sinterklaas, May 14, 2021.

  1. Sinterklaas

    Sinterklaas

    Joined:
    Jun 6, 2018
    Posts:
    93
    This one kinda has me stumped. I'm trying to render my own depth textures, using command buffers, but I can't figure out how to do it. I'm having two main problems.

    First, I can't find a good way to clear my depth texture. I create my render targets and command buffer with:
    Code (CSharp):
    1. renderTexture = new RenderTexture(Camera.main.pixelWidth, Camera.main.pixelHeight, 16,
    2.     RenderTextureFormat.Depth);
    3. dummyColorTexture = new RenderTexture(Camera.main.pixelWidth, Camera.main.pixelHeight, 0);
    4. commandBuffer = new CommandBuffer();
    5. Camera.main.AddCommandBuffer(CameraEvent.AfterDepthTexture, commandBuffer);
    I then try to clear this texture using:
    Code (CSharp):
    1. commandBuffer.Clear();
    2. commandBuffer.SetRenderTarget(dummyColorTexture, renderTexture);
    3. commandBuffer.ClearRenderTarget(true, true, Color.white, 1f);
    I'd expect depth to be cleared to 1. My depth texture shows up as fully black instead. This doesn't seem to be what the documentation suggests should happen, so could this be a bug maybe?

    Second, I have this shader:
    Code (CSharp):
    1. struct VertexData
    2. {
    3.     float4 vertex   : POSITION;
    4. };
    5.  
    6. struct Interpolators
    7. {
    8.     float4 pos      : SV_POSITION;
    9.     float3 worldPos : TEXCOORD0;
    10. };
    11.  
    12. Interpolators depthVert(VertexData v)
    13. {
    14.     Interpolators i;
    15.     i.pos = UnityObjectToClipPos(v.vertex);
    16.     i.worldPos = mul(unity_ObjectToWorld, v.vertex);
    17.     return i;
    18. }
    19.  
    20. half4 depthFrag(Interpolators i, out float depth : SV_DEPTH) : SV_TARGET
    21. {
    22.     depth = (i.worldPos.z - _ProjectionParams.y) / (_ProjectionParams.z
    23.         - _ProjectionParams.y);
    24.     return 0; // dummy output to dummy color texture
    25. }
    ZTest is set to LEqual, and ZWrite is set to On.

    For some reason, darker objects (that are closer to the camera) appear behind objects that are brighter (and thus further away from the camera), despite ZTest being set to LEqual. This is especially weird because the depth texture is fully black before I start rendering, so I'd expect nothing to be drawn at all. Very strange.

    Anyone got some clues? Cause I feel like I'm missing something obvious.

     
    AlejMC likes this.