Field of grass

Slow as heck grass rendering.
Best use the "fast" style when exporting to GIF.

Log in to post a comment.

// LL 2021

const density = 30; // min=1 max=100 step=1
const thickness = 0.1; // min=0.001 max=0.5 step=0.001
const max_life = 50; // min=1 max=500 step=1
const wave = 0; // min=0 max=5 step=0.01
const seed = 1; // min=0 max=100 step=1

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

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

const offset_y = 100;
const scale = 30; // min=1 max=50 step=1
const style = 2; // min=0 max=2 step=1 (Lines,Polygons (fast),Polygons (slow))

const draw_hatching = 1; // min=0 max=1 step=1 (No,Yes)

var max_life_t = max_life;

var particles_to_draw = [];

Canvas.setpenopacity(1);

const turtle = new Turtle();

var polygons = null;

var current_particle = null;
var current_x = 0;
var current_y = 0;

var wave_t = wave;

class Particle {
    constructor(x, y, px, py, radius, current_life) {
        this.x = x;
        this.y = y;
        this.px = px;
        this.py = py;
        this.radius = radius;
        this.current_life = current_life;
    }
    
    dup() {
        return new Particle(this.x, this.y, this.px, this.py, this.radius, this.current_life);
    }

    getDrawRadius() {
        return this.radius * Math.pow((1 - this.current_life / max_life_t), 2);
    }
    
    draw() {
        if (style == 0) {
            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 * (rng.nextFloat() - 0.5);
        y += ry * l * max_variation * (rng.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++;
    }
    
    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 newBlade() {
    particles_to_draw = [];

    const spread_x = 7;
    const spread_y = 7;

    const x = ((current_x+rng.nextFloat()) / density - 0.5) * spread_x;
    const y = ((current_y-1+rng.nextFloat()) / density) * -spread_y;
    const px = x + 1 * Math.sin((wave_t - 0.5 * (current_x / density)) * Math.PI * 2) * Math.cos((wave_t + 0.2 + current_y / density) * Math.PI * 2) + 0.25 * (rng.nextFloat() - 0.5);
    const py = y + 1;
    const radius = thickness;
    const current_life = 0;

    current_x++;
    if (current_x >= density) {
        current_x = 0;
        current_y++;
        if (current_y >= density) return null;
    }

    return new Particle(x, y, px, py, radius, current_life);
}

function walk(i, t) {
    if (i==0) {
        rng = new RNG(seed);
        //max_life_t = max_life * t;
        wave_t = wave + t;

        polygons = new Polygons();
        current_x = current_y = 0;    
    }

    var current_particle = null;
    while (true) {
        if ((current_particle === null) && ((current_particle = newBlade()) === null)) {
            if (style == 2) { // && !draw_hatching) {
                const p1 = polygons.create();
                const points = [[-100,-100], [100,-100], [100,100], [-100,100]];
                p1.addPoints(...points);
                p1.addHatching(Math.PI/4, 1);
                polygons.draw(turtle, p1, true);
            }

            return false;
        }

        current_particle.update();

        if (current_particle.isAlive()) {
            current_particle.draw();
        } else {
            if (particles_to_draw.length > 0) {
                const points = [];
                particles_to_draw.forEach( (p, id) => {
                    const l = getDistance(p.x, p.y, p.px, p.py);
                    var dx = rotX(p.x - p.px, p.y - p.py, Math.PI / 2) / l;
                    var dy = rotY(p.x - p.px, p.y - p.py, Math.PI / 2) / l;
                    if (id < 4) { dx = 1; dy = 0; }
                    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 == 1) {
                    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 - Math.pow((current_y / density), 0.3) * 0.75);
                    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);
}

var rng = new RNG(seed);

////////////////////////////////////////////////////////////////
// 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);
		}
	};
}