接上一节这节我们来针对每个 fragment 计算光照,只需要改变 shader 把光照的逻辑从 vertex shader 中转移到 fragment shader 中计算。
<script id="vertex-shader" type="glsl">
attribute vec4 a_Position;
attribute vec4 a_Color;
attribute vec3 a_Normal;
uniform mat4 u_mvpMatrix;
uniform mat4 u_ModelMatrix;
uniform mat4 u_NormalMatrix;
varying vec4 v_Color;
varying vec3 v_Normal;
varying vec3 v_Position;
void main() {
gl_Position = u_mvpMatrix * a_Position;
v_Position = vec3(u_ModelMatrix * a_Position);
v_Normal = normalize(vec3(u_NormalMatrix * vec4(a_Normal,1.0)));
v_Color = a_Color;
}
</script>
<script id="fragment-shader" type="glsl">
precision mediump float;
uniform vec3 u_LightColor;
uniform vec3 u_LightPosition;
uniform vec3 u_AmbientLight;
varying vec4 v_Color;
varying vec3 v_Normal;
varying vec3 v_Position;
void main() {
vec3 normal = normalize(v_Normal);
vec3 lightDirection = normalize(u_LightPosition - v_Position);
float nDotL = max(dot(lightDirection, normal), 0.0);
vec3 diffuse = u_LightColor * v_Color.rgb * nDotL;
vec3 ambient = u_AmbientLight * v_Color.rgb;
gl_FragColor = vec4(diffuse + ambient, v_Color.a);
}
</script>