/* prac2a.c */ /* Purpose: open a window, clear the background, construct Sierpinski gasket */ #ifdef __APPLE__ #include #else #include #endif #include #include #include #define KEY_ESC 27 /* glut doesn't define this one */ /* New Types */ typedef struct PointCoord PointCoord; struct PointCoord { float x; float y; }; /* Module constants and variables */ const static PointCoord triangle[3]={{-0.8,-0.8},{0.8,-0.8},{0.0,0.8}}; void printHelp( void ) { fprintf(stdout, "Sierpinski gasket\n\n" "SPACE key - generates 1000 points\n" "Escape key - exit the program\n\n"); } GLvoid keyboard( GLubyte key, GLint x, GLint y) { switch (key) { case KEY_ESC: /* exit when escape key is pressed */ exit(0); break; case ' ': /* Generate another 1000 points */ glutPostRedisplay(); break; } } GLvoid specialkeys( GLint key, GLint x, GLint y) { switch (key) { case GLUT_KEY_F1: /* print Help information */ printHelp(); break; } } GLvoid checkError( const char* const label ) { GLenum error; error = glGetError(); while ( GL_NO_ERROR != error ) { fprintf( stderr,"%s: %s\n", label, gluErrorString(error) ); error = glGetError(); } } int myrandom(int m) { return rand()%m; } GLvoid display( GLvoid ) { /* Do all your OpenGL rendering here */ PointCoord point={0.0, 0.8}; /* seed the point generation */ int i; int k; glClear( GL_COLOR_BUFFER_BIT ); /* draw outline of initial triangle first */ glColor3f(1.0,0.0,0.0); glLineWidth(5.0); glBegin(GL_LINE_LOOP); glVertex2f(triangle[0].x,triangle[0].y); glVertex2f(triangle[1].x,triangle[1].y); glVertex2f(triangle[2].x,triangle[2].y); glEnd(); /* set random colour for points */ glColor3f(myrandom(10)/10.0,myrandom(10)/10.0,myrandom(10)/10.0); glBegin(GL_POINTS); for (k=0; k<1000; k++) { i = myrandom(3); point.x = (point.x+triangle[i].x)/2; point.y = (point.y+triangle[i].y)/2; glVertex2f(point.x,point.y); } glEnd(); checkError( "display" ); glFlush(); } void init( void ) { glClearColor( 1.0, 1.0, 1.0, 1.0); glPointSize(3.0); /* set large point size */ } int main( int argc, char *argv[] ) { glutInit( &argc, argv ); glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB ); glutCreateWindow( argv[0] ); printHelp(); glutDisplayFunc( display ); glutKeyboardFunc( keyboard ); glutSpecialFunc( specialkeys ); init(); glutMainLoop(); return 0; }