在基于多边形的Sierpinski镂垫的基础上增加如下功能:
1、按q键退出;
2、右键菜单-随机换一种颜色;
3、在细分三角形之前增加了扰动;
代码如下:
#include <Windows.h> #include <cstdio> #include <random> #include <functional> #include "glut.h" typedef GLfloat point2d[2]; point2d v[3] = { { 0.0, 0.0 }, { 250.0, 500.0 }, { 500.0, 0.0 } }; std::uniform_int_distribution<int> uniform_dist(0, 255); std::normal_distribution<double> normal_dist(2.0, 0.05); //这个正态分布发生器用于扰动细分三角形的中点 std::default_random_engine engine; auto uniform_rand = std::bind(uniform_dist, engine); auto normal_rand = std::bind(normal_dist, engine); void triangle(point2d a, point2d b, point2d c) { glBegin(GL_LINE_LOOP); glVertex2fv(a); glVertex2fv(b); glVertex2fv(c); glEnd(); } void divide_triangle(point2d a, point2d b, point2d c, int k) { point2d ab, ac, bc; if (k > 0) { for (int j = 0; j < 2; j++) ab[j] = (a[j] + b[j]) / normal_rand(); for (int j = 0; j < 2; j++) ac[j] = (a[j] + c[j]) / normal_rand(); for (int j = 0; j < 2; j++) bc[j] = (b[j] + c[j]) / normal_rand(); divide_triangle(a, ab, ac, k - 1); divide_triangle(b, ab, bc, k - 1); divide_triangle(c, ac, bc, k - 1); } else triangle(a, b, c); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); divide_triangle(v[0], v[1], v[2], 5); glFlush(); } void my_init(void) { glClearColor(1.0, 1.0, 1.0, 1.0); glColor3f(1.0, 0.0, 0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, 500.0, 0.0, 500.0); glMatrixMode(GL_MODELVIEW); } void my_menu(int entry_id) { switch (entry_id) { case 0: glClear(GL_COLOR_BUFFER_BIT); glColor3b(uniform_rand(), uniform_rand(), uniform_rand()); glutPostRedisplay(); break; /*case 1: { CHOOSECOLOR color; printf("%d\n", ChooseColor(&color)); glClear(GL_COLOR_BUFFER_BIT); glColor3b(GetRValue(color.rgbResult), GetGValue(color.rgbResult), GetBValue(color.rgbResult)); glutPostRedisplay(); break; }*/ default: break; } } void keyboard(unsigned char key, int x, int y) { if (key = ‘q‘ || key == ‘Q‘) exit(0); } int main(int argc, char *argv[]) { HWND hWnd = GetForegroundWindow(); ShowWindow(hWnd, SW_HIDE); //hide cmd window glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowPosition(100, 100); glutInitWindowSize(500, 500); glutCreateWindow("2D Sierpinski (Triangle Ver)"); glutDisplayFunc(display); int menu_id = glutCreateMenu(my_menu); glutAddMenuEntry("随机颜色重画", 0); //glutAddMenuEntry("选择颜色", 1); glutAttachMenu(GLUT_RIGHT_BUTTON); glutKeyboardFunc(keyboard); my_init(); glutMainLoop(); return 0; }
运行截图:
时间: 2024-10-21 11:27:13