时间:2025-08-31 11:23
人气:
作者:admin
【从UnityURP开始探索游戏渲染】专栏-直达
通过动态调整顶点深度值,人为制造深度间隙避免冲突。其核心参数组合为:
基于表面斜率的动态偏移量(变量),计算公式为:
最终深度修正公式:
最终深度值 = 原始深度值 + (Units × 最小深度单位) + (动态偏移量)
ZFightingFix.shader
Shader "URP/ZFightingFix" {
Properties {
_MainTex ("Texture", 2D) = "white" {}
_Units ("Units", Float) = 0 // 固定偏移
_Factor ("Slope Factor", Float) = 0 // 坡度系数
}
SubShader {
Tags { "RenderPipeline"="UniversalPipeline" }
Pass {
HLSLPROGRAM
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
struct Attributes {
float4 positionOS : POSITION;
float3 normalOS : NORMAL;
};
struct Varyings {
float4 positionCS : SV_POSITION;
};
float _Units, _Factor;
Varyings vert(Attributes v) {
Varyings o;
// 转换到裁剪空间
o.positionCS = TransformObjectToHClip(v.positionOS.xyz);
// 计算表面斜率(视图空间法线Z分量)
float3 normalVS = normalize(TransformWorldToViewDir(
TransformObjectToWorldNormal(v.normalOS)
));
float slope = abs(normalVS.z); // Z越小表面越陡峭
// 应用深度偏移
float bias = _Units * 0.0001 + _Factor * (1 - slope);
o.positionCS.z -= bias * o.positionCS.w; // 按w缩放适配透视
return o;
}
// ... 片元着色器省略
ENDHLSL
}
}
}
_DepthBias: 固定深度偏移量,正值使物体看起来更近_SlopeScale: 基于表面斜率的动态偏移量,解决陡峭表面的深度冲突output.positionCS.z += ...: 在裁剪空间直接修改深度值slope计算: 基于法线向量计算表面斜率_DepthBias值(0.001-0.01)_SlopeScale值(0.1-1.0)Renderer组件的ShadowCastingMode设置全局深度偏移Shader "Custom/DepthBiasExample"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_DepthBias ("Depth Bias", Float) = 0
_SlopeScale ("Slope Scale", Float) = 0
}
SubShader
{
Tags { "RenderType"="Opaque" "RenderPipeline"="UniversalPipeline" }
Pass
{
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
struct Attributes
{
float4 positionOS : POSITION;
float2 uv : TEXCOORD0;
};
struct Varyings
{
float4 positionCS : SV_POSITION;
float2 uv : TEXCOORD0;
};
CBUFFER_START(UnityPerMaterial)
float _DepthBias;
float _SlopeScale;
CBUFFER_END
TEXTURE2D(_MainTex);
SAMPLER(sampler_MainTex);
Varyings vert(Attributes input)
{
Varyings output;
output.positionCS = TransformObjectToHClip(input.positionOS.xyz);
// 应用深度偏移
output.positionCS.z += _DepthBias * output.positionCS.w;
// 基于斜率应用额外偏移
float3 normalVS = TransformWorldToViewDir(float3(0,1,0)); // 示例法线
float slope = 1.0 - abs(normalVS.z);
output.positionCS.z += _SlopeScale * slope * output.positionCS.w;
output.uv = input.uv;
return output;
}
half4 frag(Varyings input) : SV_Target
{
return SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.uv);
}
ENDHLSL
}
}
}
【从UnityURP开始探索游戏渲染】专栏-直达
(欢迎点赞留言探讨,更多人加入进来能更加完善这个探索的过程,????)