透明度度测试缺点
透明度度测试结果,要么完全透明,要么完全不透明;而且,得到的透明度效果在边缘处往往参差不齐,有锯齿,这是因为在边界处纹理的透明度的变化精度问题。
透明度测试基本原理:
只要一个片元的透明度不满足条件(通常是小于某个阈值),那么它对应的片元就会被舍弃。被舍弃的片元将不会再进行任何处理,也不会对颜色缓冲产生任何影响;否则,就会按照普通的不透明物体的处理方法来处理它。
透明度测试不需要关闭深度写入
可以利用深度缓冲按逐像素的粒度进行深度排序,保证渲染的正确性。
通常使用 Clip 函数来进行透明度测试
函数:void clip(float4 x);void clip(float3 x);void clip(float2 x);void clip(float x)
参数:裁剪时使用的标量或矢量条件
描述:如果给定参数的任何一个分量是负数,就会舍弃当前像素的输出颜色。等同于
void clip(float4 x)
{
if(any(x<0))
discard;
}
Tags
通常,使用了透明度测试的 Shader 都应该在SubShader 中设置这三个标签
Tags { "Queue"="AlphaTest" "RenderType"="TransparentCutout" "IgnoreProjector"="True"}
说明:
"Queue"="AlphaTest"
开启透明度测试
"RenderType"="TransparentCutout"
可以让Unity把这个shader归入到提前定义的组(这里就是TransparentCutout组),以指明该shader是一个使用了透明测试的Shader。RenderType标签通常被用于着色器替换功能。
"IgnoreProjector"="True"
这个shader忽略投影器(Projectors)的影响。
FallBack
FallBack "Transparent/Cutout/VertexLit"
由于 Transparent/Cutout/VertexLit
中计算透明度测试时,使用了 _Cutoff 的属性来进行透明度测试,因此,这要求我们的shader中必须提供名为 _Cutoff 的属性,否则同样无法得到正确的结果。
注意
处理透明度测试时,实际上对待普通的不透明物体几乎是一样的,只是在片元着色器中增加了对透明度判断并裁剪片元的代码。
Shader "zjt/Shader8_1_test"
{
Properties
{
_Color("Color", COlor) = (1,1,1,1)
_MainTex("Maint Tex", 2D) = "white"{}
_Cutoff("Alpha Cutoff", Range(0, 1)) = 0.5 // 注意,FallBack中 Transparent/Cutout/VertexLit 计算透明度时,使用了 _Cutoff 属性
}
SubShader
{
// 通常,使用了透明度测试的 Shader 都应该在SubShader 中设置这三个标签
// "Queue"="AlphaTest" 开启透明度测试
// "RenderType"="TransparentCutout" 可以让Unity把这个shader归入到提前定义的组(这里就是TransparentCutout组),
// 以指明该shader是一个使用了透明测试的Shader。RenderType标签通常被用于着色器替换功能。
// "IgnoreProjector"="True" 这个shader忽略投影器(Projectors)的影响。
Tags { "Queue"="AlphaTest" "RenderType"="TransparentCutout" "IgnoreProjector"="True"}
LOD 200
Pass
{
Tags{"LightMode"="ForwardBase" }
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
fixed4 _Color;
sampler2D _MainTex;
float4 _MainTex_ST;
float _Cutoff;
struct a2v
{
float4 position:POSITION;
float4 texcoord:TEXCOORD0;
float3 normal:NORMAL;
};
struct v2f
{
float4 pos:SV_POSITION;
float2 uv:TEXCOORD0;
float3 worldNor:TEXCOORD1;
float3 worldPos:TEXCOORD2;
};
v2f vert(a2v v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.position);
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
o.worldNor = UnityObjectToWorldNormal(v.position);
o.worldPos = mul(unity_ObjectToWorld, v.position).xyz;
return o;
}
fixed4 frag(v2f IN):SV_Target
{
fixed4 texColor = tex2D(_MainTex, IN.uv);
clip(texColor.a - _Cutoff); // 当 texColor.a - _Cutoff 为负时,舍弃该片元的输出,该片元产生完全透明的效果
fixed3 worldNor = normalize(IN.worldNor);
fixed3 worldLight = normalize(UnityWorldSpaceLightDir(IN.worldPos));
fixed3 albedo = texColor.rgb * _Color.rgb;
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;
fixed3 diffuse = _LightColor0.rgb * albedo * (0.5 * dot(worldNor, worldLight) + 0.5);
return fixed4(ambient + diffuse, 1);
}
ENDCG
}
}
FallBack "Transparent/Cutout/VertexLit"
}