注意事项:配置好OpenGL环境。
//Koch.h #include <GL/glut.h> #include <math.h> #define PI 3.1415926 void Koch(float ax,float ay,float bx,float by, float c); void DrawTrigon(float ax,float ay, float bx,float by,float cx,float cy,float c);
//Koch.cpp #include"Koch.h" //ax,ay,bx,by是直线端点坐标,c是最小分形线段长度 void Koch(float ax,float ay,float bx,float by, float c){ if( (bx-ax)*(bx-ax) +(by-ay)*(by-ay) < c*c ){ glBegin(GL_LINES); glVertex2f(ax,ay); glVertex2f(bx,by); glEnd(); }else { float dx,dy,ex,ey,fx,fy; dx = ax + (bx - ax)/3; dy = ay + (by - ay)/3; fx = ax + (bx - ax)*2/3; fy = ay + (by - ay)*2/3; float l = sqrt( (fx - dx)*(fx - dx)+ (fy-dy)*(fy-dy) ); //get the angle double angle = atan( (fy - dy)/(fx - dx) ); if( ( (angle>0&&(fx - dx) <0))||( (angle<0&&(fx - dx) <0)))angle += PI; ex = dx + cos(angle + PI/3)*l; ey = dy + sin(angle + PI/3)*l; Koch(ax,ay,dx,dy,c); Koch(dx,dy,ex,ey,c); Koch(ex,ey,fx,fy,c); Koch(fx,fy,bx,by,c); } } //ax,ay,bx,by,cx,cy是三角形顶点坐标,c是最小分形线段长度 void DrawTrigon(float ax,float ay, float bx,float by,float cx,float cy,float c){ Koch(ax,ay,bx,by,c); Koch(bx,by,cx,cy,c); Koch(cx,cy,ax,ay,c); }
//main.cpp #include "Koch.h" void display(){ glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0,1.0,1.0); /* Koch(0.2,0.5 ,0.8,0.8,0.002); Koch(0.8,0.8, 0.5,0.2,0.002); Koch(0.5,0.2, 0.2,0.5,0.002);*/ DrawTrigon(0.2,0.8,0.8,0.8,0.5,0.2,0.005); glFlush(); } void init(){ glClearColor(0.0,0.0,0.0,0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0,1.0,0.0,1.0,-1.0,1.0); } int main(int argc, char * argv[]){ glutInit(&argc,argv); glutInitWindowSize(800,800); glutInitWindowPosition(100,100); glutCreateWindow("Koch"); init(); glutDisplayFunc(display); glutMainLoop(); return 0; }
作者:Wei_Yuan_2012 发表于2013-3-20 0:27:18 原文链接
阅读:26 评论:0 查看评论