"Maximum call stack size exceeded" 在处理 JS 时实施 Fractal plant 时出错

"Maximum call stack size exceeded" error while implementing Fractal plant in processing JS

我正在尝试在处理 javascript 中实现一个分形工厂(直到级别 - 6)。即使满足基本条件,我仍收到 "Maximum call stack size exceeded" 错误。

代码如下: 第一个函数自定义画线根据长度、角度和原点画线。 增量功能将角度增加 25 度。 减量函数将角度减小 25 度。

var customDrawLine = function(x, y, length, angle)
{
    var f={x2:'', y2:''};
    f.x2 = x+(sqrt(sq(length)/(1+sq(tan (angle)))));
    f.y2 = y + ((f.x2-x) * tan (angle));
    line(x, y, f.x2, f.y2);
    return f;
};
var incrementAngle = function(angle)
{
    return (angle+25);
};
var decrementAngle = function(angle)
{
    return (angle-25);
};

var fProductionRule = function(x, y, z, degrees, flag)
{
    var l = {x1:'', y1:''};
    if(flag === 1)
    {
        for (var a=0; a<2;a++)
        {
           l = customDrawLine(l.x1, l.y1, z, degrees);
        }
    }
    else
    {
        l = customDrawLine(l.x1, l.y1, z, degrees);
    }
    return l;
};
var xProductionRule = function(x, y, degrees, nLevel, flag)
{
    var k = {x1:'', y1:''};
    var m;
    k.x1 = x;
    k.y1 = y;
    m = degrees;
    for(var z=0; z<7; z++)
    {
        var f = fProductionRule(k.x1, k.y1, (10-z), m, flag);
        m = incrementAngle(m);
        flag = 1;
        {
            {
                xProductionRule(f.x2,f.y2, m, z);
            }
            m = decrementAngle(m);
            xProductionRule(f.x2,f.y2, m, z);
        }
        m = decrementAngle(m);
        f = fProductionRule(k.x1, k.y1, (10-z), m, flag);
        {
            m = decrementAngle(m);
            f = fProductionRule(k.x1, k.y1, (10-z), m, flag);
            xProductionRule(f.x2,f.y2, m, z);
        }
        m = incrementAngle(m);
        xProductionRule(f.x2,f.y2, m, z);
       }
   };
var drawShape = function(x, y, degrees) 
{
   xProductionRule(x, y, degrees, 0, 0);
};
drawShape(10, 380, 25);

您的代码包含无限递归,因为 xProductionRule 无条件调用自身。

要绘制分形,您必须限制递归的深度,或者防止渲染特定尺寸(如 1 像素)以下的部分。

我看到 xProductionRule 有 5 个参数,其中一个叫做 nLevel,但是那个参数没有在任何地方使用,实际上你调用函数只有 4 个参数。我认为您将使用该参数来限制递归的深度。向函数添加一些检查 (nLevel < 7),并使每个递归调用都包含 nLevel+1 作为参数。

在我看来,根据您提到的维基百科文章,您的代码框架应该像这样构造:

function drawA(depth, ... /* placement information */) {
    // here, draw the current branch
    // and then continue with it's children
    if (depth > 0) {
        drawA(depth - 1, ... /* derived placement information  */)
        drawB(depth - 1, ... /* another derived placement information  */)
    }
}

function drawB(depth, ... /* placement information */) {
    // here, draw the current branch
    // and then continue with it's children
    if (depth > 0) {
        drawA(depth - 1, ... /* derived placement information  */)
    }
}

drawA(7, ... /* placement of the root branch */)

我看不到需要 7 环的地方。