Last active
August 29, 2015 14:24
-
-
Save anjiro/2e115bbb7b54cd699b71 to your computer and use it in GitHub Desktop.
Pythagoras tree in OpenJSCAD
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Experiment with rendering L-Systems in OpenJSCAD | |
// (see https://en.wikipedia.org/wiki/L-system#Example_2:_Pythagoras_tree) | |
//Production rules | |
var rules = | |
{ | |
"1": "11", | |
"0": "1[0]0", | |
}; | |
//One level of production | |
function proc(s) | |
{ | |
var r = ""; | |
s.split('').forEach( | |
function(c) | |
{ | |
r += rules[c] || c; | |
} | |
); | |
return r; | |
} | |
//Run the production rules n times on string s | |
function doL(s, n) | |
{ | |
for(var i = 0; i < n; i++) | |
s = proc(s); | |
return s; | |
} | |
//OpenJSCAD main | |
function main() | |
{ | |
var cl = 2; //cylinder length | |
var o = [], tx = 0, ty = 0, tz = 0, ry = 0; | |
var pos = []; | |
var rot = []; | |
var s = doL("0", 5); | |
s.split('').forEach( | |
function(c) | |
{ | |
if(c == "1") | |
{ | |
o.push(cylinder({r:1, h:cl}).rotateY(ry).translate([tx, ty, tz])); | |
tz += cl * cos(ry); | |
tx += cl * sin(ry); | |
} | |
else if(c == "[") | |
{ | |
pos.push([tx, ty, tz]); | |
rot.push(ry); | |
ry -= 45; | |
} | |
else if(c == "]") | |
{ | |
ry = rot.pop(); | |
t = pos.pop(); | |
tx = t[0]; ty = t[1]; tz = t[2]; | |
ry += 45; | |
} | |
else if(c == "0") | |
{ | |
o.push(cylinder({r:1, h:cl}).rotateY(ry).translate([tx, ty, tz])); | |
tz += cl * cos(ry); | |
tx += cl * sin(ry); | |
o.push(sphere({r:2, center:true}).translate([tx, ty, tz])); | |
} | |
} | |
); | |
return o; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment