分形之树(Tree)
似乎每一个有关分形的教程都要讲到分形树,大概是因为树是生活中最常见的分形实物吧。这一节将展示下如何一步一步地生长出一棵树来。其实现算法不难,就是在每一次生长迭代中,使线段生长出几条新的线段来。
核心代码:
static void FractalTree(const Vector3& vStart, const Vector3& vEnd, Yreal trunk_angle, Yreal branch_angle, Yreal trunk_c, Yreal branch_c, Vector3* pVertices) { Vector3 vSub = vEnd - vStart; Yreal len = D3DXVec3Length(&vSub); Yreal alfa = atan2f(vSub.y, vSub.x); Yreal trunk = len*trunk_c; Yreal branch = len*branch_c; Yreal branch2 = branch*1.25f; pVertices[0] = vEnd; //pVertices[1] = pVertices[0] + vSub*trunk_c; pVertices[1].x = pVertices[0].x + trunk*cosf(alfa + trunk_angle); pVertices[1].y = pVertices[0].y + trunk*sinf(alfa + trunk_angle); pVertices[1].z = 0.0f; pVertices[2] = vEnd; pVertices[3].x = pVertices[2].x + branch*cosf(alfa + branch_angle); pVertices[3].y = pVertices[2].y + branch*sinf(alfa + branch_angle); pVertices[3].z = 0.0f; pVertices[4] = pVertices[2]; pVertices[5].x = pVertices[4].x + branch*cosf(alfa - branch_angle); pVertices[5].y = pVertices[4].y + branch*sinf(alfa - branch_angle); pVertices[5].z = 0.0f; pVertices[6] = vStart + vSub*0.55f; pVertices[7].x = pVertices[6].x + branch2*cosf(alfa + branch_angle); pVertices[7].y = pVertices[6].y + branch2*sinf(alfa + branch_angle); pVertices[7].z = 0.0f; pVertices[8] = pVertices[6]; pVertices[9].x = pVertices[8].x + branch2*cosf(alfa - branch_angle); pVertices[9].y = pVertices[8].y + branch2*sinf(alfa - branch_angle); pVertices[9].z = 0.0f; }
软件截图:
树的生成需要若干个参数:树干的偏角,树枝的偏角,树干的生长长度,树枝的生长长度,修改下参数可以得到如下形状的树: