核心
效果圖
遮罩紋理
Shader "Unlit/015"
{
Properties
{
_MainTex ("MainTex", 2D )= "white" {}
_BumpMap ("normal Map", 2D) = "bump"{}
_BumpScale("Bump Scale",float) = 1
_SpecularMask("Specular Mask", 2D) = "white" {}
_SpecularScale("Specular Scale", float) = 1
_Diffuse("Diffuse",Color) = (1,1,1,1)
_Specular("Specular",Color) = (1,1,1,1)
_Gloss("Gloss",Range(1,256)) = 5
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "Lighting.cginc"
sampler2D _MainTex;
float4 _MainTex_ST;
sampler2D _BumpMap;
float4 _BumpMap_ST;
sampler2D _SpecularMask;
float4 _SpecularMask_ST;
float _SpecularScale;
float _BumpScale;
fixed4 _Diffuse;
fixed4 _Specular;
float _Gloss;
struct v2f
{
float4 vertex :SV_POSITION;
fixed3 lightDir: TEXCOORD0;
float3 viewDir: TEXCOORD1;
float4 uv : TEXCOORD2;
float2 maskUv: TEXCOORD3;
};
v2f vert (appdata_tan v)
{
v2f o;
//頂點位置
o.vertex = UnityObjectToClipPos(v.vertex);
//UV =頂點紋理坐標進行縮放+偏移
o.uv.xy =TRANSFORM_TEX(v.texcoord, _MainTex);
o.uv.zw =TRANSFORM_TEX(v.texcoord, _BumpMap);
//法線貼圖UV =頂點紋理坐標進行縮放+偏移
o.maskUv =TRANSFORM_TEX(v.texcoord, _SpecularMask);
//內(nèi)置宏畸陡,用于得到模型空間到切線空間的變換矩陣rotation
TANGENT_SPACE_ROTATION;
//求切線空間光源方向=矩陣乘積(變換矩陣,模型空間下光照方向).xyz西潘;
o.lightDir = mul(rotation,ObjSpaceLightDir (v.vertex)).xyz;
//求切線空間視角方向=矩陣乘積(變換矩陣,模型空間下視角方向).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);
//采樣
fixed4 packedNormal = tex2D(_BumpMap,i.uv.zw);
//切線中法線方向爽雄,設置成normalMap的
fixed3 tangentNormal = UnpackNormal(packedNormal);
tangentNormal.xy *= _BumpScale;
//紋素值=對紋理進行采樣(采樣紋理,float2紋理坐標)
fixed3 albedo = tex2D(_MainTex,i.uv).rgb;
//漫反射光=入射光線強度*紋素值*材質(zhì)的漫反射系數(shù)*取值為正數(shù)(切線光源方向 · 切線法線方向)
fixed3 diffuse = _LightColor0.rgb * albedo * _Diffuse.rgb * (dot(tangentLightDir,tangentNormal)*0.5+0.5);
//環(huán)境光
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
//高光遮罩
fixed specularMask = tex2D(_SpecularMask, i.maskUv).r * _SpecularScale;
//半角方向
fixed3 halfDir =normalize(tangentLightDir + tangentViewDir);
//BlinnPhong高光反射=入射光線顏色強度*材質(zhì)的高光反射系數(shù)*n次平方(取值為正數(shù)(切線法線方向 · 半角方向)怖亭,n)* 高光遮罩涎显;
fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(saturate(dot(tangentNormal,halfDir)),_Gloss) * specularMask;
fixed3 color = ambient + diffuse + specular;
return fixed4(color,1);
}
ENDCG
}
}
}