在學習Directx11編程中,你會發現圖形渲染等等很大一部分需要一種叫做HLSL(High Level Shading Language),中文應該叫:進階著色器語言,由微軟擁有及開發的一種語言,HLSL 獨立的工作在 Windows 平台上,只能供Direct3D使用。 HLSL是微軟抗衡GLSL的產品,同時不能與OpenGL標準相容,廢話不多說了,我們來看看到底啥子是HLSL,希望我們可以慢慢熟悉他。
一·變數
在HLSL中變數有點像C語言中的一樣,也分為局部變數和全域變數,變數也由類型修飾,變數的聲明格式如下:
1 [Storage_Class] [Type_Modifier] Type Name[Index]
2
3 [: Semantic]
4
5 [Annotations]
6
7 [= Initial_Value]
8
9 [: Packoffset]
10
11 [: Register];
參數說明:
- Storage_Class:相當於C等等的域【註:暫時還只是學習,很多都需要在實踐中才能真正明白其中的道理,那樣才能說得更清楚,所以如果有錯誤希望訪問者能夠指出來,這樣我也能夠進步,也有助於我的學習】。
extern(全域變數預設聲明,不能和static合用);
nointerpolation(當頂點著色器進入到像素著色器時,不使用插入補點)[註:可能翻譯有點錯誤,以後再說!];
precise(嚴格限定,感覺不好翻譯,直接英文注釋吧:Affects all results that contribute to the variable's outcome by preventing the compiler from doing unsafe optimizations. For instance, to improve performance the compiler ingores the possibility of NaN and INF results for floating point variables from constant and stream inputs in order to do several optimizations. By using the precise keyword, these optimizations will be prohibited for all calculations affecting the result of the variable.);
shared(共用Mark a variable for sharing between effects; this is a hint to the compiler.);
groupshared(Mark a variable for thread-group-shared memory for compute shaders. In D3D10 the maximum total size of all variables with the groupshared storage class is 16kb, in D3D11 the maximum size is 32kb.);
static(主要限定局部變數,即初始化只有一次,第一次使用時初始化,如果沒有初始化預設為0,這個和C++局部靜態變數有點一樣);
uniform(Mark a variable whose data is constant throughout the execution of a shader (such as a material color in a vertex shader); global variables are considered uniform by default.);
volatile(僅限局部變數,這個應該和C++裡的一樣,經常變動改變的變數);
- Type_Modifier:類型修飾符,一般有const(表示常量),row_major(行,將4個部分連續的儲存在同一行中),column_major(列,將4個部分連續儲存在同一列中)。後面兩個相當於一個4x4矩陣中的行和列,在Direct3D編程中4x4矩陣是經常使用的,在Directx11的學習中我們會提到。
- Type類型,就是資料類型,在後面將進行討論。
- Name[Index]變數名稱,大家都懂,後面“[]”表示數組。
- Semantic 語義聲明,主要描述變數使用資訊,一般作為編譯器連結著色器輸入和輸出使用。只有在全域變數和函數輸入輸出參數和傳回值時才有用,其它地方使用編譯器將過濾。頂點著色器和像素著色器都預定義了一些聲明,在以後使用時將進行介紹。
- Annotation(s) 注釋,以“<DataType Name = Value; ... ;>”格式進行注釋,一般在全域變數中使用,HLSL編譯器將過濾注釋字串。 1 int i <int blabla=27; string blacksheep="Hello There";>;
2
3 int j <int bambam=30; string blacksheep="Goodbye There";> = 5 ;
4
5 float y <float y=2.3;> = 2.3, z <float y=1.3;> = 1.3 ;
6
7 half w <half GlobalW = 3.62;>;
8
9 float4 main(float4 pos : SV_POSITION ) : SV_POSITION
10 {
11 pos.y = pos.x > 0 ? pos.w * 1.3 : pos.z * .032;
12 for (int x = i; x < j ; x++)
13 {
14 pos.w = pos.w * pos.y + x + j - y * w;
15 }
16
17 return pos;
18 }
- Initial_Value 初始化值;
- Packoffset
- Register
下面來看一下例子,這樣就可以讓我們更好的理解上面的一些內容。
1 float fVar;
2 float4 color;
3 float fVar = 3.1f;
4
5 int iVar[3];
6
7 int iVar[3] = {1,2,3};
8
9 uniform float4 position : SV_POSITION;
10 const float4 lightDirection = {0,0,1};
看過去是不是很像C/C++的樣子,其中float4表示是4個,相當於一個數組,在HLSL中預設的基礎資料類型都包含了4及以下的下標。當然矩陣在HLSL中是很常見的,如float4x4等,其中數字就是所說的意思。而SV_POSITION就是描述語義,即頂點座標的意思。今天就學習到這裡,有空了繼續學習........