光照
光照系统分为三部分:光源、材质、光源环境
光照类型:镜面反射、漫反射、高光反射(三种光的反射特性)
光照模型: 环境光(Ambient Light)、 漫射光(Diffuse Light)、镜面光(Specular Light)
方向光为例
#version 330 core
uniform mat4 MVPMatrix;
uniform mat3 NormalMatrix;
in vec4 VertexColor;
in vec3 VertexNormal;
in vec4 VertexPosition;
out vec4 Color;
out vec3 Normal;
void main()
{ Color = VertexColor;
Normal = normalize(NormalMatrix * VertexNormal);
gl_position = MVPMatrix * VertexPosition;
}
片元着色器:
#version 330 core
uniform vec3 ambient;
uniform vec3 LightColor;
uniform vec3 LightDirection;uniform vec3 HalfVector;
uniform float shininess;
uniform float strength;
in vec4 Color;
in vec3 Normal;
out vec4 FragColor;
void main()
{
float diffuse = max(0.0, dot(Normal, LightDirection)); //点积是判断光照的反射程度
float specular = max(0.0, dot(Normal, HalfVector));
if(diffuse==0.0) specular =0.0;
else specular = pow(specular, shininess);
vec3 scatteredLight = LightColor * diffuse + ambient;
vec3 reflectedLight = LightColor * specular *strength;
vec3 rgb = min(Color.rgb * scatteredLight + reflectedLight, vec3(1.0));
FlagColor = vec4(rgb, Color.a);
}
多光源:
scatteredLight += (Lights[light].Color * diffuse + Lights[light].ambient) * attenuation;
reflectedLight += Lights[light].Color * specular *attenuation;
多光源多材质:
scatteredLight += (Lights[light].Color * diffuse * Material[MatIndex].diffuse +
Lights[light].ambient * Material[MatIndex].ambient) * attenuation;
reflectedLight += Lights[light].Color * specular * Material[MatIndex].specular *attenuation;
rgb = min(Color.rgb * scatteredLight + reflectedLight +Material[MatIndex].emission , vec3(1.0));