#include #include /* Author: Brian J. Ross October 1999 Draw Sierpinski Triangles to level i. The unit triangle is based upon the local origin sitting in its middle. The recursive cases presume the sub-triangles are scaled 1/2, and then translated to new loci around bigger triangle position. Note the order of glTranslatef and glScalef: we scale the object first, and translate it to desired position. If these commands are reversed, then the scaling will affect translated position, which won't correctly position the triangles. (Transformations accumulate!) */ void recursive_tri(int i) { if (i <= 1) { /* Base case: draw a triangle */ glBegin(GL_TRIANGLES); glVertex2f(-80.0, -80.0); glVertex2f(80.0, -80.0); glVertex2f(0.0, 80.0); glEnd(); } else { --i; glPushMatrix(); /* draw lower-left */ glTranslatef(-40.0, -40.0, 0.0); glScalef(0.5, 0.5, 1.0); recursive_tri(i); glPopMatrix(); glPushMatrix(); /* draw lower-right */ glTranslatef(40.0, -40.0, 0.0); glScalef(0.5, 0.5, 1.0); recursive_tri(i); glPopMatrix(); glPushMatrix(); /* draw top-middle */ glTranslatef(0.0, 40.0, 0.0); glScalef(0.5, 0.5, 1.0); recursive_tri(i); glPopMatrix(); } } /* Draw 8 levels of Sierpinski Triangles. Give 5 seconds of viewing enjoyment per level. */ void drawtri() { int i; for (i=1; i < 9; i++) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0, 1.0, 1.0); printf("level = %d\n", i); recursive_tri(i); sleep(5); } } main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(600, 600); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); glutCreateWindow("Sierpinski Triangles"); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(-100.0, 100.0, -100.0, 100.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glPushMatrix(); glClearColor(0.0, 0.0, 0.0, 1.0); /* black */ glutDisplayFunc(drawtri); glutMainLoop(); return 0; }