note about glutSetVertexAttribTexCoord2 in shapes demo
[freeglut] / progs / demos / shapes / shapes.c
1 /*! \file    shapes.c
2     \ingroup demos
3
4     This program is a test harness for the various shapes
5     in OpenGLUT.  It may also be useful to see which
6     parameters control what behavior in the OpenGLUT
7     objects.
8  
9     Spinning wireframe and solid-shaded shapes are
10     displayed.  Some parameters can be adjusted.
11  
12    Keys:
13       -    <tt>Esc &nbsp;</tt> Quit
14       -    <tt>q Q &nbsp;</tt> Quit
15       -    <tt>i I &nbsp;</tt> Show info
16       -    <tt>p P &nbsp;</tt> Toggle perspective or orthographic projection
17       -    <tt>r R &nbsp;</tt> Toggle fixed or animated rotation around model X-axis
18       -    <tt>s S &nbsp;</tt> Toggle toggle fixed function or shader render path
19       -    <tt>n N &nbsp;</tt> Toggle visualization of object's normal vectors
20       -    <tt>= + &nbsp;</tt> Increase \a slices
21       -    <tt>- _ &nbsp;</tt> Decreate \a slices
22       -    <tt>, < &nbsp;</tt> Decreate \a stacks
23       -    <tt>. > &nbsp;</tt> Increase \a stacks
24       -    <tt>9 ( &nbsp;</tt> Decreate \a depth  (Sierpinski Sponge)
25       -    <tt>0 ) &nbsp;</tt> Increase \a depth  (Sierpinski Sponge)
26       -    <tt>up&nbsp; &nbsp;</tt> Increase "outer radius"
27       -    <tt>down&nbsp;</tt> Decrease "outer radius"
28       -    <tt>left&nbsp;</tt> Decrease "inner radius"
29       -    <tt>right</tt> Increase "inner radius"
30       -    <tt>PgUp&nbsp;</tt> Next shape-drawing function
31       -    <tt>PgDn&nbsp;</tt> Prev shape-drawing function
32
33     \author  Written by Nigel Stewart November 2003
34
35     \author  Portions Copyright (C) 2004, the OpenGLUT project contributors. <br>
36              OpenGLUT branched from freeglut in February, 2004.
37  
38     \image   html openglut_shapes.png OpenGLUT Geometric Shapes Demonstration
39     \include demos/shapes/shapes.c
40 */
41
42 #include <GL/freeglut.h>
43
44 #include <stdarg.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47
48 #include "glmatrix.h"
49
50 #ifdef _MSC_VER
51 /* DUMP MEMORY LEAKS */
52 #include <crtdbg.h>
53 #endif
54
55 /* report GL errors, if any, to stderr */
56 void checkError(const char *functionName)
57 {
58     GLenum error;
59     while (( error = glGetError() ) != GL_NO_ERROR) {
60         fprintf (stderr, "GL error 0x%X detected in %s\n", error, functionName);
61     }
62 }
63
64 /*
65  * OpenGL 2+ shader mode needs some function and macro definitions, 
66  * avoiding a dependency on additional libraries like GLEW or the
67  * GL/glext.h header
68  */
69 #ifndef GL_FRAGMENT_SHADER
70 #define GL_FRAGMENT_SHADER 0x8B30
71 #endif
72
73 #ifndef GL_VERTEX_SHADER
74 #define GL_VERTEX_SHADER 0x8B31
75 #endif
76
77 #ifndef GL_COMPILE_STATUS
78 #define GL_COMPILE_STATUS 0x8B81
79 #endif
80
81 #ifndef GL_LINK_STATUS
82 #define GL_LINK_STATUS 0x8B82
83 #endif
84
85 #ifndef GL_INFO_LOG_LENGTH
86 #define GL_INFO_LOG_LENGTH 0x8B84
87 #endif
88
89 typedef ptrdiff_t ourGLsizeiptr;
90 typedef char ourGLchar;
91
92 #ifndef APIENTRY
93 #define APIENTRY
94 #endif
95
96 #ifndef GL_VERSION_2_0
97 typedef GLuint (APIENTRY *PFNGLCREATESHADERPROC) (GLenum type);
98 typedef void (APIENTRY *PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const ourGLchar **string, const GLint *length);
99 typedef void (APIENTRY *PFNGLCOMPILESHADERPROC) (GLuint shader);
100 typedef GLuint (APIENTRY *PFNGLCREATEPROGRAMPROC) (void);
101 typedef void (APIENTRY *PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
102 typedef void (APIENTRY *PFNGLLINKPROGRAMPROC) (GLuint program);
103 typedef void (APIENTRY *PFNGLUSEPROGRAMPROC) (GLuint program);
104 typedef void (APIENTRY *PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
105 typedef void (APIENTRY *PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, ourGLchar *infoLog);
106 typedef void (APIENTRY *PFNGLGETPROGRAMIVPROC) (GLenum target, GLenum pname, GLint *params);
107 typedef void (APIENTRY *PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, ourGLchar *infoLog);
108 typedef GLint (APIENTRY *PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const ourGLchar *name);
109 typedef GLint (APIENTRY *PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const ourGLchar *name);
110 typedef void (APIENTRY *PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
111 typedef void (APIENTRY *PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
112 #endif
113
114 PFNGLCREATESHADERPROC gl_CreateShader;
115 PFNGLSHADERSOURCEPROC gl_ShaderSource;
116 PFNGLCOMPILESHADERPROC gl_CompileShader;
117 PFNGLCREATEPROGRAMPROC gl_CreateProgram;
118 PFNGLATTACHSHADERPROC gl_AttachShader;
119 PFNGLLINKPROGRAMPROC gl_LinkProgram;
120 PFNGLUSEPROGRAMPROC gl_UseProgram;
121 PFNGLGETSHADERIVPROC gl_GetShaderiv;
122 PFNGLGETSHADERINFOLOGPROC gl_GetShaderInfoLog;
123 PFNGLGETPROGRAMIVPROC gl_GetProgramiv;
124 PFNGLGETPROGRAMINFOLOGPROC gl_GetProgramInfoLog;
125 PFNGLGETATTRIBLOCATIONPROC gl_GetAttribLocation;
126 PFNGLGETUNIFORMLOCATIONPROC gl_GetUniformLocation;
127 PFNGLUNIFORMMATRIX4FVPROC gl_UniformMatrix4fv;
128 PFNGLUNIFORMMATRIX3FVPROC gl_UniformMatrix3fv;
129
130 void initExtensionEntries(void)
131 {
132     gl_CreateShader = (PFNGLCREATESHADERPROC) glutGetProcAddress ("glCreateShader");
133     gl_ShaderSource = (PFNGLSHADERSOURCEPROC) glutGetProcAddress ("glShaderSource");
134     gl_CompileShader = (PFNGLCOMPILESHADERPROC) glutGetProcAddress ("glCompileShader");
135     gl_CreateProgram = (PFNGLCREATEPROGRAMPROC) glutGetProcAddress ("glCreateProgram");
136     gl_AttachShader = (PFNGLATTACHSHADERPROC) glutGetProcAddress ("glAttachShader");
137     gl_LinkProgram = (PFNGLLINKPROGRAMPROC) glutGetProcAddress ("glLinkProgram");
138     gl_UseProgram = (PFNGLUSEPROGRAMPROC) glutGetProcAddress ("glUseProgram");
139     gl_GetShaderiv = (PFNGLGETSHADERIVPROC) glutGetProcAddress ("glGetShaderiv");
140     gl_GetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC) glutGetProcAddress ("glGetShaderInfoLog");
141     gl_GetProgramiv = (PFNGLGETPROGRAMIVPROC) glutGetProcAddress ("glGetProgramiv");
142     gl_GetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC) glutGetProcAddress ("glGetProgramInfoLog");
143     gl_GetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC) glutGetProcAddress ("glGetAttribLocation");
144     gl_GetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC) glutGetProcAddress ("glGetUniformLocation");
145     gl_UniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC) glutGetProcAddress ("glUniformMatrix4fv");
146     gl_UniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC) glutGetProcAddress ("glUniformMatrix3fv");
147     if (!gl_CreateShader || !gl_ShaderSource || !gl_CompileShader || !gl_CreateProgram || !gl_AttachShader || !gl_LinkProgram || !gl_UseProgram || !gl_GetShaderiv || !gl_GetShaderInfoLog || !gl_GetProgramiv || !gl_GetProgramInfoLog || !gl_GetAttribLocation || !gl_GetUniformLocation || !gl_UniformMatrix4fv || !gl_UniformMatrix3fv)
148     {
149         fprintf (stderr, "glCreateShader, glShaderSource, glCompileShader, glCreateProgram, glAttachShader, glLinkProgram, glUseProgram, glGetShaderiv, glGetShaderInfoLog, glGetProgramiv, glGetProgramInfoLog, glGetAttribLocation, glGetUniformLocation, glUniformMatrix4fv or gl_UniformMatrix3fv not found");
150         exit(1);
151     }
152 }
153
154 const ourGLchar *vertexShaderSource[] = {
155     "/**",
156     " * From the OpenGL Programming wikibook: http://en.wikibooks.org/wiki/GLSL_Programming/GLUT/Smooth_Specular_Highlights",
157     " * This file is in the public domain.",
158     " * Contributors: Sylvain Beucler",
159     " */",
160     "attribute vec3 fg_coord;",
161     "attribute vec3 fg_normal;",
162     "varying vec4 position;  /* position of the vertex (and fragment) in world space */",
163     "varying vec3 varyingNormalDirection;  /* surface normal vector in world space */",
164     "uniform mat4 m, p;      /* don't need v, as always identity in our demo */",
165     "uniform mat3 m_3x3_inv_transp;",
166     " ",
167     "void main()",
168     "{",
169     "  vec4 fg_coord4 = vec4(fg_coord, 1.0);",
170     "  position = m * fg_coord4;",
171     "  varyingNormalDirection = normalize(m_3x3_inv_transp * fg_normal);",
172     " ",
173     "  mat4 mvp = p*m;   /* normally p*v*m */",
174     "  gl_Position = mvp * fg_coord4;",
175     "}"
176 };
177
178 const ourGLchar *fragmentShaderSource[] = {
179     "/**",
180     " * From the OpenGL Programming wikibook: http://en.wikibooks.org/wiki/GLSL_Programming/GLUT/Smooth_Specular_Highlights",
181     " * This file is in the public domain.",
182     " * Contributors: Martin Kraus, Sylvain Beucler",
183     " */",
184     "varying vec4 position;  /* position of the vertex (and fragment) in world space */",
185     "varying vec3 varyingNormalDirection;  /* surface normal vector in world space */",
186     "/* uniform mat4 v_inv;   // in this demo, the view matrix is always an identity matrix */",
187     " ",
188     "struct lightSource",
189     "{",
190     "  vec4 position;",
191     "  vec4 diffuse;",
192     "  vec4 specular;",
193     "  float constantAttenuation, linearAttenuation, quadraticAttenuation;",
194     "  float spotCutoff, spotExponent;",
195     "  vec3 spotDirection;",
196     "};",
197     "lightSource light0 = lightSource(",
198     "  vec4(2.0, 5.0, 5.0, 0.0),",
199     "  vec4(1.0, 1.0, 1.0, 1.0),",
200     "  vec4(1.0, 1.0, 1.0, 1.0),",
201     "    0.0, 1.0, 0.0,",
202     "  180.0, 0.0,",
203     "  vec3(0.0, 0.0, 0.0)",
204     ");",
205     "vec4 scene_ambient = vec4(0.2, 0.2, 0.2, 1.0);",
206     " ",
207     "struct material",
208     "{",
209     "  vec4 ambient;",
210     "  vec4 diffuse;",
211     "  vec4 specular;",
212     "  float shininess;",
213     "};",
214     "material frontMaterial = material(",
215     "  vec4(1.0, 0.0, 0.0, 1.0),",
216     "  vec4(1.0, 0.0, 0.0, 1.0),",
217     "  vec4(1.0, 1.0, 1.0, 1.0),",
218     "  100.0",
219     ");",
220     " ",
221     "void main()",
222     "{",
223     "  vec3 normalDirection = normalize(varyingNormalDirection);",
224     "  /* vec3 viewDirection = normalize(vec3(v_inv * vec4(0.0, 0.0, 0.0, 1.0) - position)); */",
225     "  vec3 viewDirection = normalize(vec3(vec4(0.0, 0.0, 0.0, 1.0) - position));    /* in this demo, the view matrix is always an identity matrix */",
226     "  vec3 lightDirection;",
227     "  float attenuation;",
228     " ",
229     "  if (0.0 == light0.position.w) /* directional light? */",
230     "    {",
231     "      attenuation = 1.0; /* no attenuation */",
232     "      lightDirection = normalize(vec3(light0.position));",
233     "    } ",
234     "  else /* point light or spotlight (or other kind of light) */",
235     "    {",
236     "      vec3 positionToLightSource = vec3(light0.position - position);",
237     "      float distance = length(positionToLightSource);",
238     "      lightDirection = normalize(positionToLightSource);",
239     "      attenuation = 1.0 / (light0.constantAttenuation",
240     "                           + light0.linearAttenuation * distance",
241     "                           + light0.quadraticAttenuation * distance * distance);",
242     " ",
243     "      if (light0.spotCutoff <= 90.0) /* spotlight? */",
244     "        {",
245     "          float clampedCosine = max(0.0, dot(-lightDirection, light0.spotDirection));",
246     "          if (clampedCosine < cos(radians(light0.spotCutoff))) /* outside of spotlight cone? */",
247     "            {",
248     "              attenuation = 0.0;",
249     "            }",
250     "          else",
251     "            {",
252     "              attenuation = attenuation * pow(clampedCosine, light0.spotExponent);   ",
253     "            }",
254     "        }",
255     "    }",
256     " ",
257     "  vec3 ambientLighting = vec3(scene_ambient) * vec3(frontMaterial.ambient);",
258     " ",
259     "  vec3 diffuseReflection = attenuation ",
260     "    * vec3(light0.diffuse) * vec3(frontMaterial.diffuse)",
261     "    * max(0.0, dot(normalDirection, lightDirection));",
262     " ",
263     "  vec3 specularReflection;",
264     "  if (dot(normalDirection, lightDirection) < 0.0) /* light source on the wrong side? */",
265     "    {",
266     "      specularReflection = vec3(0.0, 0.0, 0.0); /* no specular reflection */",
267     "    }",
268     "  else /* light source on the right side */",
269     "    {",
270     "      specularReflection = attenuation * vec3(light0.specular) * vec3(frontMaterial.specular) ",
271     "        * pow(max(0.0, dot(reflect(-lightDirection, normalDirection), viewDirection)), frontMaterial.shininess);",
272     "    }",
273     " ",
274     "  gl_FragColor = vec4(ambientLighting + diffuseReflection + specularReflection, 1.0);",
275     "}"
276 };
277
278 GLint getAttribOrUniformLocation(const char* name, GLuint program, GLboolean isAttrib)
279 {
280     if (isAttrib)
281     {
282         GLint attrib = gl_GetAttribLocation(program, name);
283         if (attrib == -1)
284         {
285             fprintf(stderr, "Warning: Could not bind attrib %s\n", name);  
286         }
287
288         return attrib;
289     }
290     else
291     {
292         GLint uniform = gl_GetUniformLocation(program, name);
293         if (uniform == -1)
294         {
295             fprintf(stderr, "Warning: Could not bind uniform %s\n", name);  
296         }
297
298         return uniform;
299     }
300     checkError ("getAttribOrUniformLocation");
301 }
302
303 GLuint program;
304 GLint attribute_fg_coord = -1, attribute_fg_normal = -1;  
305 GLint uniform_m = -1, uniform_p = -1, uniform_m_3x3_inv_transp = -1;
306 GLint shaderReady = 0;  /* Set to 1 when all initialization went well, to -1 when shader somehow unusable. */
307
308
309
310 void compileAndCheck(GLuint shader)
311 {
312     GLint status;
313     gl_CompileShader (shader);
314     gl_GetShaderiv (shader, GL_COMPILE_STATUS, &status);
315     if (status == GL_FALSE) {
316         GLint infoLogLength;
317         ourGLchar *infoLog;
318         gl_GetShaderiv (shader, GL_INFO_LOG_LENGTH, &infoLogLength);
319         infoLog = (ourGLchar*) malloc (infoLogLength);
320         gl_GetShaderInfoLog (shader, infoLogLength, NULL, infoLog);
321         fprintf (stderr, "compile log: %s\n", infoLog);
322         free (infoLog);
323     }
324     checkError ("compileAndCheck");
325 }
326
327 GLuint compileShaderSource(GLenum type, GLsizei count, const ourGLchar **string)
328 {
329     GLuint shader = gl_CreateShader (type);
330     gl_ShaderSource (shader, count, string, NULL);
331
332     checkError ("compileShaderSource");
333
334     compileAndCheck (shader);
335     return shader;
336 }
337
338 void linkAndCheck(GLuint program)
339 {
340     GLint status;
341     gl_LinkProgram (program);
342     gl_GetProgramiv (program, GL_LINK_STATUS, &status);
343     if (status == GL_FALSE) {
344         GLint infoLogLength;
345         ourGLchar *infoLog;
346         gl_GetProgramiv (program, GL_INFO_LOG_LENGTH, &infoLogLength);
347         infoLog = (ourGLchar*) malloc (infoLogLength);
348         gl_GetProgramInfoLog (program, infoLogLength, NULL, infoLog);
349         fprintf (stderr, "link log: %s\n", infoLog);
350         free (infoLog);
351     }
352     checkError ("linkAndCheck");
353 }
354
355 void createProgram(GLuint vertexShader, GLuint fragmentShader)
356 {
357     program = gl_CreateProgram ();
358     if (vertexShader != 0) {
359         gl_AttachShader (program, vertexShader);
360     }
361     if (fragmentShader != 0) {
362         gl_AttachShader (program, fragmentShader);
363     }
364
365     checkError ("createProgram");
366
367     linkAndCheck (program);
368 }
369
370 void initShader(void)
371 {
372     const GLsizei vertexShaderLines = sizeof(vertexShaderSource) / sizeof(ourGLchar*);
373     GLuint vertexShader =
374         compileShaderSource (GL_VERTEX_SHADER, vertexShaderLines, vertexShaderSource);
375
376     const GLsizei fragmentShaderLines = sizeof(fragmentShaderSource) / sizeof(ourGLchar*);
377     GLuint fragmentShader =
378         compileShaderSource (GL_FRAGMENT_SHADER, fragmentShaderLines, fragmentShaderSource);
379
380     checkError ("initShader - 1");
381
382     createProgram (vertexShader, fragmentShader);
383
384     gl_UseProgram (program);
385
386     attribute_fg_coord      = getAttribOrUniformLocation("fg_coord"         , program, GL_TRUE);
387     attribute_fg_normal     = getAttribOrUniformLocation("fg_normal"        , program, GL_TRUE);
388     uniform_m               = getAttribOrUniformLocation("m"                , program, GL_FALSE);
389     uniform_p               = getAttribOrUniformLocation("p"                , program, GL_FALSE);
390     uniform_m_3x3_inv_transp= getAttribOrUniformLocation("m_3x3_inv_transp" , program, GL_FALSE);
391
392     gl_UseProgram (0);
393
394     if (attribute_fg_coord==-1 || attribute_fg_normal==-1 ||
395         uniform_m==-1 || uniform_p==-1 || uniform_m_3x3_inv_transp==-1)
396         shaderReady = -1;
397     else
398         shaderReady = 1;
399
400     checkError ("initShader - 2");
401 }
402
403 /*
404  * This macro is only intended to be used on arrays, of course.
405  */
406 #define NUMBEROF(x) ((sizeof(x))/(sizeof(x[0])))
407
408 /*
409  * These global variables control which object is drawn,
410  * and how it is drawn.  No object uses all of these
411  * variables.
412  */
413 static int function_index;
414 static int slices = 16;
415 static int stacks = 16;
416 static double irad = .25;
417 static double orad = 1.0;   /* doubles as size for objects other than Torus */
418 static int depth = 4;
419 static double offset[ 3 ] = { 0, 0, 0 };
420 static GLboolean show_info = GL_TRUE;
421 static float ar;
422 static GLboolean persProject = GL_TRUE;
423 static GLboolean animateXRot = GL_FALSE;
424 static GLboolean useShader   = GL_FALSE;
425 static GLboolean visNormals  = GL_FALSE;
426
427 /*
428  * Enum to tell drawSizeInfo what to draw for each object
429  */
430 #define GEO_NO_SIZE 0
431 #define GEO_SIZE 1
432 #define GEO_SCALE 2
433 #define GEO_INNER_OUTER_RAD 4
434 #define GEO_RAD 8
435 #define GEO_BASE_HEIGHT 16
436 #define GEO_RAD_HEIGHT 32
437
438 /*
439  * These one-liners draw particular objects, fetching appropriate
440  * information from the above globals.  They are just thin wrappers
441  * for the FreeGLUT objects.
442  */
443 static void drawSolidTetrahedron(void)         { glutSolidTetrahedron ();                        }
444 static void drawWireTetrahedron(void)          { glutWireTetrahedron ();                         }
445 static void drawSolidCube(void)                { glutSolidCube(orad);                            }  /* orad doubles as size input */
446 static void drawWireCube(void)                 { glutWireCube(orad);                             }  /* orad doubles as size input */
447 static void drawSolidOctahedron(void)          { glutSolidOctahedron ();                         }
448 static void drawWireOctahedron(void)           { glutWireOctahedron ();                          }
449 static void drawSolidDodecahedron(void)        { glutSolidDodecahedron ();                       }
450 static void drawWireDodecahedron(void)         { glutWireDodecahedron ();                        }
451 static void drawSolidRhombicDodecahedron(void) { glutSolidRhombicDodecahedron ();                }
452 static void drawWireRhombicDodecahedron(void)  { glutWireRhombicDodecahedron ();                 }
453 static void drawSolidIcosahedron(void)         { glutSolidIcosahedron ();                        }
454 static void drawWireIcosahedron(void)          { glutWireIcosahedron ();                         }
455 static void drawSolidSierpinskiSponge(void)    { glutSolidSierpinskiSponge (depth, offset, orad);}  /* orad doubles as size input */
456 static void drawWireSierpinskiSponge(void)     { glutWireSierpinskiSponge (depth, offset, orad); }  /* orad doubles as size input */
457 static void drawSolidTorus(void)               { glutSolidTorus(irad,orad,slices,stacks);        }
458 static void drawWireTorus(void)                { glutWireTorus (irad,orad,slices,stacks);        }
459 static void drawSolidSphere(void)              { glutSolidSphere(orad,slices,stacks);            }  /* orad doubles as size input */
460 static void drawWireSphere(void)               { glutWireSphere(orad,slices,stacks);             }  /* orad doubles as size input */
461 static void drawSolidCone(void)                { glutSolidCone(irad,orad,slices,stacks);         }  /* irad doubles as base input, and orad as height input */
462 static void drawWireCone(void)                 { glutWireCone(irad,orad,slices,stacks);          }  /* irad doubles as base input, and orad as height input */
463 static void drawSolidCylinder(void)            { glutSolidCylinder(irad,orad,slices,stacks);     }  /* irad doubles as radius input, and orad as height input */
464 static void drawWireCylinder(void)             { glutWireCylinder(irad,orad,slices,stacks);      }  /* irad doubles as radius input, and orad as height input */
465 /* per Glut manpage, it should be noted that the teapot is rendered
466  * with clockwise winding for front facing polygons...
467  * Same for the teacup and teaspoon
468  */
469 static void drawSolidTeapot(void)
470 {   glFrontFace(GL_CW);    glutSolidTeapot(orad);   glFrontFace(GL_CCW);    /* orad doubles as size input */}
471 static void drawWireTeapot(void)
472 {   glFrontFace(GL_CW);    glutWireTeapot(orad);    glFrontFace(GL_CCW);    /* orad doubles as size input */}
473 static void drawSolidTeacup(void)
474 {   glFrontFace(GL_CW);    glutSolidTeacup(orad);   glFrontFace(GL_CCW);    /* orad doubles as size input */}
475 static void drawWireTeacup(void)
476 {   glFrontFace(GL_CW);    glutWireTeacup(orad);    glFrontFace(GL_CCW);    /* orad doubles as size input */}
477 static void drawSolidTeaspoon(void)
478 {   glFrontFace(GL_CW);    glutSolidTeaspoon(orad); glFrontFace(GL_CCW);    /* orad doubles as size input */}
479 static void drawWireTeaspoon(void)
480 {   glFrontFace(GL_CW);    glutWireTeaspoon(orad);  glFrontFace(GL_CCW);    /* orad doubles as size input */}
481
482 #define RADIUSFAC    0.70710678118654752440084436210485f
483
484 static void drawSolidCuboctahedron(void)
485 {
486   GLfloat radius = RADIUSFAC*(GLfloat)orad; /* orad doubles as size */
487   glBegin( GL_TRIANGLES );
488     glNormal3d( 0.577350269189, 0.577350269189, 0.577350269189); glVertex3d( radius, radius, 0.0 ); glVertex3d( 0.0, radius, radius ); glVertex3d( radius, 0.0, radius );
489     glNormal3d( 0.577350269189, 0.577350269189,-0.577350269189); glVertex3d( radius, radius, 0.0 ); glVertex3d( radius, 0.0,-radius ); glVertex3d( 0.0, radius,-radius );
490     glNormal3d( 0.577350269189,-0.577350269189, 0.577350269189); glVertex3d( radius,-radius, 0.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( 0.0,-radius, radius );
491     glNormal3d( 0.577350269189,-0.577350269189,-0.577350269189); glVertex3d( radius,-radius, 0.0 ); glVertex3d( 0.0,-radius,-radius ); glVertex3d( radius, 0.0,-radius );
492     glNormal3d(-0.577350269189, 0.577350269189, 0.577350269189); glVertex3d(-radius, radius, 0.0 ); glVertex3d(-radius, 0.0, radius ); glVertex3d( 0.0, radius, radius );
493     glNormal3d(-0.577350269189, 0.577350269189,-0.577350269189); glVertex3d(-radius, radius, 0.0 ); glVertex3d( 0.0, radius,-radius ); glVertex3d(-radius, 0.0,-radius );
494     glNormal3d(-0.577350269189,-0.577350269189, 0.577350269189); glVertex3d(-radius,-radius, 0.0 ); glVertex3d( 0.0,-radius, radius ); glVertex3d(-radius, 0.0, radius );
495     glNormal3d(-0.577350269189,-0.577350269189,-0.577350269189); glVertex3d(-radius,-radius, 0.0 ); glVertex3d(-radius, 0.0,-radius ); glVertex3d( 0.0,-radius,-radius );
496   glEnd();
497
498   glBegin( GL_QUADS );
499     glNormal3d( 1.0, 0.0, 0.0 ); glVertex3d( radius, radius, 0.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( radius,-radius, 0.0 ); glVertex3d( radius, 0.0,-radius );
500     glNormal3d(-1.0, 0.0, 0.0 ); glVertex3d(-radius, radius, 0.0 ); glVertex3d(-radius, 0.0,-radius ); glVertex3d(-radius,-radius, 0.0 ); glVertex3d(-radius, 0.0, radius );
501     glNormal3d( 0.0, 1.0, 0.0 ); glVertex3d( radius, radius, 0.0 ); glVertex3d( 0.0, radius,-radius ); glVertex3d(-radius, radius, 0.0 ); glVertex3d( 0.0, radius, radius );
502     glNormal3d( 0.0,-1.0, 0.0 ); glVertex3d( radius,-radius, 0.0 ); glVertex3d( 0.0,-radius, radius ); glVertex3d(-radius,-radius, 0.0 ); glVertex3d( 0.0,-radius,-radius );
503     glNormal3d( 0.0, 0.0, 1.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( 0.0, radius, radius ); glVertex3d(-radius, 0.0, radius ); glVertex3d( 0.0,-radius, radius );
504     glNormal3d( 0.0, 0.0,-1.0 ); glVertex3d( radius, 0.0,-radius ); glVertex3d( 0.0,-radius,-radius ); glVertex3d(-radius, 0.0,-radius ); glVertex3d( 0.0, radius,-radius );
505   glEnd();
506 }
507
508 static void drawWireCuboctahedron(void)
509 {
510   GLfloat radius = RADIUSFAC*(GLfloat)orad; /* orad doubles as size */
511   glBegin( GL_LINE_LOOP );
512     glNormal3d( 1.0, 0.0, 0.0 ); glVertex3d( radius, radius, 0.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( radius,-radius, 0.0 ); glVertex3d( radius, 0.0,-radius );
513   glEnd();
514   glBegin( GL_LINE_LOOP );
515     glNormal3d(-1.0, 0.0, 0.0 ); glVertex3d(-radius, radius, 0.0 ); glVertex3d(-radius, 0.0,-radius ); glVertex3d(-radius,-radius, 0.0 ); glVertex3d(-radius, 0.0, radius );
516   glEnd();
517   glBegin( GL_LINE_LOOP );
518     glNormal3d( 0.0, 1.0, 0.0 ); glVertex3d( radius, radius, 0.0 ); glVertex3d( 0.0, radius,-radius ); glVertex3d(-radius, radius, 0.0 ); glVertex3d( 0.0, radius, radius );
519   glEnd();
520   glBegin( GL_LINE_LOOP );
521     glNormal3d( 0.0,-1.0, 0.0 ); glVertex3d( radius,-radius, 0.0 ); glVertex3d( 0.0,-radius, radius ); glVertex3d(-radius,-radius, 0.0 ); glVertex3d( 0.0,-radius,-radius );
522   glEnd();
523   glBegin( GL_LINE_LOOP );
524     glNormal3d( 0.0, 0.0, 1.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( 0.0, radius, radius ); glVertex3d(-radius, 0.0, radius ); glVertex3d( 0.0,-radius, radius );
525   glEnd();
526   glBegin( GL_LINE_LOOP );
527     glNormal3d( 0.0, 0.0,-1.0 ); glVertex3d( radius, 0.0,-radius ); glVertex3d( 0.0,-radius,-radius ); glVertex3d(-radius, 0.0,-radius ); glVertex3d( 0.0, radius,-radius );
528   glEnd();
529 }
530
531 #undef RADIUSFAC
532
533 /*
534  * This structure defines an entry in our function-table.
535  */
536 typedef struct
537 {
538     const char * const name;
539     void (*solid) (void);
540     void (*wire)  (void);
541     int drawSizeInfoFlag;
542 } entry;
543
544 #define ENTRY(e,f) {#e, drawSolid##e, drawWire##e,f}
545 static const entry table [] =
546 {
547     ENTRY (Tetrahedron,GEO_NO_SIZE),
548     ENTRY (Cube,GEO_SIZE),
549     ENTRY (Octahedron,GEO_NO_SIZE),
550     ENTRY (Dodecahedron,GEO_NO_SIZE),
551     ENTRY (RhombicDodecahedron,GEO_NO_SIZE),
552     ENTRY (Icosahedron,GEO_NO_SIZE),
553     ENTRY (SierpinskiSponge,GEO_SCALE),
554     ENTRY (Teapot,GEO_SIZE),
555     ENTRY (Teacup,GEO_SIZE),
556     ENTRY (Teaspoon,GEO_SIZE),
557     ENTRY (Torus,GEO_INNER_OUTER_RAD),
558     ENTRY (Sphere,GEO_RAD),
559     ENTRY (Cone,GEO_BASE_HEIGHT),
560     ENTRY (Cylinder,GEO_RAD_HEIGHT),
561     ENTRY (Cuboctahedron,GEO_SIZE)   /* This one doesn't work when in shader mode and is then skipped */
562 };
563 #undef ENTRY
564
565 /*!
566     Does printf()-like work using freeglut
567     glutBitmapString().  Uses a fixed font.  Prints
568     at the indicated row/column position.
569
570     Limitation: Cannot address pixels.
571     Limitation: Renders in screen coords, not model coords.
572 */
573 static void shapesPrintf (int row, int col, const char *fmt, ...)
574 {
575     static char buf[256];
576     int viewport[4];
577     void *font = GLUT_BITMAP_9_BY_15;
578     va_list args;
579
580     va_start(args, fmt);
581 #if defined(WIN32) && !defined(__CYGWIN__)
582     (void) _vsnprintf (buf, sizeof(buf), fmt, args);
583 #else
584     (void) vsnprintf (buf, sizeof(buf), fmt, args);
585 #endif
586     va_end(args);
587
588     glGetIntegerv(GL_VIEWPORT,viewport);
589
590     glPushMatrix();
591     glLoadIdentity();
592
593     glMatrixMode(GL_PROJECTION);
594     glPushMatrix();
595     glLoadIdentity();
596
597         glOrtho(0,viewport[2],0,viewport[3],-1,1);
598
599         glRasterPos2i
600         (
601               glutBitmapWidth(font, ' ') * col,
602             - glutBitmapHeight(font) * row + viewport[3]
603         );
604         glutBitmapString (font, (unsigned char*)buf);
605
606     glPopMatrix();
607     glMatrixMode(GL_MODELVIEW);
608     glPopMatrix();
609 }
610
611 /* Print info about the about the current shape and render state on the screen */
612 static void DrawSizeInfo(int *row)
613 {
614     switch (table [function_index].drawSizeInfoFlag)
615     {
616     case GEO_NO_SIZE:
617         break;
618     case GEO_SIZE:
619         shapesPrintf ((*row)++, 1, "Size  Up  Down : %f", orad);
620         break;
621     case GEO_SCALE:
622         shapesPrintf ((*row)++, 1, "Scale  Up  Down : %f", orad);
623         break;
624     case GEO_INNER_OUTER_RAD:
625         shapesPrintf ((*row)++, 1, "Inner radius Left Right: %f", irad);
626         shapesPrintf ((*row)++, 1, "Outer radius  Up  Down : %f", orad);
627         break;
628     case GEO_RAD:
629         shapesPrintf ((*row)++, 1, "Radius  Up  Down : %f", orad);
630         break;
631     case GEO_BASE_HEIGHT:
632         shapesPrintf ((*row)++, 1, "Base   Left Right: %f", irad);
633         shapesPrintf ((*row)++, 1, "Height  Up  Down : %f", orad);
634         break;
635     case GEO_RAD_HEIGHT:
636         shapesPrintf ((*row)++, 1, "Radius Left Right: %f", irad);
637         shapesPrintf ((*row)++, 1, "Height  Up  Down : %f", orad);
638         break;
639     }
640 }
641
642 static void drawInfo()
643 {
644     int row = 1;
645     shapesPrintf (row++, 1, "Shape PgUp PgDn: %s", table [function_index].name);
646     shapesPrintf (row++, 1, "Slices +-: %d   Stacks <>: %d", slices, stacks);
647     shapesPrintf (row++, 1, "nSides +-: %d   nRings <>: %d", slices, stacks);
648     shapesPrintf (row++, 1, "Depth  (): %d", depth);
649     DrawSizeInfo(&row);
650     if (persProject)
651         shapesPrintf (row++, 1, "Perspective projection (p)");
652     else
653         shapesPrintf (row++, 1, "Orthographic projection (p)");
654     if (useShader)
655         shapesPrintf (row++, 1, "Using shader (s)");
656     else
657         shapesPrintf (row++, 1, "Using fixed function pipeline (s)");
658     if (animateXRot)
659         shapesPrintf (row++, 1, "2D rotation (r)");
660     else
661         shapesPrintf (row++, 1, "1D rotation (r)");
662     shapesPrintf (row++, 1, "visualizing normals: %i (n)",visNormals);
663 }
664
665 /* GLUT callback Handlers */
666 static void
667 resize(int width, int height)
668 {
669     ar = (float) width / (float) height;
670
671     glViewport(0, 0, width, height);
672 }
673
674 static void display(void)
675 {
676     const double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0;
677     const double a = t*89.0;
678     const double b = (animateXRot?t:1)*67.0;
679
680     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
681
682     glutSetOption(GLUT_GEOMETRY_VISUALIZE_NORMALS,visNormals);  /* Normals visualized or not? */
683
684     if (useShader && !shaderReady)
685         initShader();
686
687     if (useShader && shaderReady)
688     {
689         /* setup use of shader (and vertex buffer by FreeGLUT) */
690         gl_UseProgram (program);
691         glutSetVertexAttribCoord3(attribute_fg_coord);
692         glutSetVertexAttribNormal(attribute_fg_normal);
693         /* There is also a glutSetVertexAttribTexCoord2, which is used only when drawing the teapot, teacup or teaspoon */
694
695         gl_matrix_mode(GL_PROJECTION);
696         gl_load_identity();
697         if (persProject)
698             gl_frustum(-ar, ar, -1.f, 1.f, 2.f, 100.f);
699         else
700             gl_ortho(-ar*3, ar*3, -3.f, 3.f, 2.f, 100.f);
701         gl_UniformMatrix4fv (uniform_p, 1, GL_FALSE, get_matrix(GL_PROJECTION));
702
703
704         gl_matrix_mode(GL_MODELVIEW);
705         gl_load_identity();
706
707         gl_push_matrix();
708             /* Not in reverse order like normal OpenGL, our util library multiplies the matrices in the order they are specified in */
709             gl_rotatef((float)a,0,0,1);
710             gl_rotatef((float)b,1,0,0);
711             gl_translatef(0,1.2f,-6);
712             gl_UniformMatrix4fv (uniform_m               , 1, GL_FALSE, get_matrix(GL_MODELVIEW));
713             gl_UniformMatrix3fv (uniform_m_3x3_inv_transp, 1, GL_FALSE, get_inv_transpose_3x3(GL_MODELVIEW));
714             table [function_index].solid ();
715         gl_pop_matrix();
716
717         gl_push_matrix();
718             gl_rotatef((float)a,0,0,1);
719             gl_rotatef((float)b,1,0,0);
720             gl_translatef(0,-1.2f,-6);
721             gl_UniformMatrix4fv (uniform_m               , 1, GL_FALSE, get_matrix(GL_MODELVIEW));
722             gl_UniformMatrix3fv (uniform_m_3x3_inv_transp, 1, GL_FALSE, get_inv_transpose_3x3(GL_MODELVIEW));
723             table [function_index].wire ();
724         gl_pop_matrix();
725
726         gl_UseProgram (0);
727         glutSetVertexAttribCoord3(-1);
728         glutSetVertexAttribNormal(-1);
729
730         checkError ("display");
731     }
732     else
733     {
734         /* fixed function pipeline */
735         glMatrixMode(GL_PROJECTION);
736         glLoadIdentity();
737         if (persProject)
738             glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0);
739         else
740             glOrtho(-ar*3, ar*3, -3.0, 3.0, 2.0, 100.0);
741         glMatrixMode(GL_MODELVIEW);
742         glLoadIdentity();
743
744         glEnable(GL_LIGHTING);
745
746         glColor3d(1,0,0);
747
748         glPushMatrix();
749             glTranslated(0,1.2,-6);
750             glRotated(b,1,0,0);
751             glRotated(a,0,0,1);
752             table [function_index].solid ();
753         glPopMatrix();
754
755         glPushMatrix();
756             glTranslated(0,-1.2,-6);
757             glRotated(b,1,0,0);
758             glRotated(a,0,0,1);
759             table [function_index].wire ();
760         glPopMatrix();
761
762         glDisable(GL_LIGHTING);
763         glColor3d(0.1,0.1,0.4);
764     }
765
766     if( show_info )
767         /* print info to screen */
768         drawInfo();
769     else
770         /* print to command line instead */
771         printf ( "Shape %d slides %d stacks %d\n", function_index, slices, stacks ) ;
772
773     glutSwapBuffers();
774 }
775
776
777 static void
778 key(unsigned char key, int x, int y)
779 {
780     switch (key)
781     {
782     case 27 :
783     case 'Q':
784     case 'q': glutLeaveMainLoop () ;      break;
785
786     case 'I':
787     case 'i': show_info=!show_info;       break;
788
789     case '=':
790     case '+': slices++;                   break;
791
792     case '-':
793     case '_': if( slices > -1 ) slices--; break;
794
795     case ',':
796     case '<': if( stacks > -1 ) stacks--; break;
797
798     case '.':
799     case '>': stacks++;                   break;
800
801     case '9': 
802     case '(': if( depth > -1 ) depth--;   break;
803
804     case '0': 
805     case ')': ++depth;                    break;
806
807     case 'P':
808     case 'p': persProject=!persProject;   break;
809
810     case 'R':
811     case 'r': animateXRot=!animateXRot;   break;
812
813     case 'S':
814     case 's':
815         useShader=!useShader;
816         /* Cuboctahedron can't be shown when in shader mode, move to next */
817         if (useShader && NUMBEROF (table)-1 == ( unsigned )function_index)
818                 function_index = 0;
819         break;
820
821     case 'N':
822     case 'n': visNormals=!visNormals;     break;
823
824     default:
825         break;
826     }
827
828     glutPostRedisplay();
829 }
830
831 static void special (int key, int x, int y)
832 {
833     switch (key)
834     {
835     case GLUT_KEY_PAGE_UP:    ++function_index; break;
836     case GLUT_KEY_PAGE_DOWN:  --function_index; break;
837     case GLUT_KEY_UP:         orad *= 2;        break;
838     case GLUT_KEY_DOWN:       orad /= 2;        break;
839
840     case GLUT_KEY_RIGHT:      irad *= 2;        break;
841     case GLUT_KEY_LEFT:       irad /= 2;        break;
842
843     default:
844         break;
845     }
846
847     if (0 > function_index)
848         function_index = NUMBEROF (table) - 1;
849
850     if (NUMBEROF (table) <= ( unsigned )function_index)
851         function_index = 0;
852
853     /* Cuboctahedron can't be shown when in shader mode, skip it */
854     if (useShader && NUMBEROF (table)-1 == ( unsigned )function_index)
855         if (key==GLUT_KEY_PAGE_UP)
856             function_index = 0;
857         else
858             function_index -= 1;
859 }
860
861
862 static void
863 idle(void)
864 {
865     glutPostRedisplay();
866 }
867
868 const GLfloat light_ambient[]  = { 0.0f, 0.0f, 0.0f, 1.0f };
869 const GLfloat light_diffuse[]  = { 1.0f, 1.0f, 1.0f, 1.0f };
870 const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
871 const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f };
872
873 const GLfloat mat_ambient[]    = { 0.7f, 0.7f, 0.7f, 1.0f };
874 const GLfloat mat_diffuse[]    = { 0.8f, 0.8f, 0.8f, 1.0f };
875 const GLfloat mat_specular[]   = { 1.0f, 1.0f, 1.0f, 1.0f };
876 const GLfloat high_shininess[] = { 100.0f };
877
878 /* Program entry point */
879
880 int
881 main(int argc, char *argv[])
882 {
883     glutInitWindowSize(800,600);
884     glutInitWindowPosition(40,40);
885     glutInit(&argc, argv);
886     glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE);
887
888     glutCreateWindow("FreeGLUT Shapes");
889
890     glutReshapeFunc(resize);
891     glutDisplayFunc(display);
892     glutKeyboardFunc(key);
893     glutSpecialFunc(special);
894     glutIdleFunc(idle);
895
896     glutSetOption ( GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION ) ;
897
898     glClearColor(1,1,1,1);
899     glEnable(GL_CULL_FACE);
900     glCullFace(GL_BACK);
901
902     glEnable(GL_DEPTH_TEST);
903     glDepthFunc(GL_LESS);
904
905     glEnable(GL_LIGHT0);
906     glEnable(GL_NORMALIZE);
907     glEnable(GL_COLOR_MATERIAL);
908
909     glLightfv(GL_LIGHT0, GL_AMBIENT,  light_ambient);
910     glLightfv(GL_LIGHT0, GL_DIFFUSE,  light_diffuse);
911     glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
912     glLightfv(GL_LIGHT0, GL_POSITION, light_position);
913
914     glMaterialfv(GL_FRONT, GL_AMBIENT,   mat_ambient);
915     glMaterialfv(GL_FRONT, GL_DIFFUSE,   mat_diffuse);
916     glMaterialfv(GL_FRONT, GL_SPECULAR,  mat_specular);
917     glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
918
919     initExtensionEntries();
920
921     glutMainLoop();
922
923 #ifdef _MSC_VER
924     /* DUMP MEMORY LEAK INFORMATION */
925     _CrtDumpMemoryLeaks () ;
926 #endif
927
928     return EXIT_SUCCESS;
929 }