參考資料
以下網址多數爲中文網址
HLSL
HLSL微軟網址
https://docs.microsoft.com/zh-cn/windows/desktop/direct3dhlsl/dx-graphics-hlsl
內置函數頁
https://docs.microsoft.com/zh-cn/windows/desktop/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions
GLSL
GLSL官方網站
內置函數頁
https://www.khronos.org/developers/reference-cards/
GLSL中文手冊
https://github.com/wshxbqq/GLSL-Card
CG
Cg Nvidia文檔
https://developer.download.nvidia.cn/cg/
內置函數頁
https://developer.download.nvidia.cn/cg/index_stdlib.html
內置函數
HLSL
Name | Description | 描述 | Minimum shader model |
---|---|---|---|
abort | Terminates the current draw or dispatch call being executed. | 終止當前正在執行的繪製或調度 | 4 |
abs | Absolute value (per component). | 絕對值(每個分量) | 1¹ |
acos | Returns the arccosine of each component of x. | 反餘弦 | 1¹ |
all | Test if all components of x are nonzero. | 所有分量均爲非零 | 1¹ |
AllMemoryBarrier | Blocks execution of all threads in a group until all memory accesses have been completed. | 終止一個組中的所有線程,直到內存訪問完成 | 5 |
AllMemoryBarrierWithGroupSync | Blocks execution of all threads in a group until all memory accesses have been completed and all threads in the group have reached this call. | 終止一個組中的所有線程,直到內存訪問完成且組內的全部線程到達調用 | 5 |
any | Test if any component of x is nonzero. | 存在非零分量 | 1¹ |
asdouble | Reinterprets a cast value into a double. | 強制轉換爲double | 5 |
asfloat | Convert the input type to a float. | 強制轉換爲float | 4 |
asin | Returns the arcsine of each component of x. | 反正弦 | 1¹ |
asint | Convert the input type to an integer. | 強制轉換爲int | 4 |
asuint | Reinterprets the bit pattern of a 64-bit type to a uint. | 強制轉換爲uint | 5 |
asuint | Convert the input type to an unsigned integer. | 強制轉換爲uint | 4 |
atan | Returns the arctangent of x. | 反正切 | 1¹ |
atan2 | Returns the arctangent of of two values (x,y). | 反正切 x/y | 1¹ |
ceil | Returns the smallest integer which is greater than or equal to x. | 返回大於等於x的最小int | 1¹ |
CheckAccessFullyMapped | Determines whether all values from a Sample or Load operation accessed mapped tiles in a tiled resource. | 確定來自採樣或加載操作的所有值是否訪問了平鋪資源中的映射圖塊。 | 5 |
clamp | Clamps x to the range [min, max]. | 將x限制在區間[min,max]中 | 1¹ |
clip | Discards the current pixel, if any component of x is less than zero. | 當x的任意分量小於0時,剔除像素 | 1¹ |
cos | Returns the cosine of x. | 餘弦 | 1¹ |
cosh | Returns the hyperbolic cosine of x. | 雙曲 | 1¹ |
countbits | Counts the number of bits (per component) in the input integer. | 統計輸入整數各分量的位數 | 5 |
cross | Returns the cross product of two 3D vectors. | 叉乘 | 1¹ |
D3DCOLORtoUBYTE4 | Swizzles and scales components of the 4D vector xto compensate for the lack of UBYTE4 support in some hardware. | 1¹ | |
ddx | Returns the partial derivative of x with respect to the screen-space x-coordinate. | 2¹ | |
ddx_coarse | Computes a low precision partial derivative with respect to the screen-space x-coordinate. | 5 | |
ddx_fine | Computes a high precision partial derivative with respect to the screen-space x-coordinate. | 5 | |
ddy | Returns the partial derivative of x with respect to the screen-space y-coordinate. | 2¹ | |
ddy_coarse | Computes a low precision partial derivative with respect to the screen-space y-coordinate. | 5 | |
ddy_fine | Computes a high precision partial derivative with respect to the screen-space y-coordinate. | 5 | |
degrees | Converts x from radians to degrees. | 1¹ | |
determinant | Returns the determinant of the square matrix m. | 1¹ | |
DeviceMemoryBarrier | Blocks execution of all threads in a group until all device memory accesses have been completed. | 5 | |
DeviceMemoryBarrierWithGroupSync | Blocks execution of all threads in a group until all device memory accesses have been completed and all threads in the group have reached this call. | 5 | |
distance | Returns the distance between two points. | 1¹ | |
dot | Returns the dot product of two vectors. | 1 | |
dst | Calculates a distance vector. | 5 | |
errorf | Submits an error message to the information queue. | 4 | |
EvaluateAttributeAtCentroid | Evaluates at the pixel centroid. | 5 | |
EvaluateAttributeAtSample | Evaluates at the indexed sample location. | 5 | |
EvaluateAttributeSnapped | Evaluates at the pixel centroid with an offset. | 5 | |
exp | Returns the base-e exponent. | 1¹ | |
exp2 | Base 2 exponent (per component). | 1¹ | |
f16tof32 | Converts the float16 stored in the low-half of the uint to a float. | 5 | |
f32tof16 | Converts an input into a float16 type. | 5 | |
faceforward | Returns -n * sign(dot(i, ng)). | 1¹ | |
firstbithigh | Gets the location of the first set bit starting from the highest order bit and working downward, per component. | 5 | |
firstbitlow | Returns the location of the first set bit starting from the lowest order bit and working upward, per component. | 5 | |
floor | Returns the greatest integer which is less than or equal to x. | 1¹ | |
fma | Returns the double-precision fused multiply-addition of a * b + c. | 5 | |
fmod | Returns the floating point remainder of x/y. | 1¹ | |
frac | Returns the fractional part of x. | 1¹ | |
frexp | Returns the mantissa and exponent of x. | 2¹ | |
fwidth | Returns abs(ddx(x)) + abs(ddy(x)) | 2¹ | |
GetRenderTargetSampleCount | Returns the number of render-target samples. | 4 | |
GetRenderTargetSamplePosition | Returns a sample position (x,y) for a given sample index. | 4 | |
GroupMemoryBarrier | Blocks execution of all threads in a group until all group shared accesses have been completed. | 5 | |
GroupMemoryBarrierWithGroupSync | Blocks execution of all threads in a group until all group shared accesses have been completed and all threads in the group have reached this call. | 5 | |
InterlockedAdd | Performs a guaranteed atomic add of value to the dest resource variable. | 5 | |
InterlockedAnd | Performs a guaranteed atomic and. | 5 | |
InterlockedCompareExchange | Atomically compares the input to the comparison value and exchanges the result. | 5 | |
InterlockedCompareStore | Atomically compares the input to the comparison value. | 5 | |
InterlockedExchange | Assigns value to dest and returns the original value. | 5 | |
InterlockedMax | Performs a guaranteed atomic max. | 5 | |
InterlockedMin | Performs a guaranteed atomic min. | 5 | |
InterlockedOr | Performs a guaranteed atomic or. | 5 | |
InterlockedXor | Performs a guaranteed atomic xor. | 5 | |
isfinite | Returns true if x is finite, false otherwise. | 1¹ | |
isinf | Returns true if x is +INF or -INF, false otherwise. | 1¹ | |
isnan | Returns true if x is NAN or QNAN, false otherwise. | 1¹ | |
ldexp | Returns x * 2exp | 1¹ | |
length | Returns the length of the vector v. | 1¹ | |
lerp | Returns x + s(y - x). | 1¹ | |
lit | Returns a lighting vector (ambient, diffuse, specular, 1) | 1¹ | |
log | Returns the base-e logarithm of x. | 1¹ | |
log10 | Returns the base-10 logarithm of x. | 1¹ | |
log2 | Returns the base-2 logarithm of x. | 1¹ | |
mad | Performs an arithmetic multiply/add operation on three values. | 5 | |
max | Selects the greater of x and y. | 1¹ | |
min | Selects the lesser of x and y. | 1¹ | |
modf | Splits the value x into fractional and integer parts. | 1¹ | |
msad4 | Compares a 4-byte reference value and an 8-byte source value and accumulates a vector of 4 sums. | 5 | |
mul | Performs matrix multiplication using x and y. | 1 | |
noise | Generates a random value using the Perlin-noise algorithm. | 1¹ | |
normalize | Returns a normalized vector. | 1¹ | |
pow | Returns xy. | 1¹ | |
printf | Submits a custom shader message to the information queue. | 4 | |
Process2DQuadTessFactorsAvg | Generates the corrected tessellation factors for a quad patch. | 5 | |
Process2DQuadTessFactorsMax | Generates the corrected tessellation factors for a quad patch. | 5 | |
Process2DQuadTessFactorsMin | Generates the corrected tessellation factors for a quad patch. | 5 | |
ProcessIsolineTessFactors | Generates the rounded tessellation factors for an isoline. | 5 | |
ProcessQuadTessFactorsAvg | Generates the corrected tessellation factors for a quad patch. | 5 | |
ProcessQuadTessFactorsMax | Generates the corrected tessellation factors for a quad patch. | 5 | |
ProcessQuadTessFactorsMin | Generates the corrected tessellation factors for a quad patch. | 5 | |
ProcessTriTessFactorsAvg | Generates the corrected tessellation factors for a tri patch. | 5 | |
ProcessTriTessFactorsMax | Generates the corrected tessellation factors for a tri patch. | 5 | |
ProcessTriTessFactorsMin | Generates the corrected tessellation factors for a tri patch. | 5 | |
radians | Converts x from degrees to radians. | 1 | |
rcp | Calculates a fast, approximate, per-component reciprocal. | 5 | |
reflect | Returns a reflection vector. | 1 | |
refract | Returns the refraction vector. | 1¹ | |
reversebits | Reverses the order of the bits, per component. | 5 | |
round | Rounds x to the nearest integer | 1¹ | |
rsqrt | Returns 1 / sqrt(x) | 1¹ | |
saturate | Clamps x to the range [0, 1] | 1 | |
sign | Computes the sign of x. | 計算x的符號 | 1¹ |
sin | Returns the sine of x | 正弦 | 1¹ |
sincos | Returns the sine and cosine of x. | 正弦餘弦 | 1¹ |
sinh | Returns the hyperbolic sine of x | 1¹ | |
smoothstep | Returns a smooth Hermite interpolation between 0 and 1. | 1¹ | |
sqrt | Square root (per component) | 1¹ | |
step | Returns (x >= a) ? 1 : 0 | 1¹ | |
tan | Returns the tangent of x | 1¹ | |
tanh | Returns the hyperbolic tangent of x | 1¹ | |
tex1D(s, t) | 1D texture lookup. | 1 | |
tex1D(s, t, ddx, ddy) | 1D texture lookup. | 2¹ | |
tex1Dbias | 1D texture lookup with bias. | 2¹ | |
tex1Dgrad | 1D texture lookup with a gradient. | 2¹ | |
tex1Dlod | 1D texture lookup with LOD. | 3¹ | |
tex1Dproj | 1D texture lookup with projective divide. | 2¹ | |
tex2D(s, t) | 2D texture lookup. | 1¹ | |
tex2D(s, t, ddx, ddy) | 2D texture lookup. | 2¹ | |
tex2Dbias | 2D texture lookup with bias. | 2¹ | |
tex2Dgrad | 2D texture lookup with a gradient. | 2¹ | |
tex2Dlod | 2D texture lookup with LOD. | 3 | |
tex2Dproj | 2D texture lookup with projective divide. | 2¹ | |
tex3D(s, t) | 3D texture lookup. | 1¹ | |
tex3D(s, t, ddx, ddy) | 3D texture lookup. | 2¹ | |
tex3Dbias | 3D texture lookup with bias. | 2¹ | |
tex3Dgrad | 3D texture lookup with a gradient. | 2¹ | |
tex3Dlod | 3D texture lookup with LOD. | 3¹ | |
tex3Dproj | 3D texture lookup with projective divide. | 2¹ | |
texCUBE(s, t) | Cube texture lookup. | 1¹ | |
texCUBE(s, t, ddx, ddy) | Cube texture lookup. | 2¹ | |
texCUBEbias | Cube texture lookup with bias. | 2¹ | |
texCUBEgrad | Cube texture lookup with a gradient. | 2¹ | |
texCUBElod | Cube texture lookup with LOD. | 3¹ | |
texCUBEproj | Cube texture lookup with projective divide. | 2¹ | |
transpose | Returns the transpose of the matrix m. | 1 | |
trunc | Truncates floating-point value(s) to integer value(s) | 1 |
GLSL
變量
GLSL的變量命名方式與C語言類似。變量的名稱可以使用字母,數字以及下劃線,但變量名不能以數字開頭,還有變量名不能以gl_作爲前綴,這個是GLSL保留的前綴,用於GLSL的內部變量。當然還有一些GLSL保留的名稱是不能夠作爲變量的名稱的。
基本類型
除了布爾型,整型,浮點型基本類型外,GLSL還引入了一些在着色器中經常用到的類型作爲基本類型。這些基本類型都可以作爲結構體內部的類型。如下表:
類型 | 描述 |
void | 跟C語言的void類似,表示空類型。作爲函數的返回類型,表示這個函數不返回值。 |
bool | 布爾類型,可以是true 和false,以及可以產生布爾型的表達式。 |
int | 整型 代表至少包含16位的有符號的整數。可以是十進制的,十六進制的,八進制的。 |
float | 浮點型 |
bvec2 | 包含2個布爾成分的向量 |
bvec3 | 包含3個布爾成分的向量 |
bvec4 | 包含4個布爾成分的向量 |
ivec2 | 包含2個整型成分的向量 |
ivec3 | 包含3個整型成分的向量 |
ivec4 | 包含4個整型成分的向量 |
mat2 或者 mat2x2 | 2x2的浮點數矩陣類型 |
mat3或者mat3x3 | 3x3的浮點數矩陣類型 |
mat4x4 | 4x4的浮點矩陣 |
mat2x3 | 2列3行的浮點矩陣(OpenGL的矩陣是列主順序的) |
mat2x4 | 2列4行的浮點矩陣 |
mat3x2 | 3列2行的浮點矩陣 |
mat3x4 | 3列4行的浮點矩陣 |
mat4x2 | 4列2行的浮點矩陣 |
mat4x3 | 4列3行的浮點矩陣 |
sampler1D | 用於內建的紋理函數中引用指定的1D紋理的句柄。只可以作爲一致變量或者函數參數使用 |
sampler2D | 二維紋理句柄 |
sampler3D | 三維紋理句柄 |
samplerCube | cube map紋理句柄 |
sampler1DShadow | 一維深度紋理句柄 |
sampler2DShadow | 二維深度紋理句柄 |
結構體
結構體
結構體可以組合基本類型和數組來形成用戶自定義的類型。在定義一個結構體的同時,你可以定義一個結構體實例。或者後面再定義。
struct surface {float indexOfRefraction;
vec3 color;float turbulence;
} mySurface;
surface secondeSurface;
你可以通過=爲結構體賦值,或者使用 ==,!=來判斷兩個結構體是否相等。
mySurface = secondSurface;
mySurface == secondSurface;
只有結構體中的每個成分都相等,那麼這兩個結構體纔是相等的。訪問結構體的內部成員使用. 來訪問。
vec3 color = mySurface.color + secondSurface.color;
結構體至少包含一個成員。固定大小的數組也可以被包含在結構體中。GLSL的結構體不支持嵌套定義。只有預先聲明的結構體可以嵌套其中。
struct myStruct {
vec3 points[3]; //固定大小的數組是合法的
surface surf; //可以,之前已經定義了
struct velocity { //不合法float speed;
vec3 direction;
} velo;
subSurface sub; //不合法,沒有預先聲明;};struct subSurface { int id;
};
數組
GLSL中只可以使用一維的數組。數組的類型可以是一切基本類型或者結構體。下面的幾種數組聲明是合法的:
surface mySurfaces[];
vec4 lightPositions[8];
vec4 lightPos[] = lightPositions;const int numSurfaces = 5;
surface myFiveSurfaces[numSurfaces];float[5] values;
指定顯示大小的數組可以作爲函數的參數或者使返回值,也可以作爲結構體的成員.數組類型內建了一個length()函數,可以返回數組的長度。
lightPositions.length() //返回數組的大小 8
最後,你不能定義數組的數組。
修飾符
變量的聲明可以使用如下的修飾符。
修飾符 | 描述 |
const | 常量值必須在聲明是初始化。它是隻讀的不可修改的。 |
attribute | 表示只讀的頂點數據,只用在頂點着色器中。數據來自當前的頂點狀態或者頂點數組。它必須是全局範圍聲明的,不能再函數內部。一個attribute可以是浮點數類型的標量,向量,或者矩陣。不可以是數組或則結構體 |
uniform | 一致變量。在着色器執行期間一致變量的值是不變的。與const常量不同的是,這個值在編譯時期是未知的是由着色器外部初始化的。一致變量在頂點着色器和片段着色器之間是共享的。它也只能在全局範圍進行聲明。 |
varying | 頂點着色器的輸出。例如顏色或者紋理座標,(插值後的數據)作爲片段着色器的只讀輸入數據。必須是全局範圍聲明的全局變量。可以是浮點數類型的標量,向量,矩陣。不能是數組或者結構體。 |
centorid varying | 在沒有多重採樣的情況下,與varying是一樣的意思。在多重採樣時,centorid varying在光柵化的圖形內部進行求值而不是在片段中心的固定位置求值。 |
invariant | (不變量)用於表示頂點着色器的輸出和任何匹配片段着色器的輸入,在不同的着色器中計算產生的值必須是一致的。所有的數據流和控制流,寫入一個invariant變量的是一致的。編譯器爲了保證結果是完全一致的,需要放棄那些可能會導致不一致值的潛在的優化。除非必要,不要使用這個修飾符。在多通道渲染中避免z-fighting可能會使用到。 |
in | 用在函數的參數中,表示這個參數是輸入的,在函數中改變這個值,並不會影響對調用的函數產生副作用。(相當於C語言的傳值),這個是函數參數默認的修飾符 |
out | 用在函數的參數中,表示該參數是輸出參數,值是會改變的。 |
inout | 用在函數的參數,表示這個參數即是輸入參數也是輸出參數。 |
內置變量
內置變量可以與固定函數功能進行交互。在使用前不需要聲明。頂點着色器可用的內置變量如下表:
名稱 | 類型 | 描述 |
gl_Color | vec4 | 輸入屬性-表示頂點的主顏色 |
gl_SecondaryColor | vec4 | 輸入屬性-表示頂點的輔助顏色 |
gl_Normal | vec3 | 輸入屬性-表示頂點的法線值 |
gl_Vertex | vec4 | 輸入屬性-表示物體空間的頂點位置 |
gl_MultiTexCoordn | vec4 | 輸入屬性-表示頂點的第n個紋理的座標 |
gl_FogCoord | float | 輸入屬性-表示頂點的霧座標 |
gl_Position | vec4 | 輸出屬性-變換後的頂點的位置,用於後面的固定的裁剪等操作。所有的頂點着色器都必須寫這個值。 |
gl_ClipVertex | vec4 | 輸出座標,用於用戶裁剪平面的裁剪 |
gl_PointSize | float | 點的大小 |
gl_FrontColor | vec4 | 正面的主顏色的varying輸出 |
gl_BackColor | vec4 | 背面主顏色的varying輸出 |
gl_FrontSecondaryColor | vec4 | 正面的輔助顏色的varying輸出 |
gl_BackSecondaryColor | vec4 | 背面的輔助顏色的varying輸出 |
gl_TexCoord[] | vec4 | 紋理座標的數組varying輸出 |
gl_FogFragCoord | float | 霧座標的varying輸出 |
片段着色器的內置變量如下表:
名稱 | 類型 | 描述 |
gl_Color | vec4 | 包含主顏色的插值只讀輸入 |
gl_SecondaryColor | vec4 | 包含輔助顏色的插值只讀輸入 |
gl_TexCoord[] | vec4 | 包含紋理座標數組的插值只讀輸入 |
gl_FogFragCoord | float | 包含霧座標的插值只讀輸入 |
gl_FragCoord | vec4 | 只讀輸入,窗口的x,y,z和1/w |
gl_FrontFacing | bool | 只讀輸入,如果是窗口正面圖元的一部分,則這個值爲true |
gl_PointCoord | vec2 | 點精靈的二維空間座標範圍在(0.0, 0.0)到(1.0, 1.0)之間,僅用於點圖元和點精靈開啓的情況下。 |
gl_FragData[] | vec4 | 使用glDrawBuffers輸出的數據數組。不能與gl_FragColor結合使用。 |
gl_FragColor | vec4 | 輸出的顏色用於隨後的像素操作 |
gl_FragDepth | float | 輸出的深度用於隨後的像素操作,如果這個值沒有被寫,則使用固定功能管線的深度值代替 |
表達式
操作符
GLSL語言的操作符與C語言相似。如下表(操作符的優先級從高到低排列)
操作符 | 描述 |
() | 用於表達式組合,函數調用,構造 |
[] | 數組下標,向量或矩陣的選擇器 |
. | 結構體和向量的成員選擇 |
++ -- | 前綴或後綴的自增自減操作符 |
+ – ! | 一元操作符,表示正 負 邏輯非 |
* / | 乘 除操作符 |
+ - | 二元操作符 表示加 減操作 |
<> <= >= == != | 小於,大於,小於等於, 大於等於,等於,不等於 判斷符 |
&& || ^^ | 邏輯與 ,或, 異或 |
?: | 條件判斷符 |
= += –= *= /= | 賦值操作符 |
, | 表示序列 |
像 求地址的& 和 解引用的 * 操作符不再GLSL中出現,因爲GLSL不能直接操作地址。類型轉換操作也是不允許的。 位操作符(&,|,^,~, <<, >> ,&=, |=, ^=, <<=, >>=)是GLSL保留的操作符,將來可能會被使用。還有求模操作(%,%=)也是保留的。
數組訪問
數組的下標從0開始。合理的範圍是[0, size - 1]。跟C語言一樣。如果數組訪問越界了,那行爲是未定義的。如果着色器的編譯器在編譯時知道數組訪問越界了,就會提示編譯失敗。
vec4 myColor, ambient, diffuse[6], specular[6];
myColor = ambient + diffuse[4] + specular[4];
構造函數
構造函數可以用於初始化包含多個成員的變量,包括數組和結構體。構造函數也可以用在表達式中。調用方式如下:
vec3 myNormal = vec3(1.0, 1.0, 1.0);
greenTint = myColor + vec3(0.0, 1.0, 0.0);
ivec4 myColor = ivec4(255);
還可以使用混合標量和向量的方式來構造,只要你的元素足以填滿該向量。
vec4 color = vec4(1.0, vec2(0.0, 1.0), 1.0);
vec3 v = vec3(1.0, 10.0, 1.0);
vec3 v1 = vec3(v);
vec2 fv = vec2(5.0, 6.0);
float f = float(fv); //用x值2.5構造,y值被捨棄
對於矩陣,OpenGL中矩陣是列主順序的。如果只傳了一個值,則會構造成對角矩陣,其餘的元素爲0.
mat3 m3 = mat3(1.0);
構造出來的矩陣式:
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
mat2 matrix1 = mat2(1.0, 0.0, 0.0, 1.0);
mat2 matrix2 = mat2(vec2(1.0, 0.0), vec2(0.0, 1.0));
mat2 matrix3 = mat2(1.0);
mat2 matrix4 = mat2(mat4(2.0)); //會取 4x4矩陣左上角的2x2矩陣。
構造函數可以用於標量數據類型的轉換。GLSL不支持隱式或顯示的轉換,只能通過構造函數來轉。其中int轉爲float值是一樣的。float轉爲int則小數部分被丟棄。int或float轉爲bool,0和0.0轉爲false,其餘的值轉爲true. bool轉爲int或float,false值轉爲0和0.0,true轉爲1和1.0.
float f = 1.7;
int I = int(f); // I = 1
數組的初始化,可以在構造函數中傳入值來初始化數組中對應的每一個值。
ivec2 position[3] = ivec2[3]((0,0), (1,1), (2,2));
ivec2 pos2[3] = ivec2[]((3,3), (2,1), (3,1));
構造函數也可以對結構體進行初始化。其中順序和類型要一一對應。
struct surface { int index;
vec3 color; float rotate;
};
surface mySurface = surface(3, vec3(red, green, blue), 0.5);
成分選擇
向量中單獨的成分可以通過{x,y,z,w},{r,g,b,a}或者{s,t,p,q}的記法來表示。這些不同的記法用於頂點,顏色,紋理座標。在成分選擇中,你不可以混合使用這些記法。其中{s,t,p,q}中的p替換了紋理的r座標,因爲與顏色r重複了。下面是用法舉例:
vec3 myVec = {0.5, 0.35, 0.7};float r = myVec.r;float myYz = myVec.yz;float myQ = myVec.q;//出錯,數組越界訪問,q代表第四個元素float myRY = myVec.ry; //不合法,混合使用記法
較特殊的使用方式,你可以重複向量中的元素,或者顛倒其順序。如:
vec3 yxz = myVec.yxz; //調換順序vec4 mySSTT = myVec.sstt; //重複其中的值
在賦值是,也可以選擇你想要的順序,但是不能重複其中的成分。
vec4 myColor = {0.0, 1.0, 2.0, 1.0};
myColor.x = -1.0;
myColor.yz = vec2(3.0, 5.0);
myColor.wx = vec2(1.0, 3.0);
myColor.zz = vec2(2.0, 3.0); //不合法
我們也可以通過使用下標來訪問向量或矩陣中的元素。如果越界那行爲將是未定義的。
float myY = myVec[1];
在矩陣中,可以通過一維的下標來獲得該列的向量(OpenGL的矩陣是列主順序的)。二維的小標來獲得向量中的元素。
mat3 myMat = mat3(1.0);
vec3 myVec = myMat[0]; //獲得第一列向量 1.0, 0.0, 0.0float f = myMat[0][0]; // 第一列的第一個向量。
控制流
循環
與C和C++相似,GLSL語言也提供了for, while, do/while的循環方式。使用continue跳入下一次循環,break結束循環。
for (l = 0; l < numLights; l++)
{if (!lightExists[l])continue;
color += light[l];
}while (i < num)
{
sum += color[i];
i++;
}do{
color += light[lightNum];
lightNum--;
}while (lightNum > 0)
if/else
color = unlitColor;if (numLights > 0)
{
color = litColor;
}else{
color = unlitColor;
}
discard
片段着色器中有一種特殊的控制流成爲discard。使用discard會退出片段着色器,不執行後面的片段着色操作。片段也不會寫入幀緩衝區。
if (color.a < 0.9)
discard;
函數
在每個shader中必須有一個main函數。main函數中的void參數是可選的,但返回值是void時必須的。
void main(void)
{
...
}
GLSL中的函數,必須是在全局範圍定義和聲明的。不能在函數定義中聲明或定義函數。函數必須有返回類型,參數是可選的。參數的修飾符(in, out, inout, const等)是可選的。
//函數聲明bool isAnyNegative(const vec4 v);//函數調用void main(void)
{bool isNegative = isAnyNegative(gl_Color);
...
}//定義bool isAnyNegative(const vec4 v)
{if (v.x < 0.0 || v.y < 0.0 || v.z < 0.0 || v.w < 0.0)return true;elsereturn false;
}
結構體和數組也可以作爲函數的參數。如果是數組作爲函數的參數,則必須制定其大小。在調用傳參時,只傳數組名就可以了。
vec4 sumVectors(int sumSize, vec4 v[10]);void main()
{
vec4 myColors[10];
...
vec4 sumColor = sumVectors(5, myColors);
}
vec4 sumVectors(int sumSize, vec4 v[10])
{int i = 0;
vec4 sum = vec4(0.0);for(; i < sumSize; ++i)
{
sum += v[i];
}return sum;
}
GLSL的函數是支持重載的。函數可以同名但其參數類型或者參數個數不同即可。
float sum(float a, float b)
{return a + b;
}
vec3 sum(vec3 v1, vec3 v2)
{return v1 + v2;
}
GLSL中函數遞歸是不被允許的。其行爲是未定義的。
GLSL中提供了許多內建的函數,來方便我們的使用。可以在官方手冊中查找相關的函數http://www.opengl.org/sdk/docs/man/
GLSL指南 http://www.opengl.org/registry/doc/GLSLangSpec.Full.1.20.8.pdf
CG
(1)數學函數
函數 | 功能描述 |
---|---|
abs(x) | 返回輸入參數的絕對值 |
acos(x) | 反餘切函數,輸入參數範圍爲[-1,1], 返回[0,π]區間的角度值 |
all(x) | 如果輸入參數均不爲0,則返回ture; 否則返回flase。&&運算 |
any(x) | 輸入參數只要有其中一個不爲0,則返回true。 |
asin(x) | 反正弦函數,輸入參數取值區間爲,返回角度值範圍爲, |
atan(x) | 反正切函數,返回角度值範圍爲 |
atan2(y,x) | 計算y/x的反正切值。實際上和atan(x)函數功能完全一樣,至少輸入參數不同。atan(x) = atan2(x, float(1))。 |
ceil(x) | 對輸入參數向上取整。例如: ceil(float(1.3)) ,其返回值爲2.0 |
clamp(x,a,b) | 如果x值小於a,則返回a; 如果x值大於b,返回b; 否則,返回x。 |
cos(x) | 返回弧度x的餘弦值。返回值範圍爲 |
cosh(x) | 雙曲餘弦(hyperbolic cosine)函數,計算x的雙曲餘弦值。 |
cross(A,B) | 返回兩個三元向量的叉積(cross product)。注意,輸入參數必須是三元向量! |
degrees(x) | 輸入參數爲弧度值(radians),函數將其轉換爲角度值(degrees) |
determinant(m) | 計算矩陣的行列式因子。 |
dot(A,B) | 返回A和B的點積(dot product)。參數A和B可以是標量,也可以是向量(輸入參數方面,點積和叉積函數有很大不同)。 |
exp(x) | 計算的值,e=2.71828182845904523536 |
exp2(x) | 計算的值 |
floor(x) | 對輸入參數向下取整。例如floor(float(1.3))返回的值爲1.0;但是floor(float(-1.3))返回的值爲-2.0。該函數與ceil(x)函數相對應。 |
fmod(x,y) | 返回x/y的餘數。如果y爲0,結果不可預料。 |
frac(x) | 返回標量或矢量的小數 |
frexp(x, out i) | 將浮點數x分解爲尾數和指數,即, 返回m,並將指數存入i中;如果x爲0,則尾數和指數都返回0 |
isfinite(x) | 判斷標量或者向量中的每個數據是否是有限數,如果是返回true;否則返回false; |
isinf(x) | 判斷標量或者向量中的每個數據是否是無限,如果是返回true;否則返回false; |
isnan(x) | 判斷標量或者向量中的每個數據是否是非數據(not-a-number NaN),如果是返回true;否則返回false; |
ldexp(x, n) | 計算的值 |
lerp(a, b, f) | 計算或者的值。即在下限a和上限b之間進行插值,f表示權值。注意,如果a和b是向量,則權值f必須是標量或者等長的向量。 |
lit(NdotL, NdotH, m) | N表示法向量; L表示入射光向量; H表示半角向量; m表示高光係數。 函數計算環境光、散射光、鏡面光的貢獻,返回的4元向量。 X位表示環境光的貢獻,總是1.0; Y位代表散射光的貢獻,如果 ,則爲0;否則爲 Z位代表鏡面光的貢獻,如果 或者,則位0;否則爲; W位始終位1.0 |
log(x) | 計算的值,x必須大於0 |
log2(x) | 計算的值,x必須大於0 |
log10(x) | 計算的值,x必須大於0 |
max(a, b) | 比較兩個標量或等長向量元素,返回最大值。 |
min(a,b) | 比較兩個標量或等長向量元素,返回最小值。 |
modf(x, out ip) | 把x分解成整數和分數兩部分,每部分都和x有着相同的符號,整數部分被保存在ip中,分數部分由函數返回 |
mul(M, N) | 矩陣M和矩陣N的積,計算方法如下 |
mul(M, v) | 矩陣M和列向量v的積,公式如下 |
mul(v, M) | 行向量v和矩陣M的積,公式如下 |
noise(x) | 根據它的參數類型,這個函數可以是一元、二元或三元噪音函數。返回的值在0和1之間,並且通常與給定的輸入值一樣 |
pow(x, y) | |
radians(x) | 函數將角度值轉換爲弧度值 |
round(x) | 返回四捨五入值。 |
rsqrt(x) | x的平方根的倒數,x必須大於0 |
saturate(x) | 把x限制到[0,1]之間 |
sign(x) | 如果則返回1;否則返回0 |
sin(x) | 輸入參數爲弧度,計算正弦值,返回值範圍 爲[-1,1] |
sincos(float x, out s, out c) | 該函數是同時計算x的sin值和cos值,其中s=sin(x),c=cos(x)。該函數用於“同時需要計算sin值和cos值的情況”,比分別運算要快很多! |
sinh(x) | 計算x的雙曲正弦 |
smoothstep(min, max, x) | 值x位於min、max區間中。如果x=min,返回0;如果x=max,返回1;如果x在兩者之間,按照下列公式返回數據: |
step(a, x) | 如果,返回0;否則,返回1 |
sqrt(x) | 求x的平方根,,x必須大於0 |
tan(x) | 計算x正切值 |
tanh(x) | 計算x的雙曲線切線 |
transpose(M) | 矩陣M的轉置矩陣 如果M是一個AxB矩陣,M的轉置是一個BxA矩陣,它的第一列是M的第一行,第二列是M的第二行,第三列是M的第三行,等等 |
(2)幾何函數
函數 | 功能描述 |
---|---|
distance(pt1, pt2) | 兩點之間的歐幾里德距離(Euclidean distance) |
faceforward(N,I,Ng) | 如果,返回N;否則返回-N。 |
length(v) | 返回一個向量的模,即sqrt(dot(v,v)) |
normalize(v) | 返回v向量的單位向量 |
reflect(I, N) | 根據入射光纖方向I和表面法向量N計算反射向量,僅對三元向量有效 |
refract(I,N,eta) |
根據入射光線方向I,表面法向量N和折射相對係數eta,計算折射向量。如果對給定的eta,I和N之間的角度太大,返回(0,0,0)。 |
(3)紋理映射函數
函數 | 功能描述 |
---|---|
tex1D(sampler1D tex, float s) | 一維紋理查詢 |
tex1D(sampler1D tex, float s, float dsdx, float dsdy) | 使用導數值(derivatives)查詢一維紋理 |
Tex1D(sampler1D tex, float2 sz) | 一維紋理查詢,並進行深度值比較 |
Tex1D(sampler1D tex, float2 sz, float dsdx,float dsdy) | 使用導數值(derivatives)查詢一維紋理, 並進行深度值比較 |
Tex1Dproj(sampler1D tex, float2 sq) | 一維投影紋理查詢 |
Tex1Dproj(sampler1D tex, float3 szq) | 一維投影紋理查詢,並比較深度值 |
Tex2D(sampler2D tex, float2 s) | 二維紋理查詢 |
Tex2D(sampler2D tex, float2 s, float2 dsdx, float2 dsdy) | 使用導數值(derivatives)查詢二維紋理 |
Tex2D(sampler2D tex, float3 sz) | 二維紋理查詢,並進行深度值比較 |
Tex2D(sampler2D tex, float3 sz, float2 dsdx,float2 dsdy) | 使用導數值(derivatives)查詢二維紋理,並進行深度值比較 |
Tex2Dproj(sampler2D tex, float3 sq) | 二維投影紋理查詢 |
Tex2Dproj(sampler2D tex, float4 szq) | 二維投影紋理查詢,並進行深度值比較 |
texRECT(samplerRECT tex, float2 s) | 二維非投影矩形紋理查詢(OpenGL獨有) |
texRECT (samplerRECT tex, float3 sz, float2 dsdx,float2 dsdy) | 二維非投影使用導數的矩形紋理查詢(OpenGL獨有) |
texRECT (samplerRECT tex, float3 sz) | 二維非投影深度比較矩形紋理查詢(OpenGL獨有) |
texRECT (samplerRECT tex, float3 sz, float2 dsdx,float2 dsdy) | 二維非投影深度比較並使用導數的矩形紋理查詢(OpenGL獨有) |
texRECT proj(samplerRECT tex, float3 sq) | 二維投影矩形紋理查詢(OpenGL獨有) |
texRECT proj(samplerRECT tex, float3 szq) | 二維投影矩形紋理深度比較查詢(OpenGL獨有) |
Tex3D(sampler3D tex, float s) | 三維紋理查詢 |
Tex3D(sampler3D tex, float3 s, float3 dsdx, float3 dsdy) | 結合導數值(derivatives)查詢三維紋理 |
Tex3Dproj(sampler3D tex, float4 szq) | 查詢三維投影紋理,並進行深度值比較 |
texCUBE(samplerCUBE tex, float3 s) | 查詢立方體紋理 |
texCUBE (samplerCUBE tex, float3 s, float3 dsdx, float3 dsdy) | 結合導數值(derivatives)查詢立方體紋理 |
texCUBEproj (samplerCUBE tex, float4 sq) | 查詢投影立方體紋理 |
在這個表中,每個函數第二個參數的名字指明瞭在執行紋理查詢的時候,它的值是如果被使用的:
- s表示這是一個一元、二元或三元紋理座標。
- z表示這是一個用來進行陰影貼圖查找的深度比較值。
- q表示這是一個透視值,在進行紋理查找之前,它被用來除以紋理座標(s)。
當你使用的紋理函數允許你指定一個深度比較值的時候,與之相關聯的紋理單元必須被設置成深度比較紋理。否則,深度比較實際上不會被執行。
(4)偏導函數
函數 | 功能描述 |
---|---|
ddx(a) | 近似a關於屏幕空間x軸的偏導數 |
ddy(a) | 近似a關於屏幕空間y軸的偏導數 |
(5)調試函數
函數 | 功能描述 |
---|---|
void debug(float4 x) | 如果在編譯時設置了DEBUG,片段着 色程序中調用該函數可以將值x作爲COLOR語義的最終輸出;否則該函數什麼也不做。 |