appalachian autumn

beziers on beziers on beziers #beziers

Created by base12 on 2018/12/19
173
1

Log in to post a comment.

const addMountainHatching = false
const addTreeHatching = false
const drawMoon = true
const addLakeSurface = false

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

class Vec2 {
    constructor(x, y) {
        this.x = x
        this.y = y
    }
    
    add(v) {
        return new Vec2(this.x + v.x, this.y + v.y)
    }
    
    sub(v) {
        return new Vec2(this.x - v.x, this.y - v.y)
    }

    scale(n) {
        return new Vec2(this.x * n, this.y * n)
    }

    distance(v) {
        return Math.sqrt((this.x - v.x) ** 2 + (this.y - v.y) ** 2)
    }
}

class Bezier {
    constructor(steps = 10) {
        this.steps = steps
        this.wayPoints = []
        this.nodes = []
        this.distances = []
    }

    addWayPoint(pt) {
        this.wayPoints.push(pt)
        if (this.wayPoints.length > 3) {
            const j = this.wayPoints.length - 1
            if (j % 2 === 0) return

            for (let i = 0; i < this.steps; i++) {
                const u = i / this.steps
                let node
                if (j === 3) {
                    node = this.interpolate(
                        u,
                        this.wayPoints[j - 3],
                        this.wayPoints[j - 2],
                        this.wayPoints[j - 1],
                        this.wayPoints[j]
                    )
                }
                else {
                    const k = j - 2
                    const pt4 = this.wayPoints[k].scale(2).sub(this.wayPoints[k - 1])
                    node = this.interpolate(
                        u,
                        this.wayPoints[k],
                        pt4,
                        this.wayPoints[k + 1],
                        this.wayPoints[k + 2]
                    )
                }
                let distance = 0
                if (this.nodes.length > 0) {
                    distance = this.distances[this.distances.length - 1] + node.distance(this.nodes[this.nodes.length - 1])
                }
                this.nodes.push(node)
                this.distances.push(distance)
            }
        }
    }
    
    interpolate(u, pt1, pt2, pt3, pt4) {
        return (
            pt1.scale(-1).add(pt2.scale(3)).sub(pt3.scale(3)).add(pt4).scale(u ** 3)
                .add(pt1.scale(3).sub(pt2.scale(6)).add(pt3.scale(3)).scale(u ** 2))
                .add(pt1.scale(-3).add(pt2.scale(3)).scale(u))
                .add(pt1)
        )
    }
}

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

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


const splinePolys = []
const treePolys = []

// The walk function will be called until it returns false.
function walk(i) {
    renderMountain(i)
    renderTree(i)

    // lake shore
    if (i === 0)
    {
        turtle.penup()
        turtle.goto(-80, 40)
        turtle.pendown()
        turtle.goto(80, 40)
    }

    // lake surface    
    if (addLakeSurface && i === 0) {
        const poly = new Polygon()
        poly.cp.push([-90, 40], [90, 40], [90, 90], [-90, 90])
        poly.addHatching(Math.PI / 8, 3)
        poly.draw(turtle)
    }
    
    // sky
    // if (i === 10) {
    //     const poly = new Polygon()
    //     poly.cp.push([-90, -90], [90, -90], [90, -55], [-90, -55])
    //     poly.addHatching(Math.PI * 2 - Math.PI / 8, 7)
    //     for (let j = 0; j < splinePolys.length; j++) {
    //         poly.boolean(splinePolys[j], true)
    //     }
    //     poly.draw(turtle)
    // }

    // hills
    // if (i === 10) {
    //     const poly = new Polygon()
    //     poly.cp.push([-90, -55], [90, -55], [90, 40], [-90, 40])
    //     // poly.addHatching(-0.2, 7)
    //     for (let j = 0; j < 20; j++) {
    //         let y = 40 - Math.log(j) * 28.5
    //         poly.dp.push(new LineSegment([-90, y], [90, y]))
    //     }
    //     for (let j = 0; j < treePolys.length; j++) {
    //         poly.boolean(treePolys[j], true)
    //     }
    //     poly.draw(turtle)
    // }

    // moon
    if (drawMoon && i === 10) {
        const poly1 = new Polygon()
        poly1.createPoly(-60, -80, 50, 7, 0)
        poly1.addOutline()

        const poly2 = new Polygon()
        poly2.createPoly(-57, -82, 50, 6, 0)
        poly2.addOutline()
        poly2.boolean(poly1, false)
        poly2.draw(turtle)

        poly1.boolean(poly2, true)
        poly1.draw(turtle)
    }
    
    return i < 10
}

function renderMountain(i) {
    let y = 10 - i
    let spline = new Bezier()
    let xcount = 15
    let xmid = (xcount - 1) / 2 + (Math.random() * 4 - 2)
    let xstep = 180 / xcount
    let x = 0
    for (; x < xcount; x++) {
        let xfactor = clamp((xmid - Math.abs(x - xmid) - 2) / xmid * 10 * 2, 0, 100)
        let ly = Math.random() * (Math.random() < 0.5 ? -1 : 1) * (((i + 2) / 10) * xfactor) + xfactor / 2
        // if (y === 9) console.log(xfactor)
        spline.addWayPoint(new Vec2(x * xstep, ly, 0))
    }
    let xfactor = 0
    let ly = Math.random() * ((x + y) % 2 ? -1 : 1) * (((y + 2) / 10) * xfactor)
    spline.addWayPoint(new Vec2(x * xstep, ly, 0))

    x++
    xfactor = 0
    ly = Math.random() * ((x + y) % 2 ? -1 : 1) * (((y + 2) / 10) * xfactor)
    spline.addWayPoint(new Vec2(x * xstep, ly, 0))

    const boty = -30

    const poly = new Polygon()
    for (let j = 0; j < spline.nodes.length; j++) {
        poly.cp.push([spline.nodes[j].x - 90, y - 55 - spline.nodes[j].y])
    }
    poly.cp.push([90, boty])
    poly.cp.push([-90, boty])
    poly.addOutline()
    if (addMountainHatching && i > 0) {
        let angle = Math.PI * 2 - Math.PI / 8
        poly.addHatching(angle, map(i, 1, 10, 3, 0.5))
    }
    for (let j = 0; j < splinePolys.length; j++) {
        poly.boolean(splinePolys[j], true)
    }
    poly.dp = poly.dp.filter(line => !(Math.abs(line.p1[1] - boty) < 0.01 || Math.abs(line.p2[1] - boty) < 0.01))
    poly.draw(turtle)

    splinePolys.push(poly)
}

function renderTree(i) {
    let x = map(i, 0, 10, -60, 60)
    let y = 30
    let spline = new Bezier()
    let height = 15 + Math.floor(map(Math.random(), 0, 1, 0, 5))
    let trunkHeight = 3 + Math.random() * 3
    for (let j = 0; j < height; j++) {
        let xvar = map(Math.random(), 0, 1, 0.2, 0.75) * ((i + j) % 2 ? 1 : 2) * (j < trunkHeight ? 0 : j > height - 3 ? 0 : height - 3 - (j - 4) / 2) * 1
        spline.addWayPoint(new Vec2(xvar, y - j * 4, 0))
    }
    
    const poly = new Polygon()
    for (let j = 0; j < spline.nodes.length; j++) {
        poly.cp.push([x - 1 - spline.nodes[j].x, spline.nodes[j].y])
    }
    for (let j = 0; j < spline.nodes.length; j++) {
        poly.cp.push([x + 1 + spline.nodes[spline.nodes.length - 1 - j].x, spline.nodes[spline.nodes.length - 1 - j].y])
    }
    poly.addOutline()
    if (addTreeHatching) {
        poly.addHatching(Math.random(), map(Math.random(), 0, 1, 0.75, 1.5))
    }
    for (let j = 0; j < treePolys.length; j++) {
        poly.boolean(treePolys[j], true)
    }
    poly.draw(turtle)
    
    treePolys.push(poly)

    renderReflection(i, height, trunkHeight)
}

function renderReflection(i, height, trunkHeight) {
    let x = map(i, 0, 10, -60, 60)
    let y = 40
    let k = i //Math.random() * 2
    let spline = new Bezier()
    for (let j = 0; j < height; j++) {
        let xvar = Math.random() * ((k + j) % 2 ? -1 : 1) * (j < trunkHeight ? 0.5 : 2) * 2
        spline.addWayPoint(new Vec2(xvar, y + j * 2.5, 0))
    }
    
    const poly = new Polygon()
    for (let j = 0; j < spline.nodes.length; j++) {
        poly.cp.push([x + spline.nodes[j].x, spline.nodes[j].y])
    }
    poly.addOutline()
    poly.dp.length = poly.dp.length - 1
    poly.draw(turtle)
}