Last active
April 6, 2024 22:49
-
-
Save chicio/d983fff6ff304bd55bebd6ff05a2f9dd to your computer and use it in GitHub Desktop.
A simple Phong reflection model implementation using GLSL 3.00
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#version 300 es | |
precision mediump float; | |
/** | |
RGB material definition. | |
*/ | |
struct RGBMaterial { | |
/// Emissive component. | |
vec4 ke; | |
/// Ambient component. | |
vec4 ka; | |
/// Diffuse component. | |
vec4 kd; | |
/// Specular component. | |
vec4 ks; | |
/// Shiness. | |
float sh; | |
}; | |
/** | |
RGB light definition. | |
It composed of a direction and a color. | |
*/ | |
struct DirectionalRGBLight { | |
/// Light direction. | |
vec3 direction; | |
/// Light rgb color. | |
vec4 color; | |
}; | |
/// Normal (from vertex shader) interpolated per fragment. | |
in vec3 normalInterp; | |
/// Vertex position. | |
in vec3 vertPos; | |
/// Final fragment color. | |
out vec4 fragmentColor; | |
/// View position. | |
uniform vec3 viewPosition; | |
/// Light data. | |
uniform DirectionalRGBLight light; | |
/// Material data. | |
uniform RGBMaterial surfaceMaterial; | |
void main() { | |
//Calculate light direction and view direction. | |
vec3 lightDirection = normalize(light.direction); | |
vec3 viewDirection = normalize(viewPosition - vertPos); | |
//Cosine theta diffuse lambertian component. | |
float cosTheta = max(0.0, dot(normalInterp, normalize(lightDirection))); | |
vec4 emissive = surfaceMaterial.ke * light.color; | |
vec4 ambient = surfaceMaterial.ka * light.color; | |
vec4 diffuse = vec4(0.0, 0.0, 0.0, 1.0); | |
vec4 specular = vec4(0.0, 0.0, 0.0, 1.0); | |
//Only if light is visible from the surface point. | |
if(cosTheta > 0.0) { | |
//Reflection vector around normal. | |
vec3 reflectionDirection = reflect(-lightDirection, normalInterp); | |
//Diffuse component. | |
diffuse = surfaceMaterial.kd * light.color * cosTheta; | |
//Specular component. | |
specular = surfaceMaterial.ks * light.color * pow(max(0.0, dot(reflectionDirection, viewDirection)), surfaceMaterial.sh); | |
} | |
fragmentColor = emissive + ambient + diffuse + specular; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@chicio Hello!
On line 73, shouldn't it be
viewDirection
instead ofnormalInterp
?