2
* Copyright (C) 1999-2001 Brian Paul All Rights Reserved.
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:
11
* The above copyright notice and this permission notice shall be included
12
* in all copies or substantial portions of the Software.
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.
24
* Kristian HĆøgsberg <krh@bitplanet.net>
28
* * Refactor gear drawing.
29
* * Use correct normals for surfaces.
31
* * Use perspective projection transformation.
34
* Alexandros Frantzis <alexandros.frantzis@linaro.org>
38
#define GL_GLEXT_PROTOTYPES
39
#define EGL_EGLEXT_PROTOTYPES
50
#include <OpenGL/gl.h>
51
#include <Glut/glut.h>
57
#define STRIPS_PER_TOOTH 7
58
#define VERTICES_PER_TOOTH 34
59
#define GEAR_VERTEX_STRIDE 6
61
#ifndef HAVE_BUILTIN_SINCOS
62
#define sincos _sincos
64
sincos (double a, double *s, double *c)
72
* Struct describing the vertices in triangle strip
75
/** The first vertex in the strip */
77
/** The number of consecutive vertices in the strip after the first */
81
/* Each vertex consist of GEAR_VERTEX_STRIDE GLfloat attributes */
82
typedef GLfloat GearVertex[GEAR_VERTEX_STRIDE];
85
* Struct representing a gear.
88
/** The array of vertices comprising the gear */
90
/** The number of vertices comprising the gear */
92
/** The array of triangle strips comprising the gear */
93
struct vertex_strip *strips;
94
/** The number of triangle strips comprising the gear */
96
/** The Vertex Buffer Object holding the vertices in the graphics card */
100
/** The view rotation [x, y, z] */
101
static GLfloat view_rot[3] = { 20.0, 30.0, 0.0 };
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};
117
* Fills a gear vertex.
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
125
* @return the operation error code
128
vert(GearVertex *v, GLfloat x, GLfloat y, GLfloat z, GLfloat n[3])
141
* Create a gear wheel.
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
149
* @return pointer to the constructed struct gear
152
create_gear(GLfloat inner_radius, GLfloat outer_radius, GLfloat width,
153
GLint teeth, GLfloat tooth_depth)
164
/* Allocate memory for the gear */
165
gear = malloc(sizeof *gear);
169
/* Calculate the radii used in the gear */
171
r1 = outer_radius - tooth_depth / 2.0;
172
r2 = outer_radius + tooth_depth / 2.0;
174
da = 2.0 * M_PI / teeth / 4.0;
176
/* Allocate memory for the triangle strip information */
177
gear->nstrips = STRIPS_PER_TOOTH * teeth;
178
gear->strips = calloc(gear->nstrips, sizeof (*gear->strips));
180
/* Allocate memory for the vertices */
181
gear->vertices = calloc(VERTICES_PER_TOOTH * teeth, sizeof(*gear->vertices));
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]);
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); \
198
#define GEAR_VERT(v, point, sign) vert((v), p[(point)].x, p[(point)].y, (sign) * width * 0.5, normal)
200
#define START_STRIP do { \
201
gear->strips[cur_strip].first = v - gear->vertices; \
204
#define END_STRIP do { \
205
int _tmp = (v - gear->vertices); \
206
gear->strips[cur_strip].count = _tmp - gear->strips[cur_strip].first; \
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); \
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
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);
248
QUAD_WITH_NORMAL(4, 6);
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);
265
QUAD_WITH_NORMAL(0, 2);
269
QUAD_WITH_NORMAL(1, 0);
273
QUAD_WITH_NORMAL(3, 1);
277
QUAD_WITH_NORMAL(5, 3);
281
gear->nvertices = (v - gear->vertices);
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);
293
* Multiplies two 4x4 matrices.
295
* The result is stored in matrix m.
297
* @param m the first matrix to multiply
298
* @param n the second matrix to multiply
301
multiply(GLfloat *m, const GLfloat *n)
304
const GLfloat *row, *column;
308
for (i = 0; i < 16; i++) {
311
row = n + d.quot * 4;
313
for (j = 0; j < 4; j++)
314
tmp[i] += row[j] * column[j * 4];
316
memcpy(m, &tmp, sizeof tmp);
320
* Rotates a 4x4 matrix.
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
329
rotate(GLfloat *m, GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
333
sincos(angle, &s, &c);
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,
346
* Translates a 4x4 matrix.
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
354
translate(GLfloat *m, GLfloat x, GLfloat y, GLfloat z)
356
GLfloat t[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 };
362
* Creates an identity 4x4 matrix.
364
* @param m the matrix make an identity matrix
376
memcpy(m, t, sizeof(t));
380
* Transposes a 4x4 matrix.
382
* @param m the matrix to transpose
385
transpose(GLfloat *m)
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]};
393
memcpy(m, t, sizeof(t));
397
* Inverts a 4x4 matrix.
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.
409
// Extract and invert the translation part 't'. The inverse of a
410
// translation matrix can be calculated by negating the translation
412
t[12] = -m[12]; t[13] = -m[13]; t[14] = -m[14];
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;
419
// inv(m) = inv(r) * inv(t)
424
* Calculate a perspective projection transformation.
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
432
void perspective(GLfloat *m, GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar)
437
double sine, cosine, cotangent, deltaZ;
438
GLfloat radians = fovy / 2 * M_PI / 180;
440
deltaZ = zFar - zNear;
441
sincos(radians, &sine, &cosine);
443
if ((deltaZ == 0) || (sine == 0) || (aspect == 0))
446
cotangent = cosine / sine;
448
tmp[0] = cotangent / aspect;
450
tmp[10] = -(zFar + zNear) / deltaZ;
452
tmp[14] = -2 * zNear * zFar / deltaZ;
455
memcpy(m, tmp, sizeof(tmp));
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
469
draw_gear(struct gear *gear, GLfloat *transform,
470
GLfloat x, GLfloat y, GLfloat angle, const GLfloat color[4])
472
GLfloat model_view[16];
473
GLfloat normal_matrix[16];
474
GLfloat model_view_projection[16];
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);
481
/* Create and set the ModelViewProjectionMatrix */
482
memcpy(model_view_projection, ProjectionMatrix, sizeof(model_view_projection));
483
multiply(model_view_projection, model_view);
485
glUniformMatrix4fv(ModelViewProjectionMatrix_location, 1, GL_FALSE,
486
model_view_projection);
489
* Create and set the NormalMatrix. It's the inverse transpose of the
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);
497
/* Set the gear color */
498
glUniform4fv(MaterialColor_location, 1, color);
500
/* Set the vertex buffer object to use */
501
glBindBuffer(GL_ARRAY_BUFFER, 0);
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), *gear->vertices);
507
glBindBuffer(GL_ARRAY_BUFFER, gear->vbo); // second is not clientside
508
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
509
6 * sizeof(GLfloat), (GLfloat *) 0 + 3);
510
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, // third is not clientside either, but not enabled
511
6 * sizeof(GLfloat), ((float*)*gear->vertices) + 6*4);
512
glBindBuffer(GL_ARRAY_BUFFER, 0);
514
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, // also never enabled
515
6 * sizeof(GLfloat), ((float*)*gear->vertices) + 9*4);
517
/* Enable the attributes */
518
glEnableVertexAttribArray(0);
519
glEnableVertexAttribArray(1);
521
/* Draw the triangle strips that comprise the gear */
523
for (n = 0; n < gear->nstrips; n++)
524
glDrawArrays(GL_TRIANGLE_STRIP, gear->strips[n].first, gear->strips[n].count);
526
/* Disable the attributes */
527
glDisableVertexAttribArray(1);
528
glDisableVertexAttribArray(0);
537
const static GLfloat red[4] = { 0.8, 0.1, 0.0, 1.0 };
538
const static GLfloat green[4] = { 0.0, 0.8, 0.2, 1.0 };
539
const static GLfloat blue[4] = { 0.2, 0.2, 1.0, 1.0 };
540
GLfloat transform[16];
543
glClearColor(0.0, 0.0, 0.0, 0.0);
544
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
546
/* Translate and rotate the view */
547
translate(transform, 0, 0, -20);
548
rotate(transform, 2 * M_PI * view_rot[0] / 360.0, 1, 0, 0);
549
rotate(transform, 2 * M_PI * view_rot[1] / 360.0, 0, 1, 0);
550
rotate(transform, 2 * M_PI * view_rot[2] / 360.0, 0, 0, 1);
553
draw_gear(gear1, transform, -3.0, -2.0, angle, red);
554
draw_gear(gear2, transform, 3.1, -2.0, -2 * angle - 9.0, green);
555
draw_gear(gear3, transform, -3.1, 4.2, -2 * angle - 25.0, blue);
561
* Handles a new window size or exposure.
563
* @param width the window width
564
* @param height the window height
567
gears_reshape(int width, int height)
569
/* Update the projection matrix */
570
perspective(ProjectionMatrix, 60.0, width / (float)height, 1.0, 1024.0);
572
/* Set the viewport */
573
glViewport(0, 0, (GLint) width, (GLint) height);
577
* Handles special glut events.
579
* @param special the event to handle.
582
gears_special(int special, int crap, int morecrap)
606
static int frames = 0;
607
static double tRot0 = -1.0, tRate0 = -1.0;
608
double dt, t = glutGet(GLUT_ELAPSED_TIME) / 1000.0;
615
/* advance rotation for next frame */
616
angle += 70.0 * dt; /* 70 degrees per second */
625
if (t - tRate0 >= 5.0) {
626
GLfloat seconds = t - tRate0;
627
GLfloat fps = frames / seconds;
628
printf("%d frames in %3.1f seconds = %6.3f FPS\n", frames, seconds,
635
static const char vertex_shader[] =
636
"attribute vec3 position;\n"
637
"attribute vec3 normal;\n"
639
"uniform mat4 ModelViewProjectionMatrix;\n"
640
"uniform mat4 NormalMatrix;\n"
641
"uniform vec4 LightSourcePosition;\n"
642
"uniform vec4 MaterialColor;\n"
644
"varying vec4 Color;\n"
648
" // Transform the normal to eye coordinates\n"
649
" vec3 N = normalize(vec3(NormalMatrix * vec4(normal, 1.0)));\n"
651
" // The LightSourcePosition is actually its direction for directional light\n"
652
" vec3 L = normalize(LightSourcePosition.xyz);\n"
654
" // Multiply the diffuse value by the vertex color (which is fixed in this case)\n"
655
" // to get the actual color that we will use to draw this vertex with\n"
656
" float diffuse = max(dot(N, L), 0.0);\n"
657
" Color = diffuse * MaterialColor;\n"
659
" // Transform the position to clip coordinates\n"
660
" gl_Position = ModelViewProjectionMatrix * vec4(position, 1.0);\n"
663
static const char fragment_shader[] =
665
"precision mediump float;\n"
667
"varying vec4 Color;\n"
671
" gl_FragColor = Color;\n"
677
GLuint v, f, program;
681
glEnable(GL_CULL_FACE);
682
glEnable(GL_DEPTH_TEST);
684
/* Compile the vertex shader */
686
v = glCreateShader(GL_VERTEX_SHADER);
687
glShaderSource(v, 1, &p, NULL);
689
glGetShaderInfoLog(v, sizeof msg, NULL, msg);
690
printf("vertex shader info: %s\n", msg);
692
/* Compile the fragment shader */
694
f = glCreateShader(GL_FRAGMENT_SHADER);
695
glShaderSource(f, 1, &p, NULL);
697
glGetShaderInfoLog(f, sizeof msg, NULL, msg);
698
printf("fragment shader info: %s\n", msg);
700
/* Create and link the shader program */
701
program = glCreateProgram();
702
glAttachShader(program, v);
703
glAttachShader(program, f);
704
glBindAttribLocation(program, 0, "position");
705
glBindAttribLocation(program, 1, "normal");
707
glLinkProgram(program);
708
glGetProgramInfoLog(program, sizeof msg, NULL, msg);
709
printf("info: %s\n", msg);
711
/* Enable the shaders */
712
glUseProgram(program);
714
/* Get the locations of the uniforms so we can access them */
715
ModelViewProjectionMatrix_location = glGetUniformLocation(program, "ModelViewProjectionMatrix");
716
NormalMatrix_location = glGetUniformLocation(program, "NormalMatrix");
717
LightSourcePosition_location = glGetUniformLocation(program, "LightSourcePosition");
718
MaterialColor_location = glGetUniformLocation(program, "MaterialColor");
720
/* Set the LightSourcePosition uniform which is constant throught the program */
721
glUniform4fv(LightSourcePosition_location, 1, LightSourcePosition);
724
gear1 = create_gear(1.0, 4.0, 1.0, 20, 0.7);
725
gear2 = create_gear(0.5, 2.0, 2.0, 10, 0.7);
726
gear3 = create_gear(1.3, 2.0, 0.5, 10, 0.7);
730
main(int argc, char *argv[])
732
/* Initialize the window */
733
glutInit(&argc, argv);
734
glutInitWindowSize(300, 300);
735
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
737
glutCreateWindow("es2gears");
739
/* Set up glut callback functions */
740
glutIdleFunc (gears_idle);
741
glutReshapeFunc(gears_reshape);
742
glutDisplayFunc(gears_draw);
743
glutSpecialFunc(gears_special);
745
/* Initialize the gears */