认识Shader
Shade是什么?
Shader(着色器),本质上就是一小段程序片段。主要是告诉图形硬件如何输出图像。可编程图形管线的算法片段。
渲染管线:是芯片内部处理图形信号的相互独立的并行处理单元。
Shader有三种:
1、固定管线着色器(由于方法固定,操作有限所以已经被淘汰使用)
2、顶点+片段着色器(能够在底层实现一些复杂的效果)
3、表面着色器(高层封装使用,无法实现一些细节操作,底层的实现还是用顶点着色器)
Shader的基础语法结构:
Shader "Name"
{
Properties{}
SubShader{}
FallBack{}
}
其中Properties定义了一些属性,常见的包括
Unlit:不发光(纹理不受光照影响)
VertexLit:顶点光照
Diffuse:漫反射
Specular:高光增加了特殊的光照计算
Shininess:自调整
Emission:自发光
NormalMappedSpecular:高光法线贴图
Parallax Normal mapped:视差法线贴图
Properties语法:实际变量名称(“界面上显示的变量名称”,类型)
FallBack的参数用来表示如果SubShader不支持的话,会回退到哪一个Shader算法。默认是“Diffuse”因为DIffuse是所有显卡都具有的算法。
不同的Shader对应的SubShader中的函数也不同,下面一一介绍三种着色器
1、固定顶点着色器
pass
{
//Color[_Color]
//固定颜色
//Color[1,1,0,1]
material
{
diffuse[_Color]//漫反射光照
ambient[_Ambient]//环境光
specular[_Specular]//高光调整,必须开启高光调整才可以
shininess[_Shininess]
emission[_Emission]
}
lighting on
separatespecular on
settexture[MainTex]
{
combine texture *primary double
}
}
2、顶点着色器
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "qhy.cginc"
//顶点着色器的输出作为片段着色器的输入
float4 vert(in float2 objPos:POSITION,out float4 pos:POSITION,in float4 col:COLOR):COLOR
{
pos=float4(objPos,0,1);
if(pos.x<0 && pos.y>0)
{
col=float4(1,0,0,1);
}
else if(pos.x<0 && pos.y<0)
{
col=float4(0,1,0,1);
}
else if(pos.x>0&&pos.y>0)
{
col=float4(0,0,1,1);
}
else
{
col=float4(1,1,1,1);
}
return pos;
}
float4 frag(in float4 col:COLOR):COLOR
{
Function(col);
return col;
}
ENDCG
}
}
3、表面着色器
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 200
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
//与上面给出的便变量进行匹配,命名一样
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;
// fixed4 c =_Color;
o.Albedo = c.rgb;
// Metallic and smoothness come from slider variables
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
}
ENDCG
}