#if !defined(Linux) #include //Not Linux must be windows #else #include //use for exit(0) function #endif #include #include #include #include #define drand48() (double)rand()/RAND_MAX //Take care of SGIs drand48 function /* Author: Brian J. Ross October 1999 Draw 3D Sierpinski Pyramids to level i. The unit pyramid is based upon the local origin sitting in its middle. The recursive cases presume the sub-pyramids are scaled 1/2, and then translated to new loci around bigger triangle position. */ void recursive_tri(int i) { if (i <= 1) { /* Base case: draw a pyramid */ glBegin(GL_TRIANGLES); glColor3f(drand48(), drand48(), drand48()); glVertex3f(-80.0, -80.0, 80.0); glVertex3f(80.0, -80.0, 80.0); glVertex3f(0.0, 80.0, 0.0); glColor3f(drand48(), drand48(), drand48()); glVertex3f(80.0, -80.0, 80.0); glVertex3f(0.0, -80.0, -80.0); glVertex3f(0.0, 80.0, 0.0); glColor3f(drand48(), drand48(), drand48()); glVertex3f(0.0, -80.0, -80.0); glVertex3f(-80.0, -80.0, 80.0); glVertex3f(0.0, 80.0, 0.0); glColor3f(drand48(), drand48(), drand48()); glVertex3f(-80.0, -80.0, 80.0); glVertex3f(80.0, -80.0, 80.0); glVertex3f(0.0, -80.0, -80.0); glEnd(); } else { --i; glPushMatrix(); /* draw lower front left */ glTranslatef(-40.0, -40.0, 40.0); glScalef(0.5, 0.5, 0.5); recursive_tri(i); glPopMatrix(); glPushMatrix(); /* draw lower front right */ glTranslatef(40.0, -40.0, 40.0); glScalef(0.5, 0.5, 0.5); recursive_tri(i); glPopMatrix(); glPushMatrix(); /* draw lower back middle */ glTranslatef(0.0, -40.0, -40.0); glScalef(0.5, 0.5, 0.5); recursive_tri(i); glPopMatrix(); glPushMatrix(); /* draw top-middle */ glTranslatef(0.0, 40.0, 0.0); glScalef(0.5, 0.5, 0.5); recursive_tri(i); glPopMatrix(); } } /* Draw 8 levels of Sierpinski Pyramids. Give 5 seconds of viewing enjoyment per level. */ void drawtri(void) { int i; for (i=1; i < 9; i++) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); printf("level = %d\n", i); recursive_tri(i); glFlush(); #if !defined(Linux) Sleep(500); //in ms #else sleep(1); // Linux in sec #endif }; // exit (0); } main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(600, 600); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH); glutCreateWindow("3D Sierpinski Pyramids"); srand( (unsigned)time( NULL ) ); //VS, initialize the random # gen glMatrixMode(GL_PROJECTION); glOrtho(-125.0, 125.0, -125.0, 125.0, -125.0, 125.0); glMatrixMode(GL_MODELVIEW); glRotatef(15.0, 1.0, 0.0, 0.0); glRotatef(45.0, 0.0, 1.0, 0.0); glEnable(GL_DEPTH_TEST); glClearColor(0.0, 0.0, 0.0, 1.0); /* black */ glutDisplayFunc(drawtri); glutMainLoop(); return 0; }