Unity Shader 之 透明效果


透明效果

透明效果一般有兩種實現方法:

  • 第一種,使用透明度測試(Alpha Test)
  • 第二種,使用透明度混合(Alpha Blending)

透明度測試透明度混合機制

透明度測試(Alpha Test):只要一個片元的透明度不滿足條件(小於某閥值),那么它對應的片元就會被舍棄。被舍棄的片元將不會再進行任何處理,也不會對顏色緩沖產生任何影響;否則,就按照普通的不透明物體處理,即進行深度測試、深度寫入。透明度測試不需要關閉深度寫入。

透明度混合(Alpha Blending):使用當前片元的透明度作為混合因子,與已經存儲在顏色緩沖中的顏色值進行混合,得到新的顏色值。但是,這需要關閉深度寫入。雖然關閉了深度寫入,但是沒有關閉了深度緩沖,此時深度緩沖還是可讀的。

不同的渲染順序帶來的結果:(A半透明,B不透明)

渲染順序

第一種:先渲染B,再渲染A.

結果:能得到正確的渲染效果。

第二種:先渲染A,再渲染B.

結果:不能得到正確的渲染效果,因為在渲染A時已經關閉了深度寫入,所以A不會修改深度緩沖,等到渲染B時,B直接覆蓋了A的顏色。

渲染常用順序:

  1. 先渲染所有不透明物體,開啟深度測試和深度寫入。
  2. 半透明物體按離攝像機距離遠近排序,從后往前渲染,開啟深度測試,關閉深度寫入。

部分相互重疊的物體不適用,解決方法是分割網格。

unity shader的渲染順序

Unity為了解決渲染順序問題提供了渲染隊列(render queue)解決方案。

unity渲染隊列

實現透明度測試時需要添加代碼:

SubShader{
    Tags {"Queue" = "AlphaTest"}
    Pass{
        ...
    }
}

實現透明度混合需要添加代碼:

SubShader{
    Tags {"Queue" = "Transform"}
    Pass{
        ZWrite Off
        ...
    }
}

透明度測試

關鍵函數

clip函數是CG中的一個函數:

void clip(float4 x);
void clip(float3 x);
void clip(float2 x);
void clip(float1 x);
void clip(float x);

全部代碼

Shader "Unity Shaders Book/Chapter 8/Alpha Test" {
	Properties {
		_Color ("Color Tint", Color) = (1, 1, 1, 1)
		_MainTex ("Main Tex", 2D) = "white" {}
		_Cutoff ("Alpha Cutoff", Range(0, 1)) = 0.5
	}
	SubShader {
		Tags {"Queue"="AlphaTest" "IgnoreProjector"="True" "RenderType"="TransparentCutout"}
		
		Pass {
			Tags { "LightMode"="ForwardBase" }
			
			CGPROGRAM
			
			#pragma vertex vert
			#pragma fragment frag
			
			#include "Lighting.cginc"
			
			fixed4 _Color;
			sampler2D _MainTex;
			float4 _MainTex_ST;
			fixed _Cutoff;
			
			struct a2v {
				float4 vertex : POSITION;
				float3 normal : NORMAL;
				float4 texcoord : TEXCOORD0;
			};
			
			struct v2f {
				float4 pos : SV_POSITION;
				float3 worldNormal : TEXCOORD0;
				float3 worldPos : TEXCOORD1;
				float2 uv : TEXCOORD2;
			};
			
			v2f vert(a2v v) {
				v2f o;
				o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
				
				o.worldNormal = UnityObjectToWorldNormal(v.normal);
				
				o.worldPos = mul(_Object2World, v.vertex).xyz;
				
				o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
				
				return o;
			}
			
			fixed4 frag(v2f i) : SV_Target {
				fixed3 worldNormal = normalize(i.worldNormal);
				fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
				
				fixed4 texColor = tex2D(_MainTex, i.uv);
				
				// Alpha test
				clip (texColor.a - _Cutoff);
				// Equal to 
//				if ((texColor.a - _Cutoff) < 0.0) {
//					discard;
//				}
				
				fixed3 albedo = texColor.rgb * _Color.rgb;
				
				fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;
				
				fixed3 diffuse = _LightColor0.rgb * albedo * max(0, dot(worldNormal, worldLightDir));
				
				return fixed4(ambient + diffuse, 1.0);
			}
			
			ENDCG
		}
	} 
	FallBack "Transparent/Cutout/VertexLit"
}

效果

透明度測試

透明度混合

透明度混合的本質就是用當前片元的透明度作為混合因子,與已經存儲在顏色緩沖中的顏色值進行混合,得到新顏色。

混合公式如下:

透明度混合公式

unity提供的混合命令:

shaderlab中的Blend命令

透明度混合完整代碼

Shader "Unity Shaders Book/Chapter 8/Alpha Blend" {
	Properties {
		_Color ("Color Tint", Color) = (1, 1, 1, 1)
		_MainTex ("Main Tex", 2D) = "white" {}
		_AlphaScale ("Alpha Scale", Range(0, 1)) = 1
	}
	SubShader {
		Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
		
		Pass {
			Tags { "LightMode"="ForwardBase" }
			ZWrite Off
			Blend SrcAlpha OneMinusSrcAlpha
			
			CGPROGRAM
			
			#pragma vertex vert
			#pragma fragment frag
			
			#include "Lighting.cginc"
			
			fixed4 _Color;
			sampler2D _MainTex;
			float4 _MainTex_ST;
			fixed _AlphaScale;
			
			struct a2v {
				float4 vertex : POSITION;
				float3 normal : NORMAL;
				float4 texcoord : TEXCOORD0;
			};
			
			struct v2f {
				float4 pos : SV_POSITION;
				float3 worldNormal : TEXCOORD0;
				float3 worldPos : TEXCOORD1;
				float2 uv : TEXCOORD2;
			};
			
			v2f vert(a2v v) {
				v2f o;
				o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
				
				o.worldNormal = UnityObjectToWorldNormal(v.normal);
				
				o.worldPos = mul(_Object2World, v.vertex).xyz;
				
				o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
				
				return o;
			}
			
			fixed4 frag(v2f i) : SV_Target {
				fixed3 worldNormal = normalize(i.worldNormal);
				fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
				
				fixed4 texColor = tex2D(_MainTex, i.uv);
				
				fixed3 albedo = texColor.rgb * _Color.rgb;
				
				fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;
				
				fixed3 diffuse = _LightColor0.rgb * albedo * max(0, dot(worldNormal, worldLightDir));
				
				return fixed4(ambient + diffuse, texColor.a * _AlphaScale);
			}
			
			ENDCG
		}
	} 
	FallBack "Transparent/VertexLit"
}

效果

透明度混合

開啟深度寫入的半透明效果

前面提到由於關閉深度寫入而造成的錯誤排序的情況。可以使用兩個Pass的辦法來解決

第一個Pass: 開啟深度寫入,但不輸出顏色,它的目的僅僅是為了把該模型的深度值寫入深度緩沖中

第二個Pass: 進行正常的透明度混合,由於上個Pass已經的到了像素的正確深度信息,所以可以得到正確的渲染結果。

這種辦法的缺點是對性能有一定影響

ShaderLab的混合命令

ShaderLab中的混合因子

參數 描述
One The value of one - use this to let either the source or the destination color come through fully.
Zero The value zero - use this to remove either the source or the destination values.
SrcColor The value of this stage is multiplied by the source color value.
SrcAlpha The value of this stage is multiplied by the source alpha value.
DstColor The value of this stage is multiplied by frame buffer source color value.
DstAlpha The value of this stage is multiplied by frame buffer source alpha value.
OneMinusSrcColor The value of this stage is multiplied by (1 - source color).
OneMinusSrcAlpha The value of this stage is multiplied by (1 - source alpha).
OneMinusDstColor The value of this stage is multiplied by (1 - destination color).
OneMinusDstAlpha The value of this stage is multiplied by (1 - destination alpha).

ShaderLab中的混合操作

操作 描述
Add Add source and destination together.
Sub Subtract destination from source.
RevSub Subtract source from destination.
Min Use the smaller of source and destination.
Max Use the larger of source and destination.
LogicalClear Logical operation: Clear (0) DX11.1 only.
LogicalSet Logical operation: Set (1) DX11.1 only.
LogicalCopy Logical operation: Copy (s) DX11.1 only.
LogicalCopyInverted Logical operation: Copy inverted (!s) DX11.1 only.
LogicalNoop Logical operation: Noop (d) DX11.1 only.
LogicalInvert Logical operation: Invert (!d) DX11.1 only.
LogicalAnd Logical operation: And (s & d) DX11.1 only.
LogicalNand Logical operation: Nand !(s & d) DX11.1 only.
LogicalOr Logical operation: Or (s | d) DX11.1 only.
LogicalNor Logical operation: Nor !(s | d) DX11.1 only.
LogicalXor Logical operation: Xor (s ^ d) DX11.1 only.
LogicalEquiv Logical operation: Equivalence !(s ^ d) DX11.1 only.
LogicalAndReverse Logical operation: Reverse And (s & !d) DX11.1 only.
LogicalAndInverted Logical operation: Inverted And (!s & d) DX11.1 only.
LogicalOrReverse Logical operation: Reverse Or (s | !d) DX11.1 only.
LogicalOrInverted Logical operation: Inverted Or (!s | d) DX11.1 only.

雙面渲染的透明效果

上面的透明度測試和透明度混合都無法將物體的背面顯示出來,這是因為渲染引擎剔除了物體的背面,所以需要在渲染透明物體使用Cull指令控制需要剔除的渲染圖元。

  • Cull Back | Front | Off

分別是:剔除背面的圖元 | 剔除前面的圖元 | 關閉功能

完整代碼

Shader "Unity Shaders Book/Chapter 8/Alpha Blend With Both Side" {
	Properties {
		_Color ("Color Tint", Color) = (1, 1, 1, 1)
		_MainTex ("Main Tex", 2D) = "white" {}
		_AlphaScale ("Alpha Scale", Range(0, 1)) = 1
	}
	SubShader {
		Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
		
		Pass {
			Tags { "LightMode"="ForwardBase" }
			
			// First pass renders only back faces 
			Cull Front
			
			ZWrite Off
			Blend SrcAlpha OneMinusSrcAlpha
			
			CGPROGRAM
			
			#pragma vertex vert
			#pragma fragment frag
			
			#include "Lighting.cginc"
			
			fixed4 _Color;
			sampler2D _MainTex;
			float4 _MainTex_ST;
			fixed _AlphaScale;
			
			struct a2v {
				float4 vertex : POSITION;
				float3 normal : NORMAL;
				float4 texcoord : TEXCOORD0;
			};
			
			struct v2f {
				float4 pos : SV_POSITION;
				float3 worldNormal : TEXCOORD0;
				float3 worldPos : TEXCOORD1;
				float2 uv : TEXCOORD2;
			};
			
			v2f vert(a2v v) {
				v2f o;
				o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
				
				o.worldNormal = UnityObjectToWorldNormal(v.normal);
				
				o.worldPos = mul(_Object2World, v.vertex).xyz;
				
				o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
				
				return o;
			}
			
			fixed4 frag(v2f i) : SV_Target {
				fixed3 worldNormal = normalize(i.worldNormal);
				fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
				
				fixed4 texColor = tex2D(_MainTex, i.uv);
				
				fixed3 albedo = texColor.rgb * _Color.rgb;
				
				fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;
				
				fixed3 diffuse = _LightColor0.rgb * albedo * max(0, dot(worldNormal, worldLightDir));
				
				return fixed4(ambient + diffuse, texColor.a * _AlphaScale);
			}
			
			ENDCG
		}
		
		Pass {
			Tags { "LightMode"="ForwardBase" }
			
			// Second pass renders only front faces 
			Cull Back
			
			ZWrite Off
			Blend SrcAlpha OneMinusSrcAlpha
			
			CGPROGRAM
			
			#pragma vertex vert
			#pragma fragment frag
			
			#include "Lighting.cginc"
			
			fixed4 _Color;
			sampler2D _MainTex;
			float4 _MainTex_ST;
			fixed _AlphaScale;
			
			struct a2v {
				float4 vertex : POSITION;
				float3 normal : NORMAL;
				float4 texcoord : TEXCOORD0;
			};
			
			struct v2f {
				float4 pos : SV_POSITION;
				float3 worldNormal : TEXCOORD0;
				float3 worldPos : TEXCOORD1;
				float2 uv : TEXCOORD2;
			};
			
			v2f vert(a2v v) {
				v2f o;
				o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
				
				o.worldNormal = UnityObjectToWorldNormal(v.normal);
				
				o.worldPos = mul(_Object2World, v.vertex).xyz;
				
				o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
				
				return o;
			}
			
			fixed4 frag(v2f i) : SV_Target {
				fixed3 worldNormal = normalize(i.worldNormal);
				fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
				
				fixed4 texColor = tex2D(_MainTex, i.uv);
				
				fixed3 albedo = texColor.rgb * _Color.rgb;
				
				fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;
				
				fixed3 diffuse = _LightColor0.rgb * albedo * max(0, dot(worldNormal, worldLightDir));
				
				return fixed4(ambient + diffuse, texColor.a * _AlphaScale);
			}
			
			ENDCG
		}
	} 
	FallBack "Transparent/VertexLit"
}

效果

雙面渲染的透明效果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM