/* PYTHAGORAS TREE Jeff Thompson Fall 2011 A classic fractal, drawn recursively using a custom function and a 'while' loop. For more info: http://en.wikipedia.org/wiki/Pythagoras_tree_(fractal) www.jeffreythompson.org */ float boxSize = 140; // size of box (starting size, in this case) int minSize = 5; // minimum size for box float rotL = -45; // rotation angle L float rotR = 45; // rotation angle R float twist; // twist the tree's angle using the mouse void setup() { size(1000, 800); smooth(); rectMode(CENTER); noStroke(); } void draw() { // clear background background(255); // update twist if mouse is pressed if (mousePressed) { twist = map(mouseX, 0, width, -135, 225); } else { twist = 0; // reset when the mouse is released } // first box translate(width/2, height-height/3); // starting location fill(116, 50, 0, 100); rect(0, 0, boxSize, boxSize); // initial box // fractalize! branch(boxSize); // draw branches } void branch(float s) { // box size (changes as we iterate) float prevS = s; // store previous size (used to translate) s *= 0.5 * sqrt(2); // update size: 1/2 * sqrt(2) float pythagoreanRise = sqrt((s*s) + (s*s)); // how far to move up // scale color as scale decreases: from (255,150,0) > (116,50,0) float r = map(s, minSize, boxSize, 255, 116); float g = map(s, minSize, boxSize, 150, 50); float b = 0; // exit if the size is too small, otherwise continue! if (s > minSize) { // rotate left pushMatrix(); // local transformations translate(-prevS/2, -prevS/2); // move to UL corner of previous box rotate(radians(rotL-twist)); // rotate 45ยบ translate(s/2, -s/2); // move to center of new box fill(r, g, b, 100); rect(0, 0, s, s); // draw the rectangle branch(s); // recursively call the function - makes the fractal! popMatrix(); // rotate right pushMatrix(); // ditto for right side translate(prevS/2, -prevS/2); rotate(radians(rotR+twist)); translate(-s/2, -s/2); fill(r, g, b, 100); rect(0, 0, s, s); branch(s); popMatrix(); } } void keyPressed() { // spacebar prints 'twist' if (key == 32) { // (for debugging and hacking) println("Twist: " + twist); } }