Unity中使用深度和法线纹理

本文详细介绍了如何在Unity中开启和访问深度纹理与法线纹理,包括设置Camera的depthTextureMode属性,以及在Shader中如何使用sampler2D_CameraDepthTexture和sampler2D_CameraDepthNormalsTexture变量。还提供了深度纹理线性化和法线纹理解码的方法,并展示了如何在Shader中显示深度值和法线值。此外,提供了相关参考资料供深入学习。

1、开启深度和法线纹理

通过设置Camera中的depthTextureMode变量。

camera.depthTextureMode = DepthTextureMode.None;				//不生成深度纹理
camera.depthTextureMode = DepthTextureMode.Depth;				//生成深度纹理
camera.depthTextureMode = DepthTextureMode.DepthNormals;		//生成深度法线纹理
camera.depthTextureMode = DepthTextureMode.MotionVectors;		//指定是否应渲染运动矢量

//可通过或指令同时指定生成多个纹理
camera.depthTextureMode = DepthTextureMode.Depth | DepthTextureMode.DepthNormals;

2、访问深度和法线纹理

在shader中,使用变量名_CameraDepthTexture和_CameraDepthNormalsTexture访问对应纹理。

sampler2D _CameraDepthTexture;			//深度纹理,深度值存储在r通道,范围[0,1]。通过MVP矩阵变化后的z值得到
sampler2D _CameraDepthNormalsTexture;	//深度法线纹理

深度纹理的线性化

对于透视投影,存储的深度值是非线性的,要得到线性的深度值,需要进行转化,可通过LinearEyeDepth和Linear01Depth完成这个过程

float depth = tex2D(_CameraDepthTexture, uv).r;			//获取到存储的深度值
float depth_view = LinearEyeDepth(depth);				//获取视角空间下的深度值,范围在近平面和远平面之间,[z_near, z_far]
float depth_01 = Linear01Depth(depth);					//获取[0,1]范围内线性分布的深度值, 0处于摄像机位置,1处于远平面位置

深度法线纹理的使用

深度法线纹理是32bit编码(每个通道8bit),法线信息存储在R和G通道,深度信息存储在B和A通道。深度值是16bit的数据,分别存储在两个8bit通道内。
因此,要使用深度法线纹理,在采样后需要对其解码才能使用。可使用UnityCG.cginc中的DecodeDepthNormal进行解码。

inline void DecodeDepthNormal( float4 enc, out float depth, out float3 normal )
{
    depth = DecodeFloatRG (enc.zw);
    normal = DecodeViewNormalStereo (enc);
}
float4 samplerValue = tex2D(_CameraDepthNormalsTexture, i.uv);
float depth;		//depth的最终结果为[0,1]范围的线性分布
float3 normal;		//normal为屏幕空间下的法线方向
DecodeDepthNormal(samplerValue, depth, normal);	

3、显示深度值和法线值

深度纹理显示:

float4 samplerValue = tex2D(_CameraDepthNormalsTexture, i.uv);
float depth;		//depth的最终结果为[0,1]范围的线性分布
float3 normal;		//normal为屏幕空间下的法线方向
DecodeDepthNormal(samplerValue, depth, normal);	

return fixed4(depth, depth, depth,1);

[0,1]范围的深度值
法线纹理显示:

float4 samplerValue = tex2D(_CameraDepthNormalsTexture, i.uv);
float depth;		//depth的最终结果为[0,1]范围的线性分布
float3 normal;		//normal为屏幕空间下的法线方向
DecodeDepthNormal(samplerValue, depth, normal);	

return fixed4(normal*0.5+0.5,1);

映射到[0,1]范围内的视角空间下的法线纹理

4、参考资料

[1] 冯乐乐 《Unity Shader入门精要》页269-272
[2] Unity手册 https://docs.unity3d.com/2020.2/Documentation/Manual/SL-CameraDepthTexture.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值