Unity3D Shader教程一 HLSL基础

2019-07-25  本文已影响0人  UnityAsk

Unity Shaders是在名为“Shaderlab”的自定义环境中编写的。在shaderlab文件中,主要是通过HLSL来编写着色器的大部分逻辑。下面主要讲一下HLSL中常用的几种数据类型。HLSL中必须给变量指定具体的数据类型并且不能更改。可以查看官方文档:https//docs.unity3d.com/Manual/SLANNTypesAndPrecision.html

标量类型

最基础的类型是标量,它们只有一个数字值。HLSL中有多种类型的标量。选择较低的精度值可以提高着色器的性能,但现代显卡非常快,因此差异很小。

int integer = 3; //number without fractional component
fixed fixed_point = 0.5; //fixed point number between -2 and 2
half low_precision = 3.14; //low precision number
float high_precision = 14.321; //high precision number

向量类型

向量类型的元素为标量。通过矢量类型,我们可以表示具有多个值的颜色,位置和方向等内容。要在HLSL中声明它们,我们只需要在类型的末尾写下我们需要的维数,例如float2,int3,half4等类型。您可以通过xyz和w或者r g b a访问向量的元素。x y z表示矢量的尺寸,r g b a表示颜色的红色,绿色,蓝色和α通道。

fixed4 color = fixed4(1, 0.67, 0.73, 1);
float3 position = float3(1, 1, 0);
float2 textureCoordinates = float2(0.5, 0.5);

position.xy = position.yx; //switch the first two components of position vector

矩阵类型

矩阵可以理解为元素为矢量的矢量。它们通常用于对一个矢量进行旋转,移动和缩放操作,通过矢量与矩阵相乘。您可以通过在标量类型后面写[dimension 1] x [dimension 2]来声明矩阵类型,例如 float2x2。在3D图形中,通过3x3的矩阵来旋转和缩放一个矢量,用4x4的矩阵来移动它。

float4x4 transformMatrix3d; //a matrix that can scale rotate and translate a 3d vector
//a matrix that can scale and rotate a 2d vector, but not translate it
float2x2 rotationMatrix2d = {
    0, 1,
    -1, 0
};

//when doing matrix multiplication we have to use 4d vectors, 
//the 4th component is just used to make moving the vector via matrix multiplication possible
float4 position;

//we rotate, scale and translate a position my multiplying a vector with it 
//(the order of factors is important here)
position = transformMatrix3d * position;

采样

还有用于从贴图纹理中读取信息的sampler2d。贴图的坐标系是从[0,0]到[1,1],0,0对应贴图的左下角,1,1对应贴图的右上角。

sampler2d texture; //we will mostly use 2d textures, but it's possible to feed 3d samplers to a shader.

//we will mostly read from samplers via the tex2d function 
//which takes the position to sample from as a second argument.
float4 color = tex2D(texture, coordinates);

结构体

结构体可以包含上面提到的其他几种数据类型。我们可以用结构体表示灯光,输入数据或者其他复杂数据。要使用结构我们首先必须定义它,然后才可以在其他地方使用它。

//define the struct
struct InputData{
    float4 position;
    fixed4 color;
    half4 normal;
};

//create a instance and use the struct
InputData data;
data.position = float4(1, 0, 0, 1);

函数/方法

虽然我们可以在函数之外定义变量来为着色器提供信息,但我们只能在函数中运行逻辑运算。某些函数将自动被调用,并返回值,这些值将影响我们处理顶点或绘制颜色的方式。但我们也可以自己调用函数并使用它们返回的值。返回值类型写到函数名的前面,返回类型也可以是void,这意味着函数不返回值。在函数名后面的括号内填写参数,它们是函数接收的数据。在函数中,我们返回值,然后将该值赋给调用此函数的函数。

float add(float arg1, float arg2){
    float sum = arg1 + arg2;
    return sum;
}

float function(){
    return add(3.5, 0.7);
}

包含文件

您可以在一个文件中编写代码,然后在其他文件中引用它。相当于文件中的内容出现在引用命令所在的地方。被引用的文件,也可以引用别的文件。包含文件主要用作库或将比较长的着色器文件拆分为多个文件。

#include “IncludeFile.cginc”

void function(){
    functionDeclaredInIncludeFile(3, variableInIncludeFile);
}

from:https://www.ronja-tutorials.com/2018/03/21/simple-color.html
Unity技术交流 微信公众号 UnityAsk,QQ群:891920228

上一篇下一篇

猜你喜欢

热点阅读