Point.h
#ifndef POINT_H
#define POINT_H
class Point {
public:
float x, y;
Point();
Point(float x, float y);
};
#endif
Point.cpp
#include "Point.h"
Point::Point() {
x = 0;
y = 0;
}
Point::Point(float x, float y) {
this->x = x;
this->y = y;
}
Fractal.h
#ifndef FRACTAL_H
#define FRACTAL_H
#include "Point.h"
class Fractal {
public:
static void generateFractal(const Point& T0, const Point& T1, const Point& T2, int iterations);
};
#endif
Fractal.cpp
#include "Fractal.h"
#include "glut.h"
#include <cstdlib>
void drawPoint(float x, float y) {
glBegin(GL_POINTS);
glVertex2f(x, y);
glEnd();
glFlush();
}
void Fractal::generateFractal(const Point& T0, const Point& T1, const Point& T2, int iterations) {
int r = rand() % 3;
Point cur;
if (r == 0) cur = T0;
else if (r == 1) cur = T1;
else cur = T2;
Point next;
for (int i = 0; i < iterations; i++) {
r = rand() % 3;
const Point& Ti = (r == 0) ? T0 : ((r == 1) ? T1 : T2);
next.x = (cur.x + Ti.x) / 2.0f;
next.y = (cur.y + Ti.y) / 2.0f;
drawPoint(next.x, next.y);
cur = next;
}
}
main.cpp
#include <iostream>
#include <ctime>
#include <cstdlib>
#include "glut.h"
#include "Point.h"
#include "Fractal.h"
void myInit() {
glClearColor(1, 1, 1, 0);
glColor3f(0, 0, 0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 640, 0, 640);
}
void myDisplay() {
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POINTS);
Point T0(150.0, 300.0);
Point T1(300.0, 150.0);
Point T2(440.0, 440.0);
glVertex2f(T0.x, T0.y);
glVertex2f(T1.x, T1.y);
glVertex2f(T2.x, T2.y);
Fractal::generateFractal(T0, T1, T2, 50000);
glEnd();
glFlush();
}
int main(int argc, char** argv) {
srand((unsigned int)time(NULL));
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(640, 640);
glutCreateWindow("lab1_compgraphic: fractal");
glutDisplayFunc(myDisplay);
myInit();
glutMainLoop();
return 0;
}