【风宇冲】Unity3D教程宝典之Shader篇:第十六讲自定义光照模型

原创文章如需转载请注明:转载自风宇冲Unity3D教程学院


                              Shader第十六讲  自定义光照模型

十四讲我们实现了基本的Surface Shader,十五讲讲了光照模型的基础知识。这一讲说的是如何写光照模型。
自定义光照模型主要分为4步:
(0)架设框架,填写需要的参数
(1)计算 漫反射强度
(2)计算镜面反射 强度
(3)结合漫反射光与镜面反射光

代码配有中文注释,配合上上讲的光照公式,一步一步实现即可。

  1. //  Author: 风宇冲
  2. Shader "Custom/T_customLightModel" {
  3.   Properties
  4.   {
  5.     _MainTex ("Texture", 2D) = "white" {}
  6.   }
  7.  
  8.   Subshader
  9.   {
  10.      //alpha测试,配合surf中的o.Alpha = c.a;
  11.   AlphaTest Greater 0.4
  12.   CGPROGRAM
  13.   #pragma surface surf lsyLightModel 
  14.  
  15.   //命名规则:Lighting接#pragma suface之后起的名字
  16.   //lightDir :点到光源的单位向量   viewDir:点到摄像机的单位向量   atten:衰减系数
  17.   float4 LightinglsyLightModel(SurfaceOutput s, float3 lightDir,half3 viewDir, half atten)
  18.   {
  19.   float4 c;
  20.  
  21.   //(1)漫反射强度
  22.   float diffuseF = max(0,dot(s.Normal,lightDir));
  23.  
  24.   //(2)镜面反射强度
  25.   float specF;
  26.   float3 H = normalize(lightDir+viewDir);
  27.   float specBase = max(0,dot(s.Normal,H));
  28.   // shininess 镜面强度系数,这里设置为8
  29.   specF = pow(specBase,8);
  30.  
  31.   //(3)结合漫反射光与镜面反射光
  32.   c.rgb = s.Albedo * _LightColor0 * diffuseF *atten + _LightColor0*specF; 
  33.   c.a = s.Alpha;
  34.   return c;
  35.   }
  36.  
  37.   struct Input
  38.   {
  39.   float2 uv_MainTex;
  40.   };
  41.  
  42.   void vert(inout appdata_full v)
  43.   {
  44. //这里可以做特殊位置上的处理
  45.   }
  46.   sampler2D _MainTex;
  47.  
  48.   void surf(Input IN,inout SurfaceOutput o)
  49.   {
  50.   half4 c = tex2D(_MainTex, IN.uv_MainTex);
  51.   o.Albedo = c.rgb;
  52.   o.Alpha = c.a;
  53.   }
  54.   ENDCG
  55.   }
  56. }

你可能感兴趣的:(【风宇冲】Unity3D教程宝典之Shader篇:第十六讲自定义光照模型)