Up: OpenGL Wagon examples. Next: Still wagon example.

1 #ifndef _WAGON_WHEEL_H_ 2 #define _WAGON_WHEEL_H_ 3 void wheelInit(); 4 void wheelDraw(); 5 #endif /* _WAGON_WHEEL_H_ */
1 #include <stdlib.h>
2 #include <math.h>
3 #include <GL/glut.h>
4 #include "wheel.h"
5 #define WAGON_RIM_N 24
6 #define WAGON_SPOKE_N 12
7 static double *spoke_pts = NULL;
8 static double *rim_pts;
9 // Creates an array of 2*n doubles representing n points evenly
10 // spaced around a circle of radius 1. Point i on the
11 // circumference will be at coordinates (array[2*i], array[2*i+1]).
12 static double* createCircumferencePoints(int n) {
13 double *ret;
14 int i;
15 double theta;
16
17 ret = (double*) malloc(2 * n * sizeof(double));
18 for(i = 0; i < n; i++) {
19 theta = 2 * M_PI * i / n;
20 ret[2 * i] = cos(theta);
21 ret[2 * i + 1] = sin(theta);
22 }
23 return ret;
24 }
25 // Initializes data necessary for drawing a wagon wheel.
26 void wheelInit() {
27 if(spoke_pts == NULL) {
28 spoke_pts = createCircumferencePoints(WAGON_SPOKE_N);
29 rim_pts = createCircumferencePoints(WAGON_RIM_N);
30 }
31 }
32 // Draws wagon wheel of radius 1, centered at origin.
33 void wheelDraw() {
34 int i;
35 glBegin(GL_LINES); // Draw spokes.
36 for(i = 0; i < WAGON_SPOKE_N; i++) {
37 glVertex2f(0.0, 0.0);
38 glVertex2f(spoke_pts[2 * i], spoke_pts[2 * i + 1]);
39 }
40 glEnd();
41 glBegin(GL_LINE_LOOP); // Draw rim.
42 for(i = 0; i < WAGON_RIM_N; i++) {
43 glVertex2f(rim_pts[2 * i], rim_pts[2 * i + 1]);
44 }
45 glEnd();
46 }
1 #include <GL/glut.h>
2 #include "wheel.h"
3 // Initializes information for drawing within OpenGL.
4 void init() {
5 glClearColor(1.0, 1.0, 1.0, 0.0); // Set window color to white.
6 glMatrixMode(GL_PROJECTION); // Set projection parameters.
7 gluOrtho2D(-1.5, 1.5, -1.5, 1.5); // Set viewable coordinates
8 wheelInit();
9 }
10 // Draws the picture.
11 void draw() {
12 glClear(GL_COLOR_BUFFER_BIT); // Clear display window.
13 glColor3f(0.0, 0.0, 0.0); // Set line segment color to black.
14 wheelDraw();
15 glFlush(); // Process all OpenGL routines as quickly as possible.
16 }
17 int main(int argc, char **argv) {
18 glutInit(&argc, argv);
19 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
20 glutInitWindowPosition(50, 100); // Set up display window.
21 glutInitWindowSize(200, 200);
22 glutCreateWindow("Wagon Wheel");
23 init();
24 glutDisplayFunc(draw);
25 glutMainLoop();
26 return 0;
27 }
28 // To compile: gcc wheel_main.c wheel.c -lglut -lGLU -lGL -lm