summaryrefslogtreecommitdiff
path: root/src/1/main.c
blob: ad35c47fc4b56912384ac9a2944edd70963ec2d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* 2-d serpinski gasket
 *
 * Akshay Oppiliappan
 */

#include <GL/glut.h>
#include <stdlib.h>
#include <time.h>

typedef GLfloat point2[2];

float rand_float() { return 1 * (float)rand() / (float)RAND_MAX; }

void myInit() {
    glClearColor(1.0, 1.0, 1.0, 1.0);
    glColor3f(rand_float(), rand_float(), rand_float());
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, 500.0, 0.0, 500.0);
    glMatrixMode(GL_MODELVIEW);
}

void triangle(point2 a, point2 b, point2 c) {
    glBegin(GL_TRIANGLES);
    glVertex2fv(a);
    glVertex2fv(b);
    glVertex2fv(c);
    glEnd();
}

void divide_triangle(point2 a, point2 b, point2 c, int k) {
    point2 ab, ac, bc;
    int j;
    if (k > 0) {
        for (j = 0; j < 2; j++)
            ab[j] = (a[j] + b[j]) / 2;
        for (j = 0; j < 2; j++)
            ac[j] = (a[j] + c[j]) / 2;
        for (j = 0; j < 2; j++)
            bc[j] = (b[j] + c[j]) / 2;

        divide_triangle(a, ab, ac, k - 1);
        divide_triangle(c, ac, bc, k - 1);
        divide_triangle(b, bc, ab, k - 1);
    } else {
        triangle(a, b, c);
    }
}

void display() {
    glClear(GL_COLOR_BUFFER_BIT);
    point2 v[3] = {{0.0, 0.0}, {250.0, 500.0}, {500.0, 0.0}};
    divide_triangle(v[0], v[1], v[2], 8);
    glFlush();
}

int main(int argc, char *argv[]) {
    srand(time(0));
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("Sierpinski Gasket");
    glutDisplayFunc(display);
    myInit();
    glutMainLoop();
}