Growing tree

Growing tree.
Export to GIF to see it grow.

Log in to post a comment.

// LL 2021

const spawn_rate = 11; // min=1 max=50 step=1
const thickness = 0.2; // min=0.001 max=0.5 step=0.001
const max_life = 333; // min=1 max=500 step=1
const seed = 0; // min=0 max=100 step=1

const gravity = 0.1; // min=0 max=1 step=0.001

const variation = 90; // min=0 max=100 step=1
const max_variation = variation ? 1 / Math.pow(101-variation, 2.5) : 0;

const offset_y = 90;
const scale = 20; // min=1 max=50 step=1
const style = 2; // min=0 max=3 step=1 (Circles,Lines,Polygons (fast),Polygons (slow))
const circle_fill = 1; // min=0.05 max=1 step=0.05

const max_iterations = 1000; 

const draw_hatching = Math.random() < 0.5;

var max_life_t = max_life;

var new_particles = [];
var particles_to_draw = [];

Canvas.setpenopacity(1);

const turtle = new Turtle();

console.clear();

var polygons = null;

class Particle {
    constructor(x, y, px, py, radius, current_life, spawn) {
        this.x = x;
        this.y = y;
        this.px = px;
        this.py = py;
        this.radius = radius;
        this.current_life = current_life;
        this.spawn = spawn;
        this.rng_move = new RNG(seed*(39+current_life)); 
        this.rng_spawn = new RNG(seed*(95+current_life)); 
    }
    
    dup() {
        return new Particle(this.x, this.y, this.px, this.py, this.radius, this.current_life, this.spawn);
    }

    getDrawRadius() {
        return this.radius * Math.pow((1 - this.current_life / max_life_t), 2);
    }
    
    draw() {
        if (style == 0) {
            const radius = this.getDrawRadius();
            turtle.jump(this.x * scale, (this.y-radius) * scale + offset_y);
            turtle.circle(radius * scale);
            for (var r = radius * scale - circle_fill; r > 0 && circle_fill < 1; r -= circle_fill) {
                turtle.jump(this.x * scale, this.y * scale - r + offset_y);
                turtle.circle(r)
            }
        } else if (style == 1) {
            const x = this.px * scale, y = this.py * scale + offset_y;
            if (getDistance(x, y, turtle.x(), turtle.y()) > 0.1) {
                turtle.jump(x, y);
            }
            turtle.goto(this.x * scale, this.y * scale + offset_y);
        } else {
            particles_to_draw.push(this.dup());
        }
    }
    
    update() {
        var x = this.x, y = this.y, px = this.px, py = this.py;
        this.px = this.x; this.py = this.y;

        // Verlet
        const friction = 0.999;
        x += (x - px) * friction;
        y += (y - py) * friction;
        
        y += gravity / 100 * Math.pow(this.current_life / max_life_t, 5);
        
        const l = getDistance(x, y);
        const rx = rotX(x/l, y/l, Math.PI / 2);
        const ry = rotY(x/l, y/l, Math.PI / 2);
        
        x += rx * l * max_variation * (this.rng_move.nextFloat() - 0.5);
        y += ry * l * max_variation * (this.rng_move.nextFloat() - 0.5);
        
        var dx = x - this.x;
        var dy = y - this.y;
        const l2 = getDistance(dx, dy);
        const max_distance = 0.03;
        if (l2 > max_distance) {
            dx = dx / l2 * max_distance;
            dy = dy / l2 * max_distance;
        }
        
        this.x += dx; this.y += dy;
        const min_distance = 0.0001;
        //if (l2 < min_distance) this.current_life = max_life_t;

        //this.radius *= 0.993;
        if (this.radius < 0.0001) this.current_life = max_life_t;

        this.current_life++;

        const spawn_mod = Math.max(20, Math.floor(this.spawn * (1 - this.current_life / 300)));
        if ((this.current_life % spawn_mod) == 0) {
            const x = this.x;
            const y = this.y;
            const angle = 1 * (this.rng_spawn.nextFloat() - 0.5);
            const px = x - rotX(this.x - this.px, this.y - this.py, angle);
            const py = y - rotY(this.x - this.px, this.y - this.py, angle);
            const radius = this.radius; // * 0.9;
            const current_life = Math.round(this.current_life / (this.rng_spawn.nextFloat() * 0.2 + 0.8));
            const spawn = this.spawn; //Math.floor(this.spawn * 0.5);

            return new Particle(x, y, px, py, radius, current_life, spawn);
        }
        
        return null;
    }
    
    isAlive() { return this.current_life < max_life_t; }
}

function rotX(x, y, a) { return Math.cos(a) * x - Math.sin(a) * y; }
function rotY(x, y, a) { return Math.sin(a) * x + Math.cos(a) * y; }

function getDistance(x1, y1, x2, y2) {
    if (x2 === undefined) x2 = 0;
    if (y2 === undefined) y2 = 0;
    const dx = x1 - x2, dy = y1 - y2;
    return Math.sqrt(dx*dx + dy*dy);
}

function initParticles() {
    polygons = new Polygons();

    const x = 0;
    const y = 0;
    const px = x + 0;
    const py = y + 1;
    const radius = thickness;
    const current_life = 0;
    const spawn = Math.floor(1000/spawn_rate);

    new_particles = [];
    new_particles.push(new Particle(x, y, px, py, radius, current_life, spawn));

    particles_to_draw = [];
}

function walk(i, t) {
    if (i==0) {
        //max_life_t = max_life * (Math.cos(t * Math.PI * 2) + 1) / 2;
        max_life_t = max_life * t;
    
        initParticles();
    }

    var current_particle = null;
    while (true) {
        var early_exit = (i > max_iterations);
        if (current_particle === null || early_exit) {
            if (new_particles.length == 0 || early_exit) {
                console.log(`Final iteration count: ${i-1}`);
                return false;
            }
            current_particle = new_particles.shift();
        }

        const new_particle = current_particle.update();
        if (new_particle != null) new_particles.push(new_particle);

        if (current_particle.isAlive()) {
            current_particle.draw();
        } else {
            if (particles_to_draw.length > 0) {
                const points = [];
                particles_to_draw.forEach( p => {
                    const l = getDistance(p.x, p.y, p.px, p.py);
                    const dx = rotX(p.x - p.px, p.y - p.py, Math.PI / 2) / l;
                    const dy = rotY(p.x - p.px, p.y - p.py, Math.PI / 2) / l;
                    const radius = p.getDrawRadius();
                    var p1x = (p.x + radius * dx) * scale ;
                    var p1y = (p.y + radius * dy) * scale + offset_y;
                    var p2x = (p.x - radius * dx) * scale;
                    var p2y = (p.y - radius * dy) * scale + offset_y;
                    points.push([p1x, p1y]);
                    points.unshift([p2x, p2y]);
                });

                if (style == 2) {
                    turtle.jump(points[0]);
                    points.forEach(p=>turtle.goto(p));
                } else {
                    const p1 = polygons.create();
                    p1.addPoints(...points);
                    if (draw_hatching) p1.addHatching(-Math.PI/4, 1);
                    p1.addOutline();
                    polygons.draw(turtle, p1, true);
                }

                particles_to_draw = [];
            }
            break;
        }
    }

    //sleep(100);
    
    return true;
}

////

function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}

//// Random with seed

function RNG(_seed) {
  // LCG using GCC's constants
  this.m = 0x80000000; // 2**31;
  this.a = 1103515245;
  this.c = 12345;

  this.state = _seed ? _seed : Math.floor(Math.random() * (this.m - 1));
}
RNG.prototype.nextFloat = function() {
  // returns in range [0,1]
  this.state = (this.a * this.state + this.c) % this.m;
  return this.state / (this.m - 1);
}

////////////////////////////////////////////////////////////////
// Polygon Clipping utility code - Created by Reinder Nijhoff 2019
// https://turtletoy.net/turtle/a5befa1f8d
////////////////////////////////////////////////////////////////

function Polygons() {
	const polygonList = [];
	const Polygon = class {
		constructor() {
			this.cp = [];       // clip path: array of [x,y] pairs
			this.dp = [];       // 2d lines [x0,y0],[x1,y1] to draw
			this.aabb = [];     // AABB bounding box
		}
		addPoints(...points) {
		    // add point to clip path and update bounding box
		    let xmin = 1e5, xmax = -1e5, ymin = 1e5, ymax = -1e5;
			(this.cp = [...this.cp, ...points]).forEach( p => {
				xmin = Math.min(xmin, p[0]), xmax = Math.max(xmax, p[0]);
				ymin = Math.min(ymin, p[1]), ymax = Math.max(ymax, p[1]);
			});
		    this.aabb = [(xmin+xmax)/2, (ymin+ymax)/2, (xmax-xmin)/2, (ymax-ymin)/2];
		}
		addSegments(...points) {
		    // add segments (each a pair of points)
		    points.forEach(p => this.dp.push(p));
		}
		addOutline() {
			for (let i = 0, l = this.cp.length; i < l; i++) {
				this.dp.push(this.cp[i], this.cp[(i + 1) % l]);
			}
		}
		draw(t) {
			for (let i = 0, l = this.dp.length; i < l; i+=2) {
				t.jump(this.dp[i]), t.goto(this.dp[i + 1]);
			}
		}
		addHatching(a, d) {
			const tp = new Polygon();
			tp.cp.push([-1e5,-1e5],[1e5,-1e5],[1e5,1e5],[-1e5,1e5]);
			const dx = Math.sin(a) * d,   dy = Math.cos(a) * d;
			const cx = Math.sin(a) * 200, cy = Math.cos(a) * 200;
			for (let i = 0.5; i < 150 / d; i++) {
				tp.dp.push([dx * i + cy,   dy * i - cx], [dx * i - cy,   dy * i + cx]);
				tp.dp.push([-dx * i + cy, -dy * i - cx], [-dx * i - cy, -dy * i + cx]);
			}
			tp.boolean(this, false);
			this.dp = [...this.dp, ...tp.dp];
		}
		inside(p) {
			let int = 0; // find number of i ntersection points from p to far away
			for (let i = 0, l = this.cp.length; i < l; i++) {
				if (this.segment_intersect(p, [0.1, -1000], this.cp[i], this.cp[(i + 1) % l])) {
					int++;
				}
			}
			return int & 1; // if even your outside
		}
		boolean(p, diff = true) {
		    // bouding box optimization by ge1doot.
		    if (Math.abs(this.aabb[0] - p.aabb[0]) - (p.aabb[2] + this.aabb[2]) >= 0 &&
				Math.abs(this.aabb[1] - p.aabb[1]) - (p.aabb[3] + this.aabb[3]) >= 0) return this.dp.length > 0;
				
			// polygon diff algorithm (narrow phase)
			const ndp = [];
			for (let i = 0, l = this.dp.length; i < l; i+=2) {
				const ls0 = this.dp[i];
				const ls1 = this.dp[i + 1];
				// find all intersections with clip path
				const int = [];
				for (let j = 0, cl = p.cp.length; j < cl; j++) {
					const pint = this.segment_intersect(ls0, ls1, p.cp[j], p.cp[(j + 1) % cl]);
					if (pint !== false) {
						int.push(pint);
					}
				}
				if (int.length === 0) {
					// 0 intersections, inside or outside?
					if (diff === !p.inside(ls0)) {
						ndp.push(ls0, ls1);
					}
				} else {
					int.push(ls0, ls1);
					// order intersection points on line ls.p1 to ls.p2
					const cmpx = ls1[0] - ls0[0];
					const cmpy = ls1[1] - ls0[1];
					int.sort( (a,b) =>  (a[0] - ls0[0]) * cmpx + (a[1] - ls0[1]) * cmpy - 
					                    (b[0] - ls0[0]) * cmpx - (b[1] - ls0[1]) * cmpy);
					 
					for (let j = 0; j < int.length - 1; j++) {
						if ((int[j][0] - int[j+1][0])**2 + (int[j][1] - int[j+1][1])**2 >= 0.001) {
							if (diff === !p.inside([(int[j][0]+int[j+1][0])/2,(int[j][1]+int[j+1][1])/2])) {
								ndp.push(int[j], int[j+1]);
							}
						}
					}
				}
			}
			return (this.dp = ndp).length > 0;
		}
		//port of http://paulbourke.net/geometry/pointlineplane/Helpers.cs
		segment_intersect(l1p1, l1p2, l2p1, l2p2) {
			const d   = (l2p2[1] - l2p1[1]) * (l1p2[0] - l1p1[0]) - (l2p2[0] - l2p1[0]) * (l1p2[1] - l1p1[1]);
			if (d === 0) return false;
			const n_a = (l2p2[0] - l2p1[0]) * (l1p1[1] - l2p1[1]) - (l2p2[1] - l2p1[1]) * (l1p1[0] - l2p1[0]);
			const n_b = (l1p2[0] - l1p1[0]) * (l1p1[1] - l2p1[1]) - (l1p2[1] - l1p1[1]) * (l1p1[0] - l2p1[0]);
			const ua = n_a / d;
			const ub = n_b / d;
			if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) {
				return [l1p1[0] + ua * (l1p2[0] - l1p1[0]), l1p1[1] + ua * (l1p2[1] - l1p1[1])];
			}
			return false;
		}
	};
	return {
		list: () => polygonList,
		create: () => new Polygon(),
		draw: (turtle, p, addToVisList=true) => {
			for (let j = 0; j < polygonList.length && p.boolean(polygonList[j]); j++);
			p.draw(turtle);
			if (addToVisList) polygonList.push(p);
		}
	};
}