分形之樹(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;
}
樹的生成需要若干個參數:樹干的偏角,樹枝的偏角,樹干的生長長度,樹枝的生長長度,修改下參數可以得到如下形狀的樹: