最近在看基础光照模型,比较感兴趣的是高光反射模型,有下列两种:

 

1.Phong模型

 

 

  

R = 2*N(dot(N, L)) - L

specular = lightColor * SpecularColor*(max(V· R, 0)) ^shininess;

 

2.Blinn-Phong模型

 引入了H,Blinn模型不仅在速度上更快,而且更符合实际。

H = normalize(L+V)

specular = lightColor * SpecularColor*(max(N· H, 0)) ^shininess;

 下面上Shader代码

 1 Shader "基础光照/BlinnPhongShader"
 2 {
 3     Properties
 4     {
 5         _MainTex ("Texture", 2D) = "white" {}
 6         _SpecularColor("SpecColor",Color) = (1,1,1,1)
 7         _DiffuseColor("DiffuseColor",Color) = (1,1,1,1)
 8         _Gloss("Gloss",Range(0,20)) = 1
 9     }
10     SubShader
11     {
12         Tags{"RenderType"="Opaque"}
13         //Cull Off ZWrite Off ZTest Always
14 
15         Pass
16         {
17             CGPROGRAM
18             #pragma vertex vert
19             #pragma fragment frag
20             #include "Lighting.cginc"
21             #include "UnityCG.cginc"
22 
23             struct appdata
24             {
25                 float4 pos : POSITION;
26                 float3 normal : NORMAL;
27                 float2 uv: TEXCOORD0;
28                 
29             };
30 
31             struct v2f
32             {
33 
34 
35                 float4 pos: SV_POSITION;
36 
37                 float2 uv :TEXCOORD0;
38 
39                 float3 normal : TEXCOORD1;
40 
41 
42                 float4 worldPos : TEXCOORD2;
43             };
44 
45             v2f vert (appdata v)
46             {
47                 v2f o;
48                 o.pos = mul(UNITY_MATRIX_MVP,v.pos);
49                 o.worldPos= mul(_Object2World,v.pos);
50                 o.normal = normalize( mul(v.normal,(float3x3)_World2Object));
51                 o.uv = v.uv;
52                 return o;
53             }
54             
55             sampler2D _MainTex;
56             fixed4 _DiffuseColor;
57             fixed4 _SpecularColor;
58             float _Gloss;
59 
60             fixed4 frag(v2f i): SV_Target
61             {
62                 //计算环境光
63                 fixed3 ambient  = UNITY_LIGHTMODEL_AMBIENT.xyz;
64 
65                 float3 worldNormal = i.normal;
66 
67                 float3 worldLightDir = -normalize(_WorldSpaceLightPos0.xyz);
68 
69 
70                 //计算漫反射 
71                 fixed3 diffuse = _LightColor0.rgb*_DiffuseColor*saturate(dot(worldNormal,worldLightDir));
72 
73 
74                 //计算高光反射
75 
76 
77                 float3 viewDir = normalize(_WorldSpaceCameraPos.xyz - i.worldPos.xyz);
78 
79                 fixed3 h = normalize(worldLightDir+viewDir);
80 
81                 fixed3 specular = _LightColor0.rgb*_SpecularColor*(pow(saturate(dot(h,worldNormal)),_Gloss));
82                 fixed4 col = tex2D(_MainTex,i.uv);
83                 return col*fixed4(ambient+diffuse+specular,1.0);
84             }
85 
86             ENDCG
87         }
88     }
89     FallBack "Specular"
90 }

效果展示