using UnityEngine; public class ShowCameraDepthTexture : MonoBehaviour { public Material mat; private void Awake() { Camera camera = this.GetComponent<Camera>(); //只要将相机的这个参数设置为DepthNormals就可以在Shader中使用_CameraDepthNormalsTexture访问深度贴图了 camera.depthTextureMode = DepthTextureMode.DepthNormals; } private void OnRenderImage(RenderTexture source, RenderTexture destination) { if (mat != null) { Graphics.Blit(source, destination, mat); } else { Graphics.Blit(source, destination); } } }
Shader "Unlit/DepthTexShow" { Properties { _MainTex ("Texture", 2D) = "white" {} } SubShader { Tags { "RenderType"="Opaque" } LOD 100 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct v2f { float2 uv : TEXCOORD0; float4 vertex : SV_POSITION; }; sampler2D _MainTex; float4 _MainTex_ST; sampler2D _CameraDepthNormalsTexture; v2f vert (appdata_img v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.uv = v.texcoord; return o; } fixed4 frag (v2f i) : SV_Target { float d; float3 normal; float4 enc = tex2D(_CameraDepthNormalsTexture,i.uv); DecodeDepthNormal(enc,d,normal);//获取深度值和法线值 return fixed4(normal * 0.5 + 0.5, 1); //return fixed4(d,d,d, 1); } ENDCG } } }
通过DecodeDepthNormal去解析取样的结果,可以获得out的深度值和法线方向,enc中xy存储的是视角空间下的法线信息,zw存储的是深度信息。
inline void DecodeDepthNormal( float4 enc, out float depth, out float3 normal ) { depth = DecodeFloatRG (enc.zw); normal = DecodeViewNormalStereo (enc); }