- Home /
How do you pass the depth buffer of a RenderTexture to a CommandBuffer
I have a RenderTexture with a depth component. I render objects and depth into it and verify this in RenderDoc. I then pass that texture to another shader like so
m_blitToScreenCommand.SetGlobalTexture( "_MainTex", m_overrideTexture.colorBuffer );
m_blitToScreenCommand.SetGlobalTexture( "_MainDepth", m_overrideTexture.depthBuffer );
m_blitToScreenCommand.DrawMesh( screenMesh, Matrix4x4.identity, customBlit );
However, when I check in RenderDoc, the shader is receiving two copies of the colour buffer. It doesn't seem to matter if the camera is running in deferred or forward rendering. Unity version 2017.2
Here is the shader
Shader "Test"
{
// Command buffers write to global keywords so "white" will always take priority because it is more specific than the global
//Properties
//{
// _MainTex ("Texture", 2D) = "white" {}
//}
SubShader
{
Tags{ "Queue" = "Geometry" "PreviewType" = "Plane" }
CGINCLUDE
#pragma enable_d3d11_debug_symbols
#pragma target 3.0
#include "UnityCG.cginc"
struct appdata
{
float3 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
sampler2D _MainDepth;
v2f vert(appdata v)
{
v2f o;
o.vertex = float4(v.vertex, 1);
o.uv = v.uv;
#ifndef UNITY_UV_STARTS_AT_TOP
o.uv.y = 1 - o.uv.y;
#endif
return o;
}
fixed4 frag(v2f i, out float out_depth : SV_Depth) : SV_Target
{
out_depth = UNITY_SAMPLE_DEPTH(tex2D(_MainDepth, i.uv));
return tex2D(_MainTex, i.uv);
}
ENDCG
Pass
{
ZWrite on
ZTest off
Cull off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
ENDCG
}
}
}
Answer by sbsmith · Dec 08, 2017 at 11:36 PM
In Unity 2017.2 you cannot pass the color and depth of the same RenderTexture as separate parameters. The only thing that works is to have two separate RenderTextures where one is colour only and the other is depth only. You can then pass the colorBuffer of the first and the depthBuffer of the second and things will behave as intended.
Your answer
Follow this Question
Related Questions
commandbuffer can't get depth buffer in forward rendering but correct in Deferred .Why? 1 Answer
Read depth buffer on the cpu 1 Answer
Copying depth from one RenderTexture to another 2 Answers
Is there a way to write to Deferred Depth from a command buffer in CameraEvent.AfterImageEffects? 1 Answer
How does _CameraDepthTexture work with Cameras that are using a RenderTexture? 0 Answers