Shader "zxwlx/BlinnPhong"
{
Properties
{
_Diffuse("Diffuse", Color) = (1,1,1,1)
_Specular("Specular", Color) = (1,1,1,1)
_Gloss("Gloss", Range(1.0, 256)) = 20
}
SubShader
{
Pass
{
Tags{ "LightingMode" = "ForwardBase" }
CGPROGRAM
#include "Lighting.cginc"
#pragma vertex vert
#pragma fragment frag
fixed4 _Diffuse;
fixed4 _Specular;
float _Gloss;
struct a2v
{
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct v2f
{
float4 pos : SV_POSITION;
float3 worldNormal : NORMAL;
float3 worldPos : TEXCOORD1;
};
v2f vert(a2v v)
{
v2f o;
o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
o.pos = UnityObjectToClipPos(v.vertex);
//法线转化到世界空间
o.worldNormal = normalize(mul(v.normal, (float3x3)unity_WorldToObject));
//顶点位置转化到世界空间
return o;
}
fixed4 frag(v2f i) : SV_Target
{
//环境光
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * _Diffuse;
//世界空间下光线方向
fixed3 worldLight = normalize(_WorldSpaceLightPos0.xyz);
//需要再次normalize
fixed3 worldNormal = normalize(i.worldNormal);
//计算Diffuse
fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal, worldLight));
//计算视线方向(相机位置-像素对应位置)
fixed3 viewDir = normalize(_WorldSpaceCameraPos.xyz - i.worldPos.xyz);
//计算半角向量(光线方向 + 视线方向,结果归一化)
fixed3 halfDir = normalize(worldLight + viewDir);
//计算Specular(Blinn-Phong计算的是)
fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(saturate(dot(halfDir, worldNormal)), _Gloss);
//结果为diffuse + ambient + specular
fixed3 color = diffuse + ambient + specular;
return fixed4(color, 1.0);
}
ENDCG
}
}
FallBack "Diffuse"
}
原理公式:
I(spcular) = I * k * pow(max(0,dot(N,H)), gloss)
,其中I为入射光颜色向量,k为镜面反射系数,gloss为光滑程度。