LearnOpenGL/shader.fs

99 lines
2.4 KiB
Forth
Raw Normal View History

2022-02-11 21:24:15 +00:00
#version 460 core
out vec4 FragColor;
in vec3 Normal;
in vec3 FragPos;
2022-02-16 18:46:19 +00:00
in vec2 TexCoords;
struct Material {
2022-02-16 18:46:19 +00:00
sampler2D diffuse;
sampler2D specular;
float shininess;
};
struct DirLight {
vec3 direction;
vec3 ambient;
vec3 diffuse;
vec3 specular;
2022-02-16 19:12:07 +00:00
};
struct PointLight{
vec3 position;
2022-02-16 19:12:07 +00:00
float constant;
float linear;
float quadratic;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
#define NR_POINT_LIGHTS 4
2022-02-16 19:12:07 +00:00
uniform PointLight PointLights[NR_POINT_LIGHTS];
uniform DirLight dirlight;
uniform Material material;
uniform vec3 viewPos;
vec3 CalcDirLight(DirLight light , vec3 normal , vec3 viewDir)
2022-02-11 21:24:15 +00:00
{
vec3 lightDir = normalize(-light.direction);
float diff = max(dot(normal,lightDir), 0.0);
vec3 reflectDir = reflect(-lightDir, normal);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
2022-02-16 19:32:55 +00:00
vec3 ambient = light.ambient * vec3 (texture(material.diffuse, TexCoords));
vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords));
vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));
return (ambient + diffuse + specular);
}
vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir)
{
vec3 lightDir = normalize(light.position - fragPos );
float diff = max(dot(normal, lightDir), 0.0);
vec3 reflectDir = reflect(-lightDir, normal);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
2022-02-16 19:32:55 +00:00
float distance = length(light.position - fragPos);
float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance *distance));
2022-02-16 19:32:55 +00:00
vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords));
vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords));
vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));
2022-02-16 19:32:55 +00:00
ambient *= attenuation;
diffuse *= attenuation;
specular *= attenuation;
2022-02-16 19:32:55 +00:00
return (ambient + diffuse + specular);
2022-02-16 19:32:55 +00:00
}
2022-02-16 19:12:07 +00:00
2022-02-16 19:32:55 +00:00
void main()
{
2022-02-16 19:32:55 +00:00
vec3 norm = normalize(Normal);
vec3 viewDir = normalize(viewPos - FragPos);
2022-02-16 19:32:55 +00:00
// Fase 1 : Directional lighting
vec3 result = CalcDirLight(dirlight, norm, viewDir);
// Fase 2 : Point lights
for( int i = 0; i < NR_POINT_LIGHTS; i++){
result += CalcPointLight(PointLights[i], norm, FragPos, viewDir);
}
FragColor = vec4(result, 1.0);
2022-02-11 21:24:15 +00:00
}