How to do it...

The vertex shader is nearly identical to the one from the previous recipe, except that the Phong model is evaluated within a function, and we add another function to convert the position and the normal to camera coordinates:

// Uniform variables and attributes omitted... void getCamSpace( out vec3 norm, out vec3 position ) {    norm = normalize( NormalMatrix * VertexNormal);    position = (ModelViewMatrix * vec4(VertexPosition,1.0)).xyz;}vec3 phongModel( vec3 position, vec3 n ) {   vec3 ambient = Light.La * Material.Ka;  vec3 s = normalize( Light.Position.xyz - position );  float sDotN = max( dot(s,n), 0.0 );  vec3 diffuse = Light.Ld * Material.Kd * sDotN;  vec3 spec = vec3(0.0);  if( sDotN > 0.0 ) { vec3 v = normalize(-position.xyz); ...

Get OpenGL 4 Shading Language Cookbook - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.