随机L系统分形树 分类: 计算机图形学 2014-06-01 23:27 376人阅读 评论(0) 收藏
下面代码需要插入到MFC项目中运行,实现了计算机图形学中的L系统分形树。 class Node { public: int x,y; double direction; Node(){} }; CString way[3] ;//提供三种生成规则 CString rule,temprule; int len ; //单步长 int angle; //旋转转角度 int degree ; //迭代次数 int x,y ; //原点坐标 Node stack[1024]; int stackpointer; CTest18View::CTest18View() { way[0] = "F[+F]F[-F]F"; way[1] = "F[+F]F[-F[+F]]"; way[2] = "FF-[-F+F+F]+[+F-F-F]"; len =3 ; angle = 30 ; degree =5; x = 400 ; y = 500 ; stackpointer = 0 ; for (int i = 0 ; i <1024 ; i++ ) { stack[i].x = 0 ; stack[i].direction = NULL ; } rule = way[rand() % 3] ; for ( int i=1;i<= degree;i++) { int curlen = temprule.GetLength (); int pos=0 , j = 0 ; while (j < curlen) { if(temprule[j] == 'F' ) { rule += way[rand()%3 ]; j++; pos = rule.GetLength()-1 ; } else { rule += temprule[j] ; pos ++; j++; } } temprule = rule ; rule.Empty(); } rule = temprule ; } void CTest18View::OnDraw(CDC* pDC) { CTest18Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; CPen pen(PS_SOLID,1,RGB(0,0,255)); pDC->SelectObject(pen); Node Nextnode ,Curnode; Curnode.x = x ; Curnode.y = y ; Curnode.direction = 90 ; int length =rule.GetLength (); int i = 0; pDC ->MoveTo (x,y); while (i<length) { switch(rule[i]) { case 'F': Nextnode.x = Curnode.x + len * cos(Curnode.direction * PI /180); Nextnode.y = Curnode.y - len * sin(Curnode.direction * PI /180); Nextnode.direction =Curnode.direction ; pDC ->LineTo (Nextnode.x,Nextnode.y); Curnode = Nextnode; break ; case '[': stack[stackpointer] = Curnode; stackpointer ++; break; case ']': Curnode = stack[stackpointer-1]; stackpointer -- ; pDC ->MoveTo (Curnode.x,Curnode.y); break; case '+': Curnode.direction = Curnode.direction + angle; break; case '-': Curnode.direction = Curnode.direction -angle; break; default: ; } i++; } }
效果图如下:
版权声明:本文为博主原创文章,未经博主允许不得转载。