漫反射光照符合蘭伯特定律 : 反射光線的強度 與 表面法線 和 光源方向 之間的夾角的余弦值成正比 .
計算機圖形第一定律 : 如果它看起來是對的 , 那么它就是對的 .
逐頂點光照的計算量往往要小於逐像素光照 .
逐頂點光照依賴於線性插值來得到像素光照 , 當光照模型中有非線性的計算的時候 , 逐頂點光照就會出問題 , 例如計算高光反射 .
逐頂點光照會在渲染圖元內部對頂點進行插值 , 渲染圖元內部的顏色總是暗於頂點處的最高顏色 , 在某些情況下會產生明顯的棱角現象 .
// Upgrade NOTE: replaced '_World2Object' with 'unity_WorldToObject'
Shader "Custom/DiffuseVertexLevel" {
Properties {
_Diffuse("Diffuse", Color) = (1, 1, 1, 1)
}
SubShader {
Pass {
Tags { "LightMode"="ForwardBase" }
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
fixed4 _Diffuse;
struct a2v {
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct v2f {
float4 pos : SV_POSITION;
fixed3 color : COLOR;
};
// 逐頂點的漫反射光照
v2f vert(a2v v) {
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
fixed3 worldNormal = normalize(mul(v.normal, (float3x3)unity_WorldToObject));
fixed3 worldLight = normalize(_WorldSpaceLightPos0.xyz);
fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal, worldLight));
o.color = ambient + diffuse; // 環境光 + 漫射光
return o;
}
fixed4 frag(v2f f) : SV_Target {
return fixed4(f.color, 1.0);
}
ENDCG
}
}
FallBack "Diffuse"
}
逐像素光照可以得到更加平滑的光照效果 , 但是有一個問題存在 : 當光照無法到達的區域 , 模型的外觀通常是全黑的 , 沒有任何的額明暗變化 , 失去了模型細節表現 , 因此有一種改善技術提出 , 即 , 半蘭布特光照模型(沒有任何物理依據 , 只是一個視覺加強技術) .
Shader "Custom/DiffusePixelLevel" {
Properties {
_Diffuse("Diffuse", Color) = (1,1,1,1)
}
SubShader {
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
fixed4 _Diffuse;
struct a2v {
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct v2f {
float4 pos : SV_POSITION;
float3 worldNormal : TEXCOORD0;
};
v2f vert(a2v v) {
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
o.worldNormal = mul(v.normal, (float3x3)_World2Object);
return o;
}
// 逐像素漫反射光照
fixed4 frag(v2f f) : SV_Target {
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
fixed3 worldNormal = normalize(f.worldNormal);
fixed3 worldLightDir = normalize(_WorldSpaceLightPos0.xyz);
fixed3 diffuse = _LightColor0 * _Diffuse.rgb * (dot(worldNormal, worldLightDir) * 0.5 + 0.5); // 半蘭伯特光照模型
fixed3 color = ambient + diffuse;
return fixed4(color, 1.0);
}
ENDCG
}
}
FallBack "Diffuse"
}
End.
