Hilly sunrise 🌅

or sunset...

Log in to post a comment.

const largePeriod = 350; //min=1 max=500 step=1
const largeAmplitude = 35; //min=0 max=50 step=1
const smallPeriod = 100; //min=1 max=500 step=1
const smallAmplitude = 10; //min=0 max=50 step=1
const microPeriod = 7; //min=1 max=500 step=1
const microAmplitude = 2; //min=0 max=10 step=1
const ridgeCount = 10; //min=1 max=10 step=1
const distExp = 1.1; //min=0 max=5 step=.1
const sunRadius = 20; //min=0 max=50 step=.1
const sunFlareRadius = 150; //min=50 max=300 step=1
const sunFlareCount = 18; //min=3 max=30 step=1
const sunFlareOffset = 5; //min=0 max=360 step=.1
const gradientDistance = .2; //min=.2 max=10 step=.1

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

// Global code will be evaluated once.
turtlelib_init();
loadHatcheryNamespace();
R.seed('test');
const polygons = new Polygons();
const turtle = new Bale(.04);
const s = Simplex().createNoise2D();


const ridges = Array.from({length: ridgeCount}).map((e, i) => {
    const mY = (80 - Math.sin(i/(ridgeCount - 1) * Math.PI / 2) * 80);
    const dist = 1 - (i / (ridgeCount - 1));
    return Array.from({length: 201}).map((e, i) => [i-100, 
        mY +
        (dist / 3)**distExp * largeAmplitude*s(i/((dist / 3)*largePeriod), 0 + mY)+
        (dist / 1.5)**distExp * smallAmplitude*s(i/((dist / 1.5)*smallPeriod), 50 + mY)+
        dist**distExp * microAmplitude*s(i/(dist*microPeriod), 100 + mY)
    ])
});

///console.log(ridges);

// The walk function will be called until it returns false.
let ridgePts = [];
function walk(i) {
    const ridge = ridges[i];

    turtle.setOpacity(1 - i/(ridges.length - 1))
    
    const p = polygons.create();
    ridgePts = [[-110, 110], [-110, ridge[0][1]], ...ridge, [110, ridge[ridge.length - 1][1]], [110, 110]];
    p.opacity = 1 - i/(ridges.length - 1);
    p.addPoints(...ridgePts);
    p.addHatching(1, gradientDistance);
    polygons.draw(turtle, p);
    
    turtle[i == 0? 'jump': 'goto'](ridges[i]);
    
    if(i == ridges.length - 2) {
        const maxRidgeY = ridgePts.reduce((a, c) => Math.max(a, c[1]), -100);
        
        const radPerFlare = 2 * Math.PI / sunFlareCount;

        const subSun = [];
        const subFlare = [];
        for(let j = 0, max = radPerFlare * sunRadius | 0; j < max; j++) {
            subSun.push([
                sunRadius * Math.cos(.5 * radPerFlare * j / (max - 1)),
                sunRadius * Math.sin(.5 * radPerFlare * j / (max - 1))
            ]);
        }
        for(let j = 0, max = radPerFlare * sunFlareRadius | 0; j < max; j++) {
            subFlare.push([
                sunFlareRadius * Math.cos(.5 * radPerFlare + .5 * radPerFlare * j / (max - 1)),
                sunFlareRadius * Math.sin(.5 * radPerFlare + .5 * radPerFlare * j / (max - 1))
            ]);
        }
        const rotX = sunFlareOffset * Math.PI / 180;
        const sunPts = Array.from({length: sunFlareCount})
                            .flatMap((e, i) => [...subSun, ...subFlare].map(pt => V.trans(V.rot2d(rotX + -i * Math.PI * 2 / sunFlareCount), pt)))
                            .filter(pt => pt[1] < maxRidgeY);

        const sun = polygons.create();
        sun.addPoints(...sunPts);
        //sun.opacity = .25;
        //sun.addHatching(1, 1);
        sun.addHatching(new GradientCircularHatching(turtle, gradientDistance, [0, 0], 1, [[0, 0], [sunRadius + .25 * (sunFlareRadius - sunRadius), 0], [sunFlareRadius, .5]]))
        //sun.opacity = 1;
        //sun.addOutline();
        polygons.draw(turtle, sun);
        
        const bgPts = [[-101, maxRidgeY], [-101, -101], [101, -101], [101, maxRidgeY]];
        const bg = polygons.create();
        bg.addPoints(...bgPts);
        bg.opacity = .5;
        bg.addHatching(new LineHatching(0, gradientDistance, 0, [ [[0,-10], .2], [[0, -100], .5]]));
        polygons.draw(turtle, bg);
    }
    
    return i < ridges.length - 1;
}

////////////////////////////////////////////////////////////////
// Bale utility code 2.0 - Created by Jurgen Westerhof 2025
// https://turtletoy.net/turtle/7b8c486a30
// (Ab)using the opacity, usage:
//      Canvas.setpenopacity(sceneOpacity);
//      const bale = new Bale(sceneOpacity);
// Then use bale wherever you would use a turtle object to 'draw'
// in 'opacity' x (i.e Polygon hatching with a bale object and
// .25 interspacing), or:
//      bale.setOpacity(.5);
//      bale.jump(0,0);
//      bale.goto(40,0);
////////////////////////////////////////////////////////////////
function Bale(sceneOpacity, turtleClass = Turtle) {
    class Turtle {
        #useTurtleCount = 0;
        #turtles = [];
        #sceneOpacity = 0;
        #opacity = 1;
        #useTurtleCounts = {};
        constructor(sceneOpacity, turtleClass) {
            this.#sceneOpacity = sceneOpacity;
            this.#turtles = Array.from({length: Math.max(1, this.getTurtleCountForOpacity(1))}, (e,i) => new turtleClass());
            this.#useTurtleCount = this.#turtles.length;
        }
        //set opacity(op) {
        //    
        //}
        get opacity() {
            return this.#opacity;
        }
        setOpacity(opacity) {
            if(opacity < 0 || 1 < opacity) {
                throw new Error(`Out of bounds opacity. 0 <= opacity <= 1, got ${opacity}`);
            }
            this.#opacity = opacity;
            if(this.#useTurtleCounts[''+this.#opacity] === undefined) {
                this.#useTurtleCounts[''+this.#opacity] = this.getTurtleCountForOpacity(opacity);
            }
            this.#useTurtleCount = this.#useTurtleCounts[''+this.#opacity];
        }
        getProp(prop) {
            return this.#turtles[0][prop];
        }
        invokeProp(action, a, b, c, d, e, f, g) {
            return this.#turtles.reduce((acc, turtle, i) => turtle[action == 'goto' && this.#useTurtleCount <= i? 'jump': action](a, b, c, d, e, f, g), 0);
        }
        getTurtleCountForOpacity(targetOpacity) {
            if (targetOpacity <= 0) return 0;
            if (targetOpacity >= .5 && this.#turtles.length == 1) return 1;
            return Math.round(Math.log(1 - Math.min(.99, targetOpacity)) / Math.log(1 - this.#sceneOpacity));
        }
    }
    
    const TurtleProxy = {
        get(target, prop, receiver) {
            switch(prop) {
                case 'setOpacity':
                    return (opacity) => target.setOpacity(opacity);
                case 'clone':
                    throw new Error('Cloning not implemented');
                case 'position': //for faster processing, known functions
                case 'pos':      //of a turtle that don't change the
                case 'xcor':     //the state of a turtle but just tell
                case 'x':        //the state of a turtle, there's no need
                case 'ycor':     //to iterate over the whole bale but
                case 'y':        //only return the value from the first
                case 'heading':  //turtle in the bale. That's where these
                case 'h':        //9 cases are an exception to the rest
                case 'isdown':   //of a turtle's functions
                    return target.getProp(prop);
                default:
                    return (a, b, c, d, e, f, g) => target.invokeProp(prop, a, b, c, d, e, f, g);
            }
        },
    };
    return new Proxy(new Turtle(sceneOpacity, turtleClass), TurtleProxy);
}


// Ported https://www.skypack.dev/view/simplex-noise
function Simplex() {
    const F2 = 0.5 * (Math.sqrt(3) - 1);
    const G2 = (3 - Math.sqrt(3)) / 6;
    const F3 = 1 / 3;
    const G3 = 1 / 6;
    const F4 = (Math.sqrt(5) - 1) / 4;
    const G4 = (5 - Math.sqrt(5)) / 20;
    const fastFloor = (x) => Math.floor(x) | 0;
    const grad2 = /* @__PURE__ */ new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);
    const grad3 = /* @__PURE__ */ new Float64Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]);
    const grad4 = /* @__PURE__ */ new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);
    function createNoise2D(random = Math.random) {
      const perm = buildPermutationTable(random);
      const permGrad2x = new Float64Array(perm).map((v) => grad2[v % 12 * 2]);
      const permGrad2y = new Float64Array(perm).map((v) => grad2[v % 12 * 2 + 1]);
      return function noise2D(x, y) {
        let n0 = 0;
        let n1 = 0;
        let n2 = 0;
        const s = (x + y) * F2;
        const i = fastFloor(x + s);
        const j = fastFloor(y + s);
        const t = (i + j) * G2;
        const X0 = i - t;
        const Y0 = j - t;
        const x0 = x - X0;
        const y0 = y - Y0;
        let i1, j1;
        if (x0 > y0) {
          i1 = 1;
          j1 = 0;
        } else {
          i1 = 0;
          j1 = 1;
        }
        const x1 = x0 - i1 + G2;
        const y1 = y0 - j1 + G2;
        const x2 = x0 - 1 + 2 * G2;
        const y2 = y0 - 1 + 2 * G2;
        const ii = i & 255;
        const jj = j & 255;
        let t0 = 0.5 - x0 * x0 - y0 * y0;
        if (t0 >= 0) {
          const gi0 = ii + perm[jj];
          const g0x = permGrad2x[gi0];
          const g0y = permGrad2y[gi0];
          t0 *= t0;
          n0 = t0 * t0 * (g0x * x0 + g0y * y0);
        }
        let t1 = 0.5 - x1 * x1 - y1 * y1;
        if (t1 >= 0) {
          const gi1 = ii + i1 + perm[jj + j1];
          const g1x = permGrad2x[gi1];
          const g1y = permGrad2y[gi1];
          t1 *= t1;
          n1 = t1 * t1 * (g1x * x1 + g1y * y1);
        }
        let t2 = 0.5 - x2 * x2 - y2 * y2;
        if (t2 >= 0) {
          const gi2 = ii + 1 + perm[jj + 1];
          const g2x = permGrad2x[gi2];
          const g2y = permGrad2y[gi2];
          t2 *= t2;
          n2 = t2 * t2 * (g2x * x2 + g2y * y2);
        }
        return 70 * (n0 + n1 + n2);
      };
    }
    function createNoise3D(random = Math.random) {
      const perm = buildPermutationTable(random);
      const permGrad3x = new Float64Array(perm).map((v) => grad3[v % 12 * 3]);
      const permGrad3y = new Float64Array(perm).map((v) => grad3[v % 12 * 3 + 1]);
      const permGrad3z = new Float64Array(perm).map((v) => grad3[v % 12 * 3 + 2]);
      return function noise3D(x, y, z) {
        let n0, n1, n2, n3;
        const s = (x + y + z) * F3;
        const i = fastFloor(x + s);
        const j = fastFloor(y + s);
        const k = fastFloor(z + s);
        const t = (i + j + k) * G3;
        const X0 = i - t;
        const Y0 = j - t;
        const Z0 = k - t;
        const x0 = x - X0;
        const y0 = y - Y0;
        const z0 = z - Z0;
        let i1, j1, k1;
        let i2, j2, k2;
        if (x0 >= y0) {
          if (y0 >= z0) {
            i1 = 1;
            j1 = 0;
            k1 = 0;
            i2 = 1;
            j2 = 1;
            k2 = 0;
          } else if (x0 >= z0) {
            i1 = 1;
            j1 = 0;
            k1 = 0;
            i2 = 1;
            j2 = 0;
            k2 = 1;
          } else {
            i1 = 0;
            j1 = 0;
            k1 = 1;
            i2 = 1;
            j2 = 0;
            k2 = 1;
          }
        } else {
          if (y0 < z0) {
            i1 = 0;
            j1 = 0;
            k1 = 1;
            i2 = 0;
            j2 = 1;
            k2 = 1;
          } else if (x0 < z0) {
            i1 = 0;
            j1 = 1;
            k1 = 0;
            i2 = 0;
            j2 = 1;
            k2 = 1;
          } else {
            i1 = 0;
            j1 = 1;
            k1 = 0;
            i2 = 1;
            j2 = 1;
            k2 = 0;
          }
        }
        const x1 = x0 - i1 + G3;
        const y1 = y0 - j1 + G3;
        const z1 = z0 - k1 + G3;
        const x2 = x0 - i2 + 2 * G3;
        const y2 = y0 - j2 + 2 * G3;
        const z2 = z0 - k2 + 2 * G3;
        const x3 = x0 - 1 + 3 * G3;
        const y3 = y0 - 1 + 3 * G3;
        const z3 = z0 - 1 + 3 * G3;
        const ii = i & 255;
        const jj = j & 255;
        const kk = k & 255;
        let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;
        if (t0 < 0)
          n0 = 0;
        else {
          const gi0 = ii + perm[jj + perm[kk]];
          t0 *= t0;
          n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);
        }
        let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
        if (t1 < 0)
          n1 = 0;
        else {
          const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];
          t1 *= t1;
          n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);
        }
        let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
        if (t2 < 0)
          n2 = 0;
        else {
          const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];
          t2 *= t2;
          n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);
        }
        let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
        if (t3 < 0)
          n3 = 0;
        else {
          const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];
          t3 *= t3;
          n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);
        }
        return 32 * (n0 + n1 + n2 + n3);
      };
    }
    function createNoise4D(random = Math.random) {
      const perm = buildPermutationTable(random);
      const permGrad4x = new Float64Array(perm).map((v) => grad4[v % 32 * 4]);
      const permGrad4y = new Float64Array(perm).map((v) => grad4[v % 32 * 4 + 1]);
      const permGrad4z = new Float64Array(perm).map((v) => grad4[v % 32 * 4 + 2]);
      const permGrad4w = new Float64Array(perm).map((v) => grad4[v % 32 * 4 + 3]);
      return function noise4D(x, y, z, w) {
        let n0, n1, n2, n3, n4;
        const s = (x + y + z + w) * F4;
        const i = fastFloor(x + s);
        const j = fastFloor(y + s);
        const k = fastFloor(z + s);
        const l = fastFloor(w + s);
        const t = (i + j + k + l) * G4;
        const X0 = i - t;
        const Y0 = j - t;
        const Z0 = k - t;
        const W0 = l - t;
        const x0 = x - X0;
        const y0 = y - Y0;
        const z0 = z - Z0;
        const w0 = w - W0;
        let rankx = 0;
        let ranky = 0;
        let rankz = 0;
        let rankw = 0;
        if (x0 > y0)
          rankx++;
        else
          ranky++;
        if (x0 > z0)
          rankx++;
        else
          rankz++;
        if (x0 > w0)
          rankx++;
        else
          rankw++;
        if (y0 > z0)
          ranky++;
        else
          rankz++;
        if (y0 > w0)
          ranky++;
        else
          rankw++;
        if (z0 > w0)
          rankz++;
        else
          rankw++;
        const i1 = rankx >= 3 ? 1 : 0;
        const j1 = ranky >= 3 ? 1 : 0;
        const k1 = rankz >= 3 ? 1 : 0;
        const l1 = rankw >= 3 ? 1 : 0;
        const i2 = rankx >= 2 ? 1 : 0;
        const j2 = ranky >= 2 ? 1 : 0;
        const k2 = rankz >= 2 ? 1 : 0;
        const l2 = rankw >= 2 ? 1 : 0;
        const i3 = rankx >= 1 ? 1 : 0;
        const j3 = ranky >= 1 ? 1 : 0;
        const k3 = rankz >= 1 ? 1 : 0;
        const l3 = rankw >= 1 ? 1 : 0;
        const x1 = x0 - i1 + G4;
        const y1 = y0 - j1 + G4;
        const z1 = z0 - k1 + G4;
        const w1 = w0 - l1 + G4;
        const x2 = x0 - i2 + 2 * G4;
        const y2 = y0 - j2 + 2 * G4;
        const z2 = z0 - k2 + 2 * G4;
        const w2 = w0 - l2 + 2 * G4;
        const x3 = x0 - i3 + 3 * G4;
        const y3 = y0 - j3 + 3 * G4;
        const z3 = z0 - k3 + 3 * G4;
        const w3 = w0 - l3 + 3 * G4;
        const x4 = x0 - 1 + 4 * G4;
        const y4 = y0 - 1 + 4 * G4;
        const z4 = z0 - 1 + 4 * G4;
        const w4 = w0 - 1 + 4 * G4;
        const ii = i & 255;
        const jj = j & 255;
        const kk = k & 255;
        const ll = l & 255;
        let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;
        if (t0 < 0)
          n0 = 0;
        else {
          const gi0 = ii + perm[jj + perm[kk + perm[ll]]];
          t0 *= t0;
          n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);
        }
        let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;
        if (t1 < 0)
          n1 = 0;
        else {
          const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];
          t1 *= t1;
          n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);
        }
        let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;
        if (t2 < 0)
          n2 = 0;
        else {
          const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];
          t2 *= t2;
          n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);
        }
        let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;
        if (t3 < 0)
          n3 = 0;
        else {
          const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];
          t3 *= t3;
          n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);
        }
        let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;
        if (t4 < 0)
          n4 = 0;
        else {
          const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];
          t4 *= t4;
          n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);
        }
        return 27 * (n0 + n1 + n2 + n3 + n4);
      };
    }
    function buildPermutationTable(random) {
      const tableSize = 512;
      const p = new Uint8Array(tableSize);
      for (let i = 0; i < tableSize / 2; i++) {
        p[i] = i;
      }
      for (let i = 0; i < tableSize / 2 - 1; i++) {
        const r = i + ~~(random() * (256 - i));
        const aux = p[i];
        p[i] = p[r];
        p[r] = aux;
      }
      for (let i = 256; i < tableSize; i++) {
        p[i] = p[i - 256];
      }
      return p;
    }
    
    class Simplex {
        buildPermutationTable(random) { return buildPermutationTable(random); }
        createNoise2D(random) { return createNoise2D(random); }
        createNoise3D(random) { return createNoise3D(random); }
        createNoise4D(random) { return createNoise4D(random); }
    }
    return new Simplex();
}

///////////////////////////////////////////////////////////////////
// Polygon Hatching utility code - Created by Jurgen Westerhof 2024
// https://turtletoy.net/turtle/d068ad6040
// ////////////////////////////////////////////////////////////////
// // To be used with modified Polygon Clipping utility code
// //            Orginal: https://turtletoy.net/turtle/a5befa1f8d
// //    Polygon binning: https://turtletoy.net/turtle/95f33bd383
// // Delegated Hatching: https://turtletoy.net/turtle/d068ad6040
///////////////////////////////////////////////////////////////////
function loadHatcheryNamespace() {
    //for convenience on Turtletoy you can click the arrow to the right of the line number to collapse a class
    //////////////////////////////////////////////////// root
    class PolygonHatching {
        constructor() {
            if (this.constructor === PolygonHatching) {
                throw new Error("PolygonHatching is an abstract class and can't be instantiated.");
            }
            
            this.minX = -100;
            this.minY = -100;
            this.maxX = 100;
            this.maxY = 100;
            this.width = 200;
            this.height = 200;
            
            this.segments = [];
            
            this.init();
        }
        hatch(polygonsClass, thePolygonToHatch) {
            const e = new polygonsClass;
            e.cp.push(...thePolygonToHatch.aabb);//[-1e5,-1e5],[1e5,-1e5],[1e5,1e5],[-1e5,1e5]);
            
            this.addHatchSegments(e.dp);
            
            e.boolean(thePolygonToHatch,!1);
            thePolygonToHatch.dp=[...thePolygonToHatch.dp,...e.dp];
        }
        addHatchSegments(segments) {
            this.getSegments().forEach(e => segments.push(e));
        }
        getSegments() { return this.segments; }
        init() {
            ///////////////////////////////////////////////////////
            // Vector functions - Created by Jurgen Westerhof 2024
            // https://turtletoy.net/turtle/d068ad6040
            ///////////////////////////////////////////////////////
            class Vector {
                static add  (a,b) { return a.map((v,i)=>v+b[i]); }
                static sub  (a,b) { return a.map((v,i)=>v-b[i]); }
                static mul  (a,b) { return a.map((v,i)=>v*b[i]); }
                static div  (a,b) { return a.map((v,i)=>v/b[i]); }
                static scale(a,s) { return a.map(v=>v*s); }
            
                static det(m)                { return m.length == 1? m[0][0]: m.length == 2 ? m[0][0]*m[1][1]-m[0][1]*m[1][0]: m[0].reduce((r,e,i) => r+(-1)**(i+2)*e*this.det(m.slice(1).map(c => c.filter((_,j) => i != j))),0); }
                static angle(a)              { return Math.PI - Math.atan2(a[1], -a[0]); } //compatible with turtletoy heading
                static rot2d(angle)          { return [[Math.cos(angle), -Math.sin(angle)], [Math.sin(angle), Math.cos(angle)]]; }
                static rot3d(yaw,pitch,roll) { return [[Math.cos(yaw)*Math.cos(pitch), Math.cos(yaw)*Math.sin(pitch)*Math.sin(roll)-Math.sin(yaw)*Math.cos(roll), Math.cos(yaw)*Math.sin(pitch)*Math.cos(roll)+Math.sin(yaw)*Math.sin(roll)],[Math.sin(yaw)*Math.cos(pitch), Math.sin(yaw)*Math.sin(pitch)*Math.sin(roll)+Math.cos(yaw)*Math.cos(roll), Math.sin(yaw)*Math.sin(pitch)*Math.cos(roll)-Math.cos(yaw)*Math.sin(roll)],[-Math.sin(pitch), Math.cos(pitch)*Math.sin(roll), Math.cos(pitch)*Math.cos(roll)]]; }
                static trans(matrix,a)       { return a.map((v,i) => a.reduce((acc, cur, ci) => acc + cur * matrix[ci][i], 0)); }
                //Mirror vector a in a ray through [0,0] with direction mirror
                static mirror2d(a,mirror)    { return [Math.atan2(...mirror)].map(angle => this.trans(this.rot2d(angle), this.mul([-1,1], this.trans(this.rot2d(-angle), a)))).pop(); }
        
                static approx(a,b,p) { return this.len(this.sub(a,b)) < (p === undefined? .001: p); }
                static norm  (a)     { return this.scale(a,1/this.len(a)); }
                static len   (a)     { return Math.hypot(...a); }
                static lenSq (a)     { return a.reduce((a,c)=>a+c**2,0); }
                static lerp  (a,b,t) { return a.map((v, i) => v*(1-t) + b[i]*t); }
                static dist  (a,b)   { return Math.hypot(...this.sub(a,b)); }
                
                static dot  (a,b)   { return a.reduce((a,c,i) => a+c*b[i], 0); }
                static cross(...ab) { return ab[0].map((e, i) => ab.map(v => v.filter((ee, ii) => ii != i))).map((m,i) => (i%2==0?-1:1)*this.det(m)); }
            }
            this.V = Vector;
            
            class Intersection2D {
                //a-start, a-direction, b-start, b-direction
                //returns false on no intersection or [[intersection:x,y], scalar a-direction, scalar b-direction
                static info(as, ad, bs, bd) {
                    const d = V.sub(bs, as), det = -V.det([bd, ad]);
                    if(det === 0) return false;
                    const res = [V.det([d, bd]) / det, V.det([d, ad]) / det];
                    return [V.add(as, V.scale(ad, res[0])), ...res];
                }
                static ray(a, b, c, d) {
                    return this.info(a, b, c, d);
                }
                static segment(a,b,c,d, inclusiveStart = true, inclusiveEnd = true) {
                    const i = this.info(a, V.sub(b, a), c, V.sub(d, c));
                    return i === false? false: (
                        (inclusiveStart? 0<=i[1] && 0<=i[2]: 0<i[1] && 0<i[2])
                     && (inclusiveEnd?   i[1]<=1 && i[2]<=1: i[1]<1 && i[2]<1)
                    )?i[0]:false;
                }
            }
            this.Intersection = Intersection2D;
        }
    }
    this.PolygonHatching = PolygonHatching;
    class LineHatching extends PolygonHatching {
        constructor(angle, distance, inp = 0, gradientStops = [ [[0,0], 0], [[0, -100], .5]]) {
            super();
            console.log(gradientStops);
            const h=Math.sin(angle)*distance,o=Math.cos(angle)*distance,a=200*Math.sin(angle),i=200*Math.cos(angle);

            this.segments = Array.from({length: 150/distance}).flatMap((x,y,z,t=.5+y) => {
                const f1 = [h*t+i+inp*(Math.random()-.5),o*t-a+inp*(Math.random()-.5)];
                const t1 = [h*t-i+inp*(Math.random()-.5),o*t+a+inp*(Math.random()-.5)];
                const f2 = [-h*t+i+inp*(Math.random()-.5),-o*t-a+inp*(Math.random()-.5)];
                const t2 = [-h*t-i+inp*(Math.random()-.5),-o*t+a+inp*(Math.random()-.5)];
                const i1 = Intersection.info(f1, V.sub(t1, f1), gradientStops[0][0], V.sub(gradientStops[1][0], gradientStops[0][0]));
                const i2 = Intersection.info(f2, V.sub(t2, f2), gradientStops[0][0], V.sub(gradientStops[1][0], gradientStops[0][0]));
                return [
                    [
                        f1,
                        t1,
                        i1[2] <= 0? gradientStops[0][1]: (1 <= i1[2]? gradientStops[1][1]: N.lerp(gradientStops[0][1], gradientStops[1][1], i1[2]))
                    ],
                    [
                        f2,
                        t2,
                        i2[2] <= 0? gradientStops[0][1]: (1 <= i2[2]? gradientStops[1][1]: N.lerp(gradientStops[0][1], gradientStops[1][1], i2[2]))
                    ],
                ];
            });
        }
    }
    this.LineHatching = LineHatching;
    //////////////////////////////////////////////////// first gen
    // extending PolygonHatching
    class GradientCircularHatching extends PolygonHatching {
        constructor(turtle, distance = 360, center = [0,0], precision = 1, gradientStops = [[0, 1]]) {
            super();
            this.turtle = turtle;
            this.dist = typeof distance == 'function'? distance: (c) => distance;
            this.center = center;
            this.precision = precision;
            this.gradientStops = gradientStops;
        }
        hatch(polygonsClass, thePolygonToHatch) {

            const hp = new polygonsClass;
            hp.cp.push(...thePolygonToHatch.aabb);//[-1e5,-1e5],[1e5,-1e5],[1e5,1e5],[-1e5,1e5]);

            let gsIdx = 0;
            const opacities = [];
            for(let j = 0, r = this.dist(j)/2; r < 301; r+=this.dist(j++)) {
                const opacity = 1;
                while(this.gradientStops[gsIdx][0] <= r && gsIdx < this.gradientStops.length - 1) {
                    gsIdx++;
                }
                if(gsIdx == this.gradientStops.length) {
                    opacities.push(this.gradientStops[this.gradientStops.length - 1][1]);
                    continue;
                }
                if(gsIdx == 0) {
                    opacities.push(1);
                    continue;
                }
                opacities.push(N.lerp(
                    this.gradientStops[gsIdx - 1][1],
                    this.gradientStops[gsIdx][1],
                    (r - this.gradientStops[gsIdx - 1][0]) / (this.gradientStops[gsIdx][0] - this.gradientStops[gsIdx - 1][0])
                ));
            }
            for(let j = 0, r = this.dist(j)/2; r < 301; r+=this.dist(j++)) {
                const opacity = opacities[j];//Math.min(1, Math.max(0, r / 20));
                const segments = [];
                for(let i = 0, max = Math.max(12, 2*Math.PI*r/this.precision | 0); i < max; i++) {
                    segments.push([
                        [this.center[0]+r*Math.sin(i*2*Math.PI/max),this.center[1]+r*-Math.cos(i*2*Math.PI/max)],
                        [this.center[0]+r*Math.sin((i+1)*2*Math.PI/max),this.center[1]+r*-Math.cos((i+1)*2*Math.PI/max)],
                        opacity
                    ]);
                }

                segments.forEach(e => hp.dp.push(e));
                hp.boolean(thePolygonToHatch,!1);

                const dpLen = thePolygonToHatch.dp.length;
                //for(let j = 0; j < hp.dp.length; j++) {
                //    thePolygonToHatch.dpOpacity[dpLen+j] = opacity/4;
                //}
                //console.log('dp', hp.dp)
                thePolygonToHatch.dp=[...thePolygonToHatch.dp,...hp.dp];

                hp.dp = [];
            }
            return;
        }
    }
    this.GradientCircularHatching = GradientCircularHatching
    
}

////////////////////////////////////////////////////////////////
// Polygon Clipping utility code - Created by Reinder Nijhoff 2019
// (Polygon binning by Lionel Lemarie 2021) https://turtletoy.net/turtle/95f33bd383
// (Delegated Hatching by Jurgen Westerhof 2024) https://turtletoy.net/turtle/d068ad6040
// https://turtletoy.net/turtle/a5befa1f8d
//
//
//                       HEAVILY MODIFIED TO ACCOMODATE BALE OPACITY
//                  making it possibly incompatible withother code using
//                            the original version of this code
//
//
// const polygons = new Polygons();
// const p = polygons.create();
// polygons.draw(turtle, p);
// polygons.list();
//
// p.addPoints(...[[x,y],]);
// p.addSegments(...[[x,y],]);
// p.addOutline();
// p.addHatching(angle, distance); OR p.addHatching(HatchObject); where HatchObject has a method 'hatch(PolygonClass, thisPolygonInstance)'
// p.inside([x,y]);
// p.boolean(polygon, diff = true);
// p.segment_intersect([x,y], [x,y], [x,y], [x,y]);
////////////////////////////////////////////////////////////////
function Polygons(){
    const t=[],s=25,e=Array.from({length:s**2},t=>[]),n=class{
        #opacity = 1;
        constructor(){
            this.cp=[],this.dp=[],this.aabb=[],this.dpOpacity=[]
        }
        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]}
        set opacity(op) {
            if(op < 0 || 1 < op) throw new Error(`0 <= Opacity <= 1, got ${op}`);
            this.#opacity = op;
        }
        get opacity() {
            return this.#opacity;
        }
        addSegments(...t){
            for(let i = 0; i < t.length; i+=2) {
                this.dp.push([t[i], t[i+1], this.#opacity]);
            }
        }
        addOutline(){
            for(let t = 0, s = this.cp.length; t < s; t++) {
                this.dp.push([this.cp[t], this.cp[(t+1)%s], this.#opacity]);
            }
        }
        draw(t){
            const op = t.opacity;
            
            for(let s = 0, e = this.dp.length; s < e; s++) {
                t.setOpacity(this.dp[s][2]);
                t.jump(this.dp[s][0]);
                t.goto(this.dp[s][1]);
            }
            /*
            for(let s=0,e=this.dp.length;s<e;s+=2) {
                t.setOpacity(this.dpOpacity[s] == undefined || this.dpOpacity[s] == null? 1: this.dpOpacity[s]);
                t.jump(this.dp[s]);
                t.goto(this.dp[s+1]);
            }
            */
            t.setOpacity(op);
        }
        addHatching(t, s) {
            if(typeof t == 'object') return t.hatch(n, this);
            
            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], this.#opacity]);
                e.dp.push([[-h*t+i,-o*t-a],[-h*t-i,-o*t+a], this.#opacity]);
            }
            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 dpIdx=0,h=this.dp.length;dpIdx<h;dpIdx++){
                const h=this.dp[dpIdx][0],o=this.dp[dpIdx][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,this.dp[dpIdx][2]]);
                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],this.dp[dpIdx][2]])
                }
            }
            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)
        }
    }
}

// Below is automatically maintained by Turtlelib 1.0
// Changes below this comment might interfere with its correct functioning.
function turtlelib_init() {
	turtlelib_ns_c6665b0e9b_Jurgen_Vector_Math();
	turtlelib_ns_13b81fd40e_Jurgen_Randomness();
	turtlelib_ns_f1d1cac336_Jurgen_Numbers();
	turtlelib_ns_c5f8fa95ed_Jurgen_Intersection();
}
// Turtlelib Jurgen Vector Math v 4 - start - {"id":"c6665b0e9b","package":"Jurgen","name":"Vector Math","version":"4"}
function turtlelib_ns_c6665b0e9b_Jurgen_Vector_Math() {
/////////////////////////////////////////////////////////
// Vector functions - Created by Jurgen Westerhof 2024 //
/////////////////////////////////////////////////////////
class Vector {
    static add  (a,b) { return a.map((v,i)=>v+b[i]); }
    static sub  (a,b) { return a.map((v,i)=>v-b[i]); }
    static mul  (a,b) { return a.map((v,i)=>v*b[i]); }
    static div  (a,b) { return a.map((v,i)=>v/b[i]); }
    static scale(a,s) { return a.map(v=>v*s); }

    static det(m)                { return m.length == 1? m[0][0]: m.length == 2 ? m[0][0]*m[1][1]-m[0][1]*m[1][0]: m[0].reduce((r,e,i) => r+(-1)**(i+2)*e*this.det(m.slice(1).map(c => c.filter((_,j) => i != j))),0); }
    static angle(a)              { return Math.PI - Math.atan2(a[1], -a[0]); } //compatible with turtletoy heading
    static rot2d(angle)          { return [[Math.cos(angle), -Math.sin(angle)], [Math.sin(angle), Math.cos(angle)]]; }
    static rot3d(yaw,pitch,roll) { return [[Math.cos(yaw)*Math.cos(pitch), Math.cos(yaw)*Math.sin(pitch)*Math.sin(roll)-Math.sin(yaw)*Math.cos(roll), Math.cos(yaw)*Math.sin(pitch)*Math.cos(roll)+Math.sin(yaw)*Math.sin(roll)],[Math.sin(yaw)*Math.cos(pitch), Math.sin(yaw)*Math.sin(pitch)*Math.sin(roll)+Math.cos(yaw)*Math.cos(roll), Math.sin(yaw)*Math.sin(pitch)*Math.cos(roll)-Math.cos(yaw)*Math.sin(roll)],[-Math.sin(pitch), Math.cos(pitch)*Math.sin(roll), Math.cos(pitch)*Math.cos(roll)]]; }
    static trans(matrix,a)       { return a.map((v,i) => a.reduce((acc, cur, ci) => acc + cur * matrix[ci][i], 0)); }
    //Mirror vector a in a ray through [0,0] with direction mirror
    static mirror2d(a,mirror)    { return [Math.atan2(...mirror)].map(angle => this.trans(this.rot2d(angle), this.mul([-1,1], this.trans(this.rot2d(-angle), a)))).pop(); }

    static equals(a,b)   { return !a.some((e, i) => e != b[i]); }
    static approx(a,b,p) { return this.len(this.sub(a,b)) < (p === undefined? .001: p); }
    static norm  (a)     { return this.scale(a,1/this.len(a)); }
    static len   (a)     { return Math.hypot(...a); }
    static lenSq (a)     { return a.reduce((a,c)=>a+c**2,0); }
    static lerp  (a,b,t) { return a.map((v, i) => v*(1-t) + b[i]*t); }
    static dist  (a,b)   { return Math.hypot(...this.sub(a,b)); }
    
    static dot  (a,b)   { return a.reduce((a,c,i) => a+c*b[i], 0); }
    static cross(...ab) { return ab[0].map((e, i) => ab.map(v => v.filter((ee, ii) => ii != i))).map((m,i) => (i%2==0?-1:1)*this.det(m)); }
    
    static clamp(a,min,max) { return a.map((e,i) => Math.min(Math.max(e, min[i]), max[i])) };
    static rotateClamp(a,min,max) { return a.map((e,i) => {const d = max[i]-min[i];if(d == 0) return min[i];while(e < min[i]) { e+=d; }while(e > max[i]) { e-=d; }return e;});
    }
}
this.V = Vector;
}
// Turtlelib Jurgen Vector Math v 4 - end
// Turtlelib Jurgen Randomness v 2 - start - {"id":"13b81fd40e","package":"Jurgen","name":"Randomness","version":"2"}
function turtlelib_ns_13b81fd40e_Jurgen_Randomness() {
///////////////////////////////////////////////////////////////
// Pseudorandom functions - Created by Jurgen Westerhof 2024 //
///////////////////////////////////////////////////////////////
class Random {
    static #apply(seed) {
        // Seedable random number generator by David Bau: http://davidbau.com/archives/2010/01/30/random_seeds_coded_hints_and_quintillions.html
        !function(a,b,c,d,e,f,g,h,i){function j(a){var b,c=a.length,e=this,f=0,g=e.i=e.j=0,h=e.S=[];for(c||(a=[c++]);d>f;)h[f]=f++;for(f=0;d>f;f++)h[f]=h[g=s&g+a[f%c]+(b=h[f])],h[g]=b;(e.g=function(a){for(var b,c=0,f=e.i,g=e.j,h=e.S;a--;)b=h[f=s&f+1],c=c*d+h[s&(h[f]=h[g=s&g+b])+(h[g]=b)];return e.i=f,e.j=g,c})(d)}function k(a,b){var c,d=[],e=typeof a;if(b&&"object"==e)for(c in a)try{d.push(k(a[c],b-1))}catch(f){}return d.length?d:"string"==e?a:a+"\0"}function l(a,b){for(var c,d=a+"",e=0;e<d.length;)b[s&e]=s&(c^=19*b[s&e])+d.charCodeAt(e++);return n(b)}function m(c){try{return o?n(o.randomBytes(d)):(a.crypto.getRandomValues(c=new Uint8Array(d)),n(c))}catch(e){return[+new Date,a,(c=a.navigator)&&c.plugins,a.screen,n(b)]}}function n(a){return String.fromCharCode.apply(0,a)}var o,p=c.pow(d,e),q=c.pow(2,f),r=2*q,s=d-1,t=c["seed"+i]=function(a,f,g){var h=[];f=1==f?{entropy:!0}:f||{};var o=l(k(f.entropy?[a,n(b)]:null==a?m():a,3),h),s=new j(h);return l(n(s.S),b),(f.pass||g||function(a,b,d){return d?(c[i]=a,b):a})(function(){for(var a=s.g(e),b=p,c=0;q>a;)a=(a+c)*d,b*=d,c=s.g(1);for(;a>=r;)a/=2,b/=2,c>>>=1;return(a+c)/b},o,"global"in f?f.global:this==c)};if(l(c[i](),b),g&&g.exports){g.exports=t;try{o=require("crypto")}catch(u){}}else h&&h.amd&&h(function(){return t})}(this,[],Math,256,6,52,"object"==typeof module&&module,"function"==typeof define&&define,"random");
        Math.seedrandom(seed);
    }
    static seedRandom() { this.#apply(new Date().getMilliseconds()); }
    static seedDaily() { this.#apply(new Date().toDateString()); }
    static seed(seed) { this.#apply(seed); }
    static getInt(min, max) { if(max == undefined) {max = min + 1; min = 0; } const [mi, ma] = [Math.min(min, max), Math.max(min, max)]; return (mi + Math.random() * (ma - mi)) | 0;}
    static get(min, max) {if(min == undefined) {return Math.random();}if(max == undefined) {max = min;min = 0;}const [mi, ma] = [Math.min(min, max), Math.max(min, max)];return mi + Math.random() * (ma - mi);}
    static fraction(whole) { return this.get(0, whole); }
    static getAngle(l = 1) { return l * this.get(0, 2*Math.PI); }
    // Standard Normal variate using Box-Muller transform.
    static getGaussian(mean=.5, stdev=.1) {const u = 1 - this.get(); /* Converting [0,1) to (0,1] */const v = this.get();const z = ( -2.0 * Math.log( u ) )**.5 * Math.cos( 2.0 * Math.PI * v );/* Transform to the desired mean and standard deviation: */return z * stdev + mean;}
    static skew(value, skew = 0) { /*skew values (from 0 to 1) by a skew from -1 to 1, respectively right and left skewed (resp more values to left or to right), 0 is not skewed*/return (skew < 0)? value - (this.skew(1-value, -skew) - (1-value)): Math.pow(value, 1-Math.abs(skew));}
    static getNormalDistributed(skew = 0) { /*skew values (from 0 to 1) by a skew from -1 to 1, respectively right and left skewed (resp more values to left or to right), 0 is not skewed*/let v = -1;while(v < 0 || 1 <= v) { v = this.getGaussian(.5, .1) };return this.skew(v, skew);}
}
this.R = Random;
}
// Turtlelib Jurgen Randomness v 2 - end
// Turtlelib Jurgen Numbers v 2 - start - {"id":"f1d1cac336","package":"Jurgen","name":"Numbers","version":"2"}
function turtlelib_ns_f1d1cac336_Jurgen_Numbers() {
/////////////////////////////////////////////////////////
// Number functions - Created by Jurgen Westerhof 2024 //
/////////////////////////////////////////////////////////
class Numbers {
    static approx(a,b,p)            { return Math.abs(a-b) < (p === undefined? .001: p); }
    static clamp(a, min, max)       { return Math.min(Math.max(a, min), max); }
    static rotateClamp(a, min, max) { if(min == max) return min;while (a < min) { a+=(max-min); }while (a > max) { a-=(max-min); }return a;}
    static lerp(a, b, t)            { return V.lerp([a], [b], t).pop(); };
}
this.N = Numbers;
}
// Turtlelib Jurgen Numbers v 2 - end
// Turtlelib Jurgen Intersection v 4 - start - {"id":"c5f8fa95ed","package":"Jurgen","name":"Intersection","version":"4"}
function turtlelib_ns_c5f8fa95ed_Jurgen_Intersection() {
///////////////////////////////////////////////////////////////
// Intersection functions - Created by Jurgen Westerhof 2024 //
///////////////////////////////////////////////////////////////
class Intersection {
    //a-start, a-direction, b-start, b-direction
    //returns false on no intersection or [[intersection:x,y], scalar a-direction, scalar b-direction
    static info(as, ad, bs, bd) { const d = V.sub(bs, as), det = -V.det([bd, ad]); if(det === 0) return false; const res = [V.det([d, bd]) / det, V.det([d, ad]) / det]; return [V.add(as, V.scale(ad, res[0])), ...res]; }
    static ray(a, b, c, d) { return this.info(a, b, c, d); }
    static segment(a,b,c,d, inclusiveStart = true, inclusiveEnd = true) { const i = this.info(a, V.sub(b, a), c, V.sub(d, c)); return i === false? false: ( (inclusiveStart? 0<=i[1] && 0<=i[2]: 0<i[1] && 0<i[2]) && (inclusiveEnd?   i[1]<=1 && i[2]<=1: i[1]<1 && i[2]<1) )?i[0]:false;}
    static tour(tour, segmentStart, segmentDirection) { return tour.map((e, i, a) => [i, this.info(e, V.sub(a[(i+1)%a.length], e), segmentStart, segmentDirection)]).filter(e => e[1] !== false && 0 <= e[1][1] && e[1][1] <= 1).filter(e => 0 <= e[1][2]).map(e => ({position: e[1][0],tourIndex: e[0],tourSegmentPortion: e[1][1],segmentPortion: e[1][2],}));}
    static inside(tour, pt) { return tour.map((e,i,a) => this.segment(e, a[(i+1)%a.length], pt, [Number.MAX_SAFE_INTEGER, 0], true, false)).filter(e => e !== false).length % 2 == 1; }
    static circles(centerA, radiusA, centerB, radiusB) {const result = {intersect_count: 0,intersect_occurs: true,one_is_in_other: false,are_equal: false,point_1: [null, null],point_2: [null, null],};const dx = centerB[0] - centerA[0];const dy = centerB[1] - centerA[1];const dist = Math.hypot(dy, dx);if (dist > radiusA + radiusB) {result.intersect_occurs = false;}if (dist < Math.abs(radiusA - radiusB) && !N.approx(dist, Math.abs(radiusA - radiusB))) {result.intersect_occurs = false;result.one_is_in_other = true;}if (V.approx(centerA, centerB) && radiusA === radiusB) {result.are_equal = true;}if (result.intersect_occurs) {const centroid = (radiusA**2 - radiusB**2 + dist * dist) / (2.0 * dist);const x2 = centerA[0] + (dx * centroid) / dist;const y2 = centerA[1] + (dy * centroid) / dist;const prec = 10000;const h = (Math.round(radiusA**2 * prec)/prec - Math.round(centroid**2 * prec)/prec)**.5;const rx = -dy * (h / dist);const ry = dx * (h / dist);result.point_1 = [x2 + rx, y2 + ry];result.point_2 = [x2 - rx, y2 - ry];if (result.are_equal) {result.intersect_count = Infinity;} else if (V.equals(result.point_1, result.point_2)) {result.intersect_count = 1;} else {result.intersect_count = 2;}}return result;}
}
this.Intersection = Intersection;
}
// Turtlelib Jurgen Intersection v 4 - end