Unity3D教程宝典之Shader篇:第十六讲自定义光照模型
十四讲我们实现了基本的Surface Shader,十五讲讲了光照模型的基础知识。这一讲说的是如何写光照模型。
自定义光照模型主要分为4步:
(0)架设框架,填写需要的参数
(1)计算漫反射强度
(2)计算镜面反射强度
(3)结合漫反射光与镜面反射光
代码配有中文注释,配合上上讲的光照公式,一步一步实现即可。
//Author: 风宇冲
Shader "Custom/T_customLightModel" {
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
Subshader
{
//alpha测试,配合surf中的o.Alpha = c.a;
AlphaTest Greater 0.4
CGPROGRAM
#pragma surface surf lsyLightModel
//命名规则:Lighting接#pragma suface之后起的名字
//lightDir :点到光源的单位向量 viewDir:点到摄像机的单位向量 atten:衰减系数
float4 LightinglsyLightModel(SurfaceOutput s, float3 lightDir,half3 viewDir, half atten)
{
float4 c;
//(1)漫反射强度
float diffuseF = max(0,dot(s.Normal,lightDir));
//(2)镜面反射强度
float specF;
float3 H = normalize(lightDir+viewDir);
float specBase = max(0,dot(s.Normal,H));
// shininess 镜面强度系数,这里设置为8
specF = pow(specBase,8);
//(3)结合漫反射光与镜面反射光
c.rgb = s.Albedo * _LightColor0 * diffuseF *atten + _LightColor0*specF;
c.a = s.Alpha;
return c;
}
struct Input
{
float2 uv_MainTex;
};
void vert(inout appdata_full v)
{
//这里可以做特殊位置上的处理
}
sampler2D _MainTex;
void surf(Input IN,inout SurfaceOutput o)
{
half4 c = tex2D(_MainTex, IN.uv_MainTex);
o.Albedo = c.rgb;
o.Alpha = c.a;
}
ENDCG
}
}

浙公网安备 33010602011771号