#include #include #include #include const int screenWidth = 500; const int screenHeight = 500; /* draw a 5000-point 2D Sierpinski gasket in the square (0,0) to (500,500) */ void drawGasket( void ) { /* define a point data type */ typedef GLfloat point2[2]; /* use it to define the three vertices of a triangle */ point2 vertices[3]={{0.0,0.0},{250.0,500.0},{500.0,0.0}}; int i, j, k; int rand(); /* standard random number generator */ point2 p ={75.0,50.0}; /* arbitrary initial point inside triangle */ /* compute and plot 5000 points on the gasket: */ for( k=0; k<5000; k++) { /* first, pick a vertex at random */ j=rand()%3; /* then, compute point halfway between selected vertex and old point */ p[0] = (p[0]+vertices[j][0])/2.0; p[1] = (p[1]+vertices[j][1])/2.0; /* plot new point */ glBegin(GL_POINTS); glVertex2fv(p); glEnd(); /* and so on. */ } } /* the mouse callback: */ void myMouse(int button, int state, int x, int y) { if(button==GLUT_LEFT_BUTTON&state==GLUT_DOWN) exit(0); if(button==GLUT_MIDDLE_BUTTON&state==GLUT_DOWN) exit(0); if(button==GLUT_RIGHT_BUTTON&state==GLUT_DOWN) exit(0); } /* the display callback: */ void myDisplay(void) { glClear(GL_COLOR_BUFFER_BIT); // clear the screen // NB: if omit that line, will get a see-through window. Try it. glViewport(0, 0, 500, 500); drawGasket(); glFlush(); } /* initialization: */ void myInit(void) { glClearColor(1.0, 1.0, 1.0, 0.0); // background glColor3f(1.0, 0.0, 0.0); // drawing color glMatrixMode(GL_PROJECTION); // random necessary wierdness glLoadIdentity(); // to set up world coordinates glOrtho(0.0, 500.0, 0.0, 500.0, -1.0, 1.0); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(screenWidth,screenHeight); glutInitWindowPosition(0,0); glutCreateWindow("Sierpinski Gasket"); glutMouseFunc(myMouse); glutDisplayFunc(myDisplay); myInit(); glutMainLoop(); }