//when seed === 0, the seed is the 'original Math.random()'

const seed = 0; //min=0 max=10000 step=1
const gridSize = 8; //min=2 max=20 step=1
const spacing = 2; //min=0 max=10 step=.2
const margin = 10; //min=0 max=50 step=1
const maxSplits = 2; //min=0 max=5 step=1
const pSplit = .9; //min=0 max=1 step=.01
const splitBase = .6;//min=0 max=1 step=.01
const allowOpague = 1; //min=0 max=1 step=1 (No, Yes)
const plotterOpacity = .15; //min=.05 max=3 step=.05

const allowFillers = allowOpague === 1;

// 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 polygons = new Polygons();

// 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('anything here' + (seed === 0? Math.random(): seed));
// Add a seed in seedrandom, then Math.random will use this seed

const randPt = [(.5 + .25 * Math.random()) * Math.sin(Math.random()*2*Math.PI), (.5 + .25 * Math.random()) * Math.cos(Math.random()*2*Math.PI)];
const targets = Array.from({length: 4}).flatMap((v, i) => Array.from({length: 5}).map((vv, ii, arr) => -1 + 2 * ii/arr.length).map(st => i % 2 == 0? [(i == 0 || i == 3? -1: 1), st * (i>1? -1: 1)]: [st * (i>1? -1: 1), (i == 0 || i == 3? -1: 1)]));

const types = [
    //circle
    [[Array.from({length: 50}).map((v, i, arr) => [Math.cos(2*Math.PI*i/arr.length), Math.sin(2*Math.PI*i/arr.length)]), (rot, scale) => [1, allowFillers && Math.random() < .5? plotterOpacity: 200 * scale]], [[[-1, -1], [-1, 1], [1, 1], [1, -1]], (rot, scale) => [rot, .1 * scale]]],
    //triangle
    [[[[1, 1], [-1, 1], [-1, -1]], (rot, scale) => [rot, .1 * scale]], [[[-1, -1], [-1, 1], [1, 1], [1, -1]], (rot, scale) => [1, allowFillers && Math.random() < .5? plotterOpacity: 200 * scale]]],
    //sun
    targets.map((v, i, arr) => [[randPt, v, arr[(i+1)%arr.length]], () => null]),
    //empty
    [[[[0,0]], () => null]],
    //straigthlines
    [[[[-1, -1], [-1, 1], [1, 1], [1, -1]],(rot, scale) => [rot, .1 * scale]]],
    //star
    [[Array.from({length: 10+((Math.random()*12)|0) * 2}).map((v, i, arr) => [(i%2==0?1:.5)*Math.sin(2*Math.PI*i/arr.length), (i%2==0?1:.5)*Math.cos(2*Math.PI*i/arr.length)]),(rot, scale) => [1, allowFillers && Math.random() < .5? plotterOpacity: 200 * scale]],[[[-1, -1], [-1, 1], [1, 1], [1, -1]],(rot, scale) => [rot, .1 * scale]]],
    //hourglass
    [[[[-1, -1], [1, 1], [1, -1], [-1, 1]],(rot, scale) => [rot, .1 * scale]],[[[-1, -1], [-1, 1], [1, 1], [1, -1]],(rot, scale) => [1, allowFillers && Math.random() < .5? plotterOpacity: 200 * scale]]]
];

class IteratorIterator {
    constructor(iterator) {
        this.iterators = iterator? [iterator]: [];
    }
    add(iterator) {
        this.iterators.push(iterator);
    }
    *iterator() {
        if(this.iterators.length === 0) { return undefined; }
        
        const item = this.iterators[this.iterators.length - 1].next();
        if(item.done) {
            this.iterators.pop();
        }
        if(this.iterators.length === 0) {
            return item.value;
        }
        yield item.value;
    }
}

const ii = new IteratorIterator((new Grid(gridSize, spacing, 200 - 2 * margin, [0,0], {generation: 1})).iterator());

// The walk function will be called until it returns false.
function walk(i) {
    const cell = ii.iterator().next();

    if(cell.value.properties.generation <= maxSplits && Math.random() < pSplit * (splitBase ** cell.value.properties.generation)) {
        return ii.add( (new Grid(2, cell.value.spacing, cell.value.size, cell.value.center, {generation: cell.value.properties.generation + 1})).iterator() ) || true;
    }
    
    drawCell(cell.value);
    
    return !cell.done;
}

function drawCell(cell){
    const rotAngle = ((Math.random() * 4) | 0) * Math.PI / 2;
    types[Math.random() * types.length | 0].forEach(l => {
        const p = polygons.create();
        const rot = rot2(rotAngle);
        p.addPoints( ...l[0].map(pt => add2(cell.center, scale2(trans2(rot, pt), cell.size / 2)) ));
        const h = l[1](rotAngle, cell.size);
        if(h) { p.addHatching(...h); }
        p.addOutline();
        polygons.draw(turtle, p);
    });
}

function norm2(a) { return scale2(a, 1/len2(a)); }
function add2(a, b) { return [a[0]+b[0], a[1]+b[1]]; }
function sub2(a, b) { return [a[0]-b[0], a[1]-b[1]]; }
function mul2(a, b) { return [a[0]*b[0], a[1]*b[1]]; }
function scale2(a, s) { return mul2(a, [s,s]); }
function lerp2(a,b,t) { return [a[0]*(1-t) + b[0]*t, a[1]*(1-t) + b[1]*t]; }
function lenSq2(a) { return a[0]**2+a[1]**2; }
function len2(a) { return Math.sqrt(lenSq2(a)); }

function rot2(a) { return [Math.cos(a), -Math.sin(a), Math.sin(a), Math.cos(a)]; }
function trans2(m, a) { return [m[0]*a[0]+m[2]*a[1], m[1]*a[0]+m[3]*a[1]]; }

function dist2(a,b) { return Math.hypot(...sub2(a,b)); }
function dot2(a,b) { return a[0]*b[0]+a[1]*b[1]; }
function cross2(a,b) { return a[0]*b[1] - a[1]*b[0]; }
function multiply2(a2x2, a) { return [(a[0]*a2x2[0])+(a[1]*a2x2[1]),(a[0]*a2x2[2])+(a[1]*a2x2[3])]; }

////////////////////////////////////////////////////////////////
// Square Grid utility code - Created by Jurgen Westerhof 2023
// https://turtletoy.net/turtle/4633bef396
////////////////////////////////////////////////////////////////
function Grid(size, spacing, canvasSize = 200, location = [0, 0], cellProperties = {}) {
    function add2(a, b) { return [a[0]+b[0], a[1]+b[1]]; }
    class Grid {
        constructor(size, spacing, canvasSize, location, cellProperties) {
            this.size = size;
            this.spacing = spacing;
            this.cellProperties = cellProperties;

            this.iterateMax = this.size**2 - 1;
            
            this.canvasSize = canvasSize;
            this.location = location;
            
            this.cellSize = (Math.max(0.1, (canvasSize - (size-1)*spacing)) / size);
        }
        getCellByIndex(i) {
            const col = i % this.size;
            const row = i / this.size | 0;
            return this.getCellByCoord(col, row);
        }
        getCellByCoord(col, row) {
            const vertice = (i) => (i + .5) * this.cellSize + i * this.spacing - this.canvasSize / 2;
            return {
                center: add2(this.location, [vertice(col), vertice(row)]),
                column: col,
                row: row,
                index: row * this.size + col,
                size: this.cellSize,
                spacing: this.spacing,
                properties: this.cellProperties,
            };
        }
        *iterator() {
            for(let i = 0; i < this.iterateMax; i++) {
                yield this.getCellByIndex(i);
            }
            return this.getCellByIndex(this.iterateMax);
        }
        hasNext(i = 0) {
            return i <= this.iterateMax;
        }
    }
    return new Grid(size, spacing, canvasSize, location, cellProperties);
}

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