Hexagon Fractal

Spawning hexagons recursively.

#hexagon #fractal

Log in to post a comment.

const turtle = new Turtle();
const maxDepth = 6; // min=1, max=10, step=1
const splitChance = 0.8; //min=0, max=1, step=0.001
const addHatching = 1; // min=0, max=1, step=1 (No, Yes)
const firstCubeSize = 140; // min=1, max=200, step=0.5

const polys = new Polygons();

class Hexagon {
    constructor(center, radius, positive, depth) {
        this.center = center;
        this.radius = radius;
        this.positive = positive;
        this.depth = depth;
        
        this.points = [this.center];
        for (let i=0; i<6; i++) {
            this.points.push(add(this.center, [radius*Math.sin(Math.PI*i/3), -radius*Math.cos(Math.PI*i/3)]));
        }
    }
    getPolygons() {
        const p = this.points;
        if (this.positive) {
            return [[p[1],p[2],p[0],p[6]], [p[0],p[2],p[3],p[4]], [p[0],p[4],p[5],p[6]]];
        } else {
            return [[p[0],p[3],p[4],p[5]], [p[1],p[0],p[5],p[6]], [p[1],p[2],p[3],p[0]]];
        }
    }
    getSpawnPoints() {
        const p = this.points, r = this.radius, d = this.depth;
        if (this.positive) {
            return [{center: p[1], depth: d+1, positive: true, radius: r / 2},
                    {center: p[3], depth: d+1, positive: true, radius: r / 2},
                    {center: p[5], depth: d+1, positive: true, radius: r / 2},
                    {center: p[0], depth: d+1, positive: false, radius: r / 2}];
        } else {
             return [{center: p[2], depth: d+1, positive: false, radius: r / 2},
                     {center: p[4], depth: d+1, positive: false, radius: r / 2},
                     {center: p[6], depth: d+1, positive: false, radius: r / 2},
                     {center: p[0], depth: d+1, positive: true, radius: r / 2}];
        }
    }
}

const hexagon = new Hexagon([0,0], firstCubeSize, true, 0);
const hexagons = [];
const pool = [hexagon];

do {
    const h = pool.shift();
    hexagons.push(h);
    
    const spawn = h.getSpawnPoints();
    spawn.forEach(p => {
       if (p.depth < maxDepth && (Math.random() < splitChance / (1 + p.depth*0.05) || p.depth < 2)) {
           pool.push(new Hexagon(p.center, p.radius, p.positive, p.depth));
       } 
    });
} while(pool.length);

hexagons.reverse();

// The walk function will be called until it returns false.
function walk(i) {
    const ps = hexagons[i].getPolygons();

    ps.forEach((p, i) => {
        const poly = polys.create();
        poly.addPoints(...p);
        poly.addOutline();
        if (i==1 && addHatching) {
            poly.addHatching(-Math.PI/4, .5);
        }
        
        polys.draw(turtle, poly);
    })    
    return i < hexagons.length - 1;
}

// 
// 2D Vector math
//

function cross(a, b) { return a[0]*b[1]-a[1]*b[0]; }
function equal(a,b) { return .001>dist_sqr(a,b); }
function scale(a,b) { return [a[0]*b,a[1]*b]; }
function add(a,b) { return [a[0]+b[0],a[1]+b[1]]; }
function sub(a,b) { return [a[0]-b[0],a[1]-b[1]]; }
function dot(a,b) { return a[0]*b[0]+a[1]*b[1]; }
function dist_sqr(a,b) { return (a[0]-b[0])**2+(a[1]-b[1])**2; }
function dist(a,b) { return Math.sqrt(dist_sqr(a,b)); }
function length(a) { return Math.sqrt(dot(a,a)); }
function normalize(a) { return scale(a, 1/length(a)); }
function lerp(a,b,t) { return [a[0]*(1-t)+b[0]*t,a[1]*(1-t)+b[1]*t]; }
function rotate(v, center, angle) {
    const x = v[0] - center[0], y = v[1] - center[1];
    return [x * Math.cos(angle) - y * Math.sin(angle) + center[0], x * Math.sin(angle) + y * Math.cos(angle) + center[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);
		}
	};
}