使用着色器实现环境光、方向光、点光源
· 阅读需 7 分钟
in real life, if an object is perfectly blue and the only light source is red, you won't see the object because it will absorb the light and not reflect it back to your eyes.
在现实生活中,如果一个物体是纯蓝色的,而唯一的光源是红色的,你将看不到这个物体,因为它会吸收红光而不会反射任何光线回到你的眼睛。这是因为:
-
实验示例:
- 在完全黑暗的房间里
- 准备一个纯蓝色的物体(比如蓝色的纸张)
- 使用一个红色LED手电筒照射
- 结果:蓝色物体会显得几乎全黑
-
科学解释:
- 蓝色物体之所以呈现蓝色,是因为它反射蓝光,吸收其他波长的光
- 红色光源只发射红光
- 当红光照射到蓝色物体上时,所有红光都被吸收
- 没有光线被反射回来,因此我们看到的是黑色
这个原理在舞台灯光设计中经常被应用,通过改变光源的颜色可以让某些颜色的道具"消失"或改变外观。
if the face faces the light, it will receive the full power if the face is at a perfect 90° angle, it won't receive any values in between will be interpolated
about normal
in the vertex shader, we get the normal in world space
normal
instead of providing the direction straight to the function, we are going to provide the position of the light and calculate the orientation from it
环境光
ambientLight.glsl
vec3 ambientLight(vec3 lightColor, float lightIntensity)
{
return lightColor * lightIntensity;
}
方向光
directionalLight.glsl
vec3 directionalLight(vec3 lightColor, float lightIntensity, vec3 normal, vec3 lightPosition, vec3 viewDirection, float specularPower)
{
vec3 lightDirection = normalize(lightPosition);
vec3 lightReflection = reflect(- lightDirection, normal);
// Shading
float shading = dot(normal, lightDirection);
shading = max(0.0, shading);
// Specular
float specular = - dot(lightReflection, viewDirection);
specular = max(0.0, specular);
specular = pow(specular, specularPower);
return lightColor * lightIntensity * (shading + specular);
}