《Unity着色器圣经》3.3.1 | Cg/HLSL变量与连接向量

目录索引

译文

继续回顾我们的 USB_simple_color 着色器,不难发现着色器中有一个 sampler2D 类型的变量和一个四维向量,用于定义 _ MainTex 纹理:

sampler2D _MainTex;
float4 _MainTex_ST;

这两个连接变量在 Cg 程序中被声明为“全局”变量,并与之前包含在着色器属性中的 _MainTex 属性引用相对应。

我们已经了解过,连接变量(connection variable)用于将属性的值与我们的程序变量或内部向量连接起来。就 _MainTex 而言,我们可以从 Unity 的材质检查器中指定一个纹理,并将其用作着色器中的纹理变量上。

为了更好地理解这一概念,现在让我们创建一个可以改变颜色的着色器。为了实现改变颜色的效果,我们需要在属性语义块中声明一个“颜色”类型,然后再在 CGPROGRAM 语义块中声明一个连接变量,这样就可以在二者之间形成连接。

Properties 
{ 
    // 首先声明属性 
    _Color ("Tint", Color) = (1, 1, 1 , 1) 
} 
    … 
    CGPROGRAM 
    … 
    // 然后声明连接变量或向量 
    sampler2D _MainTex; 
    float4 _Color; 
    … 
    ENDCG

一般来说,Cg 或 HLSL 中的全局变量在声明时会使用“uniform”关键词(例如:uniform float4 _Color),但 Unity 会忽略这一步,因为该声明包含在着色器中。


原文对照

Continuing with the USB_simple_color shader, notice that within our program there is a variable of sampler2D type and a vector of four dimensions for the definition of the _ MainTex texture.

sampler2D _MainTex;
float4 _MainTex_ST;

These connection variables have been declared “global” within the Cg program and correspond to a_MainTex property reference, previously included in the shader Properties.

The connection variables are used to connect the values or parameters of the properties with our program variables or internal vectors. In the case of _MainTex, we can assign a texture from the Unity Inspector and use it as a texture in the shader.

To understand this concept better, let’s assume that we want to create a shader that can change color. To do this, we would have to go to our properties, create a “Color” type and then generate a connection variable within the CGPROGRAM field, in this way we can generate a link between them.

Properties 
{ 
    // first we declare the property 
    _Color ("Tint", Color) = (1, 1, 1 , 1) 
} 
    … 
    CGPROGRAM 
    … 
    // then the connection variable or vector 
    sampler2D _MainTex; 
    float4 _Color; 
    … 
    ENDCG

Generally, the global variables in Cg or HLSL are declared with the word “uniform” (e.g. uniform float4 _Color) however Unity ignores this step since this declaration is included within the shader.

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容