# L-system 與碎形

March 15, 2022

## L-system 描述

• `F`：前進並畫線
• `+`：左轉
• `-`：右轉
• `[`：將目前狀態置入堆疊
• `]`：取出堆疊頂的狀態

• 初始：`X`
• 規則：`X → F[+X][-X]`

V 是符號集合，包含可被生成的變數以及不能被生成的常數；ω 是初始符號集合或稱為公理（axiom），為文法之源，P 是產生規則。

• 變數：`X`
• 常數：`F[]+-`
• 公理：`X`
• 規則：`X → F[+X][-X]`

## lsystem2 函式

dotSCAD 的 `lsystem2` 就提供了 2D 版本的 L-system 描述生成函式，實現了方才談到的簡單文法，例如，就方才的樹生長來說：

``````use <turtle/lsystem2.scad>

for(line = dedup(tree())) {
polyline_join(line)
circle(.1);
}

function tree(n = 5, angle = 20, leng = 1, heading = 0, start = [0, 0]) =
let(
axiom = "X",            // 公理
rules = [               // 規則
["X", "F[+X][-X]"]
]
)
lsystem2(axiom, rules, n, angle, leng, heading, start);
``````

``````use <turtle/lsystem2.scad>

for(i = [0:2]) {
translate([0, -i * 15])
for(line = dedup(plant())) {
polyline_join(line)
circle(.1);
}
}

function plant(n = 5, angle = 25, leng = 1, heading = 0, start = [0, 0], rule_prs = [0.6, 0.6]) =
let(
axiom = "X",
rules = [
["X", "F+[[X]-X]-F[-FX]+X"],
["F", "FF"]
]
)
lsystem2(axiom, rules, n, angle, leng, heading, start, rule_prs = rule_prs);
``````

## lsystem3 函式

dotSCAD 的 `lsystem3` 函式，提供了 3D 版本的 L-system 描述生成函式，例如，來看看 3D 版本的蕨葉成長描述：

``````use <turtle/lsystem3.scad>

for(line = dedup(fern())) {
polyline_join(line)
sphere(.5);
}

function fern(n = 8, angle = 4, leng = 1, heading = 0, start = [0, 0, 0]) =
let(
axiom = "EEEA",
rules = [
["A", "[++++++++++++++EC]B^+B[--------------ED]B+BA"],
["C", "[---------EE][+++++++++EE]B&&+C"],
["D", "[---------EE][+++++++++EE]B&&-D"]
]
)
lsystem3(axiom, rules, n, angle, leng, heading, start, forward_chars = "ABCDE");
``````

``````use <turtle/lsystem3.scad>

for(line = dedup(hilbert_curve())) {
polyline_join(line)
sphere(.25);
}

function hilbert_curve(n = 3, angle = 90, leng = 1, heading = 0, start = [0, 0, 0]) =
let(
axiom = "A",
rules = [
["A", "B-F+CFC+F-D&F^D-F+&&CFC+F+B//"],
["B", "A&F^CFB^F^D^^-F-D^|F^B|FC^F^A//"],
["C", "|D^|F^B-F+C^F^A&&FA&F^C+F+B^F^D//"],
["D", "|CFB-F+B|FA&F^A&&FB-F+B|FC//"]
]
)
lsystem3(axiom, rules, n, angle, leng, heading, start);
``````