Random Tree Code

by buechley

A tree generator that includes randomness.


import processing.pdf.*;

float theta;
int trunkWidth,trunkHeight;

//variables to play with
int initialTrunkWidth =50;
int initialTrunkHeight=100;
int minBranchLength=18;
int minBranchWidth=3;
int branchAngle = 30;
int randomNessAngle=15;

void setup() {
size(640, 500); //set the size of the window (& the pdf document)
smooth();
noLoop();
//set the name of the pdf document
trunkWidth=initialTrunkWidth;
trunkHeight=initialTrunkHeight;
keyPressed();
}

void draw() {
//set the background color to be white
background(255);
//set the foreground color to be deep blue
stroke(50,50,100);
//start the tree from the bottom of the screen
translate(width/2,height);
// Draw the trunk
strokeWeight(trunkWidth);
line(0,0,0,-90);
// Move to the end of that line
translate(0,-90);
// Start the recursive branching!
branch(trunkHeight,trunkWidth);
}

void keyPressed() {
//if the 'q' key is pressed, finish drawing the PDF & quit
if (key == 'q') {
String fileName= "tree"+millis()+".pdf"; //create a unique name for your file
beginRecord(PDF, fileName);
draw();
endRecord();
exit();
}
//if any other key is pressed, draw a new tree
else {
redraw();
}
}

void branch(float h, int w) {
//each branch will be between .7 & .9 * the size of the previous one
h = h*random(.7,.9);
//the width of each branch decreases at each iteration
w=int(w/1.4);

float a = random (branchAngle-randomNessAngle, branchAngle+randomNessAngle);
theta = radians(a);
// All recursive functions must have an exit condition!!!!
// Here, ours is defined by the max branch lengths & widths
if (h > minBranchLength & w > minBranchWidth) {

//right branch
pushMatrix(); // Save the current state of transformation (i.e. where are we now)
rotate(theta); // Rotate by theta
strokeWeight(w); //set the width of the branch
line(0, 0, 0, -h); // draw the branch
translate(0, -h); // move to the end of the branch
branch(h,w); // Ok, now call myself to draw two new branches!!
popMatrix(); // Whenever we get back here, we "pop" in order to restore the previous matrix state

// Repeat the same thing, only branch off to the "left" this time!
pushMatrix();
rotate(-theta);
strokeWeight(w);
line(0, 0, 0, -h);
translate(0, -h);
branch(h,w);
popMatrix();
}
}