1 /*
2  * Copyright (C) 1999-2001  Brian Paul   All Rights Reserved.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included
12  * in all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
18  * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20  */
21 
22 /*
23  * Ported to GLES2.
24  * Kristian Høgsberg <krh@bitplanet.net>
25  * May 3, 2010
26  *
27  * Improve GLES2 port:
28  *   * Refactor gear drawing.
29  *   * Use correct normals for surfaces.
30  *   * Improve shader.
31  *   * Use perspective projection transformation.
32  *   * Add FPS count.
33  *   * Add comments.
34  * Alexandros Frantzis <alexandros.frantzis@linaro.org>
35  * Jul 13, 2010
36  */
37 
38 #define GL_GLEXT_PROTOTYPES
39 #define EGL_EGLEXT_PROTOTYPES
40 
41 #define _GNU_SOURCE
42 
43 #include <math.h>
44 #include <stdlib.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <sys/time.h>
48 #include <unistd.h>
49 #ifdef __APPLE__
50 #include <OpenGL/gl.h>
51 #include <Glut/glut.h>
52 #else
53 #include <GL/gl.h>
54 #include <GL/glut.h>
55 #endif
56 
57 #define STRIPS_PER_TOOTH 7
58 #define VERTICES_PER_TOOTH 34
59 #define GEAR_VERTEX_STRIDE 6
60 
61 #ifndef HAVE_BUILTIN_SINCOS
62 #define sincos _sincos
63 static void
sincos(double a,double * s,double * c)64 sincos (double a, double *s, double *c)
65 {
66   *s = sin (a);
67   *c = cos (a);
68 }
69 #endif
70 
71 /**
72  * Struct describing the vertices in triangle strip
73  */
74 struct vertex_strip {
75    /** The first vertex in the strip */
76    GLint first;
77    /** The number of consecutive vertices in the strip after the first */
78    GLint count;
79 };
80 
81 /* Each vertex consist of GEAR_VERTEX_STRIDE GLfloat attributes */
82 typedef GLfloat GearVertex[GEAR_VERTEX_STRIDE];
83 
84 /**
85  * Struct representing a gear.
86  */
87 struct gear {
88    /** The array of vertices comprising the gear */
89    GearVertex *vertices;
90    /** The number of vertices comprising the gear */
91    int nvertices;
92    /** The array of triangle strips comprising the gear */
93    struct vertex_strip *strips;
94    /** The number of triangle strips comprising the gear */
95    int nstrips;
96    /** The Vertex Buffer Object holding the vertices in the graphics card */
97    GLuint vbo;
98 };
99 
100 /** The view rotation [x, y, z] */
101 static GLfloat view_rot[3] = { 20.0, 30.0, 0.0 };
102 /** The gears */
103 static struct gear *gear1, *gear2, *gear3;
104 /** The current gear rotation angle */
105 static GLfloat angle = 0.0;
106 /** The location of the shader uniforms */
107 static GLuint ModelViewProjectionMatrix_location,
108               NormalMatrix_location,
109               LightSourcePosition_location,
110               MaterialColor_location;
111 /** The projection matrix */
112 static GLfloat ProjectionMatrix[16];
113 /** The direction of the directional light for the scene */
114 static const GLfloat LightSourcePosition[4] = { 5.0, 5.0, 10.0, 1.0};
115 
116 /**
117  * Fills a gear vertex.
118  *
119  * @param v the vertex to fill
120  * @param x the x coordinate
121  * @param y the y coordinate
122  * @param z the z coortinate
123  * @param n pointer to the normal table
124  *
125  * @return the operation error code
126  */
127 static GearVertex *
vert(GearVertex * v,GLfloat x,GLfloat y,GLfloat z,GLfloat n[3])128 vert(GearVertex *v, GLfloat x, GLfloat y, GLfloat z, GLfloat n[3])
129 {
130    v[0][0] = x;
131    v[0][1] = y;
132    v[0][2] = z;
133    v[0][3] = n[0];
134    v[0][4] = n[1];
135    v[0][5] = n[2];
136 
137    return v + 1;
138 }
139 
140 /**
141  *  Create a gear wheel.
142  *
143  *  @param inner_radius radius of hole at center
144  *  @param outer_radius radius at center of teeth
145  *  @param width width of gear
146  *  @param teeth number of teeth
147  *  @param tooth_depth depth of tooth
148  *
149  *  @return pointer to the constructed struct gear
150  */
151 static struct gear *
create_gear(GLfloat inner_radius,GLfloat outer_radius,GLfloat width,GLint teeth,GLfloat tooth_depth)152 create_gear(GLfloat inner_radius, GLfloat outer_radius, GLfloat width,
153       GLint teeth, GLfloat tooth_depth)
154 {
155    GLfloat r0, r1, r2;
156    GLfloat da;
157    GearVertex *v;
158    struct gear *gear;
159    double s[5], c[5];
160    GLfloat normal[3];
161    int cur_strip = 0;
162    int i;
163 
164    /* Allocate memory for the gear */
165    gear = malloc(sizeof *gear);
166    if (gear == NULL)
167       return NULL;
168 
169    /* Calculate the radii used in the gear */
170    r0 = inner_radius;
171    r1 = outer_radius - tooth_depth / 2.0;
172    r2 = outer_radius + tooth_depth / 2.0;
173 
174    da = 2.0 * M_PI / teeth / 4.0;
175 
176    /* Allocate memory for the triangle strip information */
177    gear->nstrips = STRIPS_PER_TOOTH * teeth;
178    gear->strips = calloc(gear->nstrips, sizeof (*gear->strips));
179 
180    /* Allocate memory for the vertices */
181    gear->vertices = calloc(VERTICES_PER_TOOTH * teeth, sizeof(*gear->vertices));
182    v = gear->vertices;
183 
184    for (i = 0; i < teeth; i++) {
185       /* Calculate needed sin/cos for varius angles */
186       sincos(i * 2.0 * M_PI / teeth, &s[0], &c[0]);
187       sincos(i * 2.0 * M_PI / teeth + da, &s[1], &c[1]);
188       sincos(i * 2.0 * M_PI / teeth + da * 2, &s[2], &c[2]);
189       sincos(i * 2.0 * M_PI / teeth + da * 3, &s[3], &c[3]);
190       sincos(i * 2.0 * M_PI / teeth + da * 4, &s[4], &c[4]);
191 
192       /* A set of macros for making the creation of the gears easier */
193 #define  GEAR_POINT(r, da) { (r) * c[(da)], (r) * s[(da)] }
194 #define  SET_NORMAL(x, y, z) do { \
195    normal[0] = (x); normal[1] = (y); normal[2] = (z); \
196 } while(0)
197 
198 #define  GEAR_VERT(v, point, sign) vert((v), p[(point)].x, p[(point)].y, (sign) * width * 0.5, normal)
199 
200 #define START_STRIP do { \
201    gear->strips[cur_strip].first = v - gear->vertices; \
202 } while(0);
203 
204 #define END_STRIP do { \
205    int _tmp = (v - gear->vertices); \
206    gear->strips[cur_strip].count = _tmp - gear->strips[cur_strip].first; \
207    cur_strip++; \
208 } while (0)
209 
210 #define QUAD_WITH_NORMAL(p1, p2) do { \
211    SET_NORMAL((p[(p1)].y - p[(p2)].y), -(p[(p1)].x - p[(p2)].x), 0); \
212    v = GEAR_VERT(v, (p1), -1); \
213    v = GEAR_VERT(v, (p1), 1); \
214    v = GEAR_VERT(v, (p2), -1); \
215    v = GEAR_VERT(v, (p2), 1); \
216 } while(0)
217 
218       struct point {
219          GLfloat x;
220          GLfloat y;
221       };
222 
223       /* Create the 7 points (only x,y coords) used to draw a tooth */
224       struct point p[7] = {
225          GEAR_POINT(r2, 1), // 0
226          GEAR_POINT(r2, 2), // 1
227          GEAR_POINT(r1, 0), // 2
228          GEAR_POINT(r1, 3), // 3
229          GEAR_POINT(r0, 0), // 4
230          GEAR_POINT(r1, 4), // 5
231          GEAR_POINT(r0, 4), // 6
232       };
233 
234       /* Front face */
235       START_STRIP;
236       SET_NORMAL(0, 0, 1.0);
237       v = GEAR_VERT(v, 0, +1);
238       v = GEAR_VERT(v, 1, +1);
239       v = GEAR_VERT(v, 2, +1);
240       v = GEAR_VERT(v, 3, +1);
241       v = GEAR_VERT(v, 4, +1);
242       v = GEAR_VERT(v, 5, +1);
243       v = GEAR_VERT(v, 6, +1);
244       END_STRIP;
245 
246       /* Inner face */
247       START_STRIP;
248       QUAD_WITH_NORMAL(4, 6);
249       END_STRIP;
250 
251       /* Back face */
252       START_STRIP;
253       SET_NORMAL(0, 0, -1.0);
254       v = GEAR_VERT(v, 6, -1);
255       v = GEAR_VERT(v, 5, -1);
256       v = GEAR_VERT(v, 4, -1);
257       v = GEAR_VERT(v, 3, -1);
258       v = GEAR_VERT(v, 2, -1);
259       v = GEAR_VERT(v, 1, -1);
260       v = GEAR_VERT(v, 0, -1);
261       END_STRIP;
262 
263       /* Outer face */
264       START_STRIP;
265       QUAD_WITH_NORMAL(0, 2);
266       END_STRIP;
267 
268       START_STRIP;
269       QUAD_WITH_NORMAL(1, 0);
270       END_STRIP;
271 
272       START_STRIP;
273       QUAD_WITH_NORMAL(3, 1);
274       END_STRIP;
275 
276       START_STRIP;
277       QUAD_WITH_NORMAL(5, 3);
278       END_STRIP;
279    }
280 
281    gear->nvertices = (v - gear->vertices);
282 
283    /* Store the vertices in a vertex buffer object (VBO) */
284    glGenBuffers(1, &gear->vbo);
285    glBindBuffer(GL_ARRAY_BUFFER, gear->vbo);
286    glBufferData(GL_ARRAY_BUFFER, gear->nvertices * sizeof(GearVertex),
287          gear->vertices, GL_STATIC_DRAW);
288 
289    return gear;
290 }
291 
292 /**
293  * Multiplies two 4x4 matrices.
294  *
295  * The result is stored in matrix m.
296  *
297  * @param m the first matrix to multiply
298  * @param n the second matrix to multiply
299  */
300 static void
multiply(GLfloat * m,const GLfloat * n)301 multiply(GLfloat *m, const GLfloat *n)
302 {
303    GLfloat tmp[16];
304    const GLfloat *row, *column;
305    div_t d;
306    int i, j;
307 
308    for (i = 0; i < 16; i++) {
309       tmp[i] = 0;
310       d = div(i, 4);
311       row = n + d.quot * 4;
312       column = m + d.rem;
313       for (j = 0; j < 4; j++)
314          tmp[i] += row[j] * column[j * 4];
315    }
316    memcpy(m, &tmp, sizeof tmp);
317 }
318 
319 /**
320  * Rotates a 4x4 matrix.
321  *
322  * @param[in,out] m the matrix to rotate
323  * @param angle the angle to rotate
324  * @param x the x component of the direction to rotate to
325  * @param y the y component of the direction to rotate to
326  * @param z the z component of the direction to rotate to
327  */
328 static void
rotate(GLfloat * m,GLfloat angle,GLfloat x,GLfloat y,GLfloat z)329 rotate(GLfloat *m, GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
330 {
331    double s, c;
332 
333    sincos(angle, &s, &c);
334    GLfloat r[16] = {
335       x * x * (1 - c) + c,     y * x * (1 - c) + z * s, x * z * (1 - c) - y * s, 0,
336       x * y * (1 - c) - z * s, y * y * (1 - c) + c,     y * z * (1 - c) + x * s, 0,
337       x * z * (1 - c) + y * s, y * z * (1 - c) - x * s, z * z * (1 - c) + c,     0,
338       0, 0, 0, 1
339    };
340 
341    multiply(m, r);
342 }
343 
344 
345 /**
346  * Translates a 4x4 matrix.
347  *
348  * @param[in,out] m the matrix to translate
349  * @param x the x component of the direction to translate to
350  * @param y the y component of the direction to translate to
351  * @param z the z component of the direction to translate to
352  */
353 static void
translate(GLfloat * m,GLfloat x,GLfloat y,GLfloat z)354 translate(GLfloat *m, GLfloat x, GLfloat y, GLfloat z)
355 {
356    GLfloat t[16] = { 1, 0, 0, 0,  0, 1, 0, 0,  0, 0, 1, 0,  x, y, z, 1 };
357 
358    multiply(m, t);
359 }
360 
361 /**
362  * Creates an identity 4x4 matrix.
363  *
364  * @param m the matrix make an identity matrix
365  */
366 static void
identity(GLfloat * m)367 identity(GLfloat *m)
368 {
369    GLfloat t[16] = {
370       1.0, 0.0, 0.0, 0.0,
371       0.0, 1.0, 0.0, 0.0,
372       0.0, 0.0, 1.0, 0.0,
373       0.0, 0.0, 0.0, 1.0,
374    };
375 
376    memcpy(m, t, sizeof(t));
377 }
378 
379 /**
380  * Transposes a 4x4 matrix.
381  *
382  * @param m the matrix to transpose
383  */
384 static void
transpose(GLfloat * m)385 transpose(GLfloat *m)
386 {
387    GLfloat t[16] = {
388       m[0], m[4], m[8],  m[12],
389       m[1], m[5], m[9],  m[13],
390       m[2], m[6], m[10], m[14],
391       m[3], m[7], m[11], m[15]};
392 
393    memcpy(m, t, sizeof(t));
394 }
395 
396 /**
397  * Inverts a 4x4 matrix.
398  *
399  * This function can currently handle only pure translation-rotation matrices.
400  * Read http://www.gamedev.net/community/forums/topic.asp?topic_id=425118
401  * for an explanation.
402  */
403 static void
invert(GLfloat * m)404 invert(GLfloat *m)
405 {
406    GLfloat t[16];
407    identity(t);
408 
409    // Extract and invert the translation part 't'. The inverse of a
410    // translation matrix can be calculated by negating the translation
411    // coordinates.
412    t[12] = -m[12]; t[13] = -m[13]; t[14] = -m[14];
413 
414    // Invert the rotation part 'r'. The inverse of a rotation matrix is
415    // equal to its transpose.
416    m[12] = m[13] = m[14] = 0;
417    transpose(m);
418 
419    // inv(m) = inv(r) * inv(t)
420    multiply(m, t);
421 }
422 
423 /**
424  * Calculate a perspective projection transformation.
425  *
426  * @param m the matrix to save the transformation in
427  * @param fovy the field of view in the y direction
428  * @param aspect the view aspect ratio
429  * @param zNear the near clipping plane
430  * @param zFar the far clipping plane
431  */
perspective(GLfloat * m,GLfloat fovy,GLfloat aspect,GLfloat zNear,GLfloat zFar)432 void perspective(GLfloat *m, GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar)
433 {
434    GLfloat tmp[16];
435    identity(tmp);
436 
437    double sine, cosine, cotangent, deltaZ;
438    GLfloat radians = fovy / 2 * M_PI / 180;
439 
440    deltaZ = zFar - zNear;
441    sincos(radians, &sine, &cosine);
442 
443    if ((deltaZ == 0) || (sine == 0) || (aspect == 0))
444       return;
445 
446    cotangent = cosine / sine;
447 
448    tmp[0] = cotangent / aspect;
449    tmp[5] = cotangent;
450    tmp[10] = -(zFar + zNear) / deltaZ;
451    tmp[11] = -1;
452    tmp[14] = -2 * zNear * zFar / deltaZ;
453    tmp[15] = 0;
454 
455    memcpy(m, tmp, sizeof(tmp));
456 }
457 
458 /**
459  * Draws a gear.
460  *
461  * @param gear the gear to draw
462  * @param transform the current transformation matrix
463  * @param x the x position to draw the gear at
464  * @param y the y position to draw the gear at
465  * @param angle the rotation angle of the gear
466  * @param color the color of the gear
467  */
468 static void
draw_gear(struct gear * gear,GLfloat * transform,GLfloat x,GLfloat y,GLfloat angle,const GLfloat color[4])469 draw_gear(struct gear *gear, GLfloat *transform,
470       GLfloat x, GLfloat y, GLfloat angle, const GLfloat color[4])
471 {
472    GLfloat model_view[16];
473    GLfloat normal_matrix[16];
474    GLfloat model_view_projection[16];
475 
476    /* Translate and rotate the gear */
477    memcpy(model_view, transform, sizeof (model_view));
478    translate(model_view, x, y, 0);
479    rotate(model_view, 2 * M_PI * angle / 360.0, 0, 0, 1);
480 
481    /* Create and set the ModelViewProjectionMatrix */
482    memcpy(model_view_projection, ProjectionMatrix, sizeof(model_view_projection));
483    multiply(model_view_projection, model_view);
484 
485    glUniformMatrix4fv(ModelViewProjectionMatrix_location, 1, GL_FALSE,
486                       model_view_projection);
487 
488    /*
489     * Create and set the NormalMatrix. It's the inverse transpose of the
490     * ModelView matrix.
491     */
492    memcpy(normal_matrix, model_view, sizeof (normal_matrix));
493    invert(normal_matrix);
494    transpose(normal_matrix);
495    glUniformMatrix4fv(NormalMatrix_location, 1, GL_FALSE, normal_matrix);
496 
497    /* Set the gear color */
498    glUniform4fv(MaterialColor_location, 1, color);
499 
500    /* Set the vertex buffer object to use */
501    glBindBuffer(GL_ARRAY_BUFFER, gear->vbo);
502 
503    /* Set up the position of the attributes in the vertex buffer object */
504    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
505          6 * sizeof(GLfloat), NULL);
506    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
507          6 * sizeof(GLfloat), (GLfloat *) 0 + 3);
508 
509    /* Enable the attributes */
510    glEnableVertexAttribArray(0);
511    glEnableVertexAttribArray(1);
512 
513    /* Draw the triangle strips that comprise the gear */
514    int n;
515    for (n = 0; n < gear->nstrips; n++)
516       glDrawArrays(GL_TRIANGLE_STRIP, gear->strips[n].first, gear->strips[n].count);
517 
518    /* Disable the attributes */
519    glDisableVertexAttribArray(1);
520    glDisableVertexAttribArray(0);
521 }
522 
523 /**
524  * Draws the gears.
525  */
526 static void
gears_draw(void)527 gears_draw(void)
528 {
529    const static GLfloat red[4] = { 0.8, 0.1, 0.0, 1.0 };
530    const static GLfloat green[4] = { 0.0, 0.8, 0.2, 1.0 };
531    const static GLfloat blue[4] = { 0.2, 0.2, 1.0, 1.0 };
532    GLfloat transform[16];
533    identity(transform);
534 
535    glClearColor(0.0, 0.0, 0.0, 0.0);
536    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
537 
538    /* Translate and rotate the view */
539    translate(transform, 0, 0, -20);
540    rotate(transform, 2 * M_PI * view_rot[0] / 360.0, 1, 0, 0);
541    rotate(transform, 2 * M_PI * view_rot[1] / 360.0, 0, 1, 0);
542    rotate(transform, 2 * M_PI * view_rot[2] / 360.0, 0, 0, 1);
543 
544    /* Draw the gears */
545    draw_gear(gear1, transform, -3.0, -2.0, angle, red);
546    draw_gear(gear2, transform, 3.1, -2.0, -2 * angle - 9.0, green);
547    draw_gear(gear3, transform, -3.1, 4.2, -2 * angle - 25.0, blue);
548 
549    glutSwapBuffers();
550 
551 #ifdef LONGTEST
552    glutPostRedisplay(); // check for issues with not throttling calls
553 #endif
554 }
555 
556 /**
557  * Handles a new window size or exposure.
558  *
559  * @param width the window width
560  * @param height the window height
561  */
562 static void
gears_reshape(int width,int height)563 gears_reshape(int width, int height)
564 {
565    /* Update the projection matrix */
566    perspective(ProjectionMatrix, 60.0, width / (float)height, 1.0, 1024.0);
567 
568    /* Set the viewport */
569    glViewport(0, 0, (GLint) width, (GLint) height);
570 }
571 
572 /**
573  * Handles special glut events.
574  *
575  * @param special the event to handle.
576  */
577 static void
gears_special(int special,int crap,int morecrap)578 gears_special(int special, int crap, int morecrap)
579 {
580    switch (special) {
581       case GLUT_KEY_LEFT:
582          view_rot[1] += 5.0;
583          break;
584       case GLUT_KEY_RIGHT:
585          view_rot[1] -= 5.0;
586          break;
587       case GLUT_KEY_UP:
588          view_rot[0] += 5.0;
589          break;
590       case GLUT_KEY_DOWN:
591          view_rot[0] -= 5.0;
592          break;
593       case GLUT_KEY_F11:
594          glutFullScreen();
595          break;
596    }
597 }
598 
599 static void
gears_idle(void)600 gears_idle(void)
601 {
602    static int frames = 0;
603    static double tRot0 = -1.0, tRate0 = -1.0;
604    double dt;
605 #if ANIMATE
606    double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0;
607 #else
608    double t = 0;
609 #endif
610 
611    if (tRot0 < 0.0)
612       tRot0 = t;
613    dt = t - tRot0;
614    tRot0 = t;
615 
616    /* advance rotation for next frame */
617    angle += 70.0 * dt;  /* 70 degrees per second */
618    if (angle > 3600.0)
619       angle -= 3600.0;
620 
621 #ifdef TEST_MEMORYPROFILER_ALLOCATIONS_MAP
622    // This file is used to test --memoryprofiler linker flag, in which case
623    // add some allocation noise.
624    static void *allocatedPtr = 0;
625    free(allocatedPtr);
626    allocatedPtr = malloc(rand() % 10485760);
627 #endif
628 
629    glutPostRedisplay();
630    frames++;
631 
632    if (tRate0 < 0.0)
633       tRate0 = t;
634    if (t - tRate0 >= 5.0) {
635       GLfloat seconds = t - tRate0;
636       GLfloat fps = frames / seconds;
637       printf("%d frames in %3.1f seconds = %6.3f FPS\n", frames, seconds,
638             fps);
639       tRate0 = t;
640       frames = 0;
641 #ifdef LONGTEST
642       static int runs = 0;
643       runs++;
644       if (runs == 4) {
645         int result = fps;
646 #ifdef TEST_MEMORYPROFILER_ALLOCATIONS_MAP
647         result = 0;
648 #endif
649         REPORT_RESULT(result);
650       }
651 #endif
652    }
653 }
654 
655 static const char vertex_shader[] =
656 "attribute vec3 position;\n"
657 "attribute vec3 normal;\n"
658 "\n"
659 "uniform mat4 ModelViewProjectionMatrix;\n"
660 "uniform mat4 NormalMatrix;\n"
661 "uniform vec4 LightSourcePosition;\n"
662 "uniform vec4 MaterialColor;\n"
663 "\n"
664 "varying vec4 Color;\n"
665 "\n"
666 "void main(void)\n"
667 "{\n"
668 "    // Transform the normal to eye coordinates\n"
669 "    vec3 N = normalize(vec3(NormalMatrix * vec4(normal, 1.0)));\n"
670 "\n"
671 "    // The LightSourcePosition is actually its direction for directional light\n"
672 "    vec3 L = normalize(LightSourcePosition.xyz);\n"
673 "\n"
674 "    // Multiply the diffuse value by the vertex color (which is fixed in this case)\n"
675 "    // to get the actual color that we will use to draw this vertex with\n"
676 "    float diffuse = max(dot(N, L), 0.0);\n"
677 "    Color = diffuse * MaterialColor;\n"
678 "\n"
679 "    // Transform the position to clip coordinates\n"
680 "    gl_Position = ModelViewProjectionMatrix * vec4(position, 1.0);\n"
681 "}";
682 
683 static const char fragment_shader[] =
684 "#ifdef GL_ES\n"
685 "precision mediump float;\n"
686 "#endif\n"
687 "varying vec4 Color;\n"
688 "\n"
689 "void main(void)\n"
690 "{\n"
691 "    gl_FragColor = Color;\n"
692 "}";
693 
694 static void
gears_init(void)695 gears_init(void)
696 {
697    GLuint v, f, program;
698    const char *p;
699    char msg[512];
700 
701    glEnable(GL_CULL_FACE);
702    glEnable(GL_DEPTH_TEST);
703 
704    /* Compile the vertex shader */
705    p = vertex_shader;
706    v = glCreateShader(GL_VERTEX_SHADER);
707    glShaderSource(v, 1, &p, NULL);
708    glCompileShader(v);
709    glGetShaderInfoLog(v, sizeof msg, NULL, msg);
710    printf("vertex shader info: %s\n", msg);
711 
712    /* Compile the fragment shader */
713    p = fragment_shader;
714    f = glCreateShader(GL_FRAGMENT_SHADER);
715    glShaderSource(f, 1, &p, NULL);
716    glCompileShader(f);
717    glGetShaderInfoLog(f, sizeof msg, NULL, msg);
718    printf("fragment shader info: %s\n", msg);
719 
720    /* Create and link the shader program */
721    program = glCreateProgram();
722    glAttachShader(program, v);
723    glAttachShader(program, f);
724    glBindAttribLocation(program, 0, "position");
725    glBindAttribLocation(program, 1, "normal");
726 
727    glLinkProgram(program);
728    glGetProgramInfoLog(program, sizeof msg, NULL, msg);
729    printf("info: %s\n", msg);
730 
731    /* Enable the shaders */
732    glUseProgram(program);
733 
734    /* Get the locations of the uniforms so we can access them */
735    ModelViewProjectionMatrix_location = glGetUniformLocation(program, "ModelViewProjectionMatrix");
736    NormalMatrix_location = glGetUniformLocation(program, "NormalMatrix");
737    LightSourcePosition_location = glGetUniformLocation(program, "LightSourcePosition");
738    MaterialColor_location = glGetUniformLocation(program, "MaterialColor");
739 
740    /* Set the LightSourcePosition uniform which is constant throught the program */
741    glUniform4fv(LightSourcePosition_location, 1, LightSourcePosition);
742 
743    /* make the gears */
744    gear1 = create_gear(1.0, 4.0, 1.0, 20, 0.7);
745    gear2 = create_gear(0.5, 2.0, 2.0, 10, 0.7);
746    gear3 = create_gear(1.3, 2.0, 0.5, 10, 0.7);
747 }
748 
749 int
main(int argc,char * argv[])750 main(int argc, char *argv[])
751 {
752 #ifdef TEST_MEMORYPROFILER_ALLOCATIONS_MAP
753    printf("You should see an interactive CPU profiler graph below, and below that an allocation map of the Emscripten main HEAP, with a long blue block of allocated memory.\n");
754 #endif
755    /* Initialize the window */
756    glutInit(&argc, argv);
757    glutInitWindowSize(300, 300);
758    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
759 
760    glutCreateWindow("es2gears");
761 
762    /* Set up glut callback functions */
763    glutIdleFunc (gears_idle);
764    glutReshapeFunc(gears_reshape);
765    glutDisplayFunc(gears_draw);
766    glutSpecialFunc(gears_special);
767 
768    /* Initialize the gears */
769    gears_init();
770 
771    glutMainLoop();
772 
773    return 0;
774 }
775