Unity Shaders 基础篇(四) 光照

来源:互联网 发布:淘宝交易管理插件 编辑:程序博客网 时间:2024/06/05 10:48

声明: 本文主要参照CG_WikiBook.

漫反射(Diffuse reflection)

先上效果图:
这里写图片描述
如图所示,这是一个在单个平行光下的sphere. 采用光照计算模型为diffuse.

所谓的diffuse模型就是说不论在何方向看这个球的某一点(不被遮挡的情况下), 球的亮度都是一致的. 这个点的亮度由以下的公式决定:

Idiffuse=IincomingKdiffusemax(0,NL)
其中I的全称为Intensity. K主要代表的是物体的材质. N代表的是物体反射点的法向量.L则代表了光的朝向(从反射点指向光的方向).
代码如下:

Shader "Cg per-vertex diffuse lighting" {   Properties {      _Color ("Diffuse Material Color", Color) = (1,1,1,1)    }   SubShader {      Pass {             Tags { "LightMode" = "ForwardBase" }             // make sure that all uniforms are correctly set         CGPROGRAM         #pragma vertex vert           #pragma fragment frag          #include "UnityCG.cginc"         uniform float4 _LightColor0;             // color of light source (from "Lighting.cginc")         uniform float4 _Color; // define shader property for shaders         struct vertexInput {            float4 vertex : POSITION;            float3 normal : NORMAL;         };         struct vertexOutput {            float4 pos : SV_POSITION;            float4 col : COLOR;         };         vertexOutput vert(vertexInput input)          {            vertexOutput output;            float4x4 modelMatrix = unity_ObjectToWorld;            float4x4 modelMatrixInverse = unity_WorldToObject;            //input.normal 法向量 模型坐标系            float3 normalDirection = normalize(               mul(float4(input.normal, 0.0), modelMatrixInverse).xyz);            float3 lightDirection = normalize(_WorldSpaceLightPos0.xyz);//光的朝向 世界坐标系            float3 diffuseReflection = _LightColor0.rgb * _Color.rgb               * max(0.0, dot(normalDirection, lightDirection));            output.col = float4(diffuseReflection, 1.0);            output.pos = mul(UNITY_MATRIX_MVP, input.vertex);            return output;         }         float4 frag(vertexOutput input) : COLOR         {            return input.col;         }         ENDCG      }   }   Fallback "Diffuse"}

其中,唯一需要注意的是

float3 normalDirection = normalize(     mul(float4(input.normal, 0.0), modelMatrixInverse).xyz);

向量和坐标的转换是不一致的.(待补充)

镜面高光(Specular highlights)

光滑镜面高光(Smooth Specular highlights)

未完待续

0 0
原创粉丝点击