Path packing

Packing paths using a circle-packing algorithm. The path's bounding sphere is used for packing, and a convex hull is used to occlude the lines.

Draw your path!

#packing #handdrawing #path

Log in to post a comment.

// Path packing. Created by Reinder Nijhoff 2024 - @reindernijhoff
//
// https://turtletoy.net/turtle/e4b2bf3db6
//

const turtle = new Turtle();
const polygons = new Polygons();
const packedInCircle = 1; // min=0, max=1, step=1 (No, Yes)
const scalePower = 0.5; // min=0, max=1, step=0.0001

const path0 = `M-11,-45C-21,-35 -25,-18 -25,-4C-25,4 -27,14 -22,19C-20,21 -19,24 -17,27C-14,31 -10,33 -8,37C-8,38 -7,37 -6,38C-4,40 -2,40 0,42C1,43 3,46 4,45C5,44 5,42 6,41C8,37 11,33 13,29C15,24 20,20 22,15C24,8 24,0 24,-7C24,-12 26,-18 24,-23C22,-30 15,-35 10,-40C6,-44 4,-49 0,-53C-2,-55 -7,-60 -9,-58C-11,-56 -9,-52 -9,-49C-9,-42 -7,-36 -6,-29C-5,-20 -3,-11 -3,-2C-3,4 -5,10 -3,15C-1,20 -3,27 0,32C1,34 3,36 3,39`; // type=path, Draw your path

const canvas_size = 95;
const maxRadius = 2.5; // min=2, max=10, step=0.001
const minRadius = 1.25; // min=1, max=2, step=0.001
const pathScale = 2; // min=1, max=5, step=0.001 Scale of the path drawn relative to the bounding radius of the path
const radius_decr = .99;
const max_tries = 7500;

let radius = maxRadius;
const shapes = [];

class Shape {
    constructor(svg) {
        this.path = new Path(svg);
        let points = this.getPoints();
        
        // center
        const center = scale(points.reduce((a,c) => add(a, c), [0,0]), 1/points.length);
        points = points.map(p => sub(p, center));

        // normalize
        let radius = 0;
        points.forEach( p => radius = Math.max(radius, Math.hypot(p[0], p[1])));
        this.points = points.map(p => scale(p, 1/radius));

        // find hull        
        this.hull = this.getConvexHull(this.points);
    }
    
    getPoints(count = 200) {
        return [...new Array(count)].map( (_, i) => this.path.p(i/(count-1)) );
    }
    
    // Gift wrapping algorithm
    // https://en.wikipedia.org/wiki/Gift_wrapping_algorithm
    getConvexHull(S) {
        S = S.filter( (p, i) => i % 4 === 0);
        S = [...S].sort( (a,b) => a[0] - b[0]);
        let pointOnHull = S[0], endpoint, i = 0;
        const P = [];
        
        do {
            P[i] = pointOnHull;
            endpoint = S[0]; 
            for (let j = 0; j < S.length; j++) {
                if( equal(endpoint, pointOnHull) || cross(sub(S[j], P[i]), sub(endpoint, P[i])) < 0 ) {
                    endpoint = S[j];   // found greater left turn, update endpoint
                }
            }
            i++;
            pointOnHull = [...endpoint];
        } while (!equal(endpoint, P[0]) && i < S.length);

        return P;
    }
    
    draw(center, size, turtle, polygons) {
        const a = Math.random() * Math.PI * 2;
        const rot = [Math.cos(a), -Math.sin(a), Math.sin(a), Math.cos(a)];
        const poly = polygons.create();
        const t = (p, s) => add(scale(transform(p, rot), s), center);
        poly.addPoints(...this.hull.map(p => t(p, size)));
        for (let i=0; i<this.points.length-1; i++) {
            poly.addSegments(t(this.points[i], size), t(this.points[i+1], size));
        }
        polygons.draw(turtle, poly, true);
    }
}

const shape0 = new Shape(path0);

function add_circle(t, r) {
    let coord_found = false;
    let tries = 0;
    
    while (!coord_found && tries < max_tries) {
        tries ++;
        const rc = Math.pow(r/maxRadius, scalePower) * maxRadius;
        const x = Math.random() * (canvas_size-rc)*2 -canvas_size + rc;
        const y = Math.random() * (canvas_size-rc)*2 -canvas_size + rc;
        const possible =
            (!packedInCircle || x**2 + y**2 < (canvas_size - rc)**2) && 
            shapes.every(c => {
                const dx = c[0] - x;
                const dy = c[1] - y;
                const dr = c[2] + r;
                
                return dx**2 + dy**2 > dr**2;
            });
        if (possible) {
            coord_found = true;
            shape0.draw([x,y], rc * pathScale, turtle, polygons);
            shapes.push([x,y,r]);
            return true;
        }
    }
    return false;
}

function walk(i) {
    if (!add_circle(turtle, radius)) {
        radius *= radius_decr;
    }
    return radius >= minRadius;
}

////////////////////////////////////////////////////////////////
// Path utility code. Created by Reinder Nijhoff 2023
// Parses a single SVG path (only M, C and L statements are
// supported). The p-method will return
// [...position, ...derivative] for a normalized point t.
//
// https://turtletoy.net/turtle/46adb0ad70
////////////////////////////////////////////////////////////////
function Path(svg) {
    class MoveTo {
        constructor(p) { this.p0 = p; }
        p(t, s) { return [...this.p0, 1, 0]; }
        length() { return 0; }
    }
    class LineTo {
        constructor(p0, p1) { this.p0 = p0, this.p1 = p1; }
        p(t, s = 1) {
            const nt = 1 - t, p0 = this.p0, p1 = this.p1;
            return [ 
                nt*p0[0] + t*p1[0],
                nt*p0[1] + t*p1[1],
                (p1[0] - p0[0]) * s,
                (p1[1] - p0[1]) * s,
            ];
        }
        length() { 
            const p0 = this.p0, p1 = this.p1;
            return Math.hypot(p0[0]-p1[0], p0[1]-p1[1]);
        }
    }
    class BezierTo {
        constructor(p0, c0, c1, p1) { this.p0 = p0, this.c0 = c0, this.c1 = c1, this.p1 = p1; }
        p(t, s = 1) {
            const nt = 1 - t, p0 = this.p0, c0 = this.c0, c1 = this.c1, p1 = this.p1;
            return [ 
                nt*nt*nt*p0[0] + 3*t*nt*nt*c0[0] + 3*t*t*nt*c1[0] + t*t*t*p1[0],
                nt*nt*nt*p0[1] + 3*t*nt*nt*c0[1] + 3*t*t*nt*c1[1] + t*t*t*p1[1],
                (3*nt*nt*(c0[0]-p0[0]) + 6*t*nt*(c1[0]-c0[0]) + 3*t*t*(p1[0]-c1[0])) * s,
                (3*nt*nt*(c0[1]-p0[1]) + 6*t*nt*(c1[1]-c0[1]) + 3*t*t*(p1[1]-c1[1])) * s,
            ];
        }
        length() {
            return this._length || (
                this._length = Array.from({length:25}, (x, i) => this.p(i/25)).reduce( 
                    (a,c,i,v) => i > 0 ? a + Math.hypot(c[0]-v[i-1][0], c[1]-v[i-1][1]) : a, 0));
        }
    }
    class Path {
        constructor(svg) {
            this.segments = [];
            this.parsePath(svg);
        }
        parsePath(svg) {
            const t = svg.match(/([0-9.-]+|[MLC])/g);
            for (let s, i=0; i<t.length;) {
                switch (t[i++]) {
                    case 'M': this.add(new MoveTo(s=[t[i++],t[i++]]));
                              break;
                    case 'L': this.add(new LineTo(s, s=[t[i++],t[i++]]));
                              break;
                    case 'C': this.add(new BezierTo(s, [t[i++],t[i++]], [t[i++],t[i++]], s=[t[i++],t[i++]]));
                              break;
                    default:  i++;
                }
            }
        }
        add(segment) {
            this.segments.push(segment);
            this._length = 0;
        }
        length() {
            return this._length || (this._length = this.segments.reduce((a,c) => a + c.length(), 0));
        }
        p(t) {
            t = Math.max(Math.min(t, 1), 0) * this.length();
            for (let l=0, i=0, sl=0; i<this.segments.length; i++, l+=sl) {
                sl = this.segments[i].length();
                if (t > l && t <= l + sl) {
                    return this.segments[i].p((t-l)/sl, sl/this.length());
                }
            }
            return this.segments[Math.min(1, this.segments.length-1)].p(0);
        }
    }
    return new Path(svg);
}

// 
// 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 transform(a, mat) { return [a[0] * mat[0] + a[1] * mat[2], a[0] * mat[1] + a[1] * mat[3]]; }

////////////////////////////////////////////////////////////////
// Polygon Clipping utility code - Created by Reinder Nijhoff 2019
// (Polygon binning by Lionel Lemarie 2021)
// https://turtletoy.net/turtle/a5befa1f8d
////////////////////////////////////////////////////////////////
function Polygons(){const t=[],s=25,e=Array.from({length:s**2},t=>[]),n=class{constructor(){this.cp=[],this.dp=[],this.aabb=[]}addPoints(...t){let s=1e5,e=-1e5,n=1e5,h=-1e5;(this.cp=[...this.cp,...t]).forEach(t=>{s=Math.min(s,t[0]),e=Math.max(e,t[0]),n=Math.min(n,t[1]),h=Math.max(h,t[1])}),this.aabb=[s,n,e,h]}addSegments(...t){t.forEach(t=>this.dp.push(t))}addOutline(){for(let t=0,s=this.cp.length;t<s;t++)this.dp.push(this.cp[t],this.cp[(t+1)%s])}draw(t){for(let s=0,e=this.dp.length;s<e;s+=2)t.jump(this.dp[s]),t.goto(this.dp[s+1])}addHatching(t,s){const e=new n;e.cp.push([-1e5,-1e5],[1e5,-1e5],[1e5,1e5],[-1e5,1e5]);const h=Math.sin(t)*s,o=Math.cos(t)*s,a=200*Math.sin(t),i=200*Math.cos(t);for(let t=.5;t<150/s;t++)e.dp.push([h*t+i,o*t-a],[h*t-i,o*t+a]),e.dp.push([-h*t+i,-o*t-a],[-h*t-i,-o*t+a]);e.boolean(this,!1),this.dp=[...this.dp,...e.dp]}inside(t){let s=0;for(let e=0,n=this.cp.length;e<n;e++)this.segment_intersect(t,[.1,-1e3],this.cp[e],this.cp[(e+1)%n])&&s++;return 1&s}boolean(t,s=!0){const e=[];for(let n=0,h=this.dp.length;n<h;n+=2){const h=this.dp[n],o=this.dp[n+1],a=[];for(let s=0,e=t.cp.length;s<e;s++){const n=this.segment_intersect(h,o,t.cp[s],t.cp[(s+1)%e]);!1!==n&&a.push(n)}if(0===a.length)s===!t.inside(h)&&e.push(h,o);else{a.push(h,o);const n=o[0]-h[0],i=o[1]-h[1];a.sort((t,s)=>(t[0]-h[0])*n+(t[1]-h[1])*i-(s[0]-h[0])*n-(s[1]-h[1])*i);for(let n=0;n<a.length-1;n++)(a[n][0]-a[n+1][0])**2+(a[n][1]-a[n+1][1])**2>=.001&&s===!t.inside([(a[n][0]+a[n+1][0])/2,(a[n][1]+a[n+1][1])/2])&&e.push(a[n],a[n+1])}}return(this.dp=e).length>0}segment_intersect(t,s,e,n){const h=(n[1]-e[1])*(s[0]-t[0])-(n[0]-e[0])*(s[1]-t[1]);if(0===h)return!1;const o=((n[0]-e[0])*(t[1]-e[1])-(n[1]-e[1])*(t[0]-e[0]))/h,a=((s[0]-t[0])*(t[1]-e[1])-(s[1]-t[1])*(t[0]-e[0]))/h;return o>=0&&o<=1&&a>=0&&a<=1&&[t[0]+o*(s[0]-t[0]),t[1]+o*(s[1]-t[1])]}};return{list:()=>t,create:()=>new n,draw:(n,h,o=!0)=>{reducedPolygonList=function(n){const h={},o=200/s;for(var a=0;a<s;a++){const c=a*o-100,r=[0,c,200,c+o];if(!(n[3]<r[1]||n[1]>r[3]))for(var i=0;i<s;i++){const c=i*o-100;r[0]=c,r[2]=c+o,n[0]>r[2]||n[2]<r[0]||e[i+a*s].forEach(s=>{const e=t[s];n[3]<e.aabb[1]||n[1]>e.aabb[3]||n[0]>e.aabb[2]||n[2]<e.aabb[0]||(h[s]=1)})}}return Array.from(Object.keys(h),s=>t[s])}(h.aabb);for(let t=0;t<reducedPolygonList.length&&h.boolean(reducedPolygonList[t]);t++);h.draw(n),o&&function(n){t.push(n);const h=t.length-1,o=200/s;e.forEach((t,e)=>{const a=e%s*o-100,i=(e/s|0)*o-100,c=[a,i,a+o,i+o];c[3]<n.aabb[1]||c[1]>n.aabb[3]||c[0]>n.aabb[2]||c[2]<n.aabb[0]||t.push(h)})}(h)}}}