Skip to content

Instantly share code, notes, and snippets.

@chicio
Last active April 6, 2024 22:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chicio/d983fff6ff304bd55bebd6ff05a2f9dd to your computer and use it in GitHub Desktop.
Save chicio/d983fff6ff304bd55bebd6ff05a2f9dd to your computer and use it in GitHub Desktop.
A simple Phong reflection model implementation using GLSL 3.00
#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;
}
@aalvarezwindey
Copy link

@chicio Hello!
On line 73, shouldn't it be viewDirection instead of normalInterp?

@chicio
Copy link
Author

chicio commented Aug 10, 2020

Hi @aalvarezwindey, thanks for your feedback! Yes you're right. Fixed and updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment