效果圖
不包含光照(但包含霧效)的基本頂點/片元着色器
原理:對主紋理採樣出顏色值,並根據霧氣模式選擇相應的算法得出最終顏色值。代碼有詳細的註解(具體請參考UnityCG.cginc)
//不包含光照(但包含霧效)的基本頂點/片元着色器
Shader "Unlit/UnlitShader"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }//RenderType爲Opaque不透明渲染類型
LOD 100 //LOD值 用於控制SubShader渲染,在Unity規定範圍LOD內可進行渲染
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog //開啓霧效的一些工作:編譯霧效變體(具體內容未知)
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1) //霧效數據聲明:float1 fogCoord : TEXCOORD1;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
//頂點着色器:頂點空間變換、霧效處理
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
//UNITY_TRANSFER_FOG宏相當於
//FOG模式爲Linear:
//o.fogCoord = o.vertex.z * unity_FogParams.z + unity_FogParams.w = (end-z)/(end-start) = z * (-1/(end-start)) + (end/(end-start))
//FOG模式爲Exponential:
//o.fogCoord = exp2(-unity_FogParams.y * o.vertex.z) = exp(-density*z)
//FOG模式爲Exponential squared:
//o.fogCoord = exp2(-((unity_FogParams.x * o.vertex.z)^2)) = exp(-(density*z)^2)
//其中,exp(x)函數爲計算e^x次方值 (e=2.71828182845904523536) , exp2(x)爲e^x
//density爲霧濃度參數, unity_FogParams尚未了結具體情況, start, end 應該是霧氣起始點和終點, z爲裁剪座標的Z值(D3D爲[0,far],OPENGL爲[-near,far]範圍
return o;
}
//片元着色器: 採樣紋理顏色並輸出、霧效處理
fixed4 frag (v2f i) : SV_Target
{
// sample the texture
fixed4 col = tex2D(_MainTex, i.uv);
// apply fog
UNITY_APPLY_FOG(i.fogCoord, col);
//UNITY_APPLY_FOG(coord, col)
//在前置渲染ADD模式下:
//col.rgb = lerp((0,0,0).rgb, (col).rgb, saturate(i.fogCoord.x))
//在上述例子中,無論哪種模式都會隨着Z變大而fogCoord.x變小逐漸靠近0
//因此col顏色值會逐漸變爲霧氣顏色(0,0,0)即黑色
//非前置渲染ADD模式下:
//col.rgb = lerp((unityFogFactor).rgb, (col).rgb, saturate(i.fogCoord.x))
//逐漸靠近Unity設置好的霧氣顏色 Window -> Lighting -> Settings (lighting面板)可設置
return col;
}
ENDCG
}
}
}
其他兩種模式請自行研究