一、平行光
LightDirectional::LightDirectional(glm::vec3 _position, glm::vec3 _angles, glm::vec3 _color):
postion(_position),
angles(_angles),
color(_color)
{
UpdateDirection();
}
void LightDirectional::UpdateDirection()
{
direction = glm::vec3(0, 0, 1.0f);
direction = glm::rotateZ(direction, angles.z);
direction = glm::rotateX(direction, angles.x);
direction = glm::rotateY(direction, angles.y);
direction *= -1.0f;
}
二、点光源
LightPoint::LightPoint(glm::vec3 _position, glm::vec3 _angles, glm::vec3 _color):
postion(_position),
angles(_angles),
color(_color)
{
constant = 1.0f;
linear = 0.09f;
quadratic = 0.032f;
}
三、聚光灯
LightSpot::LightSpot(glm::vec3 _position, glm::vec3 _angles, glm::vec3 _color):
postion(_position),
angles(_angles),
color(_color)
{
UpdateDirection();
}
void LightSpot::UpdateDirection()
{
direction = glm::vec3(0, 0, 1.0f);
direction = glm::rotateZ(direction, angles.z);
direction = glm::rotateX(direction, angles.x);
direction = glm::rotateY(direction, angles.y);
direction *= -1.0f;
}
四、在fragmentShader中计算光源
vec3 lightColorReal;
vec3 lightDirReal;
//1、LightDirection 平行光
//lightDirReal = lightDirUniform;
//lightColorReal = lightColor;
//2、LightPoint 点光源
// lightDirReal = normalize(lightPos - FragPos);
// float dist = length(lightPos - FragPos);
// float attenuation = 1.0 / (lightP.constant + lightP.linear * dist +
// lightP.quadratic * (dist * dist));
// lightColorReal = lightColor*attenuation;
//3、LightSpot 聚光灯
lightDirReal = normalize(lightPos - FragPos);
float cosTheta = dot(normalize(FragPos - lightPos),-1*lightDirUniform);
float spotRatio = (cosTheta-lightS.cosPhyOutter)/(lightS.cosPhyInner-lightS.cosPhyOutter);
if(cosTheta>lightS.cosPhyInner){
//inside
lightColorReal = lightColor;
}else if(cosTheta>lightS.cosPhyOutter){
//middle
lightColorReal = lightColor*spotRatio;
}else{
//outside
lightColorReal = lightColor*0.0f;
}
//光照模型//
vec3 reflectVec =reflect(lightDirReal,Normal);
vec3 cameraVec = normalize(cameraPos - FragPos);
//specular
float specularAmount = pow(max(dot(reflectVec,cameraVec),0.0f),material.shininess);
vec3 specular = texture(material.specular,TextCoord).rgb*specularAmount*lightColorReal;
//deffuse
//vec3 diffuse =material.diffuse * max(dot(lightDir,Normal),0.0f)*lightColor;
vec3 diffuse = texture(material.diffuse,TextCoord).rgb* max(dot(lightDirReal,Normal),0.0f)*lightColorReal;
//ambient
vec3 ambient = texture(material.diffuse,TextCoord).rgb*ambientColor;
//emission
vec3 emission = texture(material.emission,TextCoord).rgb;
//FragColor = vec4((ambient+diffuse+specular)*objColor,1.0f)+vec4(emission,1.0f);
FragColor = vec4((ambient+diffuse+specular)*objColor,1.0f);