一、内置包含文件

  Unity中有类似于C++的包含文件.cginc,在编写Shader时我们可以使用#include指令把这些文件包含进来
这样我们就可以使用Unity为我们提供的一些非常好用的函数、宏和变量。

例如:#include"UnityCG.cginc"

包含文件的位置:根目录\Editor\Data\CGIncludes

知识点1:以下是Unity中常用包含文件:
  文件名 描述
  1、UnityCG.cginc 包含最常用的帮助函数、宏和结构体
  2、UnityShaderVariables.cginc 在编译Shader时,会被自动包含进来,包含了许多内置的全局变量,如UNITY_MATRIX_MVP
  3、Ligghting.cginc 包含了各种内置光照模型,如果编写SurfaceShader的话,会被自动包含进来
  4、HLSLSurport.cginc 在编译Shader时,会被自动包含进来,声明了很多跨平台编译的宏和定义

  Unity5.2引入了许多新的重要的包含文件,如UnityStandardBRDF.cginc等。这些文件用于实现基于物理的渲染

知识点2:UnityShader中常用的结构体

    名称          描述              包含的变量
  appdata_base     用于顶点着色器输入      顶点位置、顶点法线、第一组纹理坐标
  appdata_tan      用于顶点着色器输入      顶点位置、顶点切线、顶点法线、第一组纹理坐标
  appdata_full     用于顶点着色器输入      顶点位置、顶点切线、顶点法线、四组(或更多)纹理坐标
  appdata_img      用于顶点着色器输入      顶点位置、第一组纹理坐标
  v2f_img        用于顶点着色器输出      裁剪空间中的位置、纹理坐标

struct appdata_img
{
  float4 vertex : POSITION;
  half2 texcoord : TEXCOORD0;
};
struct appdata_base 
{
  float4 vertex : POSITION;
  float3 normal : NORMAL;
  float4 texcoord : TEXCOORD0;
};
struct appdata_tan 
{
  float4 vertex : POSITION;
  float4 tangent : TANGENT;
  float3 normal : NORMAL;
  float4 texcoord : TEXCOORD0;
};
struct appdata_full 
{
  float4 vertex : POSITION;
  float4 tangent : TANGENT;
  float3 normal : NORMAL;
  float4 texcoord : TEXCOORD0;
  float4 texcoord1 : TEXCOORD1;
  float4 texcoord2 : TEXCOORD2;
  float4 texcoord3 : TEXCOORD3;
#if defined(SHADER_API_XBOX360)
  half4 texcoord4 : TEXCOORD4;
  half4 texcoord5 : TEXCOORD5;
#endif
  fixed4 color : COLOR;
};
struct v2f_img
{
  float4 pos : SV_POSITION;
  half2 uv : TEXCOORD0;
};

知识点3:UnityShader中常用的帮助函数

      函数名                      描    述
float3 WorldSpaceViewDir(float4 v)          输入一个模型顶点坐标,得到世界空间中从该点到摄像机的观察方向
float3 ObjSpaceViewDir(float4 v)           输入一个模型顶点坐标,得到模型空间中从该点到摄像机的观察方向
float3 WorldSpaceLightDir(float4 v)          输入一个模型顶点坐标,得到世界空间中从该点到光源的光照方向(方向没有归一化,且只可用于前向渲染)
float3 ObjSpaceLightDir(float4 v)           输入一个模型顶点坐标,得到模型空间中从该点到光源的光照方向(方向没有归一化,且只可用于前向渲染)
float3 UnityObjectToWorldNormal(float3 norm)  将法线从模型空间转换到世界空间
float3 UnityObjectToWorldDir(in float3 dir)       把方向矢量从模型空间转换到世界空间
float3 UnityWorldToObjectDir(float3 dir)        把方向矢量从世界空间转换到模型空间

知识点4:UnityShader中内置变量
                                                                     Unity内置变换矩阵
           变量名                                                                             描         述
UNITY_MATRIX_MVP          当前模型*观察*投影矩阵,用于将模型顶点/方向矢量从模型空间转换到裁剪空间
UNITY_MATRIX_MV         当前模型*观察矩阵,用于将模型顶点/方向矢量从模型空间转换到观察空间
UNITY_MATRIX_V         当前观察矩阵,用于将顶点/方向矢量从世界空间变换到观察空间
UNITY_MATRIX_P         当前投影矩阵,用于将顶点/方向矢量从观察空间变换到裁剪空间
UNITY_MATRIX_VP       当前观察*投影矩阵,用于将顶点/方向矢量从世界空间变换到裁剪空间
UNITY_MATRIX_T_MV       UNITY_MATRIX_MV转置矩阵
UNITY_MATRIX_IT_MV      UNITY_MATRIX_MV逆转置矩阵,可将法线矢量从模型空间转换到观察空间
_Object2World          当前模型的矩阵,用于将模型顶点/方向矢量从模型空间转换到世界空间
_World2Object                _Object2World逆矩阵,用于将模型顶点/方向矢量从世界空间转换到模型空间

另外:Unity还提供了能够访问时间、光照、雾效和环境光等目的的变量。这些内置变量大多UnityShaderVariables.cginc中,
跟光照有关的还定义在Lighting.cginc 和AutoLight.cginc中。

知识点5:

1、uint CreateShader(enum type) : 创建空的shader object; 
  type: VERTEX_SHADER, 
2、void ShaderSource(uint shader, sizeicount, const **string, const int *length):加载shader源码进shader object;可能多个字符串 
3、void CompileShader(uint shader):编译shader object; 
  shader object有状态 表示编译结果 
4、void DeleteShader( uint shader ):删除 shader object; 
5、void ShaderBinary( sizei count, const uint *shaders, 
enum binaryformat, const void *binary, sizei length ): 加载预编译过的shader 二进制串; 
6、uint CreateProgram( void ):创建空的program object, programe object组织多个shader object,成为executable; 
7、void AttachShader( uint program, uint shader ):关联shader object和program object; 
8、void DetachShader( uint program, uint shader ):解除关联; 
9、void LinkProgram( uint program ):program object准备执行,其关联的shader object必须编译正确且符合限制条件; 
10、void UseProgram( uint program ):执行program object; 
11、void ProgramParameteri( uint program, enum pname, 
int value ): 设置program object的参数; 
12、void DeleteProgram( uint program ):删除program object; 
13、shader 变量的qualifier: 
   默认:无修饰符,普通变量读写, 与外界无连接; 
   const:常量 const vec3 zAxis = vec3(0.0, 0.0, 1.0); 
   attribute: 申明传给vertex shader的变量;只读;不能为array或struct;attribute vec4 position; 
   uniform: 表明整个图元处理中值相同;只读; uniform vec4 lightPos; 
   varying: 被差值;读写; varying vec3 normal; 
   in, out, inout; 

shader变量的精度: 
   highp, mediump, lowp 

shader内置变量: 
   gl_Position: 用于vertex shader, 写顶点位置;被图元收集、裁剪等固定操作功能所使用; 
                其内部声明是:highp vec4 gl_Position; 
   gl_PointSize: 用于vertex shader, 写光栅化后的点大小,像素个数; 
                其内部声明是:mediump float gl_Position; 
   gl_FragColor: 用于Fragment shader,写fragment color;被后续的固定管线使用; 
                 mediump vec4 gl_FragColor; 
   gl_FragData: 用于Fragment shader,是个数组,写gl_FragData[n] 为data n;被后续的固定管线使用; 
                 mediump vec4 gl_FragData[gl_MaxDrawBuffers]; 
   gl_FragColor和gl_FragData是互斥的,不会同时写入; 
   gl_FragCoord: 用于Fragment shader,只读, Fragment相对于窗口的坐标位置 x,y,z,1/w; 这个是固定管线图元差值后产生的;z 是深度值; mediump vec4 gl_FragCoord; 
   gl_FrontFacing: 用于判断 fragment是否属于 front-facing primitive;只读; 
                   bool gl_FrontFacing;   
   gl_PointCoord: 仅用于 point primitive; mediump vec2 gl_PointCoord; 

shader内置常量: 
   const mediump int gl_MaxVertexAttribs = 8; 
   const mediump int gl_MaxVertexUniformVectors = 128; 
   const mediump int gl_MaxVaryingVectors = 8; 
   const mediump int gl_MaxVertexTextureImageUnits = 0; 
   const mediump int gl_MaxCombinedTextureImageUnits = 8; 
   const mediump int gl_MaxTextureImageUnits = 8; 
   const mediump int gl_MaxFragmentUnitformVectors = 16; 
   const mediump int gl_MaxDrawBuffers = 1; 

shader内置数学函数: 
   一般默认都用弧度; 
   radians(degree) : 角度变弧度; 
   degrees(radian) : 弧度变角度; 
   sin(angle), cos(angle), tan(angle) 
   asin(x): arc sine, 返回弧度 [-PI/2, PI/2]; 
   acos(x): arc cosine,返回弧度 [0, PI]; 
   atan(y, x): arc tangent, 返回弧度 [-PI, PI]; 
   atan(y/x): arc tangent, 返回弧度 [-PI/2, PI/2]; 
  
   pow(x, y): x的y次方; 
   exp(x): 指数, log(x): 
   exp2(x): 2的x次方, log2(x): 
   sqrt(x): x的根号; inversesqrt(x): x根号的倒数 
  
   abs(x): 绝对值 
   sign(x): 符号, 1, 0 或 -1 

    {sign(x)或者Sign(x)叫做符号函数,在数学和计算机运算中,其功能是取某个数的符号(正或负): 
    当x>0,sign(x)=1; 
    当x=0,sign(x)=0; 
    当x<0, sign(x)=-1;}    floor(x): 底部取整 
   ceil(x): 顶部取整 
   fract(x): 取小数部分 
   mod(x, y): 取模, x - y*floor(x/y) 
   min(x, y): 取最小值 
   max(x, y): 取最大值 
   clamp(x, min, max):  min(max(x, min), max); 
   mix(x, y, a): x, y的线性混叠, x(1-a) + y*a; 
   step(edge, x): 如 x 
   smoothstep(edge0, edge1, x): threshod  smooth transition时使用。 edge0<=edge0时为0.0, x>=edge1时为1.0 
  
   length(x): 向量长度 
   distance(p0, p1): 两点距离, length(p0-p1); 
   dot(x, y): 点积,各分量分别相乘 后 相加 
   cross(x, y): 差积,x[1]*y[2]-y[1]*x[2], x[2]*y[0] - y[2]*x[0], x[0]*y[1] - y[0]*x[1] 
   normalize(x): 归一化, length(x)=1; 
   faceforward(N, I, Nref): 如 dot(Nref, I)< 0则N, 否则 -N 
   reflect(I, N): I的反射方向, I -2*dot(N, I)*N, N必须先归一化 
   refract(I, N, eta): 折射,k=1.0-eta*eta*(1.0 - dot(N, I) * dot(N, I)); 如k<0.0 则0.0,否则 eta*I - (eta*dot(N, I)+sqrt(k))*N 
  
   matrixCompMult(matX, matY): 矩阵相乘, 每个分量 自行相乘, 即 r[j] = x[j]*y[j]; 
                              矩阵线性相乘,直接用 * 
    
   lessThan(vecX, vecY): 向量 每个分量比较 x < y 
   lessThanEqual(vecX, vecY): 向量 每个分量比较 x<=y 
   greaterThan(vecX, vecY): 向量 每个分量比较 x>y 
   greaterThanEqual(vecX, vecY): 向量 每个分量比较 x>=y 
   equal(vecX, vecY): 向量 每个分量比较 x==y 
   notEqual(vecX, vexY): 向量 每个分量比较 x!=y 
   any(bvecX): 只要有一个分量是true, 则true 
   all(bvecX): 所有分量是true, 则true 
   not(bvecX): 所有分量取反 
  
   texture2D(sampler2D, coord): texture lookup 
   texture2D(sampler2D, coord, bias): LOD bias, mip-mapped texture 
   texture2DProj(sampler2D, coord): 
   texture2DProj(sampler2D, coord, bias): 
   texture2DLod(sampler2D, coord, lod): 
   texture2DProjLod(sampler2D, coord, lod): 
   textureCube(samplerCube, coord): 
   textureCube(samplerCube, coord, bias): 
   textureCubeLod(samplerCube, coord, lod):

Intrinsic Functions (DirectX HLSL)

The following table lists the intrinsic functions available in HLSL. Each function has a brief description, and a link to a reference page that has more detail about the input argument and return type.

Name

Syntax

Description

abs

abs(x)

Absolute value (per component).

acos

acos(x)

Returns the arccosine of each component of x.

all

all(x)

Test if all components of x are nonzero.

any

any(x)

Test if any component of x is nonzero.

asfloat

asfloat(x)

Convert the input type to a float.

asin

asin(x)

Returns the arcsine of each component of x.

asint

asint(x)

Convert the input type to an integer.

asuint

asuint(x)

Convert the input type to an unsigned integer.

atan

atan(x)

Returns the arctangent of x.

atan2

atan2(y, x)

Returns the arctangent of of two values (x,y).

ceil

ceil(x)

Returns the smallest integer which is greater than or equal to x.

clamp

clamp(x, min, max)

Clamps x to the range [min, max].

clip

clip(x)

Discards the current pixel, if any component of x is less than zero.

cos

cos(x)

Returns the cosine of x.

cosh

cosh(x)

Returns the hyperbolic cosine of x.

cross

cross(x, y)

Returns the cross product of two 3D vectors.

D3DCOLORtoUBYTE4

D3DCOLORtoUBYTE4(x)

Swizzles and scales components of the 4D vector x to compensate for the lack of UBYTE4 support in some hardware.

ddx

ddx(x)

Returns the partial derivative of x with respect to the screen-space x-coordinate.

ddy

ddy(x)

Returns the partial derivative of x with respect to the screen-space y-coordinate.

degrees

degrees(x)

Converts x from radians to degrees.

determinant

determinant(m)

Returns the determinant of the square matrix m.

distance

distance(x, y)

Returns the distance between two points.

dot

dot(x, y)

Returns the dot product of two vectors.

exp

exp(x)

Returns the base-e exponent.

exp2

exp2(x)

Base 2 exponent (per component).

faceforward

faceforward(n, i, ng)

Returns -n * sign(•(i, ng)).

floor

floor(x)

Returns the greatest integer which is less than or equal to x.

fmod

fmod(x, y)

Returns the floating point remainder of x/y.

frac

frac(x)

Returns the fractional part of x.

frexp

frexp(x, exp)

Returns the mantissa and exponent of x.

fwidth

fwidth(x)

Returns abs(ddx(x)) + abs(ddy(x))

GetRenderTargetSampleCount

GetRenderTargetSampleCount()

Returns the number of render-target samples.

GetRenderTargetSamplePosition

GetRenderTargetSamplePosition(x)

Returns a sample position (x,y) for a given sample index.

isfinite

isfinite(x)

Returns true if x is finite, false otherwise.

isinf

isinf(x)

Returns true if x is +INF or -INF, false otherwise.

isnan

isnan(x)

Returns true if x is NAN or QNAN, false otherwise.

ldexp

ldexp(x, exp)

Returns x * 2exp

length

length(v)

Returns the length of the vector v.

lerp

lerp(x, y, s)

Returns x + s(y - x).

lit

lit(n • l, n • h, m)

Returns a lighting vector (ambient, diffuse, specular, 1)

log

log(x)

Returns the base-e logarithm of x.

log10

log10(x)

Returns the base-10 logarithm of x.

log2

log2(x)

Returns the base-2 logarithm of x.

max

max(x, y)

Selects the greater of x and y.

min

min(x, y)

Selects the lesser of x and y.

modf

modf(x, out ip)

Splits the value x into fractional and integer parts.

mul

mul(x, y)

Performs matrix multiplication using x and y.

noise

noise(x)

Generates a random value using the Perlin-noise algorithm.

normalize

normalize(x)

Returns a normalized vector.

pow

pow(x, y)

Returns xy.

radians

radians(x)

Converts x from degrees to radians.

reflect

reflect(i, n)

Returns a reflection vector.

refract

refract(i, n, R)

Returns the refraction vector.

round

round(x)

Rounds x to the nearest integer

rsqrt

rsqrt(x)

Returns 1 / sqrt(x)

saturate

saturate(x)

Clamps x to the range [0, 1]

sign

sign(x)

Computes the sign of x.

sin

sin(x)

Returns the sine of x

sincos

sincos(x, out s, out c)

Returns the sine and cosine of x.

sinh

sinh(x)

Returns the hyperbolic sine of x

smoothstep

smoothstep(min, max, x)

Returns a smooth Hermite interpolation between 0 and 1.

sqrt

sqrt(x)

Square root (per component)

step

step(a, x)

Returns (x >= a) ? 1 : 0

tan

tan(x)

Returns the tangent of x

tanh

tanh(x)

Returns the hyperbolic tangent of x

tex1D

tex1D(s, t)

1D texture lookup.

tex1Dbias

tex1Dbias(s, t)

1D texture lookup with bias.

tex1Dgrad

tex1Dgrad(s, t, ddx, ddy)

1D texture lookup with a gradient.

tex1Dlod

tex1Dlod(s, t)

1D texture lookup with LOD.

tex1Dproj

tex1Dproj(s, t)

1D texture lookup with projective divide.

tex2D

tex2D(s, t)

2D texture lookup.

tex2Dbias

tex2Dbias(s, t)

2D texture lookup with bias.

tex2Dgrad

tex2Dgrad(s, t, ddx, ddy)

2D texture lookup with a gradient.

tex2Dlod

tex2Dlod(s, t)

2D texture lookup with LOD.

tex2Dproj

tex2Dproj(s, t)

2D texture lookup with projective divide.

tex3D

tex3D(s, t)

3D texture lookup.

tex3Dbias

tex3Dbias(s, t)

3D texture lookup with bias.

tex3Dgrad

tex3Dgrad(s, t, ddx, ddy)

3D texture lookup with a gradient.

tex3Dlod

tex3Dlod(s, t)

3D texture lookup with LOD.

tex3Dproj

tex3Dproj(s, t)

3D texture lookup with projective divide.

texCUBE

texCUBE(s, t)

Cube texture lookup.

texCUBEbias

texCUBEbias(s, t)

Cube texture lookup with bias.

texCUBEgrad

texCUBEgrad(s, t, ddx, ddy)

Cube texture lookup with a gradient.

texCUBElod

tex3Dlod(s, t)

Cube texture lookup with LOD.

texCUBEproj

texCUBEproj(s, t)

Cube texture lookup with projective divide.

transpose

transpose(m)

Returns the transpose of the matrix m.

trunc

trunc(x)

Truncates floating-point value(s) to integer value(s)

 

表 3-1 HLSL内置函数

函数名            用法

abs                         计算输入值的绝对值。

acos                        返回输入值反余弦值。

all                           测试非0值。

any                         测试输入值中的任何非零值。

asin                         返回输入值的反正弦值。

atan                        返回输入值的反正切值。

atan2                       返回y/x的反正切值。

ceil                         返回大于或等于输入值的最小整数。

clamp                      把输入值限制在[min, max]范围内。

clip                         如果输入向量中的任何元素小于0,则丢弃当前像素。

cos                         返回输入值的余弦。

cosh                       返回输入值的双曲余弦。

cross                      返回两个3D向量的叉积。

ddx                         返回关于屏幕坐标x轴的偏导数。

ddy                         返回关于屏幕坐标y轴的偏导数。

degrees                   弧度到角度的转换

determinant              返回输入矩阵的值。

distance                   返回两个输入点间的距离。

dot                          返回两个向量的点积。

exp                         返回以e为底数,输入值为指数的指数函数值。

exp2                       返回以2为底数,输入值为指数的指数函数值。

faceforward             检测多边形是否位于正面。

floor                       返回小于等于x的最大整数。

fmod                       返回a / b的浮点余数。

frac                        返回输入值的小数部分。

frexp                       返回输入值的尾数和指数

fwidth                     返回 abs ( ddx (x) + abs ( ddy(x))。

isfinite                     如果输入值为有限值则返回true,否则返回false。

isinf                        如何输入值为无限的则返回true。

isnan                       如果输入值为NAN或QNAN则返回true。

ldexp                       frexp的逆运算,返回 x * 2 ^ exp。

len / lenth                返回输入向量的长度。

lerp                         对输入值进行插值计算。

lit                            返回光照向量(环境光,漫反射光,镜面高光,1)。

log                          返回以e为底的对数。

log10                      返回以10为底的对数。

log2                        返回以2为底的对数。

max                        返回两个输入值中较大的一个。

min                         返回两个输入值中较小的一个。

modf                       把输入值分解为整数和小数部分。

mul                         返回输入矩阵相乘的积。

normalize                 返回规范化的向量,定义为 x / length(x)。

pow                        返回输入值的指定次幂。

radians                    角度到弧度的转换。

reflect                     返回入射光线i对表面法线n的反射光线。

refract                     返回在入射光线i,表面法线n,折射率为eta下的折射光线v。

round                      返回最接近于输入值的整数。

rsqrt                       返回输入值平方根的倒数。

saturate                   把输入值限制到[0, 1]之间。

sign                        计算输入值的符号。

sin                          计算输入值的正弦值。

sincos                     返回输入值的正弦和余弦值。

sinh                        返回x的双曲正弦。

smoothstep              返回一个在输入值之间平稳变化的插值。

sqrt                         返回输入值的平方根。

step                        返回(x >= a)? 1 : 0。

tan                          返回输入值的正切值。

fanh                        返回输入值的双曲线切线。

transpose                 返回输入矩阵的转置。

tex1D*                    1D纹理查询。

tex2D*                    2D纹理查询。

tex3D*                    3D纹理查询。

texCUBE*                立方纹理查询。