what is curviness?

a study of bezier

Log in to post a comment.

// polygon code pulled from: https://turtletoy.net/turtle/789cce3829
// core truchet code pulled from: https://turtletoy.net/turtle/1dc2d96bc9

const maxCurviness = 1.2

// You can find the Turtle API reference here: https://turtletoy.net/syntax
Canvas.setpenopacity(1);

// Global code will be evaluated once.
const turtle = new Turtle();

const size = 10
const tileIndexes = [...Array(size * size)].map((v, i) => i)

function walk(i) {
    const listIndex = Math.floor(Math.random() * tileIndexes.length)
    const tileIndex = tileIndexes[listIndex]
    tileIndexes.splice(listIndex, 1)
    
    const y = Math.floor(tileIndex / 10) - 5
    const x = (tileIndex % 10) - 5
    drawTile(x, y)

    return tileIndexes.length > 0
}

function drawTile(x, y) {
    const curviness = map(x, -5, 5, 0, 1)
    const controlPointOffset = map(curviness, 0, 1, 0, maxCurviness)
    const size = 20
    const xdir = Math.random() < 0.5
    const ydir = Math.random() < 0.5
    const clip = new Polygon()
    clip.createPoly(x * size + size / 2, y * size + size / 2, 4, Math.sqrt(2 * ((size / 2) ** 2)), Math.PI / 4)
    // clip.addOutline()
    // clip.draw(turtle)
    const poly = new Polygon()
    let icount = 0
    for (let ly = -size; ly < size; ly+=2) {
        for (let i = 0; i < (icount % 2 ? 1 : 2); i++) {
            const ly2 = ly + (icount % 2 ? 0 : i ? 0.2 : -0.2)
            const spt = new Vec2(0.001 + x * size + (xdir ? 0 : size), y * size + (ydir ? ly2 : size - ly2))
            const ept = new Vec2(0.001 + x * size + (xdir ? size : 0) + (xdir ? -ly2 : ly2), y * size + (ydir ? size : 0))
            const a = new Vec2(spt.x + (ept.x - spt.x) * controlPointOffset, spt.y)
            const b = new Vec2(ept.x, ept.y - (ept.y - spt.y) * controlPointOffset)
            const curve = bezierCurve([spt, a, b, ept])
            addCurve(poly, curve)
        }
        icount += 1
    }
    poly.boolean(clip, false)
    poly.draw(turtle)
}

function addCurve(poly, p) {
    for (let i = 0, l = p.length; i < l - 1; i++) {
        poly.dp.push(new LineSegment([p[i].x, p[i].y], [p[i + 1].x, p[i + 1].y]))
    }
}

function bezierCurve(p) {
    const steps = 12
    const cp = [p[0]]
    for (var i = 1; i <= steps; i++) {
        cp.push(bezierCurvePos(p, i / steps))
    }
    return cp
}

// cubic bezier curve in 2 dimensions
// equivalent to the function above, just in a more intuitive form
function bezierCurvePos(p, t) {
    // combination of 2 quadric beziers
    var q=[]; 
    var r=[]; 
    for(var i=0;i<3;i++) q.push(Vec2.lerp(p[i],p[i+1],t))
    for(var i=0;i<2;i++) r.push(Vec2.lerp(q[i],q[i+1],t))
    return Vec2.lerp(r[0],r[1],t)
}

// helpers

function avg(items) {
    return items.reduce((acc, curr) => acc + curr, 0) / items.length
}

function map(v, min, max, omin, omax) {
    return omin + (v - min) / (max - min) * (omax - omin)
}

function clamp(v, min, max) {
    return Math.max(Math.min(v, max), min)
}

function lerp(a, b, fract) {
    return a + (b - a) * fract
}

function randomFrom(arr) {
    return arr[Math.floor(Math.random() * arr.length)]
}

function isWithin(x, min, max) {
    return min <= x && x <= max
}

// vector

class Vec2 {
    constructor(x, y) {
        this.x = x
        this.y = y
    }

    rotate(angle) {
        return new Vec2(
            this.x * Math.cos(angle) - this.y * Math.sin(angle),
            this.x * Math.sin(angle) + this.y * Math.cos(angle)
        )
    }
    
    multn(n) {
        return new Vec2(this.x * n, this.y * n)
    }

    add(pt) {
        return new Vec2(this.x + pt.x, this.y + pt.y)
    }

    sub(pt) {
        return new Vec2(this.x - pt.x, this.y - pt.y)
    }
    
    index(size) {
        return Math.floor(this.x) + Math.floor(this.y) * size
    }

    equals(pt) {
        return this.x === pt.x && this.y === pt.y
    }
    
    distance(pt) {
        return Math.sqrt((this.x - pt.x) ** 2 + (this.y - pt.y) ** 2)
    }
    
    floor(pt) {
        return new Vec2(Math.floor(this.x), Math.floor(this.y))
    }

    addX(x) {
        return new Vec2(this.x + x, this.y)
    }

    addY(y) {
        return new Vec2(this.x, this.y + y)
    }    

    static lerp(a, b, fract) {
        return new Vec2(lerp(a.x, b.x, fract), lerp(a.y, b.y, fract))
    }
}

// the following is copied from: https://turtletoy.net/turtle/789cce3829

let lineSegmentsDrawn = []

// polygon functions
function LineSegment(p1, p2) {
    this.p1 = p1;
    this.p2 = p2;
}
LineSegment.prototype.unique = function() {
    for (let i=0, l=lineSegmentsDrawn.length; i<l; i++) {
        const ls = lineSegmentsDrawn[i];
        if ( (equal2(this.p1, ls.p1) && equal2(this.p2, ls.p2)) ||
             (equal2(this.p1, ls.p2) && equal2(this.p2, ls.p1)) ){
            return false;
        }
    }
    lineSegmentsDrawn.push(this);
    return true;
}

function Polygon() {
    this.cp = []; // clip path: array of [x,y] pairs
    this.dp = []; // 2d line to draw: array of linesegments
}
Polygon.prototype.clone = function() {
    const p = new Polygon()
    p.cp = [...this.cp]
    p.dp = [...this.dp]
    return p
}
Polygon.prototype.addOutline = function(s=0) {
    for (let i=s, l=this.cp.length; i<l; i++) {
        this.dp.push(new LineSegment(this.cp[i], this.cp[(i+1)%l]));
    }
}
Polygon.prototype.createPoly = function(x,y,c,r,a) {
    this.cp = [];
    for (let i=0; i<c; i++) {
        this.cp.push( [x + Math.sin(i*Math.PI*2/c+a) * r, y + Math.cos(i*Math.PI*2/c+a) * r] );
    }
}
Polygon.prototype.addHatching = function(a,d) {
    // todo, create a tight bounding polygon, for now fill screen
    const tp = new Polygon();
    tp.createPoly(0,0,4,200,Math.PI*.5);
    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 = .5; i<150/d; i++) {
        tp.dp.push(new LineSegment([dx*i+cy,dy*i-cx], [dx*i-cy,dy*i+cx]));
        tp.dp.push(new LineSegment([-dx*i+cy,-dy*i-cx], [-dx*i-cy,-dy*i+cx]));
    }
    tp.boolean(this, false);
    this.dp = this.dp.concat(tp.dp);
}
Polygon.prototype.draw = function(t) {
    if (this.dp.length ==0) {
        return;
    }
    for (let i=0, l=this.dp.length; i<l; i++) {
        const d = this.dp[i];
        if (d.unique()) {
            if (!equal2(d.p1, t.pos())) {
                t.penup();
                t.goto(d.p1);
                t.pendown();   
            }
            t.goto(d.p2);
        }
    }
}
Polygon.prototype.inside = function(p) {
    // find number of intersections from p to far away - if even you're outside
    const p1 = [0, -1000];
    let int = 0;
    for (let i=0, l=this.cp.length; i<l; i++) {
        if (segment_intersect2(p, p1, this.cp[i], this.cp[(i+1)%l])) {
            int ++;
        }    
    }
    return int & 1;
}
Polygon.prototype.boolean = function(p, diff = true) {
    // very naive polygon diff algorithm - made this up myself
    const ndp = [];
    for (let i=0, l=this.dp.length; i<l; i++) {
        const ls = this.dp[i];
        
        // find all intersections with clip path
        const int = [];
        for (let j=0, cl=p.cp.length; j<cl; j++) {
            const pint = segment_intersect2(ls.p1,ls.p2,p.cp[j],p.cp[(j+1)%cl]);
            if (pint) {
                int.push(pint);
            }
        }
        if (int.length == 0) { // 0 intersections, inside or outside?
            if (diff != p.inside(ls.p1)) {
                ndp.push(ls);
            }
        } else {
            int.push(ls.p1); int.push(ls.p2);
            // order intersection points on line ls.p1 to ls.p2
            const cmp = sub2(ls.p2,ls.p1);
            int.sort((a,b) => dot2(sub2(a,ls.p1),cmp)-dot2(sub2(b,ls.p1),cmp));
            
            for (let j=0; j<int.length-1; j++) {
                if (!equal2(int[j], int[j+1]) && 
                    diff != p.inside(scale2(add2(int[j],int[j+1]),.5))) {
                    ndp.push(new LineSegment(int[j], int[j+1]));
                }
            }
        }
    }
    this.dp = ndp;
    return this.dp.length > 0;
}

// vec2 functions
const equal2=(a,b)=>0.001>dist_sqr2(a,b);
const scale2=(a,b)=>[a[0]*b,a[1]*b];
const add2=(a,b)=>[a[0]+b[0],a[1]+b[1]];
const sub2=(a,b)=>[a[0]-b[0],a[1]-b[1]];
const dot2=(a,b)=>a[0]*b[0]+a[1]*b[1];
const dist_sqr2=(a,b)=>(a[0]-b[0])*(a[0]-b[0])+(a[1]-b[1])*(a[1]-b[1]);
const segment_intersect2=(a,b,d,c)=>{
    const e=(c[1]-d[1])*(b[0]-a[0])-(c[0]-d[0])*(b[1]-a[1]);
    if(0==e)return false;
    c=((c[0]-d[0])*(a[1]-d[1])-(c[1]-d[1])*(a[0]-d[0]))/e;
    d=((b[0]-a[0])*(a[1]-d[1])-(b[1]-a[1])*(a[0]-d[0]))/e;
    return 0<=c&&1>=c&&0<=d&&1>=d?[a[0]+c*(b[0]-a[0]),a[1]+c*(b[1]-a[1])]:false;
}