createCanvas(windowWidth, windowHeight);
this.clearItems = function () {
tree.branches.length = 0;
this.addLeaves = function () {
const mousePos = createVector(mouseX, mouseY);
if (this.leaves.length == 0) {
var pos = mousePos.copy();
var dir = createVector(0, 0);
var root = new Branch(null, pos, dir);
this.branches.push(root);
for (let i = 0; i < 10; i++) {
const distance = random(10, 50);
const randomPos = p5.Vector.random2D().mult(distance);
const pos = p5.Vector.add(mousePos, randomPos);
this.leaves.push(new Leaf(pos));
this.grow = function () {
for (var i = 0; i < this.leaves.length; i++) {
var leaf = this.leaves[i];
var closestBranch = null;
for (var j = 0; j < this.branches.length; j++) {
var branch = this.branches[j];
var d = p5.Vector.dist(leaf.pos, branch.pos);
if (closestBranch != null) {
var newDir = p5.Vector.sub(leaf.pos, closestBranch.pos);
closestBranch.dir.add(newDir);
this.leaves = this.leaves.filter((leaf) => leaf.reached == false);
for (var i = this.branches.length - 1; i >= 0; i--) {
var branch = this.branches[i];
branch.dir.div(branch.count + 1);
this.branches.push(branch.next());
this.show = function () {
this.leaves.forEach((leaf) => leaf.show());
this.branches.forEach((branch) => branch.show());
function Branch(parent, pos, dir) {
this.origDir = this.dir.copy();
this.reset = function () {
this.dir = this.origDir.copy();
this.next = function () {
var nextDir = p5.Vector.mult(this.dir, this.len);
var nextPos = p5.Vector.add(this.pos, nextDir);
var nextBranch = new Branch(this, nextPos, this.dir.copy());
this.show = function () {
line(this.pos.x, this.pos.y, this.parent.pos.x, this.parent.pos.y);
this.show = function () {
rect(this.pos.x - 1, this.pos.y - 1, 3, 3);
function mouseClicked() {
function mouseDragged() {
if (keyCode === "c" || "C") {