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