一个完整的Shader文件由Properties,SubShader,FallBack组成,命名规则遵循驼峰结构,下面会一一介绍各个部分扮演的角色
1.1 Properties
属性,是shader文件里面的基本模块,用于定义一些基本操作元素,比如颜色,纹理等
见图1-1,我们可以看到一个简单的Properties属性
在这个Shader里面,我们定义了颜色_Color,采样纹理_MainTex,材质_Glossiness(镜面质感),_Mettallic(金属质感)。
我们可以去尝试去修改这个镜面质感
其中0的情况,0.5的情况和1的情况如图1-2所示
我们可以看到这个属性可以接收环境光,也就是天空盒,从漫反射到镜面反射的这种效果可以通过修改这个属性去实现。
接下来,我们需要去理解
1._Color ("Color", Color) = (1,1,1,1)
这种定义意味着什么
_Color:你定义的变量
2.Color:基本数据类型,就是给这个值赋值为Color类型
或许这个时候你会有些好奇,就是如果你有一点基础,你会知道它存在fixed4这种类似于c++里面的int基本类型的数据类型,那么Color也是类型,他们之间存在一种什么样的关系呢?
其实可以理解为,Color是一种对象,当我给这个_Colo变量定义为Color类型的时候,_Color将会拥有Color的特质,也就是颜色改变的特质。而这种特质将会在片元着色器或者顶点着色器中被赋予其功能。
当我们存在这个意识之后,我们通过图1-1可以总结到3个Shader的基本数据类型,见表1-1
1.2 SubShader
在这个模块中,定义你的显卡的工作,它,嗯用一句话来说,它就是一个状态机。一个流水线。
你可以去尝试影响流水线中的各种细微的工作从而去实现你想要的效果,这也是图形工程师的主要工作。
我们来看一下一个SubShader的基本模块,相关注释我会写在相应的位置
SubShader {
//描述的是渲染类型,不透明或者透明,
//为什么会有这种需求?大概是你在渲染不同材质的时候会有,比如你想要渲染一个石头,你不会希望它是透明的,但是如果你要渲染一块玻璃,没有透明的效果你其实干不了是吧?
Tags { "RenderType"="Opaque" }
LOD 200
//工作代码块CGPROGRAM -> ENDCG
CGPROGRAM
// Physically based Standard lighting model, and enable shadows on all light types
#pragma surface surf Standard fullforwardshadows
// Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0
//在这里引用你定义的变量,他们的类型都是CG变量类型
sampler2D _MainTex;
struct Input {
float2 uv_MainTex;
};
half _Glossiness;
half _Metallic;
fixed4 _Color;
// Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
// See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
// #pragma instancing_options assumeuniformscaling
UNITY_INSTANCING_BUFFER_START(Props)
// put more per-instance properties here
UNITY_INSTANCING_BUFFER_END(Props)
//这一块是另外一个重点,我们只需要基本了解它的相关模块即可
void surf (Input IN, inout SurfaceOutputStandard o) {
// Albedo comes from a texture tinted by color
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;
// Metallic and smoothness come from slider variables
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
}
ENDCG
1.3 FallBack
这个模块的工作在于,当你的Subshader不工作的时候,会回调这个函数,通常对于初学者来讲,我们不喜欢去了解非主线之外的东西,因为升级很慢!