遮罩可以保护某些区域,使他们免于某些修改。例如:模型表面某些区域反光强烈一些,而某些区域弱一些,或者用于混合多张纹理
流程:通过采样得到这招纹理的纹理素值,然后使用其中某个(或某几个)通道的值来与某种表面属性进行相乘,这样,当该通道的值为0时,可以保护表面不受该属性的影响。总而言之,使用遮罩纹理可以让美术人员更加精准的控制模型表面的各种性质;
Shader "Custom/MaskTextureShader" {
Properties {
_Color ("Color", Color) = (1,1,1,1)
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_Glossiness ("Smoothness", Range(8,255)) = 20
_BumpMap("Normal Map",2D) = "white"{} //法线纹理
_BumpScale("Bump Scale",Float) = 1.0 //法线纹理控制系数
_SpecularMask("SpecularMask",2D) = "white"{} //高光反射遮罩纹理
_SpecularScale("Specular Scale",Float) = 1.0 //控制影响系数
_Specular("Specular",Color) = (1,1,1,1)
}
SubShader {
Pass{
Tags { "LightMode"="ForwardBase" }
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "lighting.cginc"
fixed4 _Color;
sampler2D _MainTex;
float4 _MainTex_ST; //我们为主纹理,法线纹理,遮罩纹理定义了他们共同使用的纹理属性变量
sampler2D _BumpMap;
float _BumpScale;
sampler2D _SpecularMask;
float _SpecularScale;
fixed4 _Specular;
float _Glossiness;
struct a2v {
float4 vertex:POSITION;
float3 normal:NORMAL;
float4 tangent:TANGENT;
float4 texcoord:TEXCOORD0;
};
struct v2f{
float4 pos:SV_POSITION;
float2 uv:TEXCOORD0;
float3 lightDir:TEXCOORD1;
float3 viewDir:TEXCOORD2;
};
v2f vert(a2v v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv.xy = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw; //对纹理的偏移缩放
TANGENT_SPACE_ROTATION;
o.lightDir = mul(rotation,ObjSpaceLightDir(v.vertex)).xyz;
o.viewDir = mul(rotation,ObjSpaceViewDir(v.vertex)).xyz;
return o;
}
fixed4 frag(v2f i):SV_Target{
fixed3 tangentLightDir = normalize(i.lightDir);
fixed3 tangentViewDir = normalize(i.viewDir);
fixed3 tangentNormal = UnpackNormal(tex2D(_BumpMap,i.uv));
tangentNormal.xy *= _BumpScale;
tangentNormal.z = sqrt(1.0 - saturate(dot(tangentNormal.xy,tangentNormal.xy)));
fixed3 albedo = tex2D(_MainTex,i.uv).rgb * _Color.rgb;
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;
fixed3 diffuse = _LightColor0.rgb * albedo * max(0,dot(tangentNormal,tangentViewDir));
fixed3 halfDir = normalize(tangentLightDir + tangentViewDir);
fixed specularMask = tex2D(_SpecularMask,i.uv).r * _SpecularScale;
fixed3 Specular = _LightColor0.rgb * _Specular.rgb * pow(max(0,dot(tangentNormal,halfDir)),_Glossiness) * specularMask;
return fixed4(ambient + diffuse + Specular,1);
}
ENDCG
}
}
FallBack "Diffuse"
}