上次說到很簡(jiǎn)單的shader焰枢,這次來用顏色可視化模擬和頂點(diǎn)相關(guān)的數(shù)據(jù),代碼如下:
Shader "Unity Shaders Book/Chapter 5/False Color" {
SubShader {
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f {
float4 pos : SV_POSITION;
fixed4 color : COLOR0;
};
v2f vert(appdata_full v) {
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
// Visualize normal
o.color = fixed4(v.normal * 0.5 + fixed3(0.5, 0.5, 0.5), 1.0);
// Visualize tangent
o.color = fixed4(v.tangent.xyz * 0.5 + fixed3(0.5, 0.5, 0.5), 1.0);
// Visualize binormal
fixed3 binormal = cross(v.normal, v.tangent.xyz) * v.tangent.w;
o.color = fixed4(binormal * 0.5 + fixed3(0.5, 0.5, 0.5), 1.0);
// Visualize the first set texcoord
o.color = fixed4(v.texcoord.xy, 0.0, 1.0);
// Visualize the second set texcoord
o.color = fixed4(v.texcoord1.xy, 0.0, 1.0);
// Visualize fractional part of the first set texcoord
o.color = frac(v.texcoord);
if (any(saturate(v.texcoord) - v.texcoord)) {
o.color.b = 0.5;
}
o.color.a = 1.0;
// Visualize fractional part of the second set texcoord
o.color = frac(v.texcoord1);
if (any(saturate(v.texcoord1) - v.texcoord1)) {
o.color.b = 0.5;
}
o.color.a = 1.0;
// Visualize vertex color
// o.color = v.color;
return o;
}
fixed4 frag(v2f i) : SV_Target {
return i.color;
}
ENDCG
}
}
}
從#include "UnityCG.cginc"說起围来,它是包含了unity的一個(gè)內(nèi)置文件UnityCG.cginc痛垛,在unity的安裝目錄 /Data/CGIncludes/UnityCG.cginc下面能夠找到。而appdata_full 結(jié)構(gòu)體就在其中定義了
v2f和fixed4決定了vert和fragment函數(shù)的輸出類型
vert函數(shù)具體代碼中步清,v.normal 可以通過加權(quán)平均共享該頂點(diǎn)的所有三角形面法線得到要门,因?yàn)関.normal 的各個(gè)分量范圍是[-1,1],而顏色RGB的分量范圍是[01,],于是就要解決這個(gè)范圍映射問題,所以就有了o.color = fixed4(v.normal * 0.5 + fixed3(0.5, 0.5, 0.5), 1.0);這樣的代碼廓啊,切線可視化類似欢搜,但需要主要的是切線是四維向量,具體可在Sahder筆記中查看谴轮,切線和副切線如何計(jì)算的可參照這個(gè)炒瘟。
o.color = fixed4(v.texcoord.xy, 0.0, 1.0);是把頂點(diǎn)的第一組紋理坐標(biāo)存到color中
o.color = frac(v.texcoord1);則是計(jì)算頂點(diǎn)第二組紋理各分量的小數(shù)部分,saturate意為返回一個(gè)[0, 1]范圍內(nèi)的數(shù)第步,如果x<0則返回0疮装,如果x>1則返回1缘琅,否則返回x。
相信通過添加注釋不同位置的代碼廓推,就能更直觀的看到結(jié)果了刷袍。