scg3  0.6
simple_flat_vert.glsl
Go to the documentation of this file.
1 /**
2  * \file simple_flat_vert.glsl
3  * \brief Minimal lighting vertex shader, using a single point light and Gouraud shading.
4  */
5 
6 #version 150
7 
8 in vec4 vVertex;
9 in vec3 vNormal;
10 
11 uniform mat4 modelViewMatrix;
12 uniform mat4 projectionMatrix;
13 uniform mat4 mvpMatrix;
14 uniform mat3 normalMatrix;
15 
16 const int MAX_NUMBER_OF_LIGHTS = 10;
17 
18 struct Light {
19  vec4 position;
20  vec4 ambient;
21  vec4 diffuse;
22  vec4 specular;
23  vec4 halfVector; // used as vec3, expected as normalized
24  vec4 spotDirection; // used as vec3, expected as normalized
25  float spotCosCutoff;
26  float spotExponent;
27 };
28 
29 layout(std140) uniform LightBlock {
30  Light lights[MAX_NUMBER_OF_LIGHTS];
31 };
32 
33 struct Material {
34  vec4 emission;
35  vec4 ambient;
36  vec4 diffuse;
37  vec4 specular;
38  float shininess;
39 };
40 
41 layout(std140) uniform MaterialBlock {
42  Material material;
43 };
44 
45 uniform int nLights;
46 uniform vec4 globalAmbientLight;
47 
48 flat out vec4 color;
49 
50 
51 // --- declarations ---
52 
53 
54 void applyLighting(const in vec3 ecVertex, const in vec3 ecNormal, out vec4 color);
55 
56 
57 // --- implementations ---
58 
59 
60 void main() {
61 
62  // transform vertex position and normal into eye coordinates
63  vec3 ecVertex = (modelViewMatrix * vVertex).xyz;
64  vec3 ecNormal = normalMatrix * vNormal;
65 
66  // apply lighting model
67  applyLighting(ecVertex, ecNormal, color);
68 
69  // set output values
70  gl_Position = mvpMatrix * vVertex;
71 }
72 
73 
74 void applyLighting(const in vec3 ecVertex, const in vec3 ecNormal, out vec4 color) {
75 
76  // normalized view direction and surface normal
77  vec3 v = normalize(-ecVertex);
78  vec3 n = normalize(ecNormal);
79 
80  // normalized light source direction and half vector
81  vec3 s = normalize(lights[0].position.xyz - ecVertex);
82  vec3 h = normalize(v + s);
83 
84  // emission and global ambient
85  color = material.emission + material.ambient * globalAmbientLight;
86 
87  if (nLights > 0) {
88  // ambient
89  color += material.ambient * lights[0].ambient;
90 
91  // diffuse
92  float sDotN = max(0., dot(s, n));
93  color += material.diffuse * lights[0].diffuse * sDotN;
94 
95  // specular
96  float hDotN = dot(h, n);
97  if (hDotN > 0.) {
98  color += material.specular * lights[0].specular * pow(hDotN, material.shininess);
99  }
100  }
101 }