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

来源:互联网 发布:unity3d游戏场景下载 编辑:程序博客网 时间:2024/05/22 12:36

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 spaceo.pos = mul(UNITY_MATRIX_MVP, v.vertex);// Transform the normal fram object space to world spaceo.worldNormal = mul(v.normal, (float3x3)_World2Object);return o;}fixed4 frag(v2f i) : SV_Target {// Get ambient termfixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;// Get the normal in world spacefixed3 worldNormal = normalize(i.worldNormal);// Get the light direction in world spacefixed3 worldLightDir = normalize(_WorldSpaceLightPos0.xyz);// Compute diffuse term 反射光颜色的计算是用光源颜色*物体表面的反射系数,即_Diffusefixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal, worldLightDir));fixed3 color = ambient + diffuse;return fixed4(color, 1.0);}ENDCG}} FallBack "Diffuse"}

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


0 0
原创粉丝点击