Search code examples
unity-game-enginecg

Cg: omit depth write


I am outputting depth in Cg in a branch, like so:

ZWrite On
..
void frag(v2f IN, out color : COLOR, out depth : DEPTH) {
 if (statement) {
  color = float4(1);
 } else {
  color = float4(0);
  depth = 0;
 }
}

However as you see I omit writing the depth in the first condition. This results in undefined behaviour, but I believe this is common practice in GLSL (omitting writing to glFragDepth will result in the original depth).

What should I do to get the original depth in the first condition in Cg when having a depth value for output?


Solution

  • YMMV w/ this script. The code, as I recall, needed to be targeted to old implementations of OpenGL or else you'd get an error like shader registers cannot be masked related to this D3D issue.

    But I believe you can pull the depth from the camera depth texture and rewrite it out. You do need to calculate a projected position first using ComputeScreenPos in the vertex shader. Documentation is non-existent, AFAIK, for the functions Linear01Depth and LinearEyeDepth so I can't tell you what the performance hit might be.

    Shader "Depth Shader" { // defines the name of the shader 
    SubShader { // Unity chooses the subshader that fits the GPU best
      Pass { // some shaders require multiple passes
         ZWrite On
         CGPROGRAM // here begins the part in Unity's Cg
    
         #pragma vertex vert 
         #pragma fragment frag
         #include "UnityCG.cginc"
         struct v2f
         {
            float4 position : POSITION;
            float4 projPos : TEXCOORD1;
         };
    
         v2f vert(float4 vertexPos : POSITION)
         {
            v2f OUT;
            OUT.position = mul(UNITY_MATRIX_MVP, vertexPos);
            OUT.projPos = ComputeScreenPos(OUT.position);
            return OUT;
         }
    
         //camera depth texture here
         uniform sampler2D _CameraDepthTexture; //Depth Texture
         void frag(v2f IN, out float4 color:COLOR, out float depth:DEPTH) // fragment shader
         {
            color = float4(0);
             // use eye depth for actual z...
            depth = LinearEyeDepth (tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(IN.projPos)).r); 
    
            //or this for depth in between [0,1]
            //depth = Linear01Depth (tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(IN.projPos)).r);
         }
    
         ENDCG // here ends the part in Cg 
      }
    }
    }