const fillBackground = 1; //min=0 max=1 step=1 (No, Yes)
const radiusPattern = 1; //min=0 max=1 step=1 (Uniform, Wavey)
const waveyPeriod = .7;//min=.05 max=3 step=.01
const areaShape = 1; //min=0 max=1 step=1 (Square, Circle)
const maxRadius = 12; //min=2 max=40 step=1
const plotterPenWidth = .15; //min=.01 max=1 step=.01
const shapes = 2; //min=1 max=8 step=1 (Random, Circle, Triangle, Square, Pentagon, Hexagon, Heptagon, Octagon)

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

const uniform = (x,y,maxByContext=maxRadius, max=maxRadius) => Math.min(maxByContext, max, areaShape == 0? 300:Math.max(0, 80-Math.hypot(x,y)) );
const wavey = (x,y,maxByContext=maxRadius,max=maxRadius) => Math.min(maxByContext, max, (Math.cos(Math.hypot(x,y)/(waveyPeriod*10))*.43 + .57) * max, areaShape == 0? 300:Math.max(0, 100-Math.hypot(x,y)) );
                                                                                        //.4 = factor of sin(); .6 gives minum of .2 and max 1
const rfn = radiusPattern == 0? uniform: wavey;


const upd = new UniformPointDistributor();
let iterator = upd.getPointIterator(rfn);

const add2=(a,b)=>[a[0]+b[0],a[1]+b[1]];

// The walk function will be called until it returns false.
function walk(i) {
    const pt = iterator.next().value;
    if(pt === false) return true;
    
    if(pt[2] > .2) {
        const rot = rot2(Math.random() * 2 * Math.PI);
        const shape = shapes == 1? ((Math.random() * 7) | 0) + 1: shapes;
        const steps = shape == 2? Math.ceil(2 * Math.PI * pt[2]): shape;
        
        const core = polygons.create();
        core.addPoints(...getCirclePoints(pt[2]/2, steps).map(p => add2(trans2(rot, p), pt)));
        core.addHatching(1,plotterPenWidth);
        core.addOutline();
        polygons.draw(turtle, core);
        const background = polygons.create();
        background.addPoints(...getCirclePoints(pt[2], steps).map(p => add2(trans2(rot, p), pt)));
        polygons.draw(turtle, background);
    }
    
    const runs = 1000;
    if(fillBackground && i == runs) {
        const p = polygons.create();
        p.addPoints([-100, -100], [100, -100], [100, 100], [-100, 100]);
        const fR = Math.random()*Math.PI;
        p.addHatching(fR,plotterPenWidth /.075);
        p.addHatching(fR+Math.PI/2,plotterPenWidth /.075);
        polygons.draw(turtle, p);
    }
    return i < runs;
}

function debugDrawPoints(turtle, pts) {
    Array.from({length: pts.length+1}).forEach((v, i) => turtle[i == 0? 'jump': 'goto']( add2(pt, pts[i%pts.length]) ));
}

function getCirclePoints(radius, steps = null) {
    return Array.from({length: Math.max(3, (steps == null? Math.ceil(2 * Math.PI * radius): steps))}).map((v, i, arr) => [
            Math.max(.15, radius) * Math.cos(i * 2 * Math.PI / arr.length),
            Math.max(.15, radius) * Math.sin(i * 2 * Math.PI / arr.length)
    ]);
}

function UniformPointDistributor(leftTop = [-100, -100], rightBottom = [100, 100]) {
    class UniformPointDistributor {
        constructor(leftTop = [-100, -100], rightBottom = [100, 100]) {
            this.leftTop = leftTop;
            this.rightBottom = rightBottom;
            this.width = rightBottom[0]-leftTop[0];
            this.height = rightBottom[1]-leftTop[1];
            this.maxDist = (this.width**2+this.height**2)**.5;
            this.pts = [];
        }
    
        *getPointIterator(radiusFunction = null, candidates = 20, maxTries = 1000) {
            if(radiusFunction == null) radiusFunction = (x, y, maximum) => 0;
            
            const randomPoint = () => [Math.random()*this.width+this.leftTop[0],Math.random()*this.height+this.leftTop[1]];
            
            this.pts.push([randomPoint()].map(pt => [...pt, radiusFunction(...pt)])[0]);
            yield this.pts[this.pts.length - 1];
            
            while(true) {
                let pt = [0,0,-1];
                let tries = 0;
                while(pt[2] < 0 && tries < maxTries) {
                    tries++;
                    //using [length] candidate points
                    pt = Array.from({length: candidates})
                         //which are random points
                         .map(i => randomPoint())
                         //then add the distance to that candidate minus the radius of each point it is compared to
                         .map(i => [i[0], i[1], this.pts.map(j => [j[0], j[1], Math.hypot(i[0]-j[0], i[1]-j[1]) - j[2]])
                                                   //so that it is the smallest distance from the
                                                   //candidate to any of the already chosen points
                                                   .reduce((prev, current) => (current[2] < prev[2])? current: prev, [0,0,this.maxDist])[2]
                            ])
                         //then pick the candidate that has the largest minimum distance from the group of candidates
                         .reduce((prev, current) => prev == null? current: ((current[2] > prev[2])? current: prev), null)
                         //and set the 3rd position to its own radius instead of the distance to the nearest point
                         .map((v, i, arr) => i < 2? v: radiusFunction(arr[0], arr[1], v))
                         ////and remove the distance before promoting the candidate
                         //.filter((i, k) => k < 2)
                }
                if(tries == maxTries) return false;
                //add a point to the list
                this.pts.push(pt);
                yield pt;
            }
        }
    }
    return new UniformPointDistributor(leftTop, rightBottom);
}

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]]; } //Matrix(2x1) x Matrix(2x2)

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