Adjustable fractal tree

Example to show how you can use adjustable variables; a new and experimental feature. You can use the sliders below to adjust the Fractal binary tree (en.wikipedia.org/wiki/L-system#Example_2:_Fractal_(binary)_tree).

#fractal #lsystem

Created by reinder on 2019/8/2
Forked from Fractal plant #1
161
1

Log in to post a comment.

// Global code will be evaluated once.
Canvas.setpenopacity(1);

const turtle = new Turtle(0,100);
turtle.left(90);

// l-system
function createLSystem(numIters, axiom) {
    let s = axiom;
    for (let i=0; i<numIters; i++) {
        s = processString(s);
    }
    return s;
}

function processString(oldStr) {
    let newstr = "";
    for (let i=0; i<oldStr.length; i++) {
        newstr += applyRules(oldStr[i]);
    }
    return newstr;
}

function applyRules(ch) {
    switch (ch) {
        case "X": return "F+[X]--[X]";       
        case "F": return "FF"; 
        default: return ch;
    }
}

const angle = 45; // min=0, max=90, step=1
const recursion = 7; // min=1, max=10, step=1
const inst = createLSystem(recursion, "X"); // number of iterations and axiom
const distance = 200*Math.pow(2,-recursion);
const states = [];

// The walk function will be called until it returns false.
function walk(i) {
    const cmd = inst[i];
    
    switch (cmd) {
        case "F":   turtle.forward(distance);
                    break;
        case "B":   turtle.backward(distance);
                    break;
        case "+":   turtle.right(angle);
                    break;
        case "-":   turtle.left(angle);
                    break;
        case "[":   states.push({
                        x: turtle.xcor(),
                        y: turtle.ycor(),
                        h: turtle.heading()
                    });
                    break;
        case "]":   const state = states.pop();
                    turtle.penup();
                    turtle.goto(state.x, state.y);
                    turtle.setheading(state.h);
                    turtle.pendown();
                    break;
        default:
    }
      
    return i < inst.length - 1;
}