LearnOpenGL/shader.fs
2022-02-16 20:32:55 +01:00

89 lines
1.9 KiB
GLSL

#version 460 core
out vec4 FragColor;
in vec3 Normal;
in vec3 FragPos;
in vec2 TexCoords;
struct Material {
sampler2D diffuse;
sampler2D specular;
float shininess;
};
struct Light{
vec3 position;
vec3 direction; // neccessary when using directional lights or spotlights.
float cutoff;
float outerCutOff;
vec3 ambient;
vec3 diffuse;
vec3 specular;
// lets create point lights
float constant;
float linear;
float quadratic;
};
uniform Light light;
uniform Material material;
uniform vec3 viewPos;
void main()
{
// ambient lighting calculation
vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords));
// diffuse lighting calculation
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(light.position - FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords));
// specular lighting
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 * vec3( texture(material.specular, TexCoords));
float theta = dot(lightDir, normalize(-light.direction));
float epsilon = light.cutoff - light.outerCutOff;
float intensity = clamp((theta - light.outerCutOff)/ epsilon, 0.0, 1.0);
diffuse *= intensity;
specular *= intensity;
// calculate the attenuation
float distance = length(light.position - FragPos);
float attenuation = 1.0/ (light.constant + light.linear * distance + light.quadratic * (distance*distance));
ambient *= attenuation;
diffuse *= attenuation;
specular *= attenuation;
vec3 result = ambient + diffuse + specular ;
FragColor = vec4(result, 1.0);
}