Sierpinski's Triangle
Programmed in C using OpenGL
Code for Sierpinski's Triangle
// appropriate includes here
#include <GL.h>
#include <glut.h>
#include <stdlib.h>
class GLintPoint{
public:
GLint x, y;
};
// function prototypes
void myInit(void);
void myDisplay(void);
void Sierpinski(void);
void drawDot(void);
int random(int);
int x, y ;
//<<<<<<<<<<<<<<< myinit >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void myInit(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0) ; // set white background color
glColor3f(1.0f, 0.0f, 0.5f) ; // set the drawing color
glPointSize(2.0) ; // a dot is 2 by 2 pixels
glMatrixMode (GL_PROJECTION) ;
glLoadIdentity () ;
gluOrtho2D(0.0, 640.0, 0.0, 480.0) ;
}
//<<<<<<<<<<<<<<< drawDot >>>>>>>>>>>>>>>>>>>>>>>>>>>>
void drawDot()
{
glBegin(GL_POINTS) ;
glVertex2i(x, y) ; //draw point
glEnd() ;
glFlush() ; //send all output to displau
}
//<<<<<<<<<<<<<<< random >>>>>>>>>>>>>>>>>>>>>>>>>>>>
int random(int m)
{
return rand()%m;
}
//<<<<<<<<<<<<<<< Sierpinski >>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Sierpinski(void)
{
GLintPoint T[3]= {{50,50},{600,50},{600, 400}};
//int x, y ;
int index = random(3); // 0, 1, or 2 equally likely
GLintPoint point = T[index]; // initial point
//x = point.x;
//y = point.y;
drawDot(); // draw initial point
for(int i = 0; i < 10000; i++) // draw 1000 dots
{
index = random(3);
point.x = (point.x + T[index].x) / 2;
point.y = (point.y + T[index].y) / 2;
x = point.x;
y = point.y;
drawDot();
}
glFlush();
}
//<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char** argv)
{
glutInit(&argc, argv) ; //initializes the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB) ; //set the display mode
glutInitWindowSize(640, 480) ; // setwindow size
glutCreateWindow("my first attempt"); // open the screen window
glutDisplayFunc(drawDot) ; // register the redraw functions
myInit(); //additional initializations as necessary
glClear(GL_COLOR_BUFFER_BIT) ; //clear the screen
Sierpinski();
glutMainLoop() ; // go into a perpetual loop
}