【unity shader】《unity shader入门精要》 光照模型

unity shader中的漫反射+高光反射光照模型


光照模型是shader的核心,它描述了光线同物体的交互方式。
对于非透明物体,光照模型一般包含两部分:漫反射和高光反射。

一个常见的包含漫反射光照模型的shader程序如下:

Shader "Unity Shaders Book/Chapter 6/Diffuse Pixel-Level" {
	Properties {
		_Diffuse ("Diffuse", Color) = (1, 1, 1, 1)
	}
	SubShader {
		Pass { 
			Tags { "LightMode"="ForwardBase" }
		
			CGPROGRAM
			
			#pragma vertex vert
			#pragma fragment frag
			
			#include "Lighting.cginc" //预设光照文件
			
			fixed4 _Diffuse;
			
			struct a2v {
				float4 vertex : POSITION;
				float3 normal : NORMAL;
			};
			
			struct v2f {
				float4 pos : SV_POSITION;
				float3 worldNormal : TEXCOORD0;
			};
			
			v2f vert(a2v v) {
				v2f o;
				// Transform the vertex from object space to projection space
				o.pos = mul(UNITY_MATRIX_MVP, v.vertex);

				// Transform the normal fram object space to world space
				o.worldNormal = mul(v.normal, (float3x3)_World2Object);

				return o;
			}
			
			fixed4 frag(v2f i) : SV_Target {
				// Get ambient term
				fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
				
				// Get the normal in world space
				fixed3 worldNormal = normalize(i.worldNormal);
				// Get the light direction in world space
				fixed3 worldLightDir = normalize(_WorldSpaceLightPos0.xyz);
				
				// Compute diffuse term 反射光颜色的计算是用光源颜色*物体表面的反射系数,即_Diffuse
				fixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal, worldLightDir));
				
				fixed3 color = ambient + diffuse;
				
				return fixed4(color, 1.0);
			}
			
			ENDCG
		}
	} 
	FallBack "Diffuse"
}

以上漫反射光照模型也成为Lambert模型。这是一个经验公式,并非基于物理定律。因为能够很好地模拟真实光照而被广泛应用。
实际应用中,很多shader程序员似乎并不严格遵守这一模型,而会根据自身需要对它进行改进。可能是因为在shader世界中,如果它看上去是对的,那它就是对的吧。


你可能感兴趣的:(【unity shader】《unity shader入门精要》 光照模型)