#include #include #include #include float randomFloat() { return static_cast(rand()) / static_cast(RAND_MAX); } void drawSquare(const float x, const float y, const float size) { glBegin(GL_POLYGON); glColor3f(randomFloat(), randomFloat(), randomFloat()); glVertex2f(x, y); glColor3f(randomFloat(), randomFloat(), randomFloat()); glVertex2f(x + size, y); glColor3f(randomFloat(), randomFloat(), randomFloat()); glVertex2f(x + size, y - size); glColor3f(randomFloat(), randomFloat(), randomFloat()); glVertex2f(x, y - size); glEnd(); } void drawFractal(const int levelsCount, const float randomness, const float x, const float y, const float rectSize) { float singleRectSize = rectSize / 3; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) continue; if (levelsCount == 0) drawSquare(x + i * singleRectSize + singleRectSize * randomFloat() * randomness, y - j * singleRectSize + singleRectSize * randomFloat() * randomness, singleRectSize); else drawFractal(levelsCount - 1, randomness, x + i * singleRectSize + singleRectSize * randomFloat() * randomness, y - j * singleRectSize + singleRectSize * randomFloat() * randomness, singleRectSize); } } } void renderScene() { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.0F, 1.0F, 0.0F); int levelCount = 2; float startX = -75.0F; float startY = 75.0F; float fractalSize = 150.0F; float randomness = 0.05; drawFractal(levelCount, randomness, startX, startY, fractalSize); glFlush(); } void changeSize(int width, int height) { if (height == 0) height = 1; glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); float aspectRatio = static_cast(width) / static_cast(height); if (width <= height) glOrtho(-100.0, 100.0, -100.0 / aspectRatio, 100.0 / aspectRatio, 1.0, -1.0); else glOrtho(-100.0 * aspectRatio, 100.0 * aspectRatio, -100.0, 100.0, 1.0, -1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void myInit() { std::srand(std::time(nullptr)); glClearColor(0.5F, 0.5F, 0.5F, 1.0F); } int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); glutCreateWindow("Dywan Sierpinskiego"); glutDisplayFunc(renderScene); glutReshapeFunc(changeSize); myInit(); glutMainLoop(); return 0; }