说明:
Surface Shade——属于Unity常见Shader之一,使用Unity预制的光照模型来进行光照运算。这里简单介绍一下Surface Shader 中有关于透明Shader:透明测试Shader,透明混合Shader。
透明测试Shader:
透明测试Shader具有如下特征:
- 只要是一个片元的透明度不满足条件,那么它对应的片元将会被舍弃掉。被舍弃的片元将不会再进行任何的处理,也不会对颜色缓冲产生任何影响;否则,将会被安装普通的不透明物体的处理方式来处理它。
- 透明度测试得到的透明效果比较极端——要么全部透明,要么全部不透明,得到的透明效果由于在边界处纹理的透明度的变化精度导致在边缘上往往处理不到位,存在锯齿的情况。
- 往往为了得到更加柔滑的透明效果需要涉及到透明混合。
透明测试Shader代码如下所示:
<pre name="code" class="csharp">Shader "Custom/AlphaTest"
{
//属性
Properties {
_Color ("Main Color", Color) = (1,1,1,1)
_MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
//透明度阀值
_Cutoff ("Alpha cutoff", Range(0,1)) = 0.5
}
SubShader {
//"Queue"="AlphaTest"——需要透明测试的物体使用“AlphaTest”队列
//"IgnoreProjector"="True"——忽略光阴影响
Tags {"Queue"="AlphaTest" "IgnoreProjector"="True" "RenderType"="TransparentCutout"}
LOD 200
CGPROGRAM
//加入一个变量_Cutoff,alpha值大于_Cutoff时,才会输出颜色 Blinn_Phong光照模型
#pragma surface surf Lambert alphatest:_Cutoff
sampler2D _MainTex;
fixed4 _Color;
//Input 这个输入结构——着色器需要的所有纹理坐标(texture coordinates)
struct Input {
float2 uv_MainTex;
};
void surf (Input IN, inout SurfaceOutput o) {
//应该返回RGBA——四元素
fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;
o.Alpha = c.a;
}
ENDCG
}
Fallback "Legacy Shaders/Transparent/Cutout/VertexLit"
}
//表面处理函数从顶点处理函数(这里自动顶点处理)接收参数Input IN,输出SurfaceOutput o至光照模型(这里是Lambert)。
//(1)通过uv取得了贴图对应uv的颜色c
//(2)把c.rgb赋给o.Albedo
//(3)把c.a赋给o.Alpha
透明度混合Shader:
透明度混合Shader具有如下特征:
- 透明度混合可以得到真正的半透明效果,它会使用当前片元的透明度作为混合因子,与已经存储在颜色缓冲中的颜色值进行混合,得到新的颜色;
- 透明度混合需要关闭深度写入——ZWrite Off, 故必须注意物体的渲染顺序。
- 为了进行混合,还得需要使用Unity提供的设置混合模式的命令——Blend.
ShaderLab 的 Blend命令:
- Blend Off ——关闭混合
- Blend SrcFactor DesFator——开启混合,并设置混合因子。
- Blend SrcFactor DesFator SrcFactorA DstFactorA——同上,混合因子不一样
- BlendOp BlendOperation——使用BlendOperation对源颜色及目标颜色进行操作
透明度混合Shader代码如下所示:
Shader "Custom/Transparent" {
Properties {
_Color ("Main Color", Color) = (1,1,1,1)
_MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
}
SubShader {
//"Queue"="Transparent"——需要透明混合的物体使用“Transparent”队列,这个队列的物体在所有Geometry
//及AlphaTest物体渲染后,再按从后向前的顺序进行渲染。
//"IgnoreProjector"="True"——忽略光阴影响
Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
LOD 200
CGPROGRAM
//使用Unity内置的光照模型,alpha:blend表明将进行的是透明混合
#pragma surface surf Lambert alpha:blend
sampler2D _MainTex;
fixed4 _Color;
struct Input {
float2 uv_MainTex;
};
void surf (Input IN, inout SurfaceOutput o) {
fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;
o.Alpha = c.a;
}
ENDCG
}
Fallback "Legacy Shaders/Transparent/VertexLit"
}