材质主要包括3种光照元素:环境光照(Ambient Lighting)、漫反射光照(Diffuse Lighting)、镜面光照(Specular Lighting)定义一个材质颜色
然后我们就可以通过修改材质里这3种光照,产生不同的现象。如:。钢看起来比陶瓷花瓶更闪闪发光,一个木头箱子不会像钢箱子一样对光产生很强的反射。每个物体对镜面高光也有不同的反应
default.vs
#version 330 core
out vec4 color;
in vec3 Normal;
in vec3 FragPos;
uniform vec3 lightPos;
uniform vec3 lightColor;
uniform vec3 objectColor;
uniform vec3 viewPos;
//设置材质
struct Material
{
vec3 ambient;//环境光照下的颜色
vec3 diffuse;//漫反射光照的颜色
vec3 specular;//镜面光照下的颜色,一般为白色
float shininess;//面高光的散射/半径
};
uniform Material material;
//调整光照的强度
struct Light
{
vec3 position;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
uniform Light light;
void main()
{
// 环境光
vec3 ambient = light.ambient * material.ambient;
// 漫反射光
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(lightPos - FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = light.diffuse * (diff * material.diffuse);
// 镜面高光
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
vec3 specular = light.specular * (spec * material.specular);
vec3 result = ambient + diffuse + specular;
color = vec4(result, 1.0f);
}
其实就用材质meterial的替换了各个属性的颜色,然后用light来修改各个属性的强度
cpp修改代码
GLint objectColorLoc = glGetUniformLocation(ourShader.Program, "objectColor");
GLint lightColorLoc = glGetUniformLocation(ourShader.Program, "lightColor");
GLint lightPosLoc = glGetUniformLocation(ourShader.Program, "lightPos");
GLint viewPosLoc = glGetUniformLocation(ourShader.Program, "viewPos");
glUniform3f(objectColorLoc, 1.0f, 0.5f, 0.31f);
glUniform3f(lightColorLoc, 1.0f, 1.0f, 1.0f);
glUniform3f(lightPosLoc, lightPos.x, lightPos.y, lightPos.z);
glUniform3f(viewPosLoc, camera.Position.x, camera.Position.y, camera.Position.z);
GLint matAmbientLoc = glGetUniformLocation(ourShader.Program, "material.ambient");
GLint matDiffuseLoc = glGetUniformLocation(ourShader.Program, "material.diffuse");
GLint matSpecularLoc = glGetUniformLocation(ourShader.Program, "material.specular");
GLint matShineLoc = glGetUniformLocation(ourShader.Program, "material.shininess");
//颜色
glUniform3f(matAmbientLoc, 1.0f, 0.5f, 0.31f);
glUniform3f(matDiffuseLoc, 1.0f, 0.5f, 0.31f);
glUniform3f(matSpecularLoc, 0.5f, 0.5f, 0.5f);
glUniform1f(matShineLoc, 32.0f);
GLint lightAmbientLoc = glGetUniformLocation(ourShader.Program, "light.ambient");
GLint lightDiffuseLoc = glGetUniformLocation(ourShader.Program, "light.diffuse");
GLint lightSpecularLoc = glGetUniformLocation(ourShader.Program, "light.specular");
//光照强度
glUniform3f(lightAmbientLoc, 0.2f, 0.2f, 0.2f);
glUniform3f(lightDiffuseLoc, 0.5f, 0.5f, 0.5f);// 让我们把这个光调暗一点,这样会看起来更自然
glUniform3f(lightSpecularLoc, 1.0f, 1.0f, 1.0f);
现象: