Last active
March 8, 2017 08:17
-
-
Save tanishiking/3a61f379c5e8fa85d1b886a4d6e2ef95 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
PenroseLSystem ds; | |
final int ZERO = 48; // ascii '0' equal to 48 | |
final int NINE = 57; // ascii '9' equal to 57 | |
void setup() { | |
size(640, 640); | |
ds = new PenroseLSystem(1000.0); | |
ds.simulate(5); | |
} | |
void draw() { | |
background(255); | |
ds.render(); | |
} | |
class PenroseLSystem { | |
String production; | |
float drawLength; | |
float theta; | |
HashMap<Character, String> rules = new HashMap<Character, String>(); | |
PenroseLSystem(float startLength) { | |
// n+ means n-times + sequence | |
// for example 4+ means ++++ | |
production = "[X]2+[X]2+[X]2+[X]2+[X]"; | |
rules.put('W', "YF2+ZF4-XF[-YF4-WF]2+"); | |
rules.put('X', "+YF2-ZF[3-WF2-XF]+"); | |
rules.put('Y', "-WF2+XF[3+YF2+ZF]-"); | |
rules.put('Z', "2-YF4+WF[+ZF4+XF]2-XF"); | |
drawLength = startLength; | |
theta = radians(36); | |
} | |
void simulate(int gen) { | |
for (int i = 0; i < gen; i++) { | |
drawLength *= 0.5; | |
production = iterate(production); | |
println(production); | |
} | |
} | |
void render() { | |
translate(width/2, height/2); | |
int repeats = 1; | |
for (int i = 0; i < production.length(); i++) { | |
char step = production.charAt(i); | |
switch(step) { | |
case 'F': | |
stroke(random(0, 255), random(0, 255), random(0,255)); | |
for (int j = 0; j < repeats; j++) { | |
line(0, 0, 0, -drawLength); | |
translate(0, -drawLength); | |
} | |
repeats = 1; | |
break; | |
case '+': | |
for (int j = 0; j < repeats; j++) { | |
rotate(theta); | |
} | |
repeats = 1; | |
break; | |
case '-': | |
for (int j =0; j < repeats; j++) { | |
rotate(-theta); | |
} | |
repeats = 1; | |
break; | |
case '[': | |
pushMatrix(); | |
break; | |
case ']': | |
popMatrix(); | |
default: | |
// if step is [0-9], assign it to repeats | |
if ((step >= ZERO) && (step <= NINE)) { | |
repeats = (int)step - ZERO; | |
} | |
break; | |
} | |
} | |
} | |
String iterate(String prod_) { | |
String nextString = ""; | |
for (int i = 0; i < prod_.length(); i++) { | |
char step = production.charAt(i); | |
if(rules.containsKey(step)){ | |
nextString += rules.get(step); | |
} else { | |
if (step != 'F') { | |
nextString += step; | |
} | |
} | |
} | |
return nextString; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment