这一篇,我们来创建一个车辆喷漆的光照模型。首先就是准备场景,新建Shader & Material。
过程比较简单,直接看完成的代码吧:
Shader "91YGame/CarOutLight" { Properties { _MainTint("Diffuse Tint",Color)=(1,1,1,1) _MainTex ("Base (RGB)", 2D) = "white" {} _SpecularColor("Specular Color",Color)=(1,1,1,1) _SpecPower("Specular Power",Range(0.1,30))=3 _RelfCube("Reflection Cube",Cube) = ""{} _BRDFTex("BRDF Texture",2D)=""{} _DiffusePower("Diffuse Power",Range(0.1,10))=0.5 _FalloffPower("Falloff Spread",Range(0.1,10))=3 _ReflAmount("Reflection Amount",Range(0.1,1))=0.5 _ReflPower("Reflection Power",Range(0.1,3))=2.0 } SubShader { Tags { "RenderType"="Opaque" } LOD 200 CGPROGRAM #pragma surface surf CarPaint sampler2D _MainTex; sampler2D _BRDFTex; float4 _MainTint; float4 _SpecularColor; fixed _SpecPower; fixed _DiffusePower; fixed _FalloffPower; fixed _ReflAmount; fixed _ReflPower; samplerCUBE _RelfCube; struct Input { float2 uv_MainTex; float3 worldRefl; float viewDir; }; inline fixed4 LightingCarPaint(SurfaceOutput s,fixed3 lightDir,half3 viewDir,fixed atten){ half3 h = normalize(lightDir+viewDir); fixed diff = max(0,dot(s.Normal,lightDir)); float ahdn = 1-dot(h,normalize(s.Normal)); ahdn = pow(clamp(ahdn,0,1),_DiffusePower); half4 brdf = tex2D(_BRDFTex,float2(diff,1-ahdn)); float nh = max(0,dot(s.Normal,h)); float spec =pow(nh,s.Specular*_SpecPower)*s.Gloss; fixed4 c; c.rgb = (s.Albedo*_LightColor0.rbg*brdf.rgb + _LightColor0.rgb*_SpecularColor.rgb*spec)*(atten*2); c.a = s.Alpha+_LightColor0.a*_SpecularColor.a*spec*atten; return c; } void surf (Input IN, inout SurfaceOutput o) { half4 c = tex2D (_MainTex, IN.uv_MainTex); fixed falloff = saturate(1-dot(normalize(IN.viewDir),o.Normal)); falloff = pow(falloff,_FalloffPower); o.Albedo = c.rgb*_MainTint; o.Emission = pow((texCUBE(_RelfCube,IN.worldRefl).rgb*falloff),_ReflPower)*_ReflAmount; o.Albedo = c.rgb*_MainTint; o.Specular = c.r; o.Gloss =1; o.Alpha = c.a; } ENDCG } FallBack "Diffuse" }
完成以后,返回编辑器,查看效果吧:
在上面的实现过程中,用到了之前说到的一些技术,我们利用BRDF来创建包含两种渐变色彩的喷漆。
再简单的计算出一个菲涅尔系数,以及一个递减的元素来决定车辆表面的反射强度。
所有这些光照强度都是由Properties模块中的ui值决定的。这样最大限度的方便美术人员。