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