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