Skip to content

Unlock custom brushes, natural fill effects and intuitive hatching in p5.js

Bug fixes

acamposuribefe434b240af8
diff --git a/README.md b/README.md
index 716a099..a10ebe8 100644
--- a/README.md
+++ b/README.md
@@ -72,10 +72,8 @@ const sketch = (p) => {
brush.instance(p);
p.setup = () => {
- // Canvas must be in WEBGL mode
+ // Canvas must be in WEBGL mode — brush initializes automatically
p.createCanvas(700, 410, p.WEBGL);
- // Initialize p5.brush after canvas is created
- brush.load();
};
p.draw = () => {
@@ -810,7 +808,7 @@ This section covers functions for initializing the drawing system, preloading re
> **Seeding**: p5.brush automatically hooks into p5's `randomSeed()` and `noiseSeed()`. Calling either of those functions seeds both p5 and the library simultaneously — no separate `brush.seed()` call is needed.
- `brush.load(buffer)`
- - **Description**: Initialize the library on the current canvas. If a `p5.Graphics` buffer is passed, the library will target that buffer instead. If a `p5.Framebuffer` is passed, it must belong to the active sketch; call `brush.load(framebuffer)` while that framebuffer is active inside `begin()` / `end()` or `draw()`. Framebuffers created from `p5.Graphics` are not supported. Call `brush.load()` again (with no argument) to switch back to the main canvas.
+ - **Description**: Redirects brush drawing to a secondary canvas target. **Not needed for the main canvas** — the library initializes automatically when `createCanvas()` is called. Pass a `p5.Graphics` buffer or an active `p5.Framebuffer` to draw into that target instead; call `brush.load()` with no argument to switch back to the main canvas. Framebuffers created from `p5.Graphics` are not supported.
- **Parameters**:
- `buffer` (p5.Graphics | p5.Framebuffer): Optional. An offscreen target to draw into.
- **How to use it**:
diff --git a/dist/p5.brush.esm.js b/dist/p5.brush.esm.js
index 1a00495..7f1df41 100644
--- a/dist/p5.brush.esm.js
+++ b/dist/p5.brush.esm.js
@@ -1,2 +1,2 @@
-let t,e,r,i,n;const o=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,s=()=>d?r:window.self.p5.instance,a=t=>{t&&"function"==typeof t.remove&&t.remove()},l=()=>i&&i._renderer&&"function"==typeof i._renderer.activeFramebuffer?i._renderer.activeFramebuffer():null,c=()=>({width:Math.max(1,Math.round(t*n)),height:Math.max(1,Math.round(e*n))}),h=t=>{if(!t)return null;const{width:e,height:r}=c(),i=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),n=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),o=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),s=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return o<=i||s<=n?null:{minX:i,minY:n,maxX:o,maxY:s}},u=()=>{const{width:t,height:e}=c();return{minX:0,minY:0,maxX:t,maxY:e}},f=(t,e,r)=>{const i=(t=>{const e=h(t);if(!e)return null;const{height:r}=c();return{x:e.minX,y:r-e.maxY,width:e.maxX-e.minX,height:e.maxY-e.minY}})(e);if(!i)return!1;const n=t.isEnabled(t.SCISSOR_TEST),o=t.getParameter(t.SCISSOR_BOX);t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{r()}finally{n?t.scissor(o[0],o[1],o[2],o[3]):t.disable(t.SCISSOR_TEST)}return!0},m=(n=!1)=>{const a=((t=!1)=>{if(d&&!t)return{renderer:r,width:r.width,height:r.height};if(!t){const t=s();return{renderer:t,width:t.width,height:t.height}}if(o(t)){if(!o(e=t)||e.renderer._pInst!==s())throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.");return{renderer:s(),width:t.width,height:t.height}}var e;return{renderer:t,width:t.width,height:t.height}})(n);if(i=a.renderer,"webgl2"!==i.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");t=a.width,e=a.height,g=!0,i.loaded&&b.load()};let g=!1,d=!1;const x=()=>{g||m()},p={},y=t=>{d=!0,r=t},v=()=>{i.loaded||(x(),b.load())},b={isBlending:!1,cachedColor:new Object,markDirtyRect(t,e){const r=h(e);var i,n;t&&r&&(t.dirtyRect=(n=r,(i=t.dirtyRect)?n?{minX:Math.min(i.minX,n.minX),minY:Math.min(i.minY,n.minY),maxX:Math.max(i.maxX,n.maxX),maxY:Math.max(i.maxY,n.maxY)}:i:n),t.isDrawn=!0)},markFull(t){t&&(t.dirtyRect=u(),t.isDrawn=!0)},clearMask(t){t&&(t.clear(),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:(t,e)=>t?t.dirtyRect?h(((t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null)(t.dirtyRect,e?2:4)):u():null,captureBlendSource(r){const o=l();if(!o)return i._renderer;var s;(!(s=i.blendSourceFramebuffer)||s.width!==t||s.height!==e||"function"==typeof s.pixelDensity&&s.pixelDensity()!==n)&&(a(i.blendSourceFramebuffer),i.blendSourceFramebuffer=i.createFramebuffer({width:t,height:e,density:n,antialias:!1,depth:!1,stencil:!1}));const c=i.blendSourceFramebuffer;return c.draw(()=>{f(i.drawingContext,r,()=>{i.clear(),i.push(),"function"==typeof i.imageMode&&i.imageMode(i.CENTER??i._renderer?._pInst?.CENTER),i.image(o,0,0,t,e),i.pop()})}),c},load(){n=i.pixelDensity();const r="function"==typeof i.createGraphics?i:i._pInst,o=r.P2D??i.P2D,s=r.WEBGL??i.WEBGL;i.loaded&&i.mask&&i.glMask&&i.mask.width===t&&i.mask.height===e&&i.glMask.width===t&&i.glMask.height===e?(this.mask=i.mask,this.glMask=i.glMask,this.ctx=this.mask.drawingContext,this.mask.dirtyRect??=null,this.mask.isDrawn??=!1,this.glMask.dirtyRect??=null,this.glMask.isDrawn??=!1):(a(i.mask),a(i.glMask),i.mask=r.createGraphics(t,e,o),i.glMask=r.createGraphics(t,e,s),i.loaded=!0,i.shaderProgram??=i.createShader("#version 300 es\n#define GLSLIFY 1\nuniform bool u_flipOutputY;out vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,u_flipOutputY ?-v.y : v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 uv1=vec2(uv.x,1.0-uv.y);vec4 source=texture(u_source,uv1);vec4 maskColor=texture(u_mask,uv1);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=uv1+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.0);}"),this.mask=i.mask,this.mask.pixelDensity(n),this.mask.clear(),this.mask.angleMode(i.DEGREES),this.mask.dirtyRect=null,this.mask.isDrawn=!1,this.ctx=this.mask.drawingContext,this.glMask=i.glMask,this.glMask.pixelDensity(n),this.glMask.clear(),this.glMask.angleMode(this.glMask.DEGREES),this.glMask.drawingContext.lineWidth=0,this.glMask.dirtyRect=null,this.glMask.isDrawn=!1),this.glMask._renderer.uModelMatrix=i._renderer.uModelMatrix},blend(t=!1,e=!1){v();const r=!0===this.isBrush,i=r?this.glMask:this.mask,n=r?this.mask:this.glMask,o=t?._array,s=!!o&&(this.cachedColor[0]!==o[0]||this.cachedColor[1]!==o[1]||this.cachedColor[2]!==o[2]||this.cachedColor[3]!==o[3]);!this.isBlending&&o&&(this.isBlending=!0,this.cachedColor=o,this.glMask.clear()),(e||s)&&(this.justChanged&&(this.applyShader(n,!r),this.justChanged=!1),this.isBlending&&this.applyShader(i,r),o&&(this.cachedColor=o),e&&(this.isBlending=!1))},applyShader(r,n){if(!r?.isDrawn)return;const o=this.getCompositeRect(r,n);if(!o)return void this.clearMask(r);let s=i.shaderProgram;const a=i.drawingContext,c=!!l(),h=this.captureBlendSource(o),u=a.getParameter(a.DEPTH_TEST);a.disable(a.DEPTH_TEST),i.push(),i.translate(0,0),i.shader(s),s.setUniform("u_source",h),s.setUniform("u_isBrush",n),s.setUniform("u_flipOutputY",c),s.setUniform("u_mask",r),s.setUniform("u_color",this.cachedColor),f(a,o,()=>{i.fill(0,0,0,0),i.noStroke(),i.rect(-t/2,-e/2,t,e)}),i.pop(),i.resetShader(),u&&a.enable(a.DEPTH_TEST),this.clearMask(r)}},_=Math.sqrt(3),w=.5*(_-1),R=(3-_)/6,M=t=>0|Math.floor(t),S=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]);function E(t=Math.random){const e=function(t){const e=new Uint8Array(512);for(let t=0;t<256;t++)e[t]=t;for(let r=0;r<255;r++){const i=r+~~(t()*(256-r)),n=e[r];e[r]=e[i],e[i]=n}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>S[t%12*2]),i=new Float64Array(e).map(t=>S[t%12*2+1]);return function(t,n){let o=0,s=0,a=0;const l=(t+n)*w,c=M(t+l),h=M(n+l),u=(c+h)*R,f=t-(c-u),m=n-(h-u);let g,d;f>m?(g=1,d=0):(g=0,d=1);const x=f-g+R,p=m-d+R,y=f-1+2*R,v=m-1+2*R,b=255&c,_=255&h;let S=.5-f*f-m*m;if(S>=0){const t=b+e[_];S*=S,o=S*S*(r[t]*f+i[t]*m)}let E=.5-x*x-p*p;if(E>=0){const t=b+g+e[_+d];E*=E,s=E*E*(r[t]*x+i[t]*p)}let A=.5-y*y-v*v;if(A>=0){const t=b+1+e[_+1];A*=A,a=A*A*(r[t]*y+i[t]*v)}return 70*(o+s+a)}}function A(t,e){let r=new P(t),i=()=>r.next();return i.double=()=>i()+11102230246251565e-32*(2097152*i()|0),i.int32=()=>4294967296*r.next()|0,i.quick=i,i}class P{constructor(t){null==t&&(t=+new Date);let e=4022871197;function r(t){t=String(t);for(let r=0;r<t.length;r++){e+=t.charCodeAt(r);let i=.02519603282416938*e;e=i>>>0,i-=e,i*=e,e=i>>>0,i-=e,e+=4294967296*i}return 2.3283064365386963e-10*(e>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(t),this.s0<0&&(this.s0+=1),this.s1-=r(t),this.s1<0&&(this.s1+=1),this.s2-=r(t),this.s2<0&&(this.s2+=1)}next(){let{c:t,s0:e,s1:r,s2:i}=this,n=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=i,this.s2=n-(this.c=0|n)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let k=A(Math.random());const I=[],C=t=>I.push(t);let L=E(A(Math.random()));const T=(t=0,e=1)=>t+k()*(e-t),N=t=>t[~~(k()*t.length)],Y=(t,e)=>~~T(t,e),z=(t=0,e=1)=>{const r=1-k(),i=k();return Math.sqrt(-2*Math.log(r))*H(360*i)*e+t},X=t=>{let e=0;const r=[];for(const i in t)e+=t[i],r.push({key:i,cumulative:e});const i=k()*e;for(const{key:t,cumulative:e}of r)if(i<e)return isNaN(t)?t:parseInt(t)},D=(t,e,r,i,n,o=!1)=>{let s=i+(t-e)/(r-e)*(n-i);return o?i<n?O(s,i,n):O(s,n,i):s},O=(t,e,r)=>Math.max(Math.min(t,r),e),B=t=>(t%=360)<0?t+360:t,F=1440,G=2*Math.PI/F,$=new Float32Array(F).fill(NaN),W=new Float32Array(F).fill(NaN),H=t=>{const e=~~(4*B(t));let r=$[e];return isNaN(r)&&(r=Math.cos(e*G),$[e]=r),r},U=t=>{const e=~~(4*B(t));let r=W[e];return isNaN(r)&&(r=Math.sin(e*G),W[e]=r),r},j=(t,e=!1)=>{if(e||i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},Z=(t,e=!1)=>e||i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS?180*t/Math.PI:t,V=(t,e,r,i,n)=>{let o=H(n),s=U(n);return{x:o*(r-t)+s*(i-e)+t,y:o*(i-e)-s*(r-t)+e}},K=(t,e,r,i)=>Math.hypot(r-t,i-e),q=(t,e,r,i)=>j(Math.atan2(-(i-e),r-t),!0),J=(t,e,r,i,n=!1)=>{let o=t.x,s=t.y,a=e.x,l=e.y,c=r.x,h=r.y,u=i.x,f=i.y;if(o===a&&s===l||c===u&&h===f)return!1;let m=a-o,g=l-s,d=u-c,x=f-h,p=x*m-d*g;if(0===p)return!1;let y=(d*(s-h)-x*(o-c))/p,v=(m*(s-h)-g*(o-c))/p;return!(!n&&(v<0||v>1))&&{x:o+y*m,y:s+y*g}},Q=()=>i._renderer.uModelMatrix.mat4[12],tt=()=>i._renderer.uModelMatrix.mat4[13],et=()=>i._renderer.uModelMatrix.mat4[0],rt=()=>i._renderer.uModelMatrix.mat4[1],it=()=>i._renderer.uModelMatrix.mat4[4],nt=()=>i._renderer.uModelMatrix.mat4[5];let ot=!1;function st(){ot||(v(),lt=.01*t,ct=-.5*t,ht=-.5*e,ut=Math.round(2*t/lt),ft=Math.round(2*e/lt),bt("hand",(t,e)=>{const r=T(.2,.8),i=Y(5,10);return Rt(e,(e,n)=>.5*i*U(r*n*e+Y(15,25))*.2*H(t)+L(e,n)*i*.7)}),bt("curved",(t,e)=>{let r=Y(-10,10);return Y(0,100)%2==0&&(r*=-1),Rt(e,(e,i)=>3*D(L(.02*e+.03*t,.02*i+.03*t),0,1,-r,r))}),bt("zigzag",(t,e)=>{let r=Y(-30,-15)+Math.abs(44*U(t));Y(0,100)%2==0&&(r*=-1);let i=r,n=0;for(let t=0;t<ut;t++){for(let r=0;r<ft;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e}),bt("waves",(t,e)=>{const r=Y(10,15)+5*U(t),i=Y(3,6)+3*H(t),n=Y(20,35);return Rt(e,(t,e)=>U(r*t)*n*H(e*i)+Y(-3,3))}),bt("seabed",(t,e)=>{const r=T(.4,.8),i=Y(18,26);return Rt(e,(e,n)=>1.1*i*U(r*n*e+Y(15,20))*H(t))}),bt("spiral",(t,e)=>{const r=Y(5,10),i=2*Y(0,2)-1,n=Y(65,80),o=Array.from({length:r},()=>({x:T(.1,.9)*ut,y:T(.1,.9)*ft}));return Rt(e,(t,e)=>{let r=0,s=0;for(const a of o){const o=t-a.x,l=e-a.y,c=1/(o*o+l*l+1),h=Math.atan2(l,o)*(180/Math.PI),u=i*(h+n)*Math.PI/180;r+=c*Math.cos(u),s+=c*Math.sin(u)}return Math.atan2(s,r)*(180/Math.PI)})}),bt("columns",(t,e)=>{const r=Y(3,8),i=Y(25,45);return Rt(e,(t,e)=>U(t*r)*i)}),ot=!0)}class at{constructor(t,e){st(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=at.getColIndex(t),this.rowIdx=at.getRowIndex(e)}reset(){this.plotted=0}isIn(){return p.field.isActive?at.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const r=t,i=e,n=this.x+Q(),o=this.y+tt();return n>=-.3*r&&n<=1.3*r&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&p.field.isActive?mt.get(p.field.current).field[this.colIdx][this.rowIdx]*p.field.wiggle:0}moveTo(t,e,r=1){this.movePos(Z(t),e,r)}_moveToDegrees(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,i=1){this.movePos(t,e,r,i)}movePos(t,e,r,i=!1){const n=i||1;if(this.isIn())for(let o=0;o<e/r;o++){const e=this.angle()-(i?t.angle(this.plotted):t);this.update(this.x+r*H(e),this.y+r*U(e)),this.plotted+=r/n}else this.plotted+=r/n}static getRowIndex(t,e=1){const r=t+tt()-ht;return Math.round(r/lt/e)}static getColIndex(t,e=1){const r=t+Q()-ct;return Math.round(r/lt/e)}static isIn(t,e){return t>=0&&e>=0&&t<ut&&e<ft}}p.field={isActive:!1,current:null,wiggle:1};let lt,ct,ht,ut,ft,mt=new Map;const gt=new Set(["degrees","radians"]);function dt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!gt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function xt(t,e){return function(t,e){if("radians"!==e)return t;for(let e=0;e<t.length;e++)for(let r=0;r<t[e].length;r++)t[e][r]=Z(t[e][r],!0);return t}(t.gen(e,new Array(ut).fill(null).map(()=>new Float32Array(ft))),t.angleMode)}function pt(t=0){if(!p.field.isActive||!p.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=mt.get(p.field.current);e.field=xt(e,t)}function yt(t){if(p.field.wiggle||(p.field.wiggle=1),st(),!mt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(mt.keys()).join(", ")}.`);p.field.isActive=!0,p.field.current=t;const e=mt.get(t);e.field||(e.field=xt(e,0))}function vt(){st(),p.field.isActive=!1}function bt(t,e,r={}){mt.set(t,{gen:e,field:null,angleMode:dt(r)})}function _t(){return st(),Array.from(mt.keys())}function wt(t=1){yt("hand"),p.field.wiggle=t}function Rt(t,e){for(let r=0;r<ut;r++)for(let i=0;i<ft;i++)t[r][i]=e(r,i);return t}class Mt{constructor(t,e=!1){this.a=t,this.vertices=e?t:t.map(([t,e])=>({x:t,y:e})),this.sides=this.vertices.map((t,e,r)=>[t,r[(e+1)%r.length]]),this._intersectionCache={}}intersect(t){const e=`${t.point1.x},${t.point1.y}-${t.point2.x},${t.point2.y}`;if(this._intersectionCache[e])return this._intersectionCache[e];const r=[];for(const[e,i]of this.sides){const n=J(t.point1,t.point2,e,i);n&&r.push(n)}return this._intersectionCache[e]=r,r}show(){p.stroke&&this.draw(),p.hatch&&this.hatch(),p.fill&&this.fill()}}class St{constructor(t){this.segments=[],this.angles=[],this.pres=[],this.type=t,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(t=0,e=0,r=1,i=!1){this.angles.length>0&&this.angles.pop(),t=i?(t%360+360)%360:j(t),this.angles.push(t,t),this.pres.push(r),this.segments.push(e),this.length=this.segments.reduce((t,e)=>t+e,0)}endPlot(t=0,e=1,r=!1){t=r?(t%360+360)%360:j(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=j(t)}pressure(t){return t>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,t)}angle(t){return t>this.length?this.angles[this.angles.length-1]:(this.calcIndex(t),"curve"===this.type?this.curving(this.angles,t)+this.dir:this.angles[this.index]+this.dir)}curving(t,e){let r=t[this.index],i=t[this.index+1]??r;return Math.abs(i-r)>180&&(i>r?i=-(360-i):r=-(360-r)),D(e-this.suma,0,this.segments[this.index],r,i,!0)}calcIndex(t){this.index=-1,this.suma=0;let e=0;for(;e<=t;)this.suma=e,e+=this.segments[this.index+1],this.index++;return this.index}genPol(r,i,n=1,o){st();const s=.5,a=[],l=Math.round(this.length/s),c=new at(r+t/2,i+e/2);let h=0,u=0;for(let r=0;r<l;r++){c.plotTo(this,s,s);const r=this.calcIndex(c.plotted);h+=s,(h>=Math.max(this.segments[r]*o*T(.7,1.3),10)||r>=u)&&c.x&&(a.push([c.x-t/2,c.y-e/2]),h=0,r>=u&&u++)}return new Mt(a)}show(t,e,r=1){p.stroke&&this.draw(t,e,r),p.hatch&&this.hatch(t,e,r),p.fill&&this.fill(t,e,r)}}function Et(t){new Mt(t).show()}function At(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),Yt(0),zt(t,e),zt(t+r,e),zt(t+r,e+i),zt(t,e+i),Xt(!0)}function Pt(t,e,r,i=!1){const n=new St("curve"),o=Math.PI*r,s=T(0,360),a=i?()=>1+.2*i*T():()=>1;for(let t=0;t<4;t++){const e=-90*t+s;n.addSegment(e*a(),o/2*a(),1,!0)}if(i){const t=i*Y(-5,5);n.addSegment(s,Math.abs(t)*(Math.PI/180)*r,1,!0),n.endPlot(t+s,1,!0)}else n.endPlot(s,1,!0);const l=t-r*U(s),c=e-r*H(-s);n.show(l,c,1)}function kt(t,e,r,i,n){const o=Z(i),s=((Z(n)-o)%360+360)%360;if(0===s)return;const a=new St("curve"),l=Math.max(1,Math.ceil(s/90)),c=s/l,h=Math.PI*r*c/180;for(let t=0;t<l;t++)a.addSegment(o+t*c+90,h,1,!0);a.endPlot(o+s+90,1,!0);const u=t+r*H(o),f=e-r*U(o);a.draw(u,f,1)}let It,Ct,Lt,Tt;class Nt{constructor(){this.isClosed=!1,this.curvature=Ct,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){Gt(this.vert,this.curvature,this.isClosed).show()}}function Yt(t=0){Ct=O(t,0,1),It=new Nt}function zt(t,e,r=1){if(!It)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");It.vertex(t,e,r)}function Xt(t=!1){if(!It)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(It.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(It.vertex(...It.vert[0]),It.isClosed=!0),It.show(),It=!1}function Dt(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Tt=[e,r],Lt=new St(t)}function Ot(t,e,r){if(!Lt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Lt.addSegment(t,e,r)}function Bt(t,e){if(!Lt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Lt.endPlot(t,e),Lt.draw(Tt[0],Tt[1],1),Lt=!1}function Ft(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");Gt(t,e).draw()}function Gt(t,e=.5,r=!1){const i=new St(0===e?"segments":"curve"),n=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let o,s,a,l=0;for(let c=0;c<t.length-1;c++)if(e>0&&c<t.length-2){const h=t[c],u=t[c+1],f=t[c+2],m=K(h[0],h[1],u[0],u[1]),g=K(u[0],u[1],f[0],f[1]),d=q(h[0],h[1],u[0],u[1]),x=q(u[0],u[1],f[0],f[1]),p=e*Math.min(m,g,.5*Math.min(m,g)),y=Math.max(m,g),v=m-p,b=g-p;if(Math.floor(d)===Math.floor(x)){const e=r&&0===c?0:m-l,n=r?0===c?0:g-a:g;i.addSegment(d,e,h[2],!0),c===t.length-3&&i.addSegment(x,n,u[2],!0),l=0,0===c&&(o=m,a=p,s=t[1],l=0)}else{const e={x:u[0]-p*H(-d),y:u[1]-p*U(-d)},f={x:e.x+y*H(90-d),y:e.y+y*U(90-d)},m={x:u[0]+p*H(-x),y:u[1]+p*U(-x)},g={x:m.x+y*H(90-x),y:m.y+y*U(90-x)},_=J(e,f,m,g,!0),w=K(e.x,e.y,_.x,_.y),R=K(e.x,e.y,m.x,m.y)/2,M=n*w*(2*Math.asin(R/w)*(180/Math.PI))/360,S=r&&0===c?0:v-l,E=c===t.length-3?r?o-p:b:0;i.addSegment(d,S,h[2],!0),i.addSegment(d,isNaN(M)?0:M,h[2],!0),i.addSegment(x,E,u[2],!0),l=p,0===c&&(o=v,a=p,s=[e.x,e.y])}c===t.length-3&&i.endPlot(x,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],n=K(e[0],e[1],r[0],r[1]),o=q(e[0],e[1],r[0],r[1]);i.addSegment(o,n,r[2],!0),c===t.length-2&&i.endPlot(o,1,!0)}i.origin=r&&0!==e?s:t[0]}return i}let $t,Wt,Ht,Ut,jt,Zt=!1,Vt=0,Kt=0;const qt={},Jt={};let Qt=1,te=0,ee=0,re=1,ie=0,ne=0,oe=new Float32Array(8192),se=0,ae=2048,le=32768;function ce(r,i,o,s){if(se>=ae){ae*=2;const t=new Float32Array(4*ae);t.set(oe),oe=t}const a=r-t/2,l=i-e/2,c=4*se,h=Qt*a+ee*l+ie+t/2,u=te*a+re*l+ne+e/2,f=n*o*Math.sqrt(Qt*Qt+te*te)/2;oe[c]=h,oe[c+1]=u,oe[c+2]=f,oe[c+3]=s/255,b.markDirtyRect(b.glMask,{minX:h*n-f-1,minY:u*n-f-1,maxX:h*n+f+1,maxY:u*n+f+1}),se++}function he(){if(0===se)return;b.glMask.isDrawn=!0;const t=p.stroke.color._array;$t.useProgram(jt),$t.enable($t.BLEND),$t.blendFunc($t.ONE_MINUS_DST_ALPHA,$t.ONE),$t.bindVertexArray(Ht),$t.bindBuffer($t.ARRAY_BUFFER,Ut);const e=16*se,r=oe.subarray(0,4*se);e>le?($t.bufferData($t.ARRAY_BUFFER,oe,$t.DYNAMIC_DRAW),le=oe.byteLength):$t.bufferSubData($t.ARRAY_BUFFER,0,r),$t.uniform4f(Jt.u_color,...t),$t.uniformMatrix4fv(Jt.u_matrix,!1,Wt),$t.drawArrays($t.POINTS,0,se),$t.bindVertexArray(null),se=0,b.glMask._renderer._curShader=null}p.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let ue,fe,me,ge,de=new Map,xe=null,pe={a:1,b:0,c:0,d:1,tx:0,ty:0};function ye(){return{...p.stroke}}function ve(t){p.stroke={...t}}function be(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0!==e.vibration&&void 0===e.scatter&&(e.scatter=e.vibration),void 0!==e.definition&&void 0===e.sharpness&&(e.sharpness=e.definition),void 0!==e.quality&&void 0===e.grain&&(e.grain=e.quality),e.pressure=function(t){if(!t||"object"==typeof t&&!Array.isArray(t))return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t};if(Array.isArray(t)){const[e,r,i]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,n=Math.min(e,r,i),o=Math.max(e,r,i),s=o-n||1,[a,l,c]=[(e-n)/s,(r-n)/s,(i-n)/s];return{type:"custom",min_max:[n,o],curve:t=>t<.5?a+(l-a)*t*2:l+(c-l)*(t-.5)*2}}}(e.pressure),"image"===e.type){if(!e.image||!e.image.src)throw new Error(`Brush "${t}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return Ke.add(e.image.src),e.tip=()=>{xe.image(Ke.tips.get(Ne.p.image.src),-Ne.p.weight/2,-Ne.p.weight/2,Ne.p.weight,Ne.p.weight)},de.set(t,{param:e,colors:[],buffers:[]}),Ke.load()}de.set(t,{param:e,colors:[],buffers:[]})}function _e(){return[...de.keys()]}function we(t){for(const{param:e}of de.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function Re(t){if(!de.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...de.keys()].join(", ")}.`);p.stroke.type=t}function Me(t,e,r){x(),p.stroke.color=i.color(...arguments),p.stroke.isActive=!0}function Se(t){p.stroke.weight=t}function Ee(t,e,r=1){Re(t),Me(e),Se(r)}function Ae(){p.stroke.isActive=!1}function Pe(){return{a:et(),b:rt(),c:it(),d:nt(),tx:Q(),ty:tt()}}function ke(t,e,r){return{x:t.a*e+t.c*r+t.tx,y:t.b*e+t.d*r+t.ty}}function Ie(t){const[e,r,i,n]=t;return{minX:Math.min(e,i),minY:Math.min(r,n),maxX:Math.max(e,i),maxY:Math.max(r,n)}}function Ce(r,i){const n=ke(pe,r-t/2,i-e/2);return{x:n.x+t/2,y:n.y+e/2}}function Le(t){x();const e=function(t){const e=t.a*t.d-t.b*t.c;return Math.abs(e)<1e-12?null:{a:t.d/e,b:-t.b/e,c:-t.c/e,d:t.a/e,tx:(t.c*t.ty-t.d*t.tx)/e,ty:(t.b*t.tx-t.a*t.ty)/e}}(Pe());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");p.stroke.clipWindow={bounds:Ie(t),inverse:e}}function Te(){p.stroke.clipWindow=null}const Ne={};function Ye(r,i,n,o=!1){Qt=et(),te=rt(),ee=it(),re=nt(),ie=Q(),ne=tt(),pe=Pe(),ue=new at(r+t/2,i+e/2),fe=n,me=o,me&&me.calcIndex(0)}const ze=[];function Xe(r,i){i||(ge=r),function(){Ne.seed=999999*T();const{param:r}=de.get(p.stroke.type)??{};if(!r)return;Ne.p=r,xe=b.glMask;const{pressure:i}=r;if(Ne.a="custom"!==i.type?T(-1,1):0,Ne.b="custom"!==i.type?T(1,1.5):0,Ne.cp="custom"!==i.type?T(3,3.5):T(-.2,.2),[Ne.min,Ne.max]=i.min_max,Ne.noiseoffset=.03,!me){const t=ge*Math.PI/180;Ne.cos=Math.cos(t),Ne.sin=Math.sin(t)}!function(){v();const r=b.glMask.drawingContext,i=!Zt||$t!==r;(i||Vt!==t||Kt!==e)&&(Wt=new Float32Array([2/t,0,0,0,0,-2/e,0,0,0,0,1,0,-1,1,0,1]),Vt=t,Kt=e),i&&($t=r,jt=(t=>{const e=t.createProgram();for(let[r,i]of[[t.VERTEX_SHADER,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}"],[t.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"]]){const n=t.createShader(r);t.shaderSource(n,i),t.compileShader(n),t.attachShader(e,n)}return t.linkProgram(e),e})($t),$t.useProgram(jt),$t.enable($t.BLEND),$t.blendFunc($t.ONE_MINUS_DST_ALPHA,$t.ONE),["a_position","a_radius","a_alpha"].forEach(t=>qt[t]=$t.getAttribLocation(jt,t)),["u_matrix","u_color"].forEach(t=>Jt[t]=$t.getUniformLocation(jt,t)),Ht=$t.createVertexArray(),$t.bindVertexArray(Ht),Ut=$t.createBuffer(),$t.bindBuffer($t.ARRAY_BUFFER,Ut),$t.bufferData($t.ARRAY_BUFFER,oe.byteLength,$t.DYNAMIC_DRAW),le=oe.byteLength,$t.enableVertexAttribArray(qt.a_position),$t.vertexAttribPointer(qt.a_position,2,$t.FLOAT,!1,16,0),$t.enableVertexAttribArray(qt.a_radius),$t.vertexAttribPointer(qt.a_radius,1,$t.FLOAT,!1,16,8),$t.enableVertexAttribArray(qt.a_alpha),$t.vertexAttribPointer(qt.a_alpha,1,$t.FLOAT,!1,16,12),$t.bindVertexArray(null),Zt=!0)}();const n=!0!==b.isBrush;b.isBrush=!0,n&&(b.justChanged=!0),Ge()&&b.blend(p.stroke.color),Ne.alpha=Fe(),He()}();const n=function(){const{param:t}=de.get(p.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(fe*(i?r:1)/n);for(let t=0;t<o;t++)ze.length<2*o&&ze.push(z()),De(),i?ue.plotTo(me,n,n,r,t<10):ue._moveToDegrees(r,n,n);he(),He()}function De(t=!1){if(!Ge())return;let e=t||Oe(),r=D(L(Ne.seed+.002*ue.plotted,0),0,1,1-Ne.noiseoffset,1+Ne.noiseoffset);switch(Ne.p.type){case"spray":!function(t){const e=p.stroke.weight*Ne.p.scatter*t+p.stroke.weight*N(ze)*Ne.p.scatter/3,r=Ne.p.weight*T(.9,1.1),i=Math.ceil(Ne.p.grain/t);for(let t=0;t<i;t++){const t=T(.9,1.1),i=t*e*T(-1,1),n=T(-1,1),o=Math.sqrt((t*e)**2-i**2);ce(ue.x+i,ue.y+n*o,r,Ne.alpha)}}(e*r);break;case"marker":$e(e*r);break;case"custom":case"image":We(e*r,Ne.alpha);break;default:!function(t,e=1){const r=(e=D(e,0,1,.9,1.05))*p.stroke.weight*Ne.p.scatter*(Ne.p.sharpness+(1-Ne.p.sharpness)*N(ze)/t);if(T(0,Ne.p.grain*t)>.4){let e,i;if(me)e=.7*r*T(-1,1),i=r*T(-1,1);else{const t=r*T(-1,1),n=.3*r*T(-1,1);e=t*-Ne.sin+n*Ne.cos,i=t*Ne.cos+n*Ne.sin}ce(ue.x+e,ue.y+i,t*t*Ne.p.weight*T(.85,1.15)*p.stroke.weight,Math.max(.9,t)*Ne.alpha*T(.75,1.1))}}(e*r)}}function Oe(){return me?Be()*me.pressure(ue.plotted):Be()}function Be(){return"custom"===Ne.p.pressure.type?D(Ne.p.pressure.curve(ue.plotted/fe)+Ne.cp,0,1,Ne.min,Ne.max,!0):function(t=.5+Ne.p.pressure.curve[0]*Ne.a,e=1-Ne.p.pressure.curve[1]*Ne.b,r=Ne.cp,i=Ne.min,n=Ne.max){const o=t*fe,s=(ue.plotted<o?1.2*e:.8*e)*(fe/2);return D(1/(1+Math.pow(Math.abs((ue.plotted-o)/s),2*r)),0,1,i,n)}()}function Fe(){return["default","spray"].includes(Ne.p.type)?Ne.p.opacity:Ne.p.opacity/Math.min(p.stroke.weight,1.3)}function Ge(){const r=ke(pe,ue.x-t/2,ue.y-e/2);if(p.stroke.clipWindow){const t=ke(p.stroke.clipWindow.inverse,r.x,r.y),{bounds:e}=p.stroke.clipWindow;return t.x>=e.minX&&t.x<=e.maxX&&t.y>=e.minY&&t.y<=e.maxY}let i=.05*t;return r.x>=-t/2-i&&r.x<=t/2+i&&r.y>=-e/2-i&&r.y<=e/2+i}function $e(t,e=!0,r=Ne.alpha){const i=e?p.stroke.weight*Ne.p.scatter:0,n=e?i*T(-1,1):0,o=e?i*T(-1,1):0;ce(ue.x+n,ue.y+o,p.stroke.weight*Ne.p.weight*t,r)}function We(r,n,o=!0){b.glMask.isDrawn=!0,xe.push(),xe.noStroke(),p.stroke.color.setAlpha(n),xe.fill(p.stroke.color);const s=o?p.stroke.weight*Ne.p.scatter:0,a=o?s*T(-1,1):0,l=o?s*T(-1,1):0;xe.translate(ue.x+a-t,ue.y+l-e);const c=p.stroke.weight*r,h=function(t,e){xe.scale(t),"image"===Ne.p.type&&xe.tint(255,0,0,e/2);let r=0;return"random"===Ne.p.rotate?r=Y(0,360):"natural"===Ne.p.rotate&&(r=(me?-me.angle(ue.plotted):-ge)+ue.angle()),xe.rotate(r),r}(c,n);Ne.p.tip(xe),xe.pop(),"image"===Ne.p.type?function(t,e,r,n){const o=Ne.p.weight/2,s=n*Math.PI/180,a=Math.cos(s),l=Math.sin(s),c=ue.x+t,h=ue.y+e,u=[[-o,-o],[o,-o],[o,o],[-o,o]];let f=Infinity,m=Infinity,g=-Infinity,d=-Infinity;for(const[t,e]of u){const n=Ce(c+r*(a*t-l*e),h+r*(l*t+a*e));f=Math.min(f,n.x*i.pixelDensity()),m=Math.min(m,n.y*i.pixelDensity()),g=Math.max(g,n.x*i.pixelDensity()),d=Math.max(d,n.y*i.pixelDensity())}b.markDirtyRect(b.glMask,{minX:f-2,minY:m-2,maxX:g+2,maxY:d+2})}(a,l,c,h):b.markFull(b.glMask)}function He(){if(Ge()){let t=Oe(),e=Fe();if("marker"===Ne.p.type){for(let r=1;r<10;r++)$e(t*r/10,!1,5*e);he()}else if("custom"===Ne.p.type||"image"===Ne.p.type)for(let r=1;r<5;r++)We(t*r/5,e,!1)}}function Ue(t,e,r,i){if(!p.stroke.isActive||!p.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");st();let n=K(t,e,r,i);0!=n&&(Ye(t,e,n),Xe(q(t,e,r,i),!1))}function je(t,e,r,i){if(!p.stroke.isActive||!p.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");st(),Ye(t,e,r),Xe(j(i),!1)}C(()=>{ze.length=0});const Ze=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],Ve=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of Ve){let e={};for(let r=0;r<t[1].length;r++)e[Ze[r]]=t[1][r];be(t[0],e)}be("diamond",{type:"custom",weight:.78,scatter:.1,opacity:17,spacing:1.3,pressure:[1.2,.82],rotate:"none",tip:t=>{t.rotate(45),t.rect(-4,-4,8,8),t.rect(2,2,3,3)}}),Mt.prototype.draw=function(t=!1,e,r){let i=ye();if(t&&Ee(t,e,r),i.isActive)for(let t of this.sides)Ue(t[0].x,t[0].y,t[1].x,t[1].y);ve(i)},St.prototype.draw=function(t,e,r){ye().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,i){st(),Ye(e,r,t.length,t),Xe(i,!0)}(this,t,e,r))};const Ke={tips:new Map,add(t){this.tips.set(t,!1)},imageToWhite(t){t.loadPixels();for(let e=0;e<4*t.width*t.height;e+=4){let r=(t.pixels[e]+t.pixels[e+1]+t.pixels[e+2])/3;t.pixels[e]=t.pixels[e+1]=t.pixels[e+2]=255,t.pixels[e+3]=255-r}t.updatePixels()},async load(){const t=[...this.tips.keys()].filter(t=>!this.tips.get(t));await Promise.all(t.map(t=>new Promise((e,r)=>{const n=new window.Image;n.onload=()=>{const r=i.createImage(n.naturalWidth,n.naturalHeight);r.drawingContext.drawImage(n,0,0),Ke.imageToWhite(r),this.tips.set(t,r),e()},n.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),n.src=t})))}};function qe(){return{...p.hatch}}function Je(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let i=p.hatch;i.isActive=!0,i.dist=t,i.angle=Z(e),i.options=r}function Qe(t,e="black",r=1){p.hatch.hBrush={brush:t,color:e,weight:r}}function tr(){p.hatch.isActive=!1,p.hatch.hBrush=!1}function er(t){let e=p.hatch.dist,r=(p.hatch.angle%180+180)%180,i=p.hatch.options,n=ye();p.hatch.hBrush&&Ee(...Object.values(p.hatch.hBrush)),Array.isArray(t)||(t=[t]);const o=function(t){let e={minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity};for(let r of t){const t=rr(r);e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY)}return e}(t);let s=new Mt([[o.minX,o.minY],[o.maxX,o.minY],[o.maxX,o.maxY],[o.minX,o.maxY]]),a=r<=90&&r>=0?o.minY:o.maxY,l=i.gradient?D(i.gradient,0,1,1,1.1,!0):1,c=[],h=0,u=e,f=t=>({point1:{x:o.minX+u*t*H(90-r),y:a+u*t*U(90-r)},point2:{x:o.minX+u*t*H(90-r)+H(-r),y:a+u*t*U(90-r)+U(-r)}});for(;s.intersect(f(h)).length>0;){let e=[];for(let r of t)e.push(r.intersect(f(h)));c[h]=e.flat().sort((t,e)=>t.x===e.x?t.y-e.y:t.x-e.x),u*=l,h++}let m=c.filter(t=>void 0!==t[0]),g=i.rand||0;for(let t=0;t<m.length;t++){let r=m[t],n=t>0&&i.continuous;for(let i=0;i<r.length-1;i+=2)0!==g&&(r[i].x+=g*e*T(-1,1),r[i].y+=g*e*T(-1,1),r[i+1].x+=g*e*T(-1,1),r[i+1].y+=g*e*T(-1,1)),Ue(r[i].x,r[i].y,r[i+1].x,r[i+1].y),n&&Ue(m[t-1][1].x,m[t-1][1].y,r[i].x,r[i].y)}ve(n)}function rr(t){if(t._boundingBox)return t._boundingBox;let e=Infinity,r=Infinity,i=-Infinity,n=-Infinity;for(let o=0;o<t.a.length;o++){const[s,a]=t.a[o];s<e&&(e=s),s>i&&(i=s),a<r&&(r=a),a>n&&(n=a)}return t._boundingBox={minX:e,minY:r,maxX:i,maxY:n},t._boundingBox}function ir(t,e,r){return{x:t.a*e+t.c*r+t.e,y:t.b*e+t.d*r+t.f}}function nr(t,e){const r=t.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(e.a,e.c),Math.hypot(e.b,e.d))/2}function or(t,e,r){const i=2*Math.PI,n=b.ctx,o=n.getTransform(),s=r/2,a=ir(o,t,e),l=s*Math.hypot(o.a,o.c),c=s*Math.hypot(o.b,o.d),h=nr(n,o);b.markDirtyRect(b.mask,{minX:a.x-l-h,minY:a.y-c-h,maxX:a.x+l+h,maxY:a.y+c+h}),n.moveTo(t+s,e),n.arc(t,e,s,0,i)}p.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},Mt.prototype.hatch=function(t=!1,e,r){let i=qe();t&&Je(t,e,r),i.isActive&&er(this),function(t){p.hatch={...t}}(i)},St.prototype.hatch=function(t,e,r){qe().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},p.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const sr=()=>({...p.fill});function ar(t,e,r,n){p.fill.opacity=(arguments.length<4?e:n)||150,p.fill.color=arguments.length<3?i.color(t):i.color(t,e,r),p.fill.isActive=!0}function lr(t,e="out"){p.fill.bleed_strength=O(t,0,1),p.fill.direction=e}function cr(t=.4,e=.4){p.fill.texture_strength=O(t,0,1),p.fill.border_strength=O(e,0,1)}function hr(){p.fill.isActive=!1}let ur;const fr=[[],[]];function mr(){for(let t=0;t<512;t++)fr[0][t]=z(.5,.2),fr[1][t]=z(0,.02)}function gr(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}C(mr);class dr{constructor(t,e,r,i=[],n=!1,o,s){if(this.v=t,this.m=e,this.dir=i,this.midP=r,n){let e=0,i=0;const n=[];for(let o=0;o<t.length;o++){const s=Math.abs(r.x-t[o].x),a=Math.abs(r.y-t[o].y);e=Math.max(e,s),i=Math.max(i,a);const l=t[o],c=t[(o+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=V(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};n.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=i,this.dir=Array(t.length),n.forEach((t,e)=>{let r=0;for(const e of ur.intersect(t.ray))gr(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=T(-.6,.6)*e,s=T(-.6,.6)*i;this.midP={x:r.x+o,y:r.y+s}}else this.sizeX=o,this.sizeY=s}trim(t=1){if(t>=1||t<0||this.v.length<=8)return{v:[...this.v],m:[...this.m],dir:[...this.dir]};const e=~~((1-t)*this.v.length),r=~~(this.v.length/2-e/2),i=[...this.v],n=[...this.m],o=[...this.dir];return i.splice(r,e),n.splice(r,e),o.splice(r,e),{v:i,m:n,dir:o}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),i=[],n=e/r;for(let t=0;t<r;t++)i.push(~~(t*n+T(0,.8*n)));const o=[],s=[],a=[],l=this.midP,c=ur.sides;for(const t of i){const r=t%e;let i=this.v[r],n=0;for(const[t,e]of c){const r=t.y,o=e.y;if(r>i.y==o>i.y)continue;const s=(i.y-r)/(o-r);i.x<t.x+s*(e.x-t.x)&&n++}n%2==0&&(i={x:l.x+(i.x-l.x)*T(.3,.6),y:l.y+(i.y-l.y)*T(.3,.6)}),o.push(i),s.push(this.m[r]),a.push(!this.dir[r])}return new dr(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new dr(this.v,this.m,this.midP,this.dir.map(t=>!t),!1,this.sizeX,this.sizeY)}grow(t=1){const{v:e,m:r,dir:i}=this.trim(t),n=e.length,o=2*n,s=new Array(o),a=new Array(o),l=new Array(o),c="out"===p.fill.direction?-90:90;0===fr[0].length&&mr();const h=fr[0],u=h.length,f=fr[1],m=f.length;let g=0,d=999===t?T(.6,.8):p.fill.bleed_strength;for(let o=0;o<n;o++){const x=e[o],p=e[o+1<n?o+1:0],y=r[o],v=i[o];t<997&&(d=y);const b=(v?c:-c)+5*T(-1,1),_=H(b),w=U(b),R=p.x-x.x,M=p.y-x.y,S=_*R+w*M,E=_*M-w*R,A=h[~~(T(0,1)*u)]*T(.65,1.35)*d;s[g]=x,a[g]=y,l[g]=v,g++,s[g]={x:x.x+.5*R+S*A,y:x.y+.5*M+E*A},a[g]=y+f[~~(T(0,1)*m)],l[g]=v,g++}let x=s,y=a,v=l,b=1024/p.fill.texture_strength;if(b&&g>b){const t=Math.ceil(g/b);x=[],y=[],v=[];for(let e=0;e<g;e+=t)x.push(s[e]),y.push(a[e]),v.push(l[e])}else x.length=g,y.length=g,v.length=g;return new dr(x,y,this.midP,v,!1,this.sizeX,this.sizeY)}fill(r,i,o){const s=3*o,a=2*i*(1+o/2),l=!1!==b.isBrush;b.isBrush=!1,l&&(b.justChanged=!0),b.blend(r),b.ctx.save(),b.ctx.setTransform(n*et(),n*rt(),n*it(),n*nt(),n*(Q()+t/2),n*(tt()+e/2)),b.ctx.strokeStyle=`rgb(${r._getRed()} ${r._getGreen()} ${r._getBlue()} / ${.005*p.fill.border_strength})`,b.ctx.lineCap="round";const c=Math.max(this.sizeX,this.sizeY),h=T(.15,.7);let u=this.grow();const f=this.scatter(.1).grow().scatter(.75).flipDirs();let m;for(let t=0;t<20;t++){t%4==0&&(u=u.grow()),t%2==0&&(m=[u.grow(1-.0125*t),u.grow(.7-.0125*t),u.grow(.4-.0125*t)]);for(const e of m)e.grow(999).grow(997).layer(t,c,a,r);f.grow(999).flipDirs().grow(997).layer(t,c,1.5*a*s,r),t%2==0&&u.grow(h).grow(999).layer(t,c,2*a,r),t%5!=0&&19!==t||(0!==s&&u.erase(3*s,i),b.blend(r,!0,!1,!0))}b.ctx.restore()}layer(t,e,r,i){b.ctx.lineWidth=D(t,0,24,e/25,e/30,!0),b.ctx.fillStyle=`rgb(${i._getRed()} ${i._getGreen()} ${i._getBlue()} / ${r}%)`,function(t){const e=b.ctx,r=e.getTransform();let i=Infinity,n=Infinity,o=-Infinity,s=-Infinity;e.beginPath(),t.forEach((t,a)=>{const l=ir(r,t.x,t.y);i=Math.min(i,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),s=Math.max(s,l.y),0===a?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.closePath();const a=nr(e,r);b.markDirtyRect(b.mask,{minX:i-a,minY:n-a,maxX:o+a,maxY:s+a})}(this.v),b.ctx.fill(),b.ctx.stroke()}erase(t,e){b.ctx.save();const r=~~(T(80,110)*D(t,0,1,2,3.5)),i=this.sizeX/1.3,n=this.sizeY/1.3,o=Math.min(this.sizeX,this.sizeY)*(1.4-p.fill.bleed_strength),s=.05*o,a=.4*o,{x:l,y:c}=this.midP;b.ctx.globalCompositeOperation="destination-out";const h=(5-D(e,80,100,.3,.7,!0))*t/255;b.ctx.fillStyle=`rgb(255 0 0 / ${h})`,b.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+z(0,i),r=c+z(0,n),o=T(s,a);b.ctx.beginPath(),or(e,r,o),t%5!=0&&b.ctx.fill()}b.ctx.globalCompositeOperation="source-over",b.ctx.restore()}}Mt.prototype.fill=function(t=!1,e,r,i,n,o){let s=sr();t&&(ar(t,e),lr(r,o),cr(i,n)),s.isActive&&(st(),function(t){if(!p.fill.isActive||!p.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");ur=t;const e=[...t.vertices],r=~~(.25*e.length*X({1:5,2:10,3:60})),i=p.fill.bleed_strength,n=e.map((t,e)=>(e>r?1:.3)*T(.85,1.2)*i),o=Y(0,e.length),s=[...e.slice(o),...e.slice(0,o)],a=function(t){if(t.length<8)return t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0}).map(e=>e/t.length);const e=[...t];e[0].x===e[e.length-1].x&&e[0].y===e[e.length-1].y||e.push(e[0]);let r=0,i=0,n=0;for(let t=0;t<e.length-1;t++){const o=e[t].x*e[t+1].y-e[t+1].x*e[t].y;r+=o,i+=(e[t].x+e[t+1].x)*o,n+=(e[t].y+e[t+1].y)*o}return r*=.5,r?{x:i/(6*r),y:n/(6*r)}:{x:e[0].x,y:e[0].y}}(s);new dr(s,n,a,[],!0).fill(p.fill.color,D(p.fill.opacity,0,255,0,1,!0),p.fill.texture_strength)}(this)),(t=>{p.fill={...t}})(s)},St.prototype.fill=function(t,e,r){sr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,D(p.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const xr=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>b.blend(!1,!0),r.postdraw=()=>b.blend(!1,!0);const i=e.push,n=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){i.call(this),st(),xr.push({fill:{...p.fill},stroke:{...p.stroke},hatch:{...p.hatch},field:{...p.field}})},e.pop=function(){n.call(this),function(){const t=xr.pop();t&&(p.stroke={...t.stroke},p.field={...t.field},p.hatch={...t.hatch},p.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{k=A(t);for(const t of I)t()})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{L=E(A(t))})(t)}});export{St as Plot,Mt as Polygon,at as Position,be as add,bt as addField,kt as arc,Yt as beginShape,Dt as beginStroke,_e as box,Pt as circle,Le as clip,Xt as endShape,Bt as endStroke,yt as field,ar as fill,lr as fillBleed,cr as fillTexture,je as flowLine,Je as hatch,er as hatchArray,Qe as hatchStyle,y as instance,Ue as line,_t as listFields,m as load,Ot as move,Te as noClip,vt as noField,hr as noFill,tr as noHatch,Ae as noStroke,Re as pick,Et as polygon,At as rect,pt as refreshField,we as scaleBrushes,Ee as set,Ft as spline,Me as stroke,Se as strokeWeight,zt as vertex,X as wRand,wt as wiggle};
+let t,e,r,i,n;const o=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,s=()=>d?r:window.self.p5.instance,a=t=>{t&&"function"==typeof t.remove&&t.remove()},l=()=>i&&i._renderer&&"function"==typeof i._renderer.activeFramebuffer?i._renderer.activeFramebuffer():null,c=()=>({width:Math.max(1,Math.round(t*n)),height:Math.max(1,Math.round(e*n))}),h=t=>{if(!t)return null;const{width:e,height:r}=c(),i=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),n=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),o=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),s=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return o<=i||s<=n?null:{minX:i,minY:n,maxX:o,maxY:s}},u=()=>{const{width:t,height:e}=c();return{minX:0,minY:0,maxX:t,maxY:e}},f=(t,e,r)=>{const i=(t=>{const e=h(t);if(!e)return null;const{height:r}=c();return{x:e.minX,y:r-e.maxY,width:e.maxX-e.minX,height:e.maxY-e.minY}})(e);if(!i)return!1;const n=t.isEnabled(t.SCISSOR_TEST),o=t.getParameter(t.SCISSOR_BOX);t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{r()}finally{n?t.scissor(o[0],o[1],o[2],o[3]):t.disable(t.SCISSOR_TEST)}return!0},m=(n=!1)=>{const a=((t=!1)=>{if(d&&!t)return{renderer:r,width:r.width,height:r.height};if(!t){const t=s();return{renderer:t,width:t.width,height:t.height}}if(o(t)){if(!o(e=t)||e.renderer._pInst!==s())throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.");return{renderer:s(),width:t.width,height:t.height}}var e;return{renderer:t,width:t.width,height:t.height}})(n);if(i=a.renderer,"webgl2"!==i.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");t=a.width,e=a.height,g=!0,i.loaded&&b.load()};let g=!1,d=!1;const x=()=>{g||m()},p={},y=t=>{d=!0,r=t},v=()=>{i?.loaded||(x(),b.load())},b={isBlending:!1,cachedColor:new Object,markDirtyRect(t,e){const r=h(e);var i,n;t&&r&&(t.dirtyRect=(n=r,(i=t.dirtyRect)?n?{minX:Math.min(i.minX,n.minX),minY:Math.min(i.minY,n.minY),maxX:Math.max(i.maxX,n.maxX),maxY:Math.max(i.maxY,n.maxY)}:i:n),t.isDrawn=!0)},markFull(t){t&&(t.dirtyRect=u(),t.isDrawn=!0)},clearMask(t){t&&(t.clear(),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:(t,e)=>t?t.dirtyRect?h(((t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null)(t.dirtyRect,e?2:4)):u():null,captureBlendSource(r){const o=l();if(!o)return i._renderer;var s;(!(s=i.blendSourceFramebuffer)||s.width!==t||s.height!==e||"function"==typeof s.pixelDensity&&s.pixelDensity()!==n)&&(a(i.blendSourceFramebuffer),i.blendSourceFramebuffer=i.createFramebuffer({width:t,height:e,density:n,antialias:!1,depth:!1,stencil:!1}));const c=i.blendSourceFramebuffer;return c.draw(()=>{f(i.drawingContext,r,()=>{i.clear(),i.push(),"function"==typeof i.imageMode&&i.imageMode(i.CENTER??i._renderer?._pInst?.CENTER),i.image(o,0,0,t,e),i.pop()})}),c},load(){n=i.pixelDensity();const r="function"==typeof i.createGraphics?i:i._pInst,o=r.P2D??i.P2D,s=r.WEBGL??i.WEBGL;i.loaded&&i.mask&&i.glMask&&i.mask.width===t&&i.mask.height===e&&i.glMask.width===t&&i.glMask.height===e?(this.mask=i.mask,this.glMask=i.glMask,this.ctx=this.mask.drawingContext,this.mask.dirtyRect??=null,this.mask.isDrawn??=!1,this.glMask.dirtyRect??=null,this.glMask.isDrawn??=!1):(a(i.mask),a(i.glMask),i.mask=r.createGraphics(t,e,o),i.glMask=r.createGraphics(t,e,s),i.loaded=!0,i.shaderProgram??=i.createShader("#version 300 es\n#define GLSLIFY 1\nuniform bool u_flipOutputY;out vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,u_flipOutputY ?-v.y : v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 uv1=vec2(uv.x,1.0-uv.y);vec4 source=texture(u_source,uv1);vec4 maskColor=texture(u_mask,uv1);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=uv1+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.0);}"),this.mask=i.mask,this.mask.pixelDensity(n),this.mask.clear(),this.mask.angleMode(i.DEGREES),this.mask.dirtyRect=null,this.mask.isDrawn=!1,this.ctx=this.mask.drawingContext,this.glMask=i.glMask,this.glMask.pixelDensity(n),this.glMask.clear(),this.glMask.angleMode(this.glMask.DEGREES),this.glMask.drawingContext.lineWidth=0,this.glMask.dirtyRect=null,this.glMask.isDrawn=!1),this.glMask._renderer.uModelMatrix=i._renderer.uModelMatrix},blend(t=!1,e=!1){v();const r=!0===this.isBrush,i=r?this.glMask:this.mask,n=r?this.mask:this.glMask,o=t?._array,s=!!o&&(this.cachedColor[0]!==o[0]||this.cachedColor[1]!==o[1]||this.cachedColor[2]!==o[2]||this.cachedColor[3]!==o[3]);!this.isBlending&&o&&(this.isBlending=!0,this.cachedColor=o,this.glMask.clear()),(e||s)&&(this.justChanged&&(this.applyShader(n,!r),this.justChanged=!1),this.isBlending&&this.applyShader(i,r),o&&(this.cachedColor=o),e&&(this.isBlending=!1))},applyShader(r,n){if(!r?.isDrawn)return;const o=this.getCompositeRect(r,n);if(!o)return void this.clearMask(r);let s=i.shaderProgram;const a=i.drawingContext,c=!!l(),h=this.captureBlendSource(o),u=a.getParameter(a.DEPTH_TEST);a.disable(a.DEPTH_TEST),i.push(),i.translate(0,0),i.shader(s),s.setUniform("u_source",h),s.setUniform("u_isBrush",n),s.setUniform("u_flipOutputY",c),s.setUniform("u_mask",r),s.setUniform("u_color",this.cachedColor),f(a,o,()=>{i.fill(0,0,0,0),i.noStroke(),i.rect(-t/2,-e/2,t,e)}),i.pop(),i.resetShader(),u&&a.enable(a.DEPTH_TEST),this.clearMask(r)}},_=Math.sqrt(3),w=.5*(_-1),R=(3-_)/6,M=t=>0|Math.floor(t),S=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]);function E(t=Math.random){const e=function(t){const e=new Uint8Array(512);for(let t=0;t<256;t++)e[t]=t;for(let r=0;r<255;r++){const i=r+~~(t()*(256-r)),n=e[r];e[r]=e[i],e[i]=n}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>S[t%12*2]),i=new Float64Array(e).map(t=>S[t%12*2+1]);return function(t,n){let o=0,s=0,a=0;const l=(t+n)*w,c=M(t+l),h=M(n+l),u=(c+h)*R,f=t-(c-u),m=n-(h-u);let g,d;f>m?(g=1,d=0):(g=0,d=1);const x=f-g+R,p=m-d+R,y=f-1+2*R,v=m-1+2*R,b=255&c,_=255&h;let S=.5-f*f-m*m;if(S>=0){const t=b+e[_];S*=S,o=S*S*(r[t]*f+i[t]*m)}let E=.5-x*x-p*p;if(E>=0){const t=b+g+e[_+d];E*=E,s=E*E*(r[t]*x+i[t]*p)}let A=.5-y*y-v*v;if(A>=0){const t=b+1+e[_+1];A*=A,a=A*A*(r[t]*y+i[t]*v)}return 70*(o+s+a)}}function A(t,e){let r=new P(t),i=()=>r.next();return i.double=()=>i()+11102230246251565e-32*(2097152*i()|0),i.int32=()=>4294967296*r.next()|0,i.quick=i,i}class P{constructor(t){null==t&&(t=+new Date);let e=4022871197;function r(t){t=String(t);for(let r=0;r<t.length;r++){e+=t.charCodeAt(r);let i=.02519603282416938*e;e=i>>>0,i-=e,i*=e,e=i>>>0,i-=e,e+=4294967296*i}return 2.3283064365386963e-10*(e>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(t),this.s0<0&&(this.s0+=1),this.s1-=r(t),this.s1<0&&(this.s1+=1),this.s2-=r(t),this.s2<0&&(this.s2+=1)}next(){let{c:t,s0:e,s1:r,s2:i}=this,n=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=i,this.s2=n-(this.c=0|n)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let k=A(Math.random());const I=[],C=t=>I.push(t);let L=E(A(Math.random()));const T=(t=0,e=1)=>t+k()*(e-t),N=t=>t[~~(k()*t.length)],Y=(t,e)=>~~T(t,e),z=(t=0,e=1)=>{const r=1-k(),i=k();return Math.sqrt(-2*Math.log(r))*H(360*i)*e+t},X=t=>{let e=0;const r=[];for(const i in t)e+=t[i],r.push({key:i,cumulative:e});const i=k()*e;for(const{key:t,cumulative:e}of r)if(i<e)return isNaN(t)?t:parseInt(t)},D=(t,e,r,i,n,o=!1)=>{let s=i+(t-e)/(r-e)*(n-i);return o?i<n?O(s,i,n):O(s,n,i):s},O=(t,e,r)=>Math.max(Math.min(t,r),e),B=t=>(t%=360)<0?t+360:t,F=1440,G=2*Math.PI/F,$=new Float32Array(F).fill(NaN),W=new Float32Array(F).fill(NaN),H=t=>{const e=~~(4*B(t));let r=$[e];return isNaN(r)&&(r=Math.cos(e*G),$[e]=r),r},U=t=>{const e=~~(4*B(t));let r=W[e];return isNaN(r)&&(r=Math.sin(e*G),W[e]=r),r},j=(t,e=!1)=>{if(e||i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},Z=(t,e=!1)=>e||i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS?180*t/Math.PI:t,V=(t,e,r,i,n)=>{let o=H(n),s=U(n);return{x:o*(r-t)+s*(i-e)+t,y:o*(i-e)-s*(r-t)+e}},K=(t,e,r,i)=>Math.hypot(r-t,i-e),q=(t,e,r,i)=>j(Math.atan2(-(i-e),r-t),!0),J=(t,e,r,i,n=!1)=>{let o=t.x,s=t.y,a=e.x,l=e.y,c=r.x,h=r.y,u=i.x,f=i.y;if(o===a&&s===l||c===u&&h===f)return!1;let m=a-o,g=l-s,d=u-c,x=f-h,p=x*m-d*g;if(0===p)return!1;let y=(d*(s-h)-x*(o-c))/p,v=(m*(s-h)-g*(o-c))/p;return!(!n&&(v<0||v>1))&&{x:o+y*m,y:s+y*g}},Q=()=>i._renderer.uModelMatrix.mat4[12],tt=()=>i._renderer.uModelMatrix.mat4[13],et=()=>i._renderer.uModelMatrix.mat4[0],rt=()=>i._renderer.uModelMatrix.mat4[1],it=()=>i._renderer.uModelMatrix.mat4[4],nt=()=>i._renderer.uModelMatrix.mat4[5];let ot=!1;function st(){ot||(v(),lt=.01*t,ct=-.5*t,ht=-.5*e,ut=Math.round(2*t/lt),ft=Math.round(2*e/lt),bt("hand",(t,e)=>{const r=T(.2,.8),i=Y(5,10);return Rt(e,(e,n)=>.5*i*U(r*n*e+Y(15,25))*.2*H(t)+L(e,n)*i*.7)}),bt("curved",(t,e)=>{let r=Y(-10,10);return Y(0,100)%2==0&&(r*=-1),Rt(e,(e,i)=>3*D(L(.02*e+.03*t,.02*i+.03*t),0,1,-r,r))}),bt("zigzag",(t,e)=>{let r=Y(-30,-15)+Math.abs(44*U(t));Y(0,100)%2==0&&(r*=-1);let i=r,n=0;for(let t=0;t<ut;t++){for(let r=0;r<ft;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e}),bt("waves",(t,e)=>{const r=Y(10,15)+5*U(t),i=Y(3,6)+3*H(t),n=Y(20,35);return Rt(e,(t,e)=>U(r*t)*n*H(e*i)+Y(-3,3))}),bt("seabed",(t,e)=>{const r=T(.4,.8),i=Y(18,26);return Rt(e,(e,n)=>1.1*i*U(r*n*e+Y(15,20))*H(t))}),bt("spiral",(t,e)=>{const r=Y(5,10),i=2*Y(0,2)-1,n=Y(65,80),o=Array.from({length:r},()=>({x:T(.1,.9)*ut,y:T(.1,.9)*ft}));return Rt(e,(t,e)=>{let r=0,s=0;for(const a of o){const o=t-a.x,l=e-a.y,c=1/(o*o+l*l+1),h=Math.atan2(l,o)*(180/Math.PI),u=i*(h+n)*Math.PI/180;r+=c*Math.cos(u),s+=c*Math.sin(u)}return Math.atan2(s,r)*(180/Math.PI)})}),bt("columns",(t,e)=>{const r=Y(3,8),i=Y(25,45);return Rt(e,(t,e)=>U(t*r)*i)}),ot=!0)}class at{constructor(t,e){st(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=at.getColIndex(t),this.rowIdx=at.getRowIndex(e)}reset(){this.plotted=0}isIn(){return p.field.isActive?at.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const r=t,i=e,n=this.x+Q(),o=this.y+tt();return n>=-.3*r&&n<=1.3*r&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&p.field.isActive?mt.get(p.field.current).field[this.colIdx][this.rowIdx]*p.field.wiggle:0}moveTo(t,e,r=1){this.movePos(Z(t),e,r)}_moveToDegrees(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,i=1){this.movePos(t,e,r,i)}movePos(t,e,r,i=!1){const n=i||1;if(this.isIn())for(let o=0;o<e/r;o++){const e=this.angle()-(i?t.angle(this.plotted):t);this.update(this.x+r*H(e),this.y+r*U(e)),this.plotted+=r/n}else this.plotted+=r/n}static getRowIndex(t,e=1){const r=t+tt()-ht;return Math.round(r/lt/e)}static getColIndex(t,e=1){const r=t+Q()-ct;return Math.round(r/lt/e)}static isIn(t,e){return t>=0&&e>=0&&t<ut&&e<ft}}p.field={isActive:!1,current:null,wiggle:1};let lt,ct,ht,ut,ft,mt=new Map;const gt=new Set(["degrees","radians"]);function dt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!gt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function xt(t,e){return function(t,e){if("radians"!==e)return t;for(let e=0;e<t.length;e++)for(let r=0;r<t[e].length;r++)t[e][r]=Z(t[e][r],!0);return t}(t.gen(e,new Array(ut).fill(null).map(()=>new Float32Array(ft))),t.angleMode)}function pt(t=0){if(!p.field.isActive||!p.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=mt.get(p.field.current);e.field=xt(e,t)}function yt(t){if(p.field.wiggle||(p.field.wiggle=1),st(),!mt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(mt.keys()).join(", ")}.`);p.field.isActive=!0,p.field.current=t;const e=mt.get(t);e.field||(e.field=xt(e,0))}function vt(){st(),p.field.isActive=!1}function bt(t,e,r={}){mt.set(t,{gen:e,field:null,angleMode:dt(r)})}function _t(){return st(),Array.from(mt.keys())}function wt(t=1){yt("hand"),p.field.wiggle=t}function Rt(t,e){for(let r=0;r<ut;r++)for(let i=0;i<ft;i++)t[r][i]=e(r,i);return t}class Mt{constructor(t,e=!1){this.a=t,this.vertices=e?t:t.map(([t,e])=>({x:t,y:e})),this.sides=this.vertices.map((t,e,r)=>[t,r[(e+1)%r.length]]),this._intersectionCache={}}intersect(t){const e=`${t.point1.x},${t.point1.y}-${t.point2.x},${t.point2.y}`;if(this._intersectionCache[e])return this._intersectionCache[e];const r=[];for(const[e,i]of this.sides){const n=J(t.point1,t.point2,e,i);n&&r.push(n)}return this._intersectionCache[e]=r,r}show(){p.stroke&&this.draw(),p.hatch&&this.hatch(),p.fill&&this.fill()}}class St{constructor(t){this.segments=[],this.angles=[],this.pres=[],this.type=t,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(t=0,e=0,r=1,i=!1){this.angles.length>0&&this.angles.pop(),t=i?(t%360+360)%360:j(t),this.angles.push(t,t),this.pres.push(r),this.segments.push(e),this.length=this.segments.reduce((t,e)=>t+e,0)}endPlot(t=0,e=1,r=!1){t=r?(t%360+360)%360:j(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=j(t)}pressure(t){return t>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,t)}angle(t){return t>this.length?this.angles[this.angles.length-1]:(this.calcIndex(t),"curve"===this.type?this.curving(this.angles,t)+this.dir:this.angles[this.index]+this.dir)}curving(t,e){let r=t[this.index],i=t[this.index+1]??r;return Math.abs(i-r)>180&&(i>r?i=-(360-i):r=-(360-r)),D(e-this.suma,0,this.segments[this.index],r,i,!0)}calcIndex(t){this.index=-1,this.suma=0;let e=0;for(;e<=t;)this.suma=e,e+=this.segments[this.index+1],this.index++;return this.index}genPol(r,i,n=1,o){st();const s=.5,a=[],l=Math.round(this.length/s),c=new at(r+t/2,i+e/2);let h=0,u=0;for(let r=0;r<l;r++){c.plotTo(this,s,s);const r=this.calcIndex(c.plotted);h+=s,(h>=Math.max(this.segments[r]*o*T(.7,1.3),10)||r>=u)&&c.x&&(a.push([c.x-t/2,c.y-e/2]),h=0,r>=u&&u++)}return new Mt(a)}show(t,e,r=1){p.stroke&&this.draw(t,e,r),p.hatch&&this.hatch(t,e,r),p.fill&&this.fill(t,e,r)}}function Et(t){new Mt(t).show()}function At(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),Yt(0),zt(t,e),zt(t+r,e),zt(t+r,e+i),zt(t,e+i),Xt(!0)}function Pt(t,e,r,i=!1){const n=new St("curve"),o=Math.PI*r,s=T(0,360),a=i?()=>1+.2*i*T():()=>1;for(let t=0;t<4;t++){const e=-90*t+s;n.addSegment(e*a(),o/2*a(),1,!0)}if(i){const t=i*Y(-5,5);n.addSegment(s,Math.abs(t)*(Math.PI/180)*r,1,!0),n.endPlot(t+s,1,!0)}else n.endPlot(s,1,!0);const l=t-r*U(s),c=e-r*H(-s);n.show(l,c,1)}function kt(t,e,r,i,n){const o=Z(i),s=((Z(n)-o)%360+360)%360;if(0===s)return;const a=new St("curve"),l=Math.max(1,Math.ceil(s/90)),c=s/l,h=Math.PI*r*c/180;for(let t=0;t<l;t++)a.addSegment(o+t*c+90,h,1,!0);a.endPlot(o+s+90,1,!0);const u=t+r*H(o),f=e-r*U(o);a.draw(u,f,1)}let It,Ct,Lt,Tt;class Nt{constructor(){this.isClosed=!1,this.curvature=Ct,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){Gt(this.vert,this.curvature,this.isClosed).show()}}function Yt(t=0){Ct=O(t,0,1),It=new Nt}function zt(t,e,r=1){if(!It)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");It.vertex(t,e,r)}function Xt(t=!1){if(!It)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(It.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(It.vertex(...It.vert[0]),It.isClosed=!0),It.show(),It=!1}function Dt(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Tt=[e,r],Lt=new St(t)}function Ot(t,e,r){if(!Lt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Lt.addSegment(t,e,r)}function Bt(t,e){if(!Lt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Lt.endPlot(t,e),Lt.draw(Tt[0],Tt[1],1),Lt=!1}function Ft(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");Gt(t,e).draw()}function Gt(t,e=.5,r=!1){const i=new St(0===e?"segments":"curve"),n=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let o,s,a,l=0;for(let c=0;c<t.length-1;c++)if(e>0&&c<t.length-2){const h=t[c],u=t[c+1],f=t[c+2],m=K(h[0],h[1],u[0],u[1]),g=K(u[0],u[1],f[0],f[1]),d=q(h[0],h[1],u[0],u[1]),x=q(u[0],u[1],f[0],f[1]),p=e*Math.min(m,g,.5*Math.min(m,g)),y=Math.max(m,g),v=m-p,b=g-p;if(Math.floor(d)===Math.floor(x)){const e=r&&0===c?0:m-l,n=r?0===c?0:g-a:g;i.addSegment(d,e,h[2],!0),c===t.length-3&&i.addSegment(x,n,u[2],!0),l=0,0===c&&(o=m,a=p,s=t[1],l=0)}else{const e={x:u[0]-p*H(-d),y:u[1]-p*U(-d)},f={x:e.x+y*H(90-d),y:e.y+y*U(90-d)},m={x:u[0]+p*H(-x),y:u[1]+p*U(-x)},g={x:m.x+y*H(90-x),y:m.y+y*U(90-x)},_=J(e,f,m,g,!0),w=K(e.x,e.y,_.x,_.y),R=K(e.x,e.y,m.x,m.y)/2,M=n*w*(2*Math.asin(R/w)*(180/Math.PI))/360,S=r&&0===c?0:v-l,E=c===t.length-3?r?o-p:b:0;i.addSegment(d,S,h[2],!0),i.addSegment(d,isNaN(M)?0:M,h[2],!0),i.addSegment(x,E,u[2],!0),l=p,0===c&&(o=v,a=p,s=[e.x,e.y])}c===t.length-3&&i.endPlot(x,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],n=K(e[0],e[1],r[0],r[1]),o=q(e[0],e[1],r[0],r[1]);i.addSegment(o,n,r[2],!0),c===t.length-2&&i.endPlot(o,1,!0)}i.origin=r&&0!==e?s:t[0]}return i}let $t,Wt,Ht,Ut,jt,Zt=!1,Vt=0,Kt=0;const qt={},Jt={};let Qt=1,te=0,ee=0,re=1,ie=0,ne=0,oe=new Float32Array(8192),se=0,ae=2048,le=32768;function ce(r,i,o,s){if(se>=ae){ae*=2;const t=new Float32Array(4*ae);t.set(oe),oe=t}const a=r-t/2,l=i-e/2,c=4*se,h=Qt*a+ee*l+ie+t/2,u=te*a+re*l+ne+e/2,f=n*o*Math.sqrt(Qt*Qt+te*te)/2;oe[c]=h,oe[c+1]=u,oe[c+2]=f,oe[c+3]=s/255,b.markDirtyRect(b.glMask,{minX:h*n-f-1,minY:u*n-f-1,maxX:h*n+f+1,maxY:u*n+f+1}),se++}function he(){if(0===se)return;b.glMask.isDrawn=!0;const t=p.stroke.color._array;$t.useProgram(jt),$t.enable($t.BLEND),$t.blendFunc($t.ONE_MINUS_DST_ALPHA,$t.ONE),$t.bindVertexArray(Ht),$t.bindBuffer($t.ARRAY_BUFFER,Ut);const e=16*se,r=oe.subarray(0,4*se);e>le?($t.bufferData($t.ARRAY_BUFFER,oe,$t.DYNAMIC_DRAW),le=oe.byteLength):$t.bufferSubData($t.ARRAY_BUFFER,0,r),$t.uniform4f(Jt.u_color,...t),$t.uniformMatrix4fv(Jt.u_matrix,!1,Wt),$t.drawArrays($t.POINTS,0,se),$t.bindVertexArray(null),se=0,b.glMask._renderer._curShader=null}p.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let ue,fe,me,ge,de=new Map,xe=null,pe={a:1,b:0,c:0,d:1,tx:0,ty:0};function ye(){return{...p.stroke}}function ve(t){p.stroke={...t}}function be(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0!==e.vibration&&void 0===e.scatter&&(e.scatter=e.vibration),void 0!==e.definition&&void 0===e.sharpness&&(e.sharpness=e.definition),void 0!==e.quality&&void 0===e.grain&&(e.grain=e.quality),e.pressure=function(t){if(!t||"object"==typeof t&&!Array.isArray(t))return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t};if(Array.isArray(t)){const[e,r,i]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,n=Math.min(e,r,i),o=Math.max(e,r,i),s=o-n||1,[a,l,c]=[(e-n)/s,(r-n)/s,(i-n)/s];return{type:"custom",min_max:[n,o],curve:t=>t<.5?a+(l-a)*t*2:l+(c-l)*(t-.5)*2}}}(e.pressure),"image"===e.type){if(!e.image||!e.image.src)throw new Error(`Brush "${t}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return Ke.add(e.image.src),e.tip=()=>{xe.image(Ke.tips.get(Ne.p.image.src),-Ne.p.weight/2,-Ne.p.weight/2,Ne.p.weight,Ne.p.weight)},de.set(t,{param:e,colors:[],buffers:[]}),Ke.load()}de.set(t,{param:e,colors:[],buffers:[]})}function _e(){return[...de.keys()]}function we(t){for(const{param:e}of de.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function Re(t){if(!de.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...de.keys()].join(", ")}.`);p.stroke.type=t}function Me(t,e,r){x(),p.stroke.color=i.color(...arguments),p.stroke.isActive=!0}function Se(t){p.stroke.weight=t}function Ee(t,e,r=1){Re(t),Me(e),Se(r)}function Ae(){p.stroke.isActive=!1}function Pe(){return{a:et(),b:rt(),c:it(),d:nt(),tx:Q(),ty:tt()}}function ke(t,e,r){return{x:t.a*e+t.c*r+t.tx,y:t.b*e+t.d*r+t.ty}}function Ie(t){const[e,r,i,n]=t;return{minX:Math.min(e,i),minY:Math.min(r,n),maxX:Math.max(e,i),maxY:Math.max(r,n)}}function Ce(r,i){const n=ke(pe,r-t/2,i-e/2);return{x:n.x+t/2,y:n.y+e/2}}function Le(t){x();const e=function(t){const e=t.a*t.d-t.b*t.c;return Math.abs(e)<1e-12?null:{a:t.d/e,b:-t.b/e,c:-t.c/e,d:t.a/e,tx:(t.c*t.ty-t.d*t.tx)/e,ty:(t.b*t.tx-t.a*t.ty)/e}}(Pe());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");p.stroke.clipWindow={bounds:Ie(t),inverse:e}}function Te(){p.stroke.clipWindow=null}const Ne={};function Ye(r,i,n,o=!1){Qt=et(),te=rt(),ee=it(),re=nt(),ie=Q(),ne=tt(),pe=Pe(),ue=new at(r+t/2,i+e/2),fe=n,me=o,me&&me.calcIndex(0)}const ze=[];function Xe(r,i){i||(ge=r),function(){Ne.seed=999999*T();const{param:r}=de.get(p.stroke.type)??{};if(!r)return;Ne.p=r,xe=b.glMask;const{pressure:i}=r;if(Ne.a="custom"!==i.type?T(-1,1):0,Ne.b="custom"!==i.type?T(1,1.5):0,Ne.cp="custom"!==i.type?T(3,3.5):T(-.2,.2),[Ne.min,Ne.max]=i.min_max,Ne.noiseoffset=.03,!me){const t=ge*Math.PI/180;Ne.cos=Math.cos(t),Ne.sin=Math.sin(t)}!function(){v();const r=b.glMask.drawingContext,i=!Zt||$t!==r;(i||Vt!==t||Kt!==e)&&(Wt=new Float32Array([2/t,0,0,0,0,-2/e,0,0,0,0,1,0,-1,1,0,1]),Vt=t,Kt=e),i&&($t=r,jt=(t=>{const e=t.createProgram();for(let[r,i]of[[t.VERTEX_SHADER,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}"],[t.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"]]){const n=t.createShader(r);t.shaderSource(n,i),t.compileShader(n),t.attachShader(e,n)}return t.linkProgram(e),e})($t),$t.useProgram(jt),$t.enable($t.BLEND),$t.blendFunc($t.ONE_MINUS_DST_ALPHA,$t.ONE),["a_position","a_radius","a_alpha"].forEach(t=>qt[t]=$t.getAttribLocation(jt,t)),["u_matrix","u_color"].forEach(t=>Jt[t]=$t.getUniformLocation(jt,t)),Ht=$t.createVertexArray(),$t.bindVertexArray(Ht),Ut=$t.createBuffer(),$t.bindBuffer($t.ARRAY_BUFFER,Ut),$t.bufferData($t.ARRAY_BUFFER,oe.byteLength,$t.DYNAMIC_DRAW),le=oe.byteLength,$t.enableVertexAttribArray(qt.a_position),$t.vertexAttribPointer(qt.a_position,2,$t.FLOAT,!1,16,0),$t.enableVertexAttribArray(qt.a_radius),$t.vertexAttribPointer(qt.a_radius,1,$t.FLOAT,!1,16,8),$t.enableVertexAttribArray(qt.a_alpha),$t.vertexAttribPointer(qt.a_alpha,1,$t.FLOAT,!1,16,12),$t.bindVertexArray(null),Zt=!0)}();const n=!0!==b.isBrush;b.isBrush=!0,n&&(b.justChanged=!0),Ge()&&b.blend(p.stroke.color),Ne.alpha=Fe(),He()}();const n=function(){const{param:t}=de.get(p.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(fe*(i?r:1)/n);for(let t=0;t<o;t++)ze.length<2*o&&ze.push(z()),De(),i?ue.plotTo(me,n,n,r,t<10):ue._moveToDegrees(r,n,n);he(),He()}function De(t=!1){if(!Ge())return;let e=t||Oe(),r=D(L(Ne.seed+.002*ue.plotted,0),0,1,1-Ne.noiseoffset,1+Ne.noiseoffset);switch(Ne.p.type){case"spray":!function(t){const e=p.stroke.weight*Ne.p.scatter*t+p.stroke.weight*N(ze)*Ne.p.scatter/3,r=Ne.p.weight*T(.9,1.1),i=Math.ceil(Ne.p.grain/t);for(let t=0;t<i;t++){const t=T(.9,1.1),i=t*e*T(-1,1),n=T(-1,1),o=Math.sqrt((t*e)**2-i**2);ce(ue.x+i,ue.y+n*o,r,Ne.alpha)}}(e*r);break;case"marker":$e(e*r);break;case"custom":case"image":We(e*r,Ne.alpha);break;default:!function(t,e=1){const r=(e=D(e,0,1,.9,1.05))*p.stroke.weight*Ne.p.scatter*(Ne.p.sharpness+(1-Ne.p.sharpness)*N(ze)/t);if(T(0,Ne.p.grain*t)>.4){let e,i;if(me)e=.7*r*T(-1,1),i=r*T(-1,1);else{const t=r*T(-1,1),n=.3*r*T(-1,1);e=t*-Ne.sin+n*Ne.cos,i=t*Ne.cos+n*Ne.sin}ce(ue.x+e,ue.y+i,t*t*Ne.p.weight*T(.85,1.15)*p.stroke.weight,Math.max(.9,t)*Ne.alpha*T(.75,1.1))}}(e*r)}}function Oe(){return me?Be()*me.pressure(ue.plotted):Be()}function Be(){return"custom"===Ne.p.pressure.type?D(Ne.p.pressure.curve(ue.plotted/fe)+Ne.cp,0,1,Ne.min,Ne.max,!0):function(t=.5+Ne.p.pressure.curve[0]*Ne.a,e=1-Ne.p.pressure.curve[1]*Ne.b,r=Ne.cp,i=Ne.min,n=Ne.max){const o=t*fe,s=(ue.plotted<o?1.2*e:.8*e)*(fe/2);return D(1/(1+Math.pow(Math.abs((ue.plotted-o)/s),2*r)),0,1,i,n)}()}function Fe(){return["default","spray"].includes(Ne.p.type)?Ne.p.opacity:Ne.p.opacity/Math.min(p.stroke.weight,1.3)}function Ge(){const r=ke(pe,ue.x-t/2,ue.y-e/2);if(p.stroke.clipWindow){const t=ke(p.stroke.clipWindow.inverse,r.x,r.y),{bounds:e}=p.stroke.clipWindow;return t.x>=e.minX&&t.x<=e.maxX&&t.y>=e.minY&&t.y<=e.maxY}let i=.05*t;return r.x>=-t/2-i&&r.x<=t/2+i&&r.y>=-e/2-i&&r.y<=e/2+i}function $e(t,e=!0,r=Ne.alpha){const i=e?p.stroke.weight*Ne.p.scatter:0,n=e?i*T(-1,1):0,o=e?i*T(-1,1):0;ce(ue.x+n,ue.y+o,p.stroke.weight*Ne.p.weight*t,r)}function We(r,n,o=!0){b.glMask.isDrawn=!0,xe.push(),xe.noStroke(),p.stroke.color.setAlpha(n),xe.fill(p.stroke.color);const s=o?p.stroke.weight*Ne.p.scatter:0,a=o?s*T(-1,1):0,l=o?s*T(-1,1):0;xe.translate(ue.x+a-t,ue.y+l-e);const c=p.stroke.weight*r,h=function(t,e){xe.scale(t),"image"===Ne.p.type&&xe.tint(255,0,0,e/2);let r=0;return"random"===Ne.p.rotate?r=Y(0,360):"natural"===Ne.p.rotate&&(r=(me?-me.angle(ue.plotted):-ge)+ue.angle()),xe.rotate(r),r}(c,n);Ne.p.tip(xe),xe.pop(),"image"===Ne.p.type?function(t,e,r,n){const o=Ne.p.weight/2,s=n*Math.PI/180,a=Math.cos(s),l=Math.sin(s),c=ue.x+t,h=ue.y+e,u=[[-o,-o],[o,-o],[o,o],[-o,o]];let f=Infinity,m=Infinity,g=-Infinity,d=-Infinity;for(const[t,e]of u){const n=Ce(c+r*(a*t-l*e),h+r*(l*t+a*e));f=Math.min(f,n.x*i.pixelDensity()),m=Math.min(m,n.y*i.pixelDensity()),g=Math.max(g,n.x*i.pixelDensity()),d=Math.max(d,n.y*i.pixelDensity())}b.markDirtyRect(b.glMask,{minX:f-2,minY:m-2,maxX:g+2,maxY:d+2})}(a,l,c,h):b.markFull(b.glMask)}function He(){if(Ge()){let t=Oe(),e=Fe();if("marker"===Ne.p.type){for(let r=1;r<10;r++)$e(t*r/10,!1,5*e);he()}else if("custom"===Ne.p.type||"image"===Ne.p.type)for(let r=1;r<5;r++)We(t*r/5,e,!1)}}function Ue(t,e,r,i){if(!p.stroke.isActive||!p.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");st();let n=K(t,e,r,i);0!=n&&(Ye(t,e,n),Xe(q(t,e,r,i),!1))}function je(t,e,r,i){if(!p.stroke.isActive||!p.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");st(),Ye(t,e,r),Xe(j(i),!1)}C(()=>{ze.length=0});const Ze=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],Ve=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of Ve){let e={};for(let r=0;r<t[1].length;r++)e[Ze[r]]=t[1][r];be(t[0],e)}be("diamond",{type:"custom",weight:.78,scatter:.1,opacity:17,spacing:1.3,pressure:[1.2,.82],rotate:"none",tip:t=>{t.rotate(45),t.rect(-4,-4,8,8),t.rect(2,2,3,3)}}),Mt.prototype.draw=function(t=!1,e,r){let i=ye();if(t&&Ee(t,e,r),i.isActive)for(let t of this.sides)Ue(t[0].x,t[0].y,t[1].x,t[1].y);ve(i)},St.prototype.draw=function(t,e,r){ye().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,i){st(),Ye(e,r,t.length,t),Xe(i,!0)}(this,t,e,r))};const Ke={tips:new Map,add(t){this.tips.set(t,!1)},imageToWhite(t){t.loadPixels();for(let e=0;e<4*t.width*t.height;e+=4){let r=(t.pixels[e]+t.pixels[e+1]+t.pixels[e+2])/3;t.pixels[e]=t.pixels[e+1]=t.pixels[e+2]=255,t.pixels[e+3]=255-r}t.updatePixels()},async load(){const t=[...this.tips.keys()].filter(t=>!this.tips.get(t));await Promise.all(t.map(t=>new Promise((e,r)=>{const n=new window.Image;n.onload=()=>{const r=i.createImage(n.naturalWidth,n.naturalHeight);r.drawingContext.drawImage(n,0,0),Ke.imageToWhite(r),this.tips.set(t,r),e()},n.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),n.src=t})))}};function qe(){return{...p.hatch}}function Je(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let i=p.hatch;i.isActive=!0,i.dist=t,i.angle=Z(e),i.options=r}function Qe(t,e="black",r=1){p.hatch.hBrush={brush:t,color:e,weight:r}}function tr(){p.hatch.isActive=!1,p.hatch.hBrush=!1}function er(t){let e=p.hatch.dist,r=(p.hatch.angle%180+180)%180,i=p.hatch.options,n=ye();p.hatch.hBrush&&Ee(...Object.values(p.hatch.hBrush)),Array.isArray(t)||(t=[t]);const o=function(t){let e={minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity};for(let r of t){const t=rr(r);e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY)}return e}(t);let s=new Mt([[o.minX,o.minY],[o.maxX,o.minY],[o.maxX,o.maxY],[o.minX,o.maxY]]),a=r<=90&&r>=0?o.minY:o.maxY,l=i.gradient?D(i.gradient,0,1,1,1.1,!0):1,c=[],h=0,u=e,f=t=>({point1:{x:o.minX+u*t*H(90-r),y:a+u*t*U(90-r)},point2:{x:o.minX+u*t*H(90-r)+H(-r),y:a+u*t*U(90-r)+U(-r)}});for(;s.intersect(f(h)).length>0;){let e=[];for(let r of t)e.push(r.intersect(f(h)));c[h]=e.flat().sort((t,e)=>t.x===e.x?t.y-e.y:t.x-e.x),u*=l,h++}let m=c.filter(t=>void 0!==t[0]),g=i.rand||0;for(let t=0;t<m.length;t++){let r=m[t],n=t>0&&i.continuous;for(let i=0;i<r.length-1;i+=2)0!==g&&(r[i].x+=g*e*T(-1,1),r[i].y+=g*e*T(-1,1),r[i+1].x+=g*e*T(-1,1),r[i+1].y+=g*e*T(-1,1)),Ue(r[i].x,r[i].y,r[i+1].x,r[i+1].y),n&&Ue(m[t-1][1].x,m[t-1][1].y,r[i].x,r[i].y)}ve(n)}function rr(t){if(t._boundingBox)return t._boundingBox;let e=Infinity,r=Infinity,i=-Infinity,n=-Infinity;for(let o=0;o<t.a.length;o++){const[s,a]=t.a[o];s<e&&(e=s),s>i&&(i=s),a<r&&(r=a),a>n&&(n=a)}return t._boundingBox={minX:e,minY:r,maxX:i,maxY:n},t._boundingBox}function ir(t,e,r){return{x:t.a*e+t.c*r+t.e,y:t.b*e+t.d*r+t.f}}function nr(t,e){const r=t.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(e.a,e.c),Math.hypot(e.b,e.d))/2}function or(t,e,r){const i=2*Math.PI,n=b.ctx,o=n.getTransform(),s=r/2,a=ir(o,t,e),l=s*Math.hypot(o.a,o.c),c=s*Math.hypot(o.b,o.d),h=nr(n,o);b.markDirtyRect(b.mask,{minX:a.x-l-h,minY:a.y-c-h,maxX:a.x+l+h,maxY:a.y+c+h}),n.moveTo(t+s,e),n.arc(t,e,s,0,i)}p.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},Mt.prototype.hatch=function(t=!1,e,r){let i=qe();t&&Je(t,e,r),i.isActive&&er(this),function(t){p.hatch={...t}}(i)},St.prototype.hatch=function(t,e,r){qe().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},p.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const sr=()=>({...p.fill});function ar(t,e,r,n){p.fill.opacity=(arguments.length<4?e:n)||150,p.fill.color=arguments.length<3?i.color(t):i.color(t,e,r),p.fill.isActive=!0}function lr(t,e="out"){p.fill.bleed_strength=O(t,0,1),p.fill.direction=e}function cr(t=.4,e=.4){p.fill.texture_strength=O(t,0,1),p.fill.border_strength=O(e,0,1)}function hr(){p.fill.isActive=!1}let ur;const fr=[[],[]];function mr(){for(let t=0;t<512;t++)fr[0][t]=z(.5,.2),fr[1][t]=z(0,.02)}function gr(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}C(mr);class dr{constructor(t,e,r,i=[],n=!1,o,s){if(this.v=t,this.m=e,this.dir=i,this.midP=r,n){let e=0,i=0;const n=[];for(let o=0;o<t.length;o++){const s=Math.abs(r.x-t[o].x),a=Math.abs(r.y-t[o].y);e=Math.max(e,s),i=Math.max(i,a);const l=t[o],c=t[(o+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=V(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};n.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=i,this.dir=Array(t.length),n.forEach((t,e)=>{let r=0;for(const e of ur.intersect(t.ray))gr(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=T(-.6,.6)*e,s=T(-.6,.6)*i;this.midP={x:r.x+o,y:r.y+s}}else this.sizeX=o,this.sizeY=s}trim(t=1){if(t>=1||t<0||this.v.length<=8)return{v:[...this.v],m:[...this.m],dir:[...this.dir]};const e=~~((1-t)*this.v.length),r=~~(this.v.length/2-e/2),i=[...this.v],n=[...this.m],o=[...this.dir];return i.splice(r,e),n.splice(r,e),o.splice(r,e),{v:i,m:n,dir:o}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),i=[],n=e/r;for(let t=0;t<r;t++)i.push(~~(t*n+T(0,.8*n)));const o=[],s=[],a=[],l=this.midP,c=ur.sides;for(const t of i){const r=t%e;let i=this.v[r],n=0;for(const[t,e]of c){const r=t.y,o=e.y;if(r>i.y==o>i.y)continue;const s=(i.y-r)/(o-r);i.x<t.x+s*(e.x-t.x)&&n++}n%2==0&&(i={x:l.x+(i.x-l.x)*T(.3,.6),y:l.y+(i.y-l.y)*T(.3,.6)}),o.push(i),s.push(this.m[r]),a.push(!this.dir[r])}return new dr(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new dr(this.v,this.m,this.midP,this.dir.map(t=>!t),!1,this.sizeX,this.sizeY)}grow(t=1){const{v:e,m:r,dir:i}=this.trim(t),n=e.length,o=2*n,s=new Array(o),a=new Array(o),l=new Array(o),c="out"===p.fill.direction?-90:90;0===fr[0].length&&mr();const h=fr[0],u=h.length,f=fr[1],m=f.length;let g=0,d=999===t?T(.6,.8):p.fill.bleed_strength;for(let o=0;o<n;o++){const x=e[o],p=e[o+1<n?o+1:0],y=r[o],v=i[o];t<997&&(d=y);const b=(v?c:-c)+5*T(-1,1),_=H(b),w=U(b),R=p.x-x.x,M=p.y-x.y,S=_*R+w*M,E=_*M-w*R,A=h[~~(T(0,1)*u)]*T(.65,1.35)*d;s[g]=x,a[g]=y,l[g]=v,g++,s[g]={x:x.x+.5*R+S*A,y:x.y+.5*M+E*A},a[g]=y+f[~~(T(0,1)*m)],l[g]=v,g++}let x=s,y=a,v=l,b=1024/p.fill.texture_strength;if(b&&g>b){const t=Math.ceil(g/b);x=[],y=[],v=[];for(let e=0;e<g;e+=t)x.push(s[e]),y.push(a[e]),v.push(l[e])}else x.length=g,y.length=g,v.length=g;return new dr(x,y,this.midP,v,!1,this.sizeX,this.sizeY)}fill(r,i,o){const s=3*o,a=2*i*(1+o/2),l=!1!==b.isBrush;b.isBrush=!1,l&&(b.justChanged=!0),b.blend(r),b.ctx.save(),b.ctx.setTransform(n*et(),n*rt(),n*it(),n*nt(),n*(Q()+t/2),n*(tt()+e/2)),b.ctx.strokeStyle=`rgb(${r._getRed()} ${r._getGreen()} ${r._getBlue()} / ${.005*p.fill.border_strength})`,b.ctx.lineCap="round";const c=Math.max(this.sizeX,this.sizeY),h=T(.15,.7);let u=this.grow();const f=this.scatter(.1).grow().scatter(.75).flipDirs();let m;for(let t=0;t<20;t++){t%4==0&&(u=u.grow()),t%2==0&&(m=[u.grow(1-.0125*t),u.grow(.7-.0125*t),u.grow(.4-.0125*t)]);for(const e of m)e.grow(999).grow(997).layer(t,c,a,r);f.grow(999).flipDirs().grow(997).layer(t,c,1.5*a*s,r),t%2==0&&u.grow(h).grow(999).layer(t,c,2*a,r),t%5!=0&&19!==t||(0!==s&&u.erase(3*s,i),b.blend(r,!0,!1,!0))}b.ctx.restore()}layer(t,e,r,i){b.ctx.lineWidth=D(t,0,24,e/25,e/30,!0),b.ctx.fillStyle=`rgb(${i._getRed()} ${i._getGreen()} ${i._getBlue()} / ${r}%)`,function(t){const e=b.ctx,r=e.getTransform();let i=Infinity,n=Infinity,o=-Infinity,s=-Infinity;e.beginPath(),t.forEach((t,a)=>{const l=ir(r,t.x,t.y);i=Math.min(i,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),s=Math.max(s,l.y),0===a?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.closePath();const a=nr(e,r);b.markDirtyRect(b.mask,{minX:i-a,minY:n-a,maxX:o+a,maxY:s+a})}(this.v),b.ctx.fill(),b.ctx.stroke()}erase(t,e){b.ctx.save();const r=~~(T(80,110)*D(t,0,1,2,3.5)),i=this.sizeX/1.3,n=this.sizeY/1.3,o=Math.min(this.sizeX,this.sizeY)*(1.4-p.fill.bleed_strength),s=.05*o,a=.4*o,{x:l,y:c}=this.midP;b.ctx.globalCompositeOperation="destination-out";const h=(5-D(e,80,100,.3,.7,!0))*t/255;b.ctx.fillStyle=`rgb(255 0 0 / ${h})`,b.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+z(0,i),r=c+z(0,n),o=T(s,a);b.ctx.beginPath(),or(e,r,o),t%5!=0&&b.ctx.fill()}b.ctx.globalCompositeOperation="source-over",b.ctx.restore()}}Mt.prototype.fill=function(t=!1,e,r,i,n,o){let s=sr();t&&(ar(t,e),lr(r,o),cr(i,n)),s.isActive&&(st(),function(t){if(!p.fill.isActive||!p.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");ur=t;const e=[...t.vertices],r=~~(.25*e.length*X({1:5,2:10,3:60})),i=p.fill.bleed_strength,n=e.map((t,e)=>(e>r?1:.3)*T(.85,1.2)*i),o=Y(0,e.length),s=[...e.slice(o),...e.slice(0,o)],a=function(t){if(t.length<8)return t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0}).map(e=>e/t.length);const e=[...t];e[0].x===e[e.length-1].x&&e[0].y===e[e.length-1].y||e.push(e[0]);let r=0,i=0,n=0;for(let t=0;t<e.length-1;t++){const o=e[t].x*e[t+1].y-e[t+1].x*e[t].y;r+=o,i+=(e[t].x+e[t+1].x)*o,n+=(e[t].y+e[t+1].y)*o}return r*=.5,r?{x:i/(6*r),y:n/(6*r)}:{x:e[0].x,y:e[0].y}}(s);new dr(s,n,a,[],!0).fill(p.fill.color,D(p.fill.opacity,0,255,0,1,!0),p.fill.texture_strength)}(this)),(t=>{p.fill={...t}})(s)},St.prototype.fill=function(t,e,r){sr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,D(p.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const xr=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>b.blend(!1,!0),r.postdraw=()=>b.blend(!1,!0);const i=e.push,n=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){i.call(this),st(),xr.push({fill:{...p.fill},stroke:{...p.stroke},hatch:{...p.hatch},field:{...p.field}})},e.pop=function(){n.call(this),function(){const t=xr.pop();t&&(p.stroke={...t.stroke},p.field={...t.field},p.hatch={...t.hatch},p.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{k=A(t);for(const t of I)t()})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{L=E(A(t))})(t)}});export{St as Plot,Mt as Polygon,at as Position,be as add,bt as addField,kt as arc,Yt as beginShape,Dt as beginStroke,_e as box,Pt as circle,Le as clip,Xt as endShape,Bt as endStroke,yt as field,ar as fill,lr as fillBleed,cr as fillTexture,je as flowLine,Je as hatch,er as hatchArray,Qe as hatchStyle,y as instance,Ue as line,_t as listFields,m as load,Ot as move,Te as noClip,vt as noField,hr as noFill,tr as noHatch,Ae as noStroke,Re as pick,Et as polygon,At as rect,pt as refreshField,we as scaleBrushes,Ee as set,Ft as spline,Me as stroke,Se as strokeWeight,zt as vertex,X as wRand,wt as wiggle};
//# sourceMappingURL=p5.brush.esm.js.map
diff --git a/dist/p5.brush.esm.js.map b/dist/p5.brush.esm.js.map
index 350e1c8..6b50aec 100644
--- a/dist/p5.brush.esm.js.map
+++ b/dist/p5.brush.esm.js.map
@@ -1 +1 @@
-{"version":3,"file":"p5.brush.esm.js","sources":["../src/core/color.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/flowfield.js","../src/core/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/core/gl/utils.js","../src/hatch/hatch.js","../src/core/mask.js","../src/fill/fill.js","../src/core/save.js","../src/index.js"],"sourcesContent":["import vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Section: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties\n\nconst isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\nconst getSketchRenderer = () =>\n _isInstanced ? Instance : window.self.p5.instance;\n\nconst isSupportedFramebufferTarget = (target) =>\n isFramebufferTarget(target) && target.renderer._pInst === getSketchRenderer();\n\nconst resolveTarget = (buffer = false) => {\n if (_isInstanced && !buffer) {\n return {\n renderer: Instance,\n width: Instance.width,\n height: Instance.height,\n };\n }\n\n if (!buffer) {\n const renderer = getSketchRenderer();\n return {\n renderer,\n width: renderer.width,\n height: renderer.height,\n };\n }\n\n if (isFramebufferTarget(buffer)) {\n if (!isSupportedFramebufferTarget(buffer)) {\n throw new Error(\n \"p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.\",\n );\n }\n\n return {\n renderer: getSketchRenderer(),\n width: buffer.width,\n height: buffer.height,\n };\n }\n\n return {\n renderer: buffer,\n width: buffer.width,\n height: buffer.height,\n };\n};\n\nconst removeTargetBuffer = (buffer) => {\n if (buffer && typeof buffer.remove === \"function\") {\n buffer.remove();\n }\n};\n\nconst getGraphicsFactory = () =>\n typeof Renderer.createGraphics === \"function\" ? Renderer : Renderer._pInst;\n\nconst getActiveFramebuffer = () =>\n Renderer &&\n Renderer._renderer &&\n typeof Renderer._renderer.activeFramebuffer === \"function\"\n ? Renderer._renderer.activeFramebuffer()\n : null;\n\nconst needsBlendSourceFramebuffer = (framebuffer) =>\n !framebuffer ||\n framebuffer.width !== Cwidth ||\n framebuffer.height !== Cheight ||\n (typeof framebuffer.pixelDensity === \"function\" &&\n framebuffer.pixelDensity() !== Density);\n\nconst needsMixBuffers = () =>\n !Renderer.mask ||\n !Renderer.glMask ||\n Renderer.mask.width !== Cwidth ||\n Renderer.mask.height !== Cheight ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight;\n\nconst DIRTY_BRUSH_PADDING = 2;\nconst DIRTY_FILL_PADDING = 4;\n\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n\n const { width, height } = getTargetPixelSize();\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\nconst unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return { minX: 0, minY: 0, maxX: width, maxY: height };\n};\n\nconst toScissorBox = (rect) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: height - normalized.maxY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\nconst withScissor = (gl, rect, draw) => {\n const box = toScissorBox(rect);\n if (!box) return false;\n\n const wasEnabled = gl.isEnabled(gl.SCISSOR_TEST);\n const prevBox = gl.getParameter(gl.SCISSOR_BOX);\n\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n if (wasEnabled) {\n gl.scissor(prevBox[0], prevBox[1], prevBox[2], prevBox[3]);\n } else {\n gl.disable(gl.SCISSOR_TEST);\n }\n }\n\n return true;\n};\n\n/**\n * Loads and initializes a canvas for the drawing system.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.\n * Pass a framebuffer only while drawing inside its begin()/end() or draw() scope.\n * Framebuffers created from p5.Graphics are not supported.\n */\nexport const load = (buffer = false) => {\n const target = resolveTarget(buffer);\n Renderer = target.renderer;\n\n // Check if Rendrer is webgl and throw error if it's not\n\n if (Renderer.webglVersion !== \"webgl2\") {\n throw new Error(\"p5.brush requires a WEBGL canvas\");\n }\n\n Cwidth = target.width;\n Cheight = target.height;\n\n _isReady = true;\n if (Renderer.loaded) Mix.load();\n};\n\nlet _isReady = false;\nlet _isInstanced = false;\n\n/**\n * Ensures the drawing system is ready before any operation.\n */\nexport const isCanvasReady = () => {\n if (!_isReady) load();\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n\nexport const instance = (inst) => {\n _isInstanced = true;\n Instance = inst;\n};\n\n\n// =============================================================================\n// Section: Color Blending\n// =============================================================================\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\nconst disable = false;\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: new Object(),\n\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n markFull(target) {\n if (!target) return;\n\n target.dirtyRect = getFullDirtyRect();\n target.isDrawn = true;\n },\n\n clearMask(target) {\n if (!target) return;\n\n target.clear();\n target.isDrawn = false;\n target.dirtyRect = null;\n },\n\n getCompositeRect(target, isBrushMask) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n\n return normalizeDirtyRect(\n expandDirtyRect(\n target.dirtyRect,\n isBrushMask ? DIRTY_BRUSH_PADDING : DIRTY_FILL_PADDING,\n ),\n );\n },\n\n captureBlendSource(dirtyRect) {\n const activeFramebuffer = getActiveFramebuffer();\n\n if (!activeFramebuffer) return Renderer._renderer;\n\n if (needsBlendSourceFramebuffer(Renderer.blendSourceFramebuffer)) {\n removeTargetBuffer(Renderer.blendSourceFramebuffer);\n Renderer.blendSourceFramebuffer = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n const source = Renderer.blendSourceFramebuffer;\n\n source.draw(() => {\n withScissor(Renderer.drawingContext, dirtyRect, () => {\n Renderer.clear();\n Renderer.push();\n if (typeof Renderer.imageMode === \"function\") {\n Renderer.imageMode(\n Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER,\n );\n }\n Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n });\n });\n\n return source;\n },\n\n /**\n * Loads necessary resources and prepares the mask buffer and shader for colour blending.\n */\n load() {\n Density = Renderer.pixelDensity();\n const graphicsFactory = getGraphicsFactory();\n const p2dMode = graphicsFactory.P2D ?? Renderer.P2D;\n const webglMode = graphicsFactory.WEBGL ?? Renderer.WEBGL;\n\n if (!Renderer.loaded || needsMixBuffers()) {\n removeTargetBuffer(Renderer.mask);\n removeTargetBuffer(Renderer.glMask);\n\n Renderer.mask = graphicsFactory.createGraphics(Cwidth, Cheight, p2dMode);\n Renderer.glMask = graphicsFactory.createGraphics(\n Cwidth,\n Cheight,\n webglMode,\n );\n Renderer.loaded = true;\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n\n this.mask = Renderer.mask;\n this.mask.pixelDensity(Density);\n this.mask.clear();\n this.mask.angleMode(Renderer.DEGREES);\n this.mask.dirtyRect = null;\n this.mask.isDrawn = false;\n\n this.ctx = this.mask.drawingContext;\n\n this.glMask = Renderer.glMask;\n this.glMask.pixelDensity(Density);\n this.glMask.clear();\n this.glMask.angleMode(this.glMask.DEGREES);\n this.glMask.drawingContext.lineWidth = 0;\n this.glMask.dirtyRect = null;\n this.glMask.isDrawn = false;\n } else {\n this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\n this.mask.dirtyRect ??= null;\n this.mask.isDrawn ??= false;\n this.glMask.dirtyRect ??= null;\n this.glMask.isDrawn ??= false;\n }\n\n // Link Matrix of GL mask to main Renderer\n this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;\n },\n\n /**\n * Applies blending effects using the current color and mask.\n * @param {Color} _color - Color to blend.\n * @param {boolean} _isLast - If this is the final blend operation.\n * @param {boolean} _isImg - If blending an image.\n * @param {boolean} _isFillLayer - If this is a special case.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n\n const activeIsBrush = this.isBrush === true;\n const mask = activeIsBrush ? this.glMask : this.mask;\n const no_mask = activeIsBrush ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor[0] !== nextColor[0] ||\n this.cachedColor[1] !== nextColor[1] ||\n this.cachedColor[2] !== nextColor[2] ||\n this.cachedColor[3] !== nextColor[3]);\n\n // Perf gains are minimal but let's keep it for now\n if (disable) {\n if (_isLast && mask.isDrawn) {\n Renderer.push();\n Renderer.translate(0, 0);\n Renderer.image(mask, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n mask.isDrawn = false;\n }\n return;\n }\n\n // Initialize blending if not already active\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Force p5 to bind its internal render target for glMask,\n // so the first glDraw() writes to the correct framebuffer.\n this.glMask.clear();\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(no_mask, !activeIsBrush);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, activeIsBrush);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) this.isBlending = false;\n }\n },\n\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n let shader = Renderer.shaderProgram;\n const gl = Renderer.drawingContext;\n const targetIsFramebuffer = !!getActiveFramebuffer();\n const source = this.captureBlendSource(dirtyRect);\n\n // Disable depth test for this compositing draw so the fullscreen rect\n // does not write Z=0 into the depth buffer — which would cause any\n // subsequent p5 geometry drawn at the same depth to fail depth testing\n // and become invisible.\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n gl.disable(gl.DEPTH_TEST);\n\n Renderer.push();\n Renderer.translate(0, 0);\n\n // Use the blend shader for rendering\n Renderer.shader(shader);\n\n // Set shader uniforms\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n shader.setUniform(\"u_flipOutputY\", targetIsFramebuffer);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", this.cachedColor);\n\n // Draw a rectangle covering the whole canvas to apply the shader\n withScissor(gl, dirtyRect, () => {\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n });\n\n // Finish and clear mask\n Renderer.pop();\n Renderer.resetShader();\n\n // Restore depth test state\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n this.clearMask(mask);\n },\n};\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { Renderer } from \"./color.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n const usesRadians =\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS);\n // Only if Renderer.angleMode() is set to radians\n if (usesRadians) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS)\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","import { isMixReady, Cwidth, Cheight, State, Renderer } from \"./color.js\";\nimport { randInt, noise, rr, sin, cos, map, toDegreesSigned } from \"./utils.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n/**\n * The `Matrix` object exposes the current 2D affine transform from p5's model matrix.\n * mat4 layout (column-major 4x4):\n * [0]=a [1]=b [4]=c [5]=d [12]=tx [13]=ty\n * where the 2D transform of a point (x,y) is: (a*x + c*y + tx, b*x + d*y + ty)\n */\nexport const Matrix = {\n x: () => Renderer._renderer.uModelMatrix.mat4[12],\n y: () => Renderer._renderer.uModelMatrix.mat4[13],\n a: () => Renderer._renderer.uModelMatrix.mat4[0],\n b: () => Renderer._renderer.uModelMatrix.mat4[1],\n c: () => Renderer._renderer.uModelMatrix.mat4[4],\n d: () => Renderer._renderer.uModelMatrix.mat4[5],\n};\n\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n this.colIdx = Position.getColIndex(x);\n this.rowIdx = Position.getRowIndex(y);\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + Matrix.x();\n const y = this.y + Matrix.y();\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle() {\n return this.isIn() && State.field.isActive\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current p5 angle mode.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1) {\n this.movePos(_plot, _length, _step_length, _scale);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n for (let i = 0; i < _length / _step; i++) {\n const angle =\n this.angle() - (_scale ? _dirPlot.angle(this.plotted) : _dirPlot);\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + Matrix.y() - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + Matrix.x() - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr(0.2, 0.8),\n ba = randInt(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt(15, 25));\n return 0.2 * angle * cos(t) + noise(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt(-10, 10);\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt(-30, -15) + Math.abs(44 * sin(t));\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt(10, 15) + 5 * sin(t),\n cr = randInt(3, 6) + 3 * cos(t),\n ba = randInt(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr(0.4, 0.8),\n ba = randInt(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt(5, 10);\n const dir = randInt(0, 2) * 2 - 1;\n const offset = randInt(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr(0.1, 0.9) * num_columns,\n y: rr(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt(3, 8),\n amp = randInt(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.stroke) this.draw();\n if (State.hatch) this.hatch();\n if (State.fill) this.fill();\n }\n}\n","import { State, Cwidth, Cheight } from \"./color.js\";\nimport { toDegrees, map, rr } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = 0.5;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n const maxSize = Math.max(this.segments[idx] * _side * rr(0.7, 1.3), 10);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.stroke) this.draw(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n }\n}\n","import {\n rr,\n randInt,\n sin,\n cos,\n toDegrees,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current p5 angle mode.\n * @param {number} end - End angle in the current p5 angle mode.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module provides functions for rendering shapes (circles and squares)\n * using WebGL2. It initializes the WebGL context and shader programs, prepares buffers,\n * and implements drawing routines based on queued drawing primitives. The module uses\n * an orthographic projection to map canvas coordinates to clip space and supports adjustable\n * blending for translucent effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\n State,\n} from \"../core/color.js\";\nimport { Matrix } from \"../core/flowfield.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n projMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0;\n\n/**\n * Snapshots the current p5 model matrix. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n _ma = Matrix.a();\n _mb = Matrix.b();\n _mc = Matrix.c();\n _md = Matrix.d();\n _mx = Matrix.x();\n _my = Matrix.y();\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n\n const nextGl = Mix.glMask.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n projMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n -2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * p5's current model matrix so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - Cwidth / 2;\n const py = y - Cheight / 2;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + Cwidth / 2;\n const screenY = _mb * px + _md * py + _my + Cheight / 2;\n const radius =\n (Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n Mix.markDirtyRect(Mix.glMask, {\n minX: screenX * Density - radius - 1,\n minY: screenY * Density - radius - 1,\n maxX: screenX * Density + radius + 1,\n maxY: screenY * Density + radius + 1,\n });\n\n circleCount++;\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader (p5 drawing may have switched programs)\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, projMatrix);\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing p5's _curShader tracking.\n // Reset it to null so p5 is forced to re-activate its own shader next time\n // it draws — otherwise p5 skips gl.useProgram() and sets uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n Mix.glMask._renderer._curShader = null;\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n State,\n Renderer,\n isCanvasReady,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed,\n} from \"../core/utils.js\";\nimport { Position, Matrix, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { isReady, glDraw, circle, snapshotMatrix } from \"./gl_draw.js\";\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n clipWindow: null,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nlet Mask = null;\nlet _strokeTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n tx: 0,\n ty: 0,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { type, min_max, curve } — old internal format, passed through unchanged\n */\nfunction normalizePressure(p) {\n if (!p || (typeof p === \"object\" && !Array.isArray(p))) return p;\n if (typeof p === \"function\")\n return { type: \"custom\", min_max: [0, 1], curve: p };\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n params.tip = () => {\n Mask.image(\n T.tips.get(current.p.image.src),\n -current.p.weight / 2,\n -current.p.weight / 2,\n current.p.weight,\n current.p.weight,\n );\n };\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = Renderer.color(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\nfunction snapshotTransform() {\n return {\n a: Matrix.a(),\n b: Matrix.b(),\n c: Matrix.c(),\n d: Matrix.d(),\n tx: Matrix.x(),\n ty: Matrix.y(),\n };\n}\n\nfunction invertTransform(transform) {\n const det = transform.a * transform.d - transform.b * transform.c;\n if (Math.abs(det) < 1e-12) return null;\n\n return {\n a: transform.d / det,\n b: -transform.b / det,\n c: -transform.c / det,\n d: transform.a / det,\n tx: (transform.c * transform.ty - transform.d * transform.tx) / det,\n ty: (transform.b * transform.tx - transform.a * transform.ty) / det,\n };\n}\n\nfunction transformPoint(transform, x, y) {\n return {\n x: transform.a * x + transform.c * y + transform.tx,\n y: transform.b * x + transform.d * y + transform.ty,\n };\n}\n\nfunction normalizeRegion(region) {\n const [x1, y1, x2, y2] = region;\n return {\n minX: Math.min(x1, x2),\n minY: Math.min(y1, y2),\n maxX: Math.max(x1, x2),\n maxY: Math.max(y1, y2),\n };\n}\n\nfunction currentPointInUserSpace() {\n return transformPoint(\n _strokeTransform,\n _position.x - Cwidth / 2,\n _position.y - Cheight / 2,\n );\n}\n\nfunction screenPointFromPosition(x, y) {\n const point = transformPoint(_strokeTransform, x - Cwidth / 2, y - Cheight / 2);\n return {\n x: point.x + Cwidth / 2,\n y: point.y + Cheight / 2,\n };\n}\n\nfunction markImageTipDirty(rx, ry, scale, angle) {\n const halfWeight = current.p.weight / 2;\n const radians = (angle * Math.PI) / 180;\n const cosAngle = Math.cos(radians);\n const sinAngle = Math.sin(radians);\n const userCenterX = _position.x + rx;\n const userCenterY = _position.y + ry;\n const corners = [\n [-halfWeight, -halfWeight],\n [halfWeight, -halfWeight],\n [halfWeight, halfWeight],\n [-halfWeight, halfWeight],\n ];\n\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n for (const [x, y] of corners) {\n const lx = scale * (cosAngle * x - sinAngle * y);\n const ly = scale * (sinAngle * x + cosAngle * y);\n const point = screenPointFromPosition(userCenterX + lx, userCenterY + ly);\n\n minX = Math.min(minX, point.x * Renderer.pixelDensity());\n minY = Math.min(minY, point.y * Renderer.pixelDensity());\n maxX = Math.max(maxX, point.x * Renderer.pixelDensity());\n maxY = Math.max(maxY, point.y * Renderer.pixelDensity());\n }\n\n Mix.markDirtyRect(Mix.glMask, {\n minX: minX - 2,\n minY: minY - 2,\n maxX: maxX + 2,\n maxY: maxY + 2,\n });\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current p5 transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n const inverse = invertTransform(snapshotTransform());\n if (!inverse) {\n throw new Error(\n \"brush.clip() cannot be used with a non-invertible transform.\",\n );\n }\n State.stroke.clipWindow = {\n bounds: normalizeRegion(region),\n inverse,\n };\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n State.stroke.clipWindow = null;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {boolean} flow - Flag for vector-field following.\n * @param {Object|boolean} plot - Plot object or false.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _strokeTransform = snapshotTransform();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n isPlot\n ? _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n )\n : _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n Mask = Mix.glMask;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.a = pressure.type !== \"custom\" ? rr(-1, 1) : 0;\n current.b = pressure.type !== \"custom\" ? rr(1, 1.5) : 0;\n current.cp = pressure.type !== \"custom\" ? rr(3, 3.5) : rr(-0.2, 0.2);\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.03;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n const dirRad = (_dir * Math.PI) / 180;\n current.cos = Math.cos(dirRad);\n current.sin = Math.sin(dirRad);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n if (isInsideClippingArea()) Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n glDraw();\n markerTip();\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n * @param {number} [customPressure=false] - Optional custom pressure.\n */\nfunction tip(customPressure = false) {\n if (!isInsideClippingArea()) return;\n let pressure = customPressure || calculatePressure();\n\n let lineNoise = map(\n noise(current.seed + _position.plotted * 0.002, 0),\n 0,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n\n switch (current.p.type) {\n case \"spray\":\n drawSpray(pressure * lineNoise);\n break;\n case \"marker\":\n drawMarker(pressure * lineNoise);\n break;\n case \"custom\":\n case \"image\":\n drawTip(pressure * lineNoise, current.alpha);\n break;\n default:\n drawDefault(pressure * lineNoise);\n break;\n }\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n return _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n return current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(_position.plotted / _length) + current.cp,\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Checks if the current drawing position is within the clipping region.\n * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n const point = currentPointInUserSpace();\n\n if (State.stroke.clipWindow) {\n const local = transformPoint(\n State.stroke.clipWindow.inverse,\n point.x,\n point.y,\n );\n const { bounds } = State.stroke.clipWindow;\n return (\n local.x >= bounds.minX &&\n local.x <= bounds.maxX &&\n local.y >= bounds.minY &&\n local.y <= bounds.maxY\n );\n }\n\n let o = Cwidth * 0.05;\n return (\n point.x >= -Cwidth / 2 - o &&\n point.x <= Cwidth / 2 + o &&\n point.y >= -Cheight / 2 - o &&\n point.y <= Cheight / 2 + o\n );\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return 1;\n return param.spacing;\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha,\n );\n}\n\n/**\n * Draws a custom or image-based brush tip.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Alpha (opacity) for drawing.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawTip(pressure, alpha, vibrate = true) {\n Mix.glMask.isDrawn = true;\n Mask.push();\n Mask.noStroke();\n let color = State.stroke.color;\n color.setAlpha(alpha);\n Mask.fill(State.stroke.color);\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n Mask.translate(_position.x + rx - Cwidth, _position.y + ry - Cheight);\n const scale = State.stroke.weight * pressure;\n const angle = adjustSizeAndRotation(scale, alpha);\n current.p.tip(Mask);\n Mask.pop();\n\n if (current.p.type === \"image\") {\n markImageTipDirty(rx, ry, scale, angle);\n } else {\n Mix.markFull(Mix.glMask);\n }\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n if (rr(0, current.p.grain * pressure) > 0.4) {\n let dx, dy;\n if (_plot) {\n dx = 0.7 * vibration * rr(-1, 1);\n dy = vibration * rr(-1, 1);\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * -current.sin + along * current.cos;\n dy = perp * current.cos + along * current.sin;\n }\n circle(\n _position.x + dx,\n _position.y + dy,\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight,\n Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1),\n );\n }\n}\n\n/**\n * Adjusts the size and rotation of the brush tip before rendering.\n * @param {number} pressure - Pressure-based scaling factor.\n * @param {number} alpha - Opacity value.\n */\nfunction adjustSizeAndRotation(pressure, alpha) {\n Mask.scale(pressure);\n if (current.p.type === \"image\") {\n Mask.tint(255, 0, 0, alpha / 2);\n }\n let angle = 0;\n if (current.p.rotate === \"random\") angle = randInt(0, 360);\n else if (current.p.rotate === \"natural\") {\n angle =\n (_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle();\n }\n Mask.rotate(angle);\n return angle;\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (isInsideClippingArea()) {\n let pressure = calculatePressure();\n let alpha = calculateAlpha(pressure);\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, false, alpha * 5);\n }\n glDraw();\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawTip((pressure * s) / 5, alpha, false);\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current p5 angle mode.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, vibration, definition, quality, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\nadd(\"diamond\", {\n type: \"custom\",\n weight: 0.78,\n scatter: 0.1,\n opacity: 17,\n spacing: 1.3,\n pressure: [1.2, 0.82],\n rotate: \"none\",\n tip: (_m) => {\n _m.rotate(45);\n _m.rect(-4, -4, 8, 8);\n _m.rect(2, 2, 3, 3);\n },\n});\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the p5.js graphics library.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The p5.Image to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const p5img = Renderer.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n T.imageToWhite(p5img);\n this.tips.set(src, p5img);\n resolve();\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.src = src;\n }),\n ),\n );\n },\n};\n\n/**\n * Loads all registered image tips. Must be awaited before setup/draw.\n * @returns {Promise}\n *\n * @example\n * // In your sketch:\n * await brush.preload();\n */\nexport async function preload() {\n await T.load();\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};","// =============================================================================\n// Module: Hatch\n// =============================================================================\n/**\n * The Hatch module contains functions and classes dedicated to applying\n * hatch patterns over shapes and polygons. It enables the simulation of\n * cross-hatching and shading effects by drawing parallel lines or strokes\n * across a geometry. The module supports adjustable spacing, angle, and\n * optional style parameters (such as randomness, continuity, and gradient),\n * giving an artistic representation similar to hand-drawn hatching techniques.\n *\n * The implementation allows for hatching to be applied either to a Polygon\n * directly or via a Plot, extending the drawing capabilities with layered,\n * stylized textures.\n */\n\nimport { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, cos, sin, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// ---------------------------------------------------------------------------\n// Hatch State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global hatch state settings.\n */\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow copy of the current hatch state.\n * @returns {object} The current hatch state.\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Updates the global hatch state.\n * @param {object} state - The new hatch state.\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Activates hatching for subsequent geometries.\n *\n * @param {number} dist - The distance between hatching lines.\n * @param {number} angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} options - Optional parameters to affect the hatching style:\n * - rand: Number value to introduce randomness.\n * - continuous: Boolean to connect adjacent lines.\n * - gradient: Number to gradually change spacing.\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Sets the hatch brush style for subsequent hatching.\n *\n * @param {string} brush - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} weight - The brush weight (size).\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Disables hatching.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a hatching pattern over the given polygon(s).\n *\n * @param {Polygon|Polygon[]} polygons - A polygon or an array of polygons.\n */\nexport function createHatch(polygons) {\n let dist = State.hatch.dist;\n let angle = ((State.hatch.angle % 180) + 180) % 180;\n let options = State.hatch.options;\n\n // Save current stroke state\n let save = BrushState();\n // If a hatch brush is set, override with those parameters.\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n\n // Compute overall bounding box for all polygons.\n if (!Array.isArray(polygons)) polygons = [polygons];\n const overallBB = computeOverallBoundingBox(polygons);\n\n // Build a bounding polygon based on the overall bounding box.\n let ventana = new Polygon([\n [overallBB.minX, overallBB.minY],\n [overallBB.maxX, overallBB.minY],\n [overallBB.maxX, overallBB.maxY],\n [overallBB.minX, overallBB.maxY],\n ]);\n\n // Determine starting y coordinate based on angle.\n let startY = angle <= 90 && angle >= 0 ? overallBB.minY : overallBB.maxY;\n let gradient = options.gradient\n ? map(options.gradient, 0, 1, 1, 1.1, true)\n : 1;\n let dots = [];\n let i = 0;\n let dist1 = dist;\n\n // Function to generate a line for index i.\n let linea = (i) => {\n return {\n point1: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90),\n y: startY + dist1 * i * sin(-angle + 90),\n },\n point2: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90) + cos(-angle),\n y: startY + dist1 * i * sin(-angle + 90) + sin(-angle),\n },\n };\n };\n\n // Generate lines and calculate intersections with polygons\n // Loop through the lines based on the distance and angle to calculate intersections with the polygons\n // The loop continues until a line does not intersect with the bounding window polygon\n // Each iteration accounts for the gradient effect by adjusting the distance between lines\n while (ventana.intersect(linea(i)).length > 0) {\n let tempArray = [];\n for (let p of polygons) {\n tempArray.push(p.intersect(linea(i)));\n }\n dots[i] = tempArray\n .flat()\n .sort((a, b) => (a.x === b.x ? a.y - b.y : a.x - b.x));\n dist1 *= gradient;\n i++;\n }\n\n // Filter out empty intersection sets.\n let gdots = dots.filter((dd) => typeof dd[0] !== \"undefined\");\n\n // Draw the hatching lines using the calculated intersections\n // If the 'rand' option is enabled, add randomness to the start and end points of the lines\n // If the 'continuous' option is set, connect the end of one line to the start of the next\n let r = options.rand || 0;\n for (let j = 0; j < gdots.length; j++) {\n let dd = gdots[j];\n let continuousLine = j > 0 && options.continuous;\n for (let i = 0; i < dd.length - 1; i += 2) {\n if (r !== 0) {\n dd[i].x += r * dist * rr(-1, 1);\n dd[i].y += r * dist * rr(-1, 1);\n dd[i + 1].x += r * dist * rr(-1, 1);\n dd[i + 1].y += r * dist * rr(-1, 1);\n }\n line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);\n if (continuousLine) {\n line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);\n }\n }\n }\n\n // Restore previous brush state.\n BrushSetState(save);\n}\n\n/**\n * Computes the bounding box for a single polygon.\n * @param {Polygon} polygon - The polygon to evaluate.\n * @returns {object} The bounding box as {minX, minY, maxX, maxY}.\n */\nfunction computeBoundingBoxForPolygon(polygon) {\n if (polygon._boundingBox) return polygon._boundingBox;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n for (let i = 0; i < polygon.a.length; i++) {\n const [x, y] = polygon.a[i];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n polygon._boundingBox = { minX, minY, maxX, maxY };\n return polygon._boundingBox;\n}\n\n/**\n * Computes an overall bounding box for an array of polygons.\n * @param {Array} polygons - Array of Polygon objects.\n * @returns {object} The overall bounding box {minX, minY, maxX, maxY}.\n */\nfunction computeOverallBoundingBox(polygons) {\n let overall = {\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity,\n };\n for (let poly of polygons) {\n const bb = computeBoundingBoxForPolygon(poly);\n overall.minX = Math.min(overall.minX, bb.minX);\n overall.minY = Math.min(overall.minY, bb.minY);\n overall.maxX = Math.max(overall.maxX, bb.maxX);\n overall.maxY = Math.max(overall.maxY, bb.maxY);\n }\n return overall;\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Adds a hatch effect to the polygon.\n *\n * If a distance is provided, activates hatching with the given parameters.\n * Then, if hatch is active, applies the hatching pattern.\n *\n * @param {number} [_dist] - The distance between hatch lines.\n * @param {number} _angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} _options - Optional hatch options.\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) {\n createHatch(this);\n }\n HatchSetState(state);\n};\n\n/**\n * Applies hatching to a plot.\n *\n * If hatching is active, generates a polygon from the plot and applies hatch.\n *\n * @param {number} x - The x-coordinate to draw at.\n * @param {number} y - The y-coordinate to draw at.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.25);\n this.pol.hatch();\n }\n};\n","import { Mix } from \"./color.js\";\n\nfunction transformPoint(matrix, x, y) {\n return {\n x: matrix.a * x + matrix.c * y + matrix.e,\n y: matrix.b * x + matrix.d * y + matrix.f,\n };\n}\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices) {\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n vertices.forEach((v, i) => {\n const point = transformPoint(matrix, v.x, v.y);\n minX = Math.min(minX, point.x);\n minY = Math.min(minY, point.y);\n maxX = Math.max(maxX, point.x);\n maxY = Math.max(maxY, point.y);\n\n if (i === 0) ctx.moveTo(v.x, v.y);\n else ctx.lineTo(v.x, v.y);\n });\n ctx.closePath();\n\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n const radius = d / 2;\n const center = transformPoint(matrix, x, y);\n const rx = radius * Math.hypot(matrix.a, matrix.c);\n const ry = radius * Math.hypot(matrix.b, matrix.d);\n const padding = strokePadding(ctx, matrix);\n\n Mix.markDirtyRect(Mix.mask, {\n minX: center.x - rx - padding,\n minY: center.y - ry - padding,\n maxX: center.x + rx + padding,\n maxY: center.y + ry + padding,\n });\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\nimport { Renderer, Mix, State, Cwidth, Cheight, Density } from \"../core/color.js\";\nimport { drawPolygon, circle } from \"../core/mask.js\";\nimport {\n constrain,\n weightedRand,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady, Matrix } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 1024;\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color =\n arguments.length < 3 ? Renderer.color(a) : Renderer.color(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length < 8) {\n // Simple average for small polygons\n return pts\n .reduce((c, p) => ({ x: c.x + p.x, y: c.y + p.y }), { x: 0, y: 0 })\n .map((v) => v / pts.length);\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n const v = [...polygon.vertices];\n\n // Map vertices\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n\n // Create bleed modifiers\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.2) * strength,\n );\n\n // Randomize starting point\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n\n // Calculate center and create FillPolygon\n const center = _center(shifted);\n new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions\n this.dir = Array(v.length);\n rayCalc.forEach((rc, i) => {\n let count = 0;\n for (const isect of _polygon.intersect(rc.ray)) {\n if (_isLeft(rc.v1, rc.v2, isect)) count++;\n }\n this.dir[i] = count % 2 === 0;\n });\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: [...this.v], m: [...this.m], dir: [...this.dir] };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Clone and splice\n const v = [...this.v],\n m = [...this.m],\n dir = [...this.dir];\n v.splice(s, n);\n m.splice(s, n);\n dir.splice(s, n);\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n\n // Build sorted random indices\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [], sm = [], sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n\n // Ray-cast: count intersections from p to far right\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y, by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n // If outside (even crossings), pull toward center\n if (crossings % 2 === 0) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]); // flip direction → grow inward\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n // Get trimmed vertices\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n \n // Pre-allocate output arrays\n const outLen = len * 2;\n const newVerts = new Array(outLen);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\n \n // Determine bleed direction\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n \n // Ensure gaussian pool is filled\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0], gPoolLen = gPool.length;\n const g2Pool = _gaussians[1], g2PoolLen = g2Pool.length;\n \n let idx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n \n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n \n if (f < 997) mod = mi;\n \n // Inline rotate: rotDeg = ±bleedDirDeg + small jitter\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n \n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n \n // Outward distance: inline rArray + rr\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n \n // First vertex: original\n newVerts[idx] = cv;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n \n // Second vertex: midpoint + outward push\n newVerts[idx] = {\n x: cv.x + sideX * 0.5 + dirX * d,\n y: cv.y + sideY * 0.5 + dirY * d,\n };\n newMods[idx] = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n newDirs[idx] = di;\n idx++;\n }\n \n // Cap vertex count to prevent exponential blowup.\n let fv = newVerts, fm = newMods, fd = newDirs;\n let growe = GROW_MAX_VERTS / (State.fill.texture_strength);\n if (growe && idx > growe) {\n const step = Math.ceil(idx / growe);\n fv = []; fm = []; fd = [];\n for (let j = 0; j < idx; j += step) {\n fv.push(newVerts[j]);\n fm.push(newMods[j]);\n fd.push(newDirs[j]);\n }\n } else {\n // Trim pre-allocated arrays to actual size\n fv.length = idx;\n fm.length = idx;\n fd.length = idx;\n }\n \n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n // Precalculate stuff\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n // Perform initial setup only once\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(), Density * Matrix.b(),\n Density * Matrix.c(), Density * Matrix.d(),\n Density * (Matrix.x() + Cwidth / 2),\n Density * (Matrix.y() + Cheight / 2),\n );\n\n Mix.ctx.strokeStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${\n 0.005 * State.fill.border_strength\n })`;\n Mix.ctx.lineCap = \"round\";\n\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n\n // Create initial polygon\n let pol = this.grow();\n // Create sparse inner polygon from original (pre-grow) vertices\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n // Grow polygon every 4 layers\n if (i % 4 === 0) pol = pol.grow();\n\n // Create variant polygons\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n // Draw layers\n for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);\n sparse.grow(999).flipDirs().grow(997).layer(i, size, int * 1.5 * texture, color);\n if (i % 2 === 0)\n pol\n .grow(darker)\n .grow(999)\n .layer(i, size, int * 2, color);\n\n // Apply texture and blend periodically\n if (i % 5 === 0 || i === numLayers - 1) {\n if (texture !== 0) pol.erase(texture * 3, intensity);\n Mix.blend(color, true, false, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, color) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\n drawPolygon(this.v);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n // Optimize by pre-calculating values\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.4 - State.fill.bleed_strength);\n const minSizeFactor = 0.05 * minSize;\n const maxSizeFactor = 0.4 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n // Set up erase mode\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n // Calculate transparency\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n // Draw erase circles\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const size = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, size);\n if (i % 5 !== 0) Mix.ctx.fill();\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n map(State.fill.bleed_strength, 0, 0.6, 0.3, 0.45, true),\n );\n this.pol.fill();\n }\n};\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n}\n","/**\n * @fileoverview p5.brush - A comprehensive toolset for brush management in p5.js.\n * @version 2.0.0-alpha\n * @license MIT\n * @author Alejandro Campos Uribe\n *\n * @description\n * p5.brush is a p5.js library dedicated to the creation and management of custom brushes.\n * It extends the drawing capabilities of p5.js by allowing users to simulate a wide range\n * of brush strokes, vector fields, hatching patterns, and fill textures. These features\n * are essential for emulating the nuanced effects found in traditional sketching and painting.\n * Whether for digital art applications or procedural generation of graphics, p5.brush provides\n * a robust framework for artists and developers to create rich, dynamic, and textured visuals.\n *\n * @example\n * // Basic usage:\n * brush.pick('marker'); // Select brush type\n * brush.stroke(255, 0, 0); // Set brush color\n * brush.strokeWeight(10); // Set brush size\n * brush.line(25, 25, 75, 75); // Draw a line\n *\n * // Add a new brush type:\n * brush.add('customBrush', { /* parameters for the brush *\\/ });\n * brush.pick('customBrush');\n *\n * // Use the custom brush for a vector-field line:\n * brush.field('field_name') // Pick a flowfield\n * brush.flowLine(50, 50, 100, PI / 4); // Draw a line within the vector-field; angle follows p5 angleMode()\n *\n * // Fill textures:\n * brush.noStroke();\n * brush.fill('#FF0000', 90); // Set fill color to red and opacity to 90\n * brush.bleed(0.3); // Set bleed effect for a watercolor-like appearance\n * brush.rect(100, 100, 50, 50); // Fill a rectangle with the bleed effect\n *\n * @license\n * MIT License\n *\n * Copyright (c) 2023-2024 Alejandro Campos Uribe\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n// Randomness and other auxiliary functions\nexport { weightedRand as wRand } from \"./core/utils.js\";\n\n// Color Blending\nexport { load, instance } from \"./core/color.js\";\n\n// Matrix transformations, FlowField and Position Class\nexport {\n field,\n noField,\n addField,\n refreshField,\n listFields,\n Position,\n wiggle,\n} from \"./core/flowfield.js\";\n\n// Polygon and Plot classes\nexport { Polygon } from \"./core/polygon.js\";\nexport { Plot } from \"./core/plot.js\";\n\n// Primitives\nexport {\n rect,\n circle,\n arc,\n beginShape,\n vertex,\n endShape,\n beginStroke,\n move,\n endStroke,\n spline,\n polygon,\n} from \"./core/primitives.js\";\n\n// Brushes\nexport {\n add,\n box,\n scaleBrushes,\n pick,\n stroke,\n strokeWeight,\n set,\n noStroke,\n clip,\n noClip,\n line,\n flowLine,\n} from \"./stroke/stroke.js\";\n\n// Section: Hatching\nexport {\n hatch,\n hatchStyle,\n noHatch,\n createHatch as hatchArray,\n} from \"./hatch/hatch.js\";\n\n// Fill\nexport { fill, noFill, fillTexture, fillBleed } from \"./fill/fill.js\";\n\n// p5 addon registration\nimport { Mix } from \"./core/color.js\";\nimport { push as brushPush, pop as brushPop } from \"./core/save.js\";\nimport { seed as brushSeed, noiseSeed as brushNoiseSeed } from \"./core/utils.js\";\n\nfunction registerAddon(_p5, fn, lifecycles) {\n lifecycles.postsetup = () => Mix.blend(false, true);\n lifecycles.postdraw = () => Mix.blend(false, true);\n\n const _push = fn.push;\n const _pop = fn.pop;\n const _randomSeed = fn.randomSeed;\n const _noiseSeed = fn.noiseSeed;\n\n fn.push = function () {\n _push.call(this);\n brushPush();\n };\n\n fn.pop = function () {\n _pop.call(this);\n brushPop();\n };\n\n fn.randomSeed = function (s) {\n _randomSeed.call(this, s);\n brushSeed(s);\n };\n\n fn.noiseSeed = function (s) {\n _noiseSeed.call(this, s);\n brushNoiseSeed(s);\n };\n}\n\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerAddon);\n"],"names":["Cwidth","Cheight","Instance","Renderer","Density","isFramebufferTarget","target","begin","end","renderer","_pInst","getSketchRenderer","_isInstanced","window","self","p5","instance","removeTargetBuffer","buffer","remove","getActiveFramebuffer","_renderer","activeFramebuffer","getTargetPixelSize","width","Math","max","round","height","normalizeDirtyRect","rect","minX","floor","min","maxX","minY","maxY","ceil","getFullDirtyRect","withScissor","gl","draw","box","normalized","x","y","toScissorBox","wasEnabled","isEnabled","SCISSOR_TEST","prevBox","getParameter","SCISSOR_BOX","enable","scissor","disable","load","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","inst","isMixReady","isBlending","cachedColor","Object","markDirtyRect","a","b","dirtyRect","isDrawn","markFull","clearMask","clear","getCompositeRect","isBrushMask","padding","expandDirtyRect","captureBlendSource","framebuffer","blendSourceFramebuffer","pixelDensity","createFramebuffer","density","antialias","depth","stencil","source","drawingContext","push","imageMode","CENTER","image","pop","graphicsFactory","createGraphics","p2dMode","P2D","webglMode","WEBGL","mask","glMask","this","ctx","shaderProgram","createShader","angleMode","DEGREES","lineWidth","uModelMatrix","blend","_color","_isLast","activeIsBrush","isBrush","no_mask","nextColor","_array","colorChanged","justChanged","applyShader","shader","targetIsFramebuffer","hadDepthTest","DEPTH_TEST","translate","setUniform","fill","noStroke","resetShader","SQRT3","sqrt","F2","G2","fastFloor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","c","s0","s1","s2","copy","f","rng","_seedCallbacks","_onSeed","cb","noise","rr","e","rArray","array","randInt","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","d","withinBounds","constrain","low","high","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","NaN","sLookup","idx","sin","toDegrees","rad","isRad","RADIANS","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","Matrix","mat4","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","update","plotted","colIdx","getColIndex","rowIdx","getRowIndex","reset","isIn","isActive","isInCanvas","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","y_offset","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","has","generateField","entry","normalizeFieldAngles","gen","refreshField","currentField","keys","join","noField","name","funct","set","listFields","fn","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","intersection","show","stroke","hatch","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","polygon","mode","beginShape","vertex","endShape","circle","radius","arcLength","angleOffset","randomFactor","randomAngle","offsetX","offsetY","arc","startDeg","sweepDeg","segmentCount","segmentSweep","startX","startY","_current","_curvature","_strokeArray","_strokeOrigin","SubPath","isClosed","curvature","vert","_createSpline","close","beginStroke","move","endStroke","spline","_array_points","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","halfDist","asin","origin","projMatrix","vao","buf","program","loadedWidth","loadedHeight","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","diameter","alpha","newData","px","py","screenX","screenY","glDraw","color","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","uniform4f","u_color","uniformMatrix4fv","u_matrix","drawArrays","POINTS","_curShader","weight","clipWindow","opacity","_position","Mask","_strokeTransform","tx","ty","BrushState","BrushSetState","state","add","params","includes","undefined","vibration","scatter","definition","sharpness","quality","grain","isArray","min_max","curve","m","range","ns","nm","ne","normalizePressure","src","T","tip","tips","param","colors","buffers","scaleBrushes","values","spacing","pick","brushName","g","arguments","strokeWeight","snapshotTransform","transformPoint","transform","normalizeRegion","region","screenPointFromPosition","point","clip","inverse","det","invertTransform","bounds","noClip","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","noiseoffset","dirRad","nextGl","needsContextRefresh","createProgram","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","isReady","switchingToBrush","isInsideClippingArea","calculateAlpha","markerTip","saveState","stepSize","totalSteps","customPressure","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","local","o","vibrate","rx","ry","setAlpha","tint","adjustSizeAndRotation","halfWeight","radians","cosAngle","sinAngle","userCenterX","userCenterY","corners","Infinity","markImageTipDirty","flowLine","_vals","_standard_brushes","obj","_m","prototype","_brush","_weight","imageToWhite","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","p5img","createImage","naturalWidth","naturalHeight","drawImage","onerror","HatchState","rand","continuous","gradient","hatchStyle","brush","hBrush","noHatch","createHatch","polygons","save","overallBB","overall","poly","bb","computeBoundingBoxForPolygon","computeOverallBoundingBox","ventana","dots","dist1","linea","tempArray","flat","sort","gdots","dd","continuousLine","_boundingBox","matrix","strokePadding","getTransform","center","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","noFill","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","sx","sy","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","splice","ratio","L","keep","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","newVerts","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","fv","fm","fd","growe","intensity","tex","texture","int","switchingToFill","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","size","darker","sparse","pols","layer","numLayers","erase","restore","fillStyle","beginPath","lineTo","closePath","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","_opacity","_bleed","fluid","strength","modifiers","_","shift","shifted","slice","pts","area","cross","_center","createFill","FillSetState","_stateStack","registerAddon","_p5","lifecycles","postsetup","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","callback","brushSeed","brushNoiseSeed"],"mappings":"AAYO,IAAIA,EAAQC,EAASC,EAAUC,EAAUC,EAEhD,MAAMC,EAAuBC,KACzBA,GACsB,mBAAjBA,EAAOC,OACQ,mBAAfD,EAAOE,OACZF,EAAOG,YACPH,EAAOG,SAASC,OAEdC,EAAoB,IACxBC,EAAeV,EAAWW,OAAOC,KAAKC,GAAGC,SA4CrCC,EAAsBC,IACtBA,GAAmC,mBAAlBA,EAAOC,QAC1BD,EAAOC,UAOLC,EAAuB,IAC3BjB,GACAA,EAASkB,WACuC,mBAAzClB,EAASkB,UAAUC,kBACtBnB,EAASkB,UAAUC,oBACnB,KAoBAC,EAAqB,KAAA,CACzBC,MAAOC,KAAKC,IAAI,EAAGD,KAAKE,MAAM3B,EAASI,IACvCwB,OAAQH,KAAKC,IAAI,EAAGD,KAAKE,MAAM1B,EAAUG,MAarCyB,EAAsBC,IAC1B,IAAKA,EAAM,OAAO,KAElB,MAAMN,MAAEA,EAAKI,OAAEA,GAAWL,IACpBQ,EAAON,KAAKC,IAAI,EAAGD,KAAKO,MAAMP,KAAKQ,IAAIH,EAAKC,KAAMD,EAAKI,QACvDC,EAAOV,KAAKC,IAAI,EAAGD,KAAKO,MAAMP,KAAKQ,IAAIH,EAAKK,KAAML,EAAKM,QACvDF,EAAOT,KAAKQ,IAAIT,EAAOC,KAAKY,KAAKZ,KAAKC,IAAII,EAAKC,KAAMD,EAAKI,QAC1DE,EAAOX,KAAKQ,IAAIL,EAAQH,KAAKY,KAAKZ,KAAKC,IAAII,EAAKK,KAAML,EAAKM,QAEjE,OAAIF,GAAQH,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AAM,IAAKnE,EAAMmE,MACjBqP,OAAQ,IAAKxT,EAAMwT,QACnBC,MAAO,IAAKzT,EAAMyT,OAClB5F,MAAO,IAAK7N,EAAM6N,QCmHpB,EAEA0E,EAAGtQ,IAAM,WACPuuB,EAAKK,KAAKnuB,MD/GP,WACL,MAAMouB,EAAQb,GAAYhuB,MACrB6uB,IACL9wB,EAAMwT,OAAS,IAAKsd,EAAMtd,QAC1BxT,EAAM6N,MAAQ,IAAKijB,EAAMjjB,OACzB7N,EAAMyT,MAAQ,IAAKqd,EAAMrd,OACzBzT,EAAMmE,KAAO,IAAK2sB,EAAM3sB,MAC1B,CCyGI4sB,EACF,EAEAxe,EAAGme,WAAa,SAAU5qB,GACxB2qB,EAAYI,KAAKnuB,KAAMoD,GZpHP,CAACA,IACnB4C,EAAMzB,EAAUnB,GAChB,IAAK,MAAMkrB,KAAYroB,EACrBqoB,KYkHAC,CAAUnrB,EACZ,EAEAyM,EAAGqe,UAAY,SAAU9qB,GACvB6qB,EAAWE,KAAKnuB,KAAMoD,GZvGD,CAACA,IACxBgD,EAAQjE,EAAcoC,EAAUnB,KYuG9BorB,CAAeprB,EACjB,CACF","x_google_ignoreList":[1,2]}
\ No newline at end of file
+{"version":3,"file":"p5.brush.esm.js","sources":["../src/core/color.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/flowfield.js","../src/core/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/core/gl/utils.js","../src/hatch/hatch.js","../src/core/mask.js","../src/fill/fill.js","../src/core/save.js","../src/index.js"],"sourcesContent":["import vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Section: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties\n\nconst isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\nconst getSketchRenderer = () =>\n _isInstanced ? Instance : window.self.p5.instance;\n\nconst isSupportedFramebufferTarget = (target) =>\n isFramebufferTarget(target) && target.renderer._pInst === getSketchRenderer();\n\nconst resolveTarget = (buffer = false) => {\n if (_isInstanced && !buffer) {\n return {\n renderer: Instance,\n width: Instance.width,\n height: Instance.height,\n };\n }\n\n if (!buffer) {\n const renderer = getSketchRenderer();\n return {\n renderer,\n width: renderer.width,\n height: renderer.height,\n };\n }\n\n if (isFramebufferTarget(buffer)) {\n if (!isSupportedFramebufferTarget(buffer)) {\n throw new Error(\n \"p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.\",\n );\n }\n\n return {\n renderer: getSketchRenderer(),\n width: buffer.width,\n height: buffer.height,\n };\n }\n\n return {\n renderer: buffer,\n width: buffer.width,\n height: buffer.height,\n };\n};\n\nconst removeTargetBuffer = (buffer) => {\n if (buffer && typeof buffer.remove === \"function\") {\n buffer.remove();\n }\n};\n\nconst getGraphicsFactory = () =>\n typeof Renderer.createGraphics === \"function\" ? Renderer : Renderer._pInst;\n\nconst getActiveFramebuffer = () =>\n Renderer &&\n Renderer._renderer &&\n typeof Renderer._renderer.activeFramebuffer === \"function\"\n ? Renderer._renderer.activeFramebuffer()\n : null;\n\nconst needsBlendSourceFramebuffer = (framebuffer) =>\n !framebuffer ||\n framebuffer.width !== Cwidth ||\n framebuffer.height !== Cheight ||\n (typeof framebuffer.pixelDensity === \"function\" &&\n framebuffer.pixelDensity() !== Density);\n\nconst needsMixBuffers = () =>\n !Renderer.mask ||\n !Renderer.glMask ||\n Renderer.mask.width !== Cwidth ||\n Renderer.mask.height !== Cheight ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight;\n\nconst DIRTY_BRUSH_PADDING = 2;\nconst DIRTY_FILL_PADDING = 4;\n\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n\n const { width, height } = getTargetPixelSize();\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\nconst unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return { minX: 0, minY: 0, maxX: width, maxY: height };\n};\n\nconst toScissorBox = (rect) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: height - normalized.maxY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\nconst withScissor = (gl, rect, draw) => {\n const box = toScissorBox(rect);\n if (!box) return false;\n\n const wasEnabled = gl.isEnabled(gl.SCISSOR_TEST);\n const prevBox = gl.getParameter(gl.SCISSOR_BOX);\n\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n if (wasEnabled) {\n gl.scissor(prevBox[0], prevBox[1], prevBox[2], prevBox[3]);\n } else {\n gl.disable(gl.SCISSOR_TEST);\n }\n }\n\n return true;\n};\n\n/**\n * Loads and initializes a canvas for the drawing system.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.\n * Pass a framebuffer only while drawing inside its begin()/end() or draw() scope.\n * Framebuffers created from p5.Graphics are not supported.\n */\nexport const load = (buffer = false) => {\n const target = resolveTarget(buffer);\n Renderer = target.renderer;\n\n // Check if Rendrer is webgl and throw error if it's not\n\n if (Renderer.webglVersion !== \"webgl2\") {\n throw new Error(\"p5.brush requires a WEBGL canvas\");\n }\n\n Cwidth = target.width;\n Cheight = target.height;\n\n _isReady = true;\n if (Renderer.loaded) Mix.load();\n};\n\nlet _isReady = false;\nlet _isInstanced = false;\n\n/**\n * Ensures the drawing system is ready before any operation.\n */\nexport const isCanvasReady = () => {\n if (!_isReady) load();\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n\nexport const instance = (inst) => {\n _isInstanced = true;\n Instance = inst;\n};\n\n\n// =============================================================================\n// Section: Color Blending\n// =============================================================================\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer?.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\nconst disable = false;\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: new Object(),\n\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n markFull(target) {\n if (!target) return;\n\n target.dirtyRect = getFullDirtyRect();\n target.isDrawn = true;\n },\n\n clearMask(target) {\n if (!target) return;\n\n target.clear();\n target.isDrawn = false;\n target.dirtyRect = null;\n },\n\n getCompositeRect(target, isBrushMask) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n\n return normalizeDirtyRect(\n expandDirtyRect(\n target.dirtyRect,\n isBrushMask ? DIRTY_BRUSH_PADDING : DIRTY_FILL_PADDING,\n ),\n );\n },\n\n captureBlendSource(dirtyRect) {\n const activeFramebuffer = getActiveFramebuffer();\n\n if (!activeFramebuffer) return Renderer._renderer;\n\n if (needsBlendSourceFramebuffer(Renderer.blendSourceFramebuffer)) {\n removeTargetBuffer(Renderer.blendSourceFramebuffer);\n Renderer.blendSourceFramebuffer = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n const source = Renderer.blendSourceFramebuffer;\n\n source.draw(() => {\n withScissor(Renderer.drawingContext, dirtyRect, () => {\n Renderer.clear();\n Renderer.push();\n if (typeof Renderer.imageMode === \"function\") {\n Renderer.imageMode(\n Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER,\n );\n }\n Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n });\n });\n\n return source;\n },\n\n /**\n * Loads necessary resources and prepares the mask buffer and shader for colour blending.\n */\n load() {\n Density = Renderer.pixelDensity();\n const graphicsFactory = getGraphicsFactory();\n const p2dMode = graphicsFactory.P2D ?? Renderer.P2D;\n const webglMode = graphicsFactory.WEBGL ?? Renderer.WEBGL;\n\n if (!Renderer.loaded || needsMixBuffers()) {\n removeTargetBuffer(Renderer.mask);\n removeTargetBuffer(Renderer.glMask);\n\n Renderer.mask = graphicsFactory.createGraphics(Cwidth, Cheight, p2dMode);\n Renderer.glMask = graphicsFactory.createGraphics(\n Cwidth,\n Cheight,\n webglMode,\n );\n Renderer.loaded = true;\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n\n this.mask = Renderer.mask;\n this.mask.pixelDensity(Density);\n this.mask.clear();\n this.mask.angleMode(Renderer.DEGREES);\n this.mask.dirtyRect = null;\n this.mask.isDrawn = false;\n\n this.ctx = this.mask.drawingContext;\n\n this.glMask = Renderer.glMask;\n this.glMask.pixelDensity(Density);\n this.glMask.clear();\n this.glMask.angleMode(this.glMask.DEGREES);\n this.glMask.drawingContext.lineWidth = 0;\n this.glMask.dirtyRect = null;\n this.glMask.isDrawn = false;\n } else {\n this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\n this.mask.dirtyRect ??= null;\n this.mask.isDrawn ??= false;\n this.glMask.dirtyRect ??= null;\n this.glMask.isDrawn ??= false;\n }\n\n // Link Matrix of GL mask to main Renderer\n this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;\n },\n\n /**\n * Applies blending effects using the current color and mask.\n * @param {Color} _color - Color to blend.\n * @param {boolean} _isLast - If this is the final blend operation.\n * @param {boolean} _isImg - If blending an image.\n * @param {boolean} _isFillLayer - If this is a special case.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n\n const activeIsBrush = this.isBrush === true;\n const mask = activeIsBrush ? this.glMask : this.mask;\n const no_mask = activeIsBrush ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor[0] !== nextColor[0] ||\n this.cachedColor[1] !== nextColor[1] ||\n this.cachedColor[2] !== nextColor[2] ||\n this.cachedColor[3] !== nextColor[3]);\n\n // Perf gains are minimal but let's keep it for now\n if (disable) {\n if (_isLast && mask.isDrawn) {\n Renderer.push();\n Renderer.translate(0, 0);\n Renderer.image(mask, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n mask.isDrawn = false;\n }\n return;\n }\n\n // Initialize blending if not already active\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Force p5 to bind its internal render target for glMask,\n // so the first glDraw() writes to the correct framebuffer.\n this.glMask.clear();\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(no_mask, !activeIsBrush);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, activeIsBrush);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) this.isBlending = false;\n }\n },\n\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n let shader = Renderer.shaderProgram;\n const gl = Renderer.drawingContext;\n const targetIsFramebuffer = !!getActiveFramebuffer();\n const source = this.captureBlendSource(dirtyRect);\n\n // Disable depth test for this compositing draw so the fullscreen rect\n // does not write Z=0 into the depth buffer — which would cause any\n // subsequent p5 geometry drawn at the same depth to fail depth testing\n // and become invisible.\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n gl.disable(gl.DEPTH_TEST);\n\n Renderer.push();\n Renderer.translate(0, 0);\n\n // Use the blend shader for rendering\n Renderer.shader(shader);\n\n // Set shader uniforms\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n shader.setUniform(\"u_flipOutputY\", targetIsFramebuffer);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", this.cachedColor);\n\n // Draw a rectangle covering the whole canvas to apply the shader\n withScissor(gl, dirtyRect, () => {\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n });\n\n // Finish and clear mask\n Renderer.pop();\n Renderer.resetShader();\n\n // Restore depth test state\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n this.clearMask(mask);\n },\n};\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { Renderer } from \"./color.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n const usesRadians =\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS);\n // Only if Renderer.angleMode() is set to radians\n if (usesRadians) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS)\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","import { isMixReady, Cwidth, Cheight, State, Renderer } from \"./color.js\";\nimport { randInt, noise, rr, sin, cos, map, toDegreesSigned } from \"./utils.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n/**\n * The `Matrix` object exposes the current 2D affine transform from p5's model matrix.\n * mat4 layout (column-major 4x4):\n * [0]=a [1]=b [4]=c [5]=d [12]=tx [13]=ty\n * where the 2D transform of a point (x,y) is: (a*x + c*y + tx, b*x + d*y + ty)\n */\nexport const Matrix = {\n x: () => Renderer._renderer.uModelMatrix.mat4[12],\n y: () => Renderer._renderer.uModelMatrix.mat4[13],\n a: () => Renderer._renderer.uModelMatrix.mat4[0],\n b: () => Renderer._renderer.uModelMatrix.mat4[1],\n c: () => Renderer._renderer.uModelMatrix.mat4[4],\n d: () => Renderer._renderer.uModelMatrix.mat4[5],\n};\n\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n this.colIdx = Position.getColIndex(x);\n this.rowIdx = Position.getRowIndex(y);\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + Matrix.x();\n const y = this.y + Matrix.y();\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle() {\n return this.isIn() && State.field.isActive\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current p5 angle mode.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1) {\n this.movePos(_plot, _length, _step_length, _scale);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n for (let i = 0; i < _length / _step; i++) {\n const angle =\n this.angle() - (_scale ? _dirPlot.angle(this.plotted) : _dirPlot);\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + Matrix.y() - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + Matrix.x() - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr(0.2, 0.8),\n ba = randInt(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt(15, 25));\n return 0.2 * angle * cos(t) + noise(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt(-10, 10);\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt(-30, -15) + Math.abs(44 * sin(t));\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt(10, 15) + 5 * sin(t),\n cr = randInt(3, 6) + 3 * cos(t),\n ba = randInt(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr(0.4, 0.8),\n ba = randInt(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt(5, 10);\n const dir = randInt(0, 2) * 2 - 1;\n const offset = randInt(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr(0.1, 0.9) * num_columns,\n y: rr(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt(3, 8),\n amp = randInt(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.stroke) this.draw();\n if (State.hatch) this.hatch();\n if (State.fill) this.fill();\n }\n}\n","import { State, Cwidth, Cheight } from \"./color.js\";\nimport { toDegrees, map, rr } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = 0.5;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n const maxSize = Math.max(this.segments[idx] * _side * rr(0.7, 1.3), 10);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.stroke) this.draw(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n }\n}\n","import {\n rr,\n randInt,\n sin,\n cos,\n toDegrees,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current p5 angle mode.\n * @param {number} end - End angle in the current p5 angle mode.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module provides functions for rendering shapes (circles and squares)\n * using WebGL2. It initializes the WebGL context and shader programs, prepares buffers,\n * and implements drawing routines based on queued drawing primitives. The module uses\n * an orthographic projection to map canvas coordinates to clip space and supports adjustable\n * blending for translucent effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\n State,\n} from \"../core/color.js\";\nimport { Matrix } from \"../core/flowfield.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n projMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0;\n\n/**\n * Snapshots the current p5 model matrix. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n _ma = Matrix.a();\n _mb = Matrix.b();\n _mc = Matrix.c();\n _md = Matrix.d();\n _mx = Matrix.x();\n _my = Matrix.y();\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n\n const nextGl = Mix.glMask.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n projMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n -2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * p5's current model matrix so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - Cwidth / 2;\n const py = y - Cheight / 2;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + Cwidth / 2;\n const screenY = _mb * px + _md * py + _my + Cheight / 2;\n const radius =\n (Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n Mix.markDirtyRect(Mix.glMask, {\n minX: screenX * Density - radius - 1,\n minY: screenY * Density - radius - 1,\n maxX: screenX * Density + radius + 1,\n maxY: screenY * Density + radius + 1,\n });\n\n circleCount++;\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader (p5 drawing may have switched programs)\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, projMatrix);\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing p5's _curShader tracking.\n // Reset it to null so p5 is forced to re-activate its own shader next time\n // it draws — otherwise p5 skips gl.useProgram() and sets uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n Mix.glMask._renderer._curShader = null;\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n State,\n Renderer,\n isCanvasReady,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed,\n} from \"../core/utils.js\";\nimport { Position, Matrix, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { isReady, glDraw, circle, snapshotMatrix } from \"./gl_draw.js\";\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n clipWindow: null,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nlet Mask = null;\nlet _strokeTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n tx: 0,\n ty: 0,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { type, min_max, curve } — old internal format, passed through unchanged\n */\nfunction normalizePressure(p) {\n if (!p || (typeof p === \"object\" && !Array.isArray(p))) return p;\n if (typeof p === \"function\")\n return { type: \"custom\", min_max: [0, 1], curve: p };\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n params.tip = () => {\n Mask.image(\n T.tips.get(current.p.image.src),\n -current.p.weight / 2,\n -current.p.weight / 2,\n current.p.weight,\n current.p.weight,\n );\n };\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = Renderer.color(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\nfunction snapshotTransform() {\n return {\n a: Matrix.a(),\n b: Matrix.b(),\n c: Matrix.c(),\n d: Matrix.d(),\n tx: Matrix.x(),\n ty: Matrix.y(),\n };\n}\n\nfunction invertTransform(transform) {\n const det = transform.a * transform.d - transform.b * transform.c;\n if (Math.abs(det) < 1e-12) return null;\n\n return {\n a: transform.d / det,\n b: -transform.b / det,\n c: -transform.c / det,\n d: transform.a / det,\n tx: (transform.c * transform.ty - transform.d * transform.tx) / det,\n ty: (transform.b * transform.tx - transform.a * transform.ty) / det,\n };\n}\n\nfunction transformPoint(transform, x, y) {\n return {\n x: transform.a * x + transform.c * y + transform.tx,\n y: transform.b * x + transform.d * y + transform.ty,\n };\n}\n\nfunction normalizeRegion(region) {\n const [x1, y1, x2, y2] = region;\n return {\n minX: Math.min(x1, x2),\n minY: Math.min(y1, y2),\n maxX: Math.max(x1, x2),\n maxY: Math.max(y1, y2),\n };\n}\n\nfunction currentPointInUserSpace() {\n return transformPoint(\n _strokeTransform,\n _position.x - Cwidth / 2,\n _position.y - Cheight / 2,\n );\n}\n\nfunction screenPointFromPosition(x, y) {\n const point = transformPoint(_strokeTransform, x - Cwidth / 2, y - Cheight / 2);\n return {\n x: point.x + Cwidth / 2,\n y: point.y + Cheight / 2,\n };\n}\n\nfunction markImageTipDirty(rx, ry, scale, angle) {\n const halfWeight = current.p.weight / 2;\n const radians = (angle * Math.PI) / 180;\n const cosAngle = Math.cos(radians);\n const sinAngle = Math.sin(radians);\n const userCenterX = _position.x + rx;\n const userCenterY = _position.y + ry;\n const corners = [\n [-halfWeight, -halfWeight],\n [halfWeight, -halfWeight],\n [halfWeight, halfWeight],\n [-halfWeight, halfWeight],\n ];\n\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n for (const [x, y] of corners) {\n const lx = scale * (cosAngle * x - sinAngle * y);\n const ly = scale * (sinAngle * x + cosAngle * y);\n const point = screenPointFromPosition(userCenterX + lx, userCenterY + ly);\n\n minX = Math.min(minX, point.x * Renderer.pixelDensity());\n minY = Math.min(minY, point.y * Renderer.pixelDensity());\n maxX = Math.max(maxX, point.x * Renderer.pixelDensity());\n maxY = Math.max(maxY, point.y * Renderer.pixelDensity());\n }\n\n Mix.markDirtyRect(Mix.glMask, {\n minX: minX - 2,\n minY: minY - 2,\n maxX: maxX + 2,\n maxY: maxY + 2,\n });\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current p5 transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n const inverse = invertTransform(snapshotTransform());\n if (!inverse) {\n throw new Error(\n \"brush.clip() cannot be used with a non-invertible transform.\",\n );\n }\n State.stroke.clipWindow = {\n bounds: normalizeRegion(region),\n inverse,\n };\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n State.stroke.clipWindow = null;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {boolean} flow - Flag for vector-field following.\n * @param {Object|boolean} plot - Plot object or false.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _strokeTransform = snapshotTransform();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n isPlot\n ? _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n )\n : _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n Mask = Mix.glMask;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.a = pressure.type !== \"custom\" ? rr(-1, 1) : 0;\n current.b = pressure.type !== \"custom\" ? rr(1, 1.5) : 0;\n current.cp = pressure.type !== \"custom\" ? rr(3, 3.5) : rr(-0.2, 0.2);\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.03;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n const dirRad = (_dir * Math.PI) / 180;\n current.cos = Math.cos(dirRad);\n current.sin = Math.sin(dirRad);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n if (isInsideClippingArea()) Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n glDraw();\n markerTip();\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n * @param {number} [customPressure=false] - Optional custom pressure.\n */\nfunction tip(customPressure = false) {\n if (!isInsideClippingArea()) return;\n let pressure = customPressure || calculatePressure();\n\n let lineNoise = map(\n noise(current.seed + _position.plotted * 0.002, 0),\n 0,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n\n switch (current.p.type) {\n case \"spray\":\n drawSpray(pressure * lineNoise);\n break;\n case \"marker\":\n drawMarker(pressure * lineNoise);\n break;\n case \"custom\":\n case \"image\":\n drawTip(pressure * lineNoise, current.alpha);\n break;\n default:\n drawDefault(pressure * lineNoise);\n break;\n }\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n return _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n return current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(_position.plotted / _length) + current.cp,\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Checks if the current drawing position is within the clipping region.\n * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n const point = currentPointInUserSpace();\n\n if (State.stroke.clipWindow) {\n const local = transformPoint(\n State.stroke.clipWindow.inverse,\n point.x,\n point.y,\n );\n const { bounds } = State.stroke.clipWindow;\n return (\n local.x >= bounds.minX &&\n local.x <= bounds.maxX &&\n local.y >= bounds.minY &&\n local.y <= bounds.maxY\n );\n }\n\n let o = Cwidth * 0.05;\n return (\n point.x >= -Cwidth / 2 - o &&\n point.x <= Cwidth / 2 + o &&\n point.y >= -Cheight / 2 - o &&\n point.y <= Cheight / 2 + o\n );\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return 1;\n return param.spacing;\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha,\n );\n}\n\n/**\n * Draws a custom or image-based brush tip.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Alpha (opacity) for drawing.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawTip(pressure, alpha, vibrate = true) {\n Mix.glMask.isDrawn = true;\n Mask.push();\n Mask.noStroke();\n let color = State.stroke.color;\n color.setAlpha(alpha);\n Mask.fill(State.stroke.color);\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n Mask.translate(_position.x + rx - Cwidth, _position.y + ry - Cheight);\n const scale = State.stroke.weight * pressure;\n const angle = adjustSizeAndRotation(scale, alpha);\n current.p.tip(Mask);\n Mask.pop();\n\n if (current.p.type === \"image\") {\n markImageTipDirty(rx, ry, scale, angle);\n } else {\n Mix.markFull(Mix.glMask);\n }\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n if (rr(0, current.p.grain * pressure) > 0.4) {\n let dx, dy;\n if (_plot) {\n dx = 0.7 * vibration * rr(-1, 1);\n dy = vibration * rr(-1, 1);\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * -current.sin + along * current.cos;\n dy = perp * current.cos + along * current.sin;\n }\n circle(\n _position.x + dx,\n _position.y + dy,\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight,\n Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1),\n );\n }\n}\n\n/**\n * Adjusts the size and rotation of the brush tip before rendering.\n * @param {number} pressure - Pressure-based scaling factor.\n * @param {number} alpha - Opacity value.\n */\nfunction adjustSizeAndRotation(pressure, alpha) {\n Mask.scale(pressure);\n if (current.p.type === \"image\") {\n Mask.tint(255, 0, 0, alpha / 2);\n }\n let angle = 0;\n if (current.p.rotate === \"random\") angle = randInt(0, 360);\n else if (current.p.rotate === \"natural\") {\n angle =\n (_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle();\n }\n Mask.rotate(angle);\n return angle;\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (isInsideClippingArea()) {\n let pressure = calculatePressure();\n let alpha = calculateAlpha(pressure);\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, false, alpha * 5);\n }\n glDraw();\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawTip((pressure * s) / 5, alpha, false);\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current p5 angle mode.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, vibration, definition, quality, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\nadd(\"diamond\", {\n type: \"custom\",\n weight: 0.78,\n scatter: 0.1,\n opacity: 17,\n spacing: 1.3,\n pressure: [1.2, 0.82],\n rotate: \"none\",\n tip: (_m) => {\n _m.rotate(45);\n _m.rect(-4, -4, 8, 8);\n _m.rect(2, 2, 3, 3);\n },\n});\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the p5.js graphics library.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The p5.Image to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const p5img = Renderer.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n T.imageToWhite(p5img);\n this.tips.set(src, p5img);\n resolve();\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.src = src;\n }),\n ),\n );\n },\n};\n\n/**\n * Loads all registered image tips. Must be awaited before setup/draw.\n * @returns {Promise}\n *\n * @example\n * // In your sketch:\n * await brush.preload();\n */\nexport async function preload() {\n await T.load();\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};","// =============================================================================\n// Module: Hatch\n// =============================================================================\n/**\n * The Hatch module contains functions and classes dedicated to applying\n * hatch patterns over shapes and polygons. It enables the simulation of\n * cross-hatching and shading effects by drawing parallel lines or strokes\n * across a geometry. The module supports adjustable spacing, angle, and\n * optional style parameters (such as randomness, continuity, and gradient),\n * giving an artistic representation similar to hand-drawn hatching techniques.\n *\n * The implementation allows for hatching to be applied either to a Polygon\n * directly or via a Plot, extending the drawing capabilities with layered,\n * stylized textures.\n */\n\nimport { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, cos, sin, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// ---------------------------------------------------------------------------\n// Hatch State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global hatch state settings.\n */\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow copy of the current hatch state.\n * @returns {object} The current hatch state.\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Updates the global hatch state.\n * @param {object} state - The new hatch state.\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Activates hatching for subsequent geometries.\n *\n * @param {number} dist - The distance between hatching lines.\n * @param {number} angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} options - Optional parameters to affect the hatching style:\n * - rand: Number value to introduce randomness.\n * - continuous: Boolean to connect adjacent lines.\n * - gradient: Number to gradually change spacing.\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Sets the hatch brush style for subsequent hatching.\n *\n * @param {string} brush - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} weight - The brush weight (size).\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Disables hatching.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a hatching pattern over the given polygon(s).\n *\n * @param {Polygon|Polygon[]} polygons - A polygon or an array of polygons.\n */\nexport function createHatch(polygons) {\n let dist = State.hatch.dist;\n let angle = ((State.hatch.angle % 180) + 180) % 180;\n let options = State.hatch.options;\n\n // Save current stroke state\n let save = BrushState();\n // If a hatch brush is set, override with those parameters.\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n\n // Compute overall bounding box for all polygons.\n if (!Array.isArray(polygons)) polygons = [polygons];\n const overallBB = computeOverallBoundingBox(polygons);\n\n // Build a bounding polygon based on the overall bounding box.\n let ventana = new Polygon([\n [overallBB.minX, overallBB.minY],\n [overallBB.maxX, overallBB.minY],\n [overallBB.maxX, overallBB.maxY],\n [overallBB.minX, overallBB.maxY],\n ]);\n\n // Determine starting y coordinate based on angle.\n let startY = angle <= 90 && angle >= 0 ? overallBB.minY : overallBB.maxY;\n let gradient = options.gradient\n ? map(options.gradient, 0, 1, 1, 1.1, true)\n : 1;\n let dots = [];\n let i = 0;\n let dist1 = dist;\n\n // Function to generate a line for index i.\n let linea = (i) => {\n return {\n point1: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90),\n y: startY + dist1 * i * sin(-angle + 90),\n },\n point2: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90) + cos(-angle),\n y: startY + dist1 * i * sin(-angle + 90) + sin(-angle),\n },\n };\n };\n\n // Generate lines and calculate intersections with polygons\n // Loop through the lines based on the distance and angle to calculate intersections with the polygons\n // The loop continues until a line does not intersect with the bounding window polygon\n // Each iteration accounts for the gradient effect by adjusting the distance between lines\n while (ventana.intersect(linea(i)).length > 0) {\n let tempArray = [];\n for (let p of polygons) {\n tempArray.push(p.intersect(linea(i)));\n }\n dots[i] = tempArray\n .flat()\n .sort((a, b) => (a.x === b.x ? a.y - b.y : a.x - b.x));\n dist1 *= gradient;\n i++;\n }\n\n // Filter out empty intersection sets.\n let gdots = dots.filter((dd) => typeof dd[0] !== \"undefined\");\n\n // Draw the hatching lines using the calculated intersections\n // If the 'rand' option is enabled, add randomness to the start and end points of the lines\n // If the 'continuous' option is set, connect the end of one line to the start of the next\n let r = options.rand || 0;\n for (let j = 0; j < gdots.length; j++) {\n let dd = gdots[j];\n let continuousLine = j > 0 && options.continuous;\n for (let i = 0; i < dd.length - 1; i += 2) {\n if (r !== 0) {\n dd[i].x += r * dist * rr(-1, 1);\n dd[i].y += r * dist * rr(-1, 1);\n dd[i + 1].x += r * dist * rr(-1, 1);\n dd[i + 1].y += r * dist * rr(-1, 1);\n }\n line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);\n if (continuousLine) {\n line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);\n }\n }\n }\n\n // Restore previous brush state.\n BrushSetState(save);\n}\n\n/**\n * Computes the bounding box for a single polygon.\n * @param {Polygon} polygon - The polygon to evaluate.\n * @returns {object} The bounding box as {minX, minY, maxX, maxY}.\n */\nfunction computeBoundingBoxForPolygon(polygon) {\n if (polygon._boundingBox) return polygon._boundingBox;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n for (let i = 0; i < polygon.a.length; i++) {\n const [x, y] = polygon.a[i];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n polygon._boundingBox = { minX, minY, maxX, maxY };\n return polygon._boundingBox;\n}\n\n/**\n * Computes an overall bounding box for an array of polygons.\n * @param {Array} polygons - Array of Polygon objects.\n * @returns {object} The overall bounding box {minX, minY, maxX, maxY}.\n */\nfunction computeOverallBoundingBox(polygons) {\n let overall = {\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity,\n };\n for (let poly of polygons) {\n const bb = computeBoundingBoxForPolygon(poly);\n overall.minX = Math.min(overall.minX, bb.minX);\n overall.minY = Math.min(overall.minY, bb.minY);\n overall.maxX = Math.max(overall.maxX, bb.maxX);\n overall.maxY = Math.max(overall.maxY, bb.maxY);\n }\n return overall;\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Adds a hatch effect to the polygon.\n *\n * If a distance is provided, activates hatching with the given parameters.\n * Then, if hatch is active, applies the hatching pattern.\n *\n * @param {number} [_dist] - The distance between hatch lines.\n * @param {number} _angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} _options - Optional hatch options.\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) {\n createHatch(this);\n }\n HatchSetState(state);\n};\n\n/**\n * Applies hatching to a plot.\n *\n * If hatching is active, generates a polygon from the plot and applies hatch.\n *\n * @param {number} x - The x-coordinate to draw at.\n * @param {number} y - The y-coordinate to draw at.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.25);\n this.pol.hatch();\n }\n};\n","import { Mix } from \"./color.js\";\n\nfunction transformPoint(matrix, x, y) {\n return {\n x: matrix.a * x + matrix.c * y + matrix.e,\n y: matrix.b * x + matrix.d * y + matrix.f,\n };\n}\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices) {\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n vertices.forEach((v, i) => {\n const point = transformPoint(matrix, v.x, v.y);\n minX = Math.min(minX, point.x);\n minY = Math.min(minY, point.y);\n maxX = Math.max(maxX, point.x);\n maxY = Math.max(maxY, point.y);\n\n if (i === 0) ctx.moveTo(v.x, v.y);\n else ctx.lineTo(v.x, v.y);\n });\n ctx.closePath();\n\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n const radius = d / 2;\n const center = transformPoint(matrix, x, y);\n const rx = radius * Math.hypot(matrix.a, matrix.c);\n const ry = radius * Math.hypot(matrix.b, matrix.d);\n const padding = strokePadding(ctx, matrix);\n\n Mix.markDirtyRect(Mix.mask, {\n minX: center.x - rx - padding,\n minY: center.y - ry - padding,\n maxX: center.x + rx + padding,\n maxY: center.y + ry + padding,\n });\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\nimport { Renderer, Mix, State, Cwidth, Cheight, Density } from \"../core/color.js\";\nimport { drawPolygon, circle } from \"../core/mask.js\";\nimport {\n constrain,\n weightedRand,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady, Matrix } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 1024;\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color =\n arguments.length < 3 ? Renderer.color(a) : Renderer.color(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length < 8) {\n // Simple average for small polygons\n return pts\n .reduce((c, p) => ({ x: c.x + p.x, y: c.y + p.y }), { x: 0, y: 0 })\n .map((v) => v / pts.length);\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n const v = [...polygon.vertices];\n\n // Map vertices\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n\n // Create bleed modifiers\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.2) * strength,\n );\n\n // Randomize starting point\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n\n // Calculate center and create FillPolygon\n const center = _center(shifted);\n new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions\n this.dir = Array(v.length);\n rayCalc.forEach((rc, i) => {\n let count = 0;\n for (const isect of _polygon.intersect(rc.ray)) {\n if (_isLeft(rc.v1, rc.v2, isect)) count++;\n }\n this.dir[i] = count % 2 === 0;\n });\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: [...this.v], m: [...this.m], dir: [...this.dir] };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Clone and splice\n const v = [...this.v],\n m = [...this.m],\n dir = [...this.dir];\n v.splice(s, n);\n m.splice(s, n);\n dir.splice(s, n);\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n\n // Build sorted random indices\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [], sm = [], sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n\n // Ray-cast: count intersections from p to far right\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y, by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n // If outside (even crossings), pull toward center\n if (crossings % 2 === 0) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]); // flip direction → grow inward\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n // Get trimmed vertices\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n \n // Pre-allocate output arrays\n const outLen = len * 2;\n const newVerts = new Array(outLen);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\n \n // Determine bleed direction\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n \n // Ensure gaussian pool is filled\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0], gPoolLen = gPool.length;\n const g2Pool = _gaussians[1], g2PoolLen = g2Pool.length;\n \n let idx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n \n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n \n if (f < 997) mod = mi;\n \n // Inline rotate: rotDeg = ±bleedDirDeg + small jitter\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n \n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n \n // Outward distance: inline rArray + rr\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n \n // First vertex: original\n newVerts[idx] = cv;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n \n // Second vertex: midpoint + outward push\n newVerts[idx] = {\n x: cv.x + sideX * 0.5 + dirX * d,\n y: cv.y + sideY * 0.5 + dirY * d,\n };\n newMods[idx] = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n newDirs[idx] = di;\n idx++;\n }\n \n // Cap vertex count to prevent exponential blowup.\n let fv = newVerts, fm = newMods, fd = newDirs;\n let growe = GROW_MAX_VERTS / (State.fill.texture_strength);\n if (growe && idx > growe) {\n const step = Math.ceil(idx / growe);\n fv = []; fm = []; fd = [];\n for (let j = 0; j < idx; j += step) {\n fv.push(newVerts[j]);\n fm.push(newMods[j]);\n fd.push(newDirs[j]);\n }\n } else {\n // Trim pre-allocated arrays to actual size\n fv.length = idx;\n fm.length = idx;\n fd.length = idx;\n }\n \n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n // Precalculate stuff\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n // Perform initial setup only once\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(), Density * Matrix.b(),\n Density * Matrix.c(), Density * Matrix.d(),\n Density * (Matrix.x() + Cwidth / 2),\n Density * (Matrix.y() + Cheight / 2),\n );\n\n Mix.ctx.strokeStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${\n 0.005 * State.fill.border_strength\n })`;\n Mix.ctx.lineCap = \"round\";\n\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n\n // Create initial polygon\n let pol = this.grow();\n // Create sparse inner polygon from original (pre-grow) vertices\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n // Grow polygon every 4 layers\n if (i % 4 === 0) pol = pol.grow();\n\n // Create variant polygons\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n // Draw layers\n for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);\n sparse.grow(999).flipDirs().grow(997).layer(i, size, int * 1.5 * texture, color);\n if (i % 2 === 0)\n pol\n .grow(darker)\n .grow(999)\n .layer(i, size, int * 2, color);\n\n // Apply texture and blend periodically\n if (i % 5 === 0 || i === numLayers - 1) {\n if (texture !== 0) pol.erase(texture * 3, intensity);\n Mix.blend(color, true, false, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, color) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\n drawPolygon(this.v);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n // Optimize by pre-calculating values\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.4 - State.fill.bleed_strength);\n const minSizeFactor = 0.05 * minSize;\n const maxSizeFactor = 0.4 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n // Set up erase mode\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n // Calculate transparency\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n // Draw erase circles\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const size = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, size);\n if (i % 5 !== 0) Mix.ctx.fill();\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n map(State.fill.bleed_strength, 0, 0.6, 0.3, 0.45, true),\n );\n this.pol.fill();\n }\n};\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n}\n","/**\n * @fileoverview p5.brush - A comprehensive toolset for brush management in p5.js.\n * @version 2.0.0-alpha\n * @license MIT\n * @author Alejandro Campos Uribe\n *\n * @description\n * p5.brush is a p5.js library dedicated to the creation and management of custom brushes.\n * It extends the drawing capabilities of p5.js by allowing users to simulate a wide range\n * of brush strokes, vector fields, hatching patterns, and fill textures. These features\n * are essential for emulating the nuanced effects found in traditional sketching and painting.\n * Whether for digital art applications or procedural generation of graphics, p5.brush provides\n * a robust framework for artists and developers to create rich, dynamic, and textured visuals.\n *\n * @example\n * // Basic usage:\n * brush.pick('marker'); // Select brush type\n * brush.stroke(255, 0, 0); // Set brush color\n * brush.strokeWeight(10); // Set brush size\n * brush.line(25, 25, 75, 75); // Draw a line\n *\n * // Add a new brush type:\n * brush.add('customBrush', { /* parameters for the brush *\\/ });\n * brush.pick('customBrush');\n *\n * // Use the custom brush for a vector-field line:\n * brush.field('field_name') // Pick a flowfield\n * brush.flowLine(50, 50, 100, PI / 4); // Draw a line within the vector-field; angle follows p5 angleMode()\n *\n * // Fill textures:\n * brush.noStroke();\n * brush.fill('#FF0000', 90); // Set fill color to red and opacity to 90\n * brush.bleed(0.3); // Set bleed effect for a watercolor-like appearance\n * brush.rect(100, 100, 50, 50); // Fill a rectangle with the bleed effect\n *\n * @license\n * MIT License\n *\n * Copyright (c) 2023-2024 Alejandro Campos Uribe\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n// Randomness and other auxiliary functions\nexport { weightedRand as wRand } from \"./core/utils.js\";\n\n// Color Blending\nexport { load, instance } from \"./core/color.js\";\n\n// Matrix transformations, FlowField and Position Class\nexport {\n field,\n noField,\n addField,\n refreshField,\n listFields,\n Position,\n wiggle,\n} from \"./core/flowfield.js\";\n\n// Polygon and Plot classes\nexport { Polygon } from \"./core/polygon.js\";\nexport { Plot } from \"./core/plot.js\";\n\n// Primitives\nexport {\n rect,\n circle,\n arc,\n beginShape,\n vertex,\n endShape,\n beginStroke,\n move,\n endStroke,\n spline,\n polygon,\n} from \"./core/primitives.js\";\n\n// Brushes\nexport {\n add,\n box,\n scaleBrushes,\n pick,\n stroke,\n strokeWeight,\n set,\n noStroke,\n clip,\n noClip,\n line,\n flowLine,\n} from \"./stroke/stroke.js\";\n\n// Section: Hatching\nexport {\n hatch,\n hatchStyle,\n noHatch,\n createHatch as hatchArray,\n} from \"./hatch/hatch.js\";\n\n// Fill\nexport { fill, noFill, fillTexture, fillBleed } from \"./fill/fill.js\";\n\n// p5 addon registration\nimport { Mix } from \"./core/color.js\";\nimport { push as brushPush, pop as brushPop } from \"./core/save.js\";\nimport { seed as brushSeed, noiseSeed as brushNoiseSeed } from \"./core/utils.js\";\n\nfunction registerAddon(_p5, fn, lifecycles) {\n lifecycles.postsetup = () => Mix.blend(false, true);\n lifecycles.postdraw = () => Mix.blend(false, true);\n\n const _push = fn.push;\n const _pop = fn.pop;\n const _randomSeed = fn.randomSeed;\n const _noiseSeed = fn.noiseSeed;\n\n fn.push = function () {\n _push.call(this);\n brushPush();\n };\n\n fn.pop = function () {\n _pop.call(this);\n brushPop();\n };\n\n fn.randomSeed = function (s) {\n _randomSeed.call(this, s);\n brushSeed(s);\n };\n\n fn.noiseSeed = function (s) {\n _noiseSeed.call(this, s);\n brushNoiseSeed(s);\n };\n}\n\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerAddon);\n"],"names":["Cwidth","Cheight","Instance","Renderer","Density","isFramebufferTarget","target","begin","end","renderer","_pInst","getSketchRenderer","_isInstanced","window","self","p5","instance","removeTargetBuffer","buffer","remove","getActiveFramebuffer","_renderer","activeFramebuffer","getTargetPixelSize","width","Math","max","round","height","normalizeDirtyRect","rect","minX","floor","min","maxX","minY","maxY","ceil","getFullDirtyRect","withScissor","gl","draw","box","normalized","x","y","toScissorBox","wasEnabled","isEnabled","SCISSOR_TEST","prevBox","getParameter","SCISSOR_BOX","enable","scissor","disable","load","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","inst","isMixReady","isBlending","cachedColor","Object","markDirtyRect","a","b","dirtyRect","isDrawn","markFull","clearMask","clear","getCompositeRect","isBrushMask","padding","expandDirtyRect","captureBlendSource","framebuffer","blendSourceFramebuffer","pixelDensity","createFramebuffer","density","antialias","depth","stencil","source","drawingContext","push","imageMode","CENTER","image","pop","graphicsFactory","createGraphics","p2dMode","P2D","webglMode","WEBGL","mask","glMask","this","ctx","shaderProgram","createShader","angleMode","DEGREES","lineWidth","uModelMatrix","blend","_color","_isLast","activeIsBrush","isBrush","no_mask","nextColor","_array","colorChanged","justChanged","applyShader","shader","targetIsFramebuffer","hadDepthTest","DEPTH_TEST","translate","setUniform","fill","noStroke","resetShader","SQRT3","sqrt","F2","G2","fastFloor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","c","s0","s1","s2","copy","f","rng","_seedCallbacks","_onSeed","cb","noise","rr","e","rArray","array","randInt","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","d","withinBounds","constrain","low","high","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","NaN","sLookup","idx","sin","toDegrees","rad","isRad","RADIANS","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","Matrix","mat4","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","update","plotted","colIdx","getColIndex","rowIdx","getRowIndex","reset","isIn","isActive","isInCanvas","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","y_offset","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","has","generateField","entry","normalizeFieldAngles","gen","refreshField","currentField","keys","join","noField","name","funct","set","listFields","fn","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","intersection","show","stroke","hatch","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","polygon","mode","beginShape","vertex","endShape","circle","radius","arcLength","angleOffset","randomFactor","randomAngle","offsetX","offsetY","arc","startDeg","sweepDeg","segmentCount","segmentSweep","startX","startY","_current","_curvature","_strokeArray","_strokeOrigin","SubPath","isClosed","curvature","vert","_createSpline","close","beginStroke","move","endStroke","spline","_array_points","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","halfDist","asin","origin","projMatrix","vao","buf","program","loadedWidth","loadedHeight","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","diameter","alpha","newData","px","py","screenX","screenY","glDraw","color","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","uniform4f","u_color","uniformMatrix4fv","u_matrix","drawArrays","POINTS","_curShader","weight","clipWindow","opacity","_position","Mask","_strokeTransform","tx","ty","BrushState","BrushSetState","state","add","params","includes","undefined","vibration","scatter","definition","sharpness","quality","grain","isArray","min_max","curve","m","range","ns","nm","ne","normalizePressure","src","T","tip","tips","param","colors","buffers","scaleBrushes","values","spacing","pick","brushName","g","arguments","strokeWeight","snapshotTransform","transformPoint","transform","normalizeRegion","region","screenPointFromPosition","point","clip","inverse","det","invertTransform","bounds","noClip","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","noiseoffset","dirRad","nextGl","needsContextRefresh","createProgram","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","isReady","switchingToBrush","isInsideClippingArea","calculateAlpha","markerTip","saveState","stepSize","totalSteps","customPressure","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","local","o","vibrate","rx","ry","setAlpha","tint","adjustSizeAndRotation","halfWeight","radians","cosAngle","sinAngle","userCenterX","userCenterY","corners","Infinity","markImageTipDirty","flowLine","_vals","_standard_brushes","obj","_m","prototype","_brush","_weight","imageToWhite","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","p5img","createImage","naturalWidth","naturalHeight","drawImage","onerror","HatchState","rand","continuous","gradient","hatchStyle","brush","hBrush","noHatch","createHatch","polygons","save","overallBB","overall","poly","bb","computeBoundingBoxForPolygon","computeOverallBoundingBox","ventana","dots","dist1","linea","tempArray","flat","sort","gdots","dd","continuousLine","_boundingBox","matrix","strokePadding","getTransform","center","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","noFill","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","sx","sy","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","splice","ratio","L","keep","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","newVerts","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","fv","fm","fd","growe","intensity","tex","texture","int","switchingToFill","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","size","darker","sparse","pols","layer","numLayers","erase","restore","fillStyle","beginPath","lineTo","closePath","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","_opacity","_bleed","fluid","strength","modifiers","_","shift","shifted","slice","pts","area","cross","_center","createFill","FillSetState","_stateStack","registerAddon","_p5","lifecycles","postsetup","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","callback","brushSeed","brushNoiseSeed"],"mappings":"AAYO,IAAIA,EAAQC,EAASC,EAAUC,EAAUC,EAEhD,MAAMC,EAAuBC,KACzBA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rd,OACzBzT,EAAMmE,KAAO,IAAK2sB,EAAM3sB,MAC1B,CCyGI4sB,EACF,EAEAxe,EAAGme,WAAa,SAAU5qB,GACxB2qB,EAAYI,KAAKnuB,KAAMoD,GZpHP,CAACA,IACnB4C,EAAMzB,EAAUnB,GAChB,IAAK,MAAMkrB,KAAYroB,EACrBqoB,KYkHAC,CAAUnrB,EACZ,EAEAyM,EAAGqe,UAAY,SAAU9qB,GACvB6qB,EAAWE,KAAKnuB,KAAMoD,GZvGD,CAACA,IACxBgD,EAAQjE,EAAcoC,EAAUnB,KYuG9BorB,CAAeprB,EACjB,CACF","x_google_ignoreList":[1,2]}
\ No newline at end of file
diff --git a/dist/p5.brush.js b/dist/p5.brush.js
index 1fe5fce..3143cb9 100644
--- a/dist/p5.brush.js
+++ b/dist/p5.brush.js
@@ -1,2 +1,2 @@
-var t,e;t=this,e=function(t){let e,r,i,n,o;const s=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,a=()=>x?i:window.self.p5.instance,l=t=>{t&&"function"==typeof t.remove&&t.remove()},c=()=>n&&n._renderer&&"function"==typeof n._renderer.activeFramebuffer?n._renderer.activeFramebuffer():null,h=()=>({width:Math.max(1,Math.round(e*o)),height:Math.max(1,Math.round(r*o))}),u=t=>{if(!t)return null;const{width:e,height:r}=h(),i=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),n=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),o=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),s=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return o<=i||s<=n?null:{minX:i,minY:n,maxX:o,maxY:s}},f=()=>{const{width:t,height:e}=h();return{minX:0,minY:0,maxX:t,maxY:e}},m=(t,e,r)=>{const i=(t=>{const e=u(t);if(!e)return null;const{height:r}=h();return{x:e.minX,y:r-e.maxY,width:e.maxX-e.minX,height:e.maxY-e.minY}})(e);if(!i)return!1;const n=t.isEnabled(t.SCISSOR_TEST),o=t.getParameter(t.SCISSOR_BOX);t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{r()}finally{n?t.scissor(o[0],o[1],o[2],o[3]):t.disable(t.SCISSOR_TEST)}return!0},g=(t=!1)=>{const o=((t=!1)=>{if(x&&!t)return{renderer:i,width:i.width,height:i.height};if(!t){const t=a();return{renderer:t,width:t.width,height:t.height}}if(s(t)){if(!s(e=t)||e.renderer._pInst!==a())throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.");return{renderer:a(),width:t.width,height:t.height}}var e;return{renderer:t,width:t.width,height:t.height}})(t);if(n=o.renderer,"webgl2"!==n.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");e=o.width,r=o.height,d=!0,n.loaded&&b.load()};let d=!1,x=!1;const p=()=>{d||g()},y={},v=()=>{n.loaded||(p(),b.load())},b={isBlending:!1,cachedColor:new Object,markDirtyRect(t,e){const r=u(e);var i,n;t&&r&&(t.dirtyRect=(n=r,(i=t.dirtyRect)?n?{minX:Math.min(i.minX,n.minX),minY:Math.min(i.minY,n.minY),maxX:Math.max(i.maxX,n.maxX),maxY:Math.max(i.maxY,n.maxY)}:i:n),t.isDrawn=!0)},markFull(t){t&&(t.dirtyRect=f(),t.isDrawn=!0)},clearMask(t){t&&(t.clear(),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:(t,e)=>t?t.dirtyRect?u(((t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null)(t.dirtyRect,e?2:4)):f():null,captureBlendSource(t){const i=c();if(!i)return n._renderer;var s;(!(s=n.blendSourceFramebuffer)||s.width!==e||s.height!==r||"function"==typeof s.pixelDensity&&s.pixelDensity()!==o)&&(l(n.blendSourceFramebuffer),n.blendSourceFramebuffer=n.createFramebuffer({width:e,height:r,density:o,antialias:!1,depth:!1,stencil:!1}));const a=n.blendSourceFramebuffer;return a.draw(()=>{m(n.drawingContext,t,()=>{n.clear(),n.push(),"function"==typeof n.imageMode&&n.imageMode(n.CENTER??n._renderer?._pInst?.CENTER),n.image(i,0,0,e,r),n.pop()})}),a},load(){o=n.pixelDensity();const t="function"==typeof n.createGraphics?n:n._pInst,i=t.P2D??n.P2D,s=t.WEBGL??n.WEBGL;n.loaded&&n.mask&&n.glMask&&n.mask.width===e&&n.mask.height===r&&n.glMask.width===e&&n.glMask.height===r?(this.mask=n.mask,this.glMask=n.glMask,this.ctx=this.mask.drawingContext,this.mask.dirtyRect??=null,this.mask.isDrawn??=!1,this.glMask.dirtyRect??=null,this.glMask.isDrawn??=!1):(l(n.mask),l(n.glMask),n.mask=t.createGraphics(e,r,i),n.glMask=t.createGraphics(e,r,s),n.loaded=!0,n.shaderProgram??=n.createShader("#version 300 es\n#define GLSLIFY 1\nuniform bool u_flipOutputY;out vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,u_flipOutputY ?-v.y : v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 uv1=vec2(uv.x,1.0-uv.y);vec4 source=texture(u_source,uv1);vec4 maskColor=texture(u_mask,uv1);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=uv1+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.0);}"),this.mask=n.mask,this.mask.pixelDensity(o),this.mask.clear(),this.mask.angleMode(n.DEGREES),this.mask.dirtyRect=null,this.mask.isDrawn=!1,this.ctx=this.mask.drawingContext,this.glMask=n.glMask,this.glMask.pixelDensity(o),this.glMask.clear(),this.glMask.angleMode(this.glMask.DEGREES),this.glMask.drawingContext.lineWidth=0,this.glMask.dirtyRect=null,this.glMask.isDrawn=!1),this.glMask._renderer.uModelMatrix=n._renderer.uModelMatrix},blend(t=!1,e=!1){v();const r=!0===this.isBrush,i=r?this.glMask:this.mask,n=r?this.mask:this.glMask,o=t?._array,s=!!o&&(this.cachedColor[0]!==o[0]||this.cachedColor[1]!==o[1]||this.cachedColor[2]!==o[2]||this.cachedColor[3]!==o[3]);!this.isBlending&&o&&(this.isBlending=!0,this.cachedColor=o,this.glMask.clear()),(e||s)&&(this.justChanged&&(this.applyShader(n,!r),this.justChanged=!1),this.isBlending&&this.applyShader(i,r),o&&(this.cachedColor=o),e&&(this.isBlending=!1))},applyShader(t,i){if(!t?.isDrawn)return;const o=this.getCompositeRect(t,i);if(!o)return void this.clearMask(t);let s=n.shaderProgram;const a=n.drawingContext,l=!!c(),h=this.captureBlendSource(o),u=a.getParameter(a.DEPTH_TEST);a.disable(a.DEPTH_TEST),n.push(),n.translate(0,0),n.shader(s),s.setUniform("u_source",h),s.setUniform("u_isBrush",i),s.setUniform("u_flipOutputY",l),s.setUniform("u_mask",t),s.setUniform("u_color",this.cachedColor),m(a,o,()=>{n.fill(0,0,0,0),n.noStroke(),n.rect(-e/2,-r/2,e,r)}),n.pop(),n.resetShader(),u&&a.enable(a.DEPTH_TEST),this.clearMask(t)}},_=Math.sqrt(3),w=.5*(_-1),R=(3-_)/6,S=t=>0|Math.floor(t),M=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]);function E(t=Math.random){const e=function(t){const e=new Uint8Array(512);for(let t=0;t<256;t++)e[t]=t;for(let r=0;r<255;r++){const i=r+~~(t()*(256-r)),n=e[r];e[r]=e[i],e[i]=n}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>M[t%12*2]),i=new Float64Array(e).map(t=>M[t%12*2+1]);return function(t,n){let o=0,s=0,a=0;const l=(t+n)*w,c=S(t+l),h=S(n+l),u=(c+h)*R,f=t-(c-u),m=n-(h-u);let g,d;f>m?(g=1,d=0):(g=0,d=1);const x=f-g+R,p=m-d+R,y=f-1+2*R,v=m-1+2*R,b=255&c,_=255&h;let M=.5-f*f-m*m;if(M>=0){const t=b+e[_];M*=M,o=M*M*(r[t]*f+i[t]*m)}let E=.5-x*x-p*p;if(E>=0){const t=b+g+e[_+d];E*=E,s=E*E*(r[t]*x+i[t]*p)}let A=.5-y*y-v*v;if(A>=0){const t=b+1+e[_+1];A*=A,a=A*A*(r[t]*y+i[t]*v)}return 70*(o+s+a)}}function A(t,e){let r=new P(t),i=()=>r.next();return i.double=()=>i()+11102230246251565e-32*(2097152*i()|0),i.int32=()=>4294967296*r.next()|0,i.quick=i,i}class P{constructor(t){null==t&&(t=+new Date);let e=4022871197;function r(t){t=String(t);for(let r=0;r<t.length;r++){e+=t.charCodeAt(r);let i=.02519603282416938*e;e=i>>>0,i-=e,i*=e,e=i>>>0,i-=e,e+=4294967296*i}return 2.3283064365386963e-10*(e>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(t),this.s0<0&&(this.s0+=1),this.s1-=r(t),this.s1<0&&(this.s1+=1),this.s2-=r(t),this.s2<0&&(this.s2+=1)}next(){let{c:t,s0:e,s1:r,s2:i}=this,n=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=i,this.s2=n-(this.c=0|n)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let k=A(Math.random());const I=[],C=t=>I.push(t);let L=E(A(Math.random()));const T=(t=0,e=1)=>t+k()*(e-t),N=t=>t[~~(k()*t.length)],Y=(t,e)=>~~T(t,e),z=(t=0,e=1)=>{const r=1-k(),i=k();return Math.sqrt(-2*Math.log(r))*H(360*i)*e+t},X=t=>{let e=0;const r=[];for(const i in t)e+=t[i],r.push({key:i,cumulative:e});const i=k()*e;for(const{key:t,cumulative:e}of r)if(i<e)return isNaN(t)?t:parseInt(t)},D=(t,e,r,i,n,o=!1)=>{let s=i+(t-e)/(r-e)*(n-i);return o?i<n?O(s,i,n):O(s,n,i):s},O=(t,e,r)=>Math.max(Math.min(t,r),e),B=t=>(t%=360)<0?t+360:t,F=1440,G=2*Math.PI/F,$=new Float32Array(F).fill(NaN),W=new Float32Array(F).fill(NaN),H=t=>{const e=~~(4*B(t));let r=$[e];return isNaN(r)&&(r=Math.cos(e*G),$[e]=r),r},U=t=>{const e=~~(4*B(t));let r=W[e];return isNaN(r)&&(r=Math.sin(e*G),W[e]=r),r},j=(t,e=!1)=>{if(e||n&&"function"==typeof n.angleMode&&n.angleMode()===n.RADIANS){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},Z=(t,e=!1)=>e||n&&"function"==typeof n.angleMode&&n.angleMode()===n.RADIANS?180*t/Math.PI:t,V=(t,e,r,i,n)=>{let o=H(n),s=U(n);return{x:o*(r-t)+s*(i-e)+t,y:o*(i-e)-s*(r-t)+e}},K=(t,e,r,i)=>Math.hypot(r-t,i-e),q=(t,e,r,i)=>j(Math.atan2(-(i-e),r-t),!0),J=(t,e,r,i,n=!1)=>{let o=t.x,s=t.y,a=e.x,l=e.y,c=r.x,h=r.y,u=i.x,f=i.y;if(o===a&&s===l||c===u&&h===f)return!1;let m=a-o,g=l-s,d=u-c,x=f-h,p=x*m-d*g;if(0===p)return!1;let y=(d*(s-h)-x*(o-c))/p,v=(m*(s-h)-g*(o-c))/p;return!(!n&&(v<0||v>1))&&{x:o+y*m,y:s+y*g}},Q=()=>n._renderer.uModelMatrix.mat4[12],tt=()=>n._renderer.uModelMatrix.mat4[13],et=()=>n._renderer.uModelMatrix.mat4[0],rt=()=>n._renderer.uModelMatrix.mat4[1],it=()=>n._renderer.uModelMatrix.mat4[4],nt=()=>n._renderer.uModelMatrix.mat4[5];let ot=!1;function st(){ot||(v(),lt=.01*e,ct=-.5*e,ht=-.5*r,ut=Math.round(2*e/lt),ft=Math.round(2*r/lt),yt("hand",(t,e)=>{const r=T(.2,.8),i=Y(5,10);return vt(e,(e,n)=>.5*i*U(r*n*e+Y(15,25))*.2*H(t)+L(e,n)*i*.7)}),yt("curved",(t,e)=>{let r=Y(-10,10);return Y(0,100)%2==0&&(r*=-1),vt(e,(e,i)=>3*D(L(.02*e+.03*t,.02*i+.03*t),0,1,-r,r))}),yt("zigzag",(t,e)=>{let r=Y(-30,-15)+Math.abs(44*U(t));Y(0,100)%2==0&&(r*=-1);let i=r,n=0;for(let t=0;t<ut;t++){for(let r=0;r<ft;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e}),yt("waves",(t,e)=>{const r=Y(10,15)+5*U(t),i=Y(3,6)+3*H(t),n=Y(20,35);return vt(e,(t,e)=>U(r*t)*n*H(e*i)+Y(-3,3))}),yt("seabed",(t,e)=>{const r=T(.4,.8),i=Y(18,26);return vt(e,(e,n)=>1.1*i*U(r*n*e+Y(15,20))*H(t))}),yt("spiral",(t,e)=>{const r=Y(5,10),i=2*Y(0,2)-1,n=Y(65,80),o=Array.from({length:r},()=>({x:T(.1,.9)*ut,y:T(.1,.9)*ft}));return vt(e,(t,e)=>{let r=0,s=0;for(const a of o){const o=t-a.x,l=e-a.y,c=1/(o*o+l*l+1),h=Math.atan2(l,o)*(180/Math.PI),u=i*(h+n)*Math.PI/180;r+=c*Math.cos(u),s+=c*Math.sin(u)}return Math.atan2(s,r)*(180/Math.PI)})}),yt("columns",(t,e)=>{const r=Y(3,8),i=Y(25,45);return vt(e,(t,e)=>U(t*r)*i)}),ot=!0)}class at{constructor(t,e){st(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=at.getColIndex(t),this.rowIdx=at.getRowIndex(e)}reset(){this.plotted=0}isIn(){return y.field.isActive?at.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,i=r,n=this.x+Q(),o=this.y+tt();return n>=-.3*t&&n<=1.3*t&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&y.field.isActive?mt.get(y.field.current).field[this.colIdx][this.rowIdx]*y.field.wiggle:0}moveTo(t,e,r=1){this.movePos(Z(t),e,r)}_moveToDegrees(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,i=1){this.movePos(t,e,r,i)}movePos(t,e,r,i=!1){const n=i||1;if(this.isIn())for(let o=0;o<e/r;o++){const e=this.angle()-(i?t.angle(this.plotted):t);this.update(this.x+r*H(e),this.y+r*U(e)),this.plotted+=r/n}else this.plotted+=r/n}static getRowIndex(t,e=1){const r=t+tt()-ht;return Math.round(r/lt/e)}static getColIndex(t,e=1){const r=t+Q()-ct;return Math.round(r/lt/e)}static isIn(t,e){return t>=0&&e>=0&&t<ut&&e<ft}}y.field={isActive:!1,current:null,wiggle:1};let lt,ct,ht,ut,ft,mt=new Map;const gt=new Set(["degrees","radians"]);function dt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!gt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function xt(t,e){return function(t,e){if("radians"!==e)return t;for(let e=0;e<t.length;e++)for(let r=0;r<t[e].length;r++)t[e][r]=Z(t[e][r],!0);return t}(t.gen(e,new Array(ut).fill(null).map(()=>new Float32Array(ft))),t.angleMode)}function pt(t){if(y.field.wiggle||(y.field.wiggle=1),st(),!mt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(mt.keys()).join(", ")}.`);y.field.isActive=!0,y.field.current=t;const e=mt.get(t);e.field||(e.field=xt(e,0))}function yt(t,e,r={}){mt.set(t,{gen:e,field:null,angleMode:dt(r)})}function vt(t,e){for(let r=0;r<ut;r++)for(let i=0;i<ft;i++)t[r][i]=e(r,i);return t}class bt{constructor(t,e=!1){this.a=t,this.vertices=e?t:t.map(([t,e])=>({x:t,y:e})),this.sides=this.vertices.map((t,e,r)=>[t,r[(e+1)%r.length]]),this._intersectionCache={}}intersect(t){const e=`${t.point1.x},${t.point1.y}-${t.point2.x},${t.point2.y}`;if(this._intersectionCache[e])return this._intersectionCache[e];const r=[];for(const[e,i]of this.sides){const n=J(t.point1,t.point2,e,i);n&&r.push(n)}return this._intersectionCache[e]=r,r}show(){y.stroke&&this.draw(),y.hatch&&this.hatch(),y.fill&&this.fill()}}class _t{constructor(t){this.segments=[],this.angles=[],this.pres=[],this.type=t,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(t=0,e=0,r=1,i=!1){this.angles.length>0&&this.angles.pop(),t=i?(t%360+360)%360:j(t),this.angles.push(t,t),this.pres.push(r),this.segments.push(e),this.length=this.segments.reduce((t,e)=>t+e,0)}endPlot(t=0,e=1,r=!1){t=r?(t%360+360)%360:j(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=j(t)}pressure(t){return t>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,t)}angle(t){return t>this.length?this.angles[this.angles.length-1]:(this.calcIndex(t),"curve"===this.type?this.curving(this.angles,t)+this.dir:this.angles[this.index]+this.dir)}curving(t,e){let r=t[this.index],i=t[this.index+1]??r;return Math.abs(i-r)>180&&(i>r?i=-(360-i):r=-(360-r)),D(e-this.suma,0,this.segments[this.index],r,i,!0)}calcIndex(t){this.index=-1,this.suma=0;let e=0;for(;e<=t;)this.suma=e,e+=this.segments[this.index+1],this.index++;return this.index}genPol(t,i,n=1,o){st();const s=.5,a=[],l=Math.round(this.length/s),c=new at(t+e/2,i+r/2);let h=0,u=0;for(let t=0;t<l;t++){c.plotTo(this,s,s);const t=this.calcIndex(c.plotted);h+=s,(h>=Math.max(this.segments[t]*o*T(.7,1.3),10)||t>=u)&&c.x&&(a.push([c.x-e/2,c.y-r/2]),h=0,t>=u&&u++)}return new bt(a)}show(t,e,r=1){y.stroke&&this.draw(t,e,r),y.hatch&&this.hatch(t,e,r),y.fill&&this.fill(t,e,r)}}let wt,Rt,St,Mt;class Et{constructor(){this.isClosed=!1,this.curvature=Rt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){It(this.vert,this.curvature,this.isClosed).show()}}function At(t=0){Rt=O(t,0,1),wt=new Et}function Pt(t,e,r=1){if(!wt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");wt.vertex(t,e,r)}function kt(t=!1){if(!wt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(wt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(wt.vertex(...wt.vert[0]),wt.isClosed=!0),wt.show(),wt=!1}function It(t,e=.5,r=!1){const i=new _t(0===e?"segments":"curve"),n=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let o,s,a,l=0;for(let c=0;c<t.length-1;c++)if(e>0&&c<t.length-2){const h=t[c],u=t[c+1],f=t[c+2],m=K(h[0],h[1],u[0],u[1]),g=K(u[0],u[1],f[0],f[1]),d=q(h[0],h[1],u[0],u[1]),x=q(u[0],u[1],f[0],f[1]),p=e*Math.min(m,g,.5*Math.min(m,g)),y=Math.max(m,g),v=m-p,b=g-p;if(Math.floor(d)===Math.floor(x)){const e=r&&0===c?0:m-l,n=r?0===c?0:g-a:g;i.addSegment(d,e,h[2],!0),c===t.length-3&&i.addSegment(x,n,u[2],!0),l=0,0===c&&(o=m,a=p,s=t[1],l=0)}else{const e={x:u[0]-p*H(-d),y:u[1]-p*U(-d)},f={x:e.x+y*H(90-d),y:e.y+y*U(90-d)},m={x:u[0]+p*H(-x),y:u[1]+p*U(-x)},g={x:m.x+y*H(90-x),y:m.y+y*U(90-x)},_=J(e,f,m,g,!0),w=K(e.x,e.y,_.x,_.y),R=K(e.x,e.y,m.x,m.y)/2,S=n*w*(2*Math.asin(R/w)*(180/Math.PI))/360,M=r&&0===c?0:v-l,E=c===t.length-3?r?o-p:b:0;i.addSegment(d,M,h[2],!0),i.addSegment(d,isNaN(S)?0:S,h[2],!0),i.addSegment(x,E,u[2],!0),l=p,0===c&&(o=v,a=p,s=[e.x,e.y])}c===t.length-3&&i.endPlot(x,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],n=K(e[0],e[1],r[0],r[1]),o=q(e[0],e[1],r[0],r[1]);i.addSegment(o,n,r[2],!0),c===t.length-2&&i.endPlot(o,1,!0)}i.origin=r&&0!==e?s:t[0]}return i}let Ct,Lt,Tt,Nt,Yt,zt=!1,Xt=0,Dt=0;const Ot={},Bt={};let Ft=1,Gt=0,$t=0,Wt=1,Ht=0,Ut=0,jt=new Float32Array(8192),Zt=0,Vt=2048,Kt=32768;function qt(t,i,n,s){if(Zt>=Vt){Vt*=2;const t=new Float32Array(4*Vt);t.set(jt),jt=t}const a=t-e/2,l=i-r/2,c=4*Zt,h=Ft*a+$t*l+Ht+e/2,u=Gt*a+Wt*l+Ut+r/2,f=o*n*Math.sqrt(Ft*Ft+Gt*Gt)/2;jt[c]=h,jt[c+1]=u,jt[c+2]=f,jt[c+3]=s/255,b.markDirtyRect(b.glMask,{minX:h*o-f-1,minY:u*o-f-1,maxX:h*o+f+1,maxY:u*o+f+1}),Zt++}function Jt(){if(0===Zt)return;b.glMask.isDrawn=!0;const t=y.stroke.color._array;Ct.useProgram(Yt),Ct.enable(Ct.BLEND),Ct.blendFunc(Ct.ONE_MINUS_DST_ALPHA,Ct.ONE),Ct.bindVertexArray(Tt),Ct.bindBuffer(Ct.ARRAY_BUFFER,Nt);const e=16*Zt,r=jt.subarray(0,4*Zt);e>Kt?(Ct.bufferData(Ct.ARRAY_BUFFER,jt,Ct.DYNAMIC_DRAW),Kt=jt.byteLength):Ct.bufferSubData(Ct.ARRAY_BUFFER,0,r),Ct.uniform4f(Bt.u_color,...t),Ct.uniformMatrix4fv(Bt.u_matrix,!1,Lt),Ct.drawArrays(Ct.POINTS,0,Zt),Ct.bindVertexArray(null),Zt=0,b.glMask._renderer._curShader=null}y.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let Qt,te,ee,re,ie=new Map,ne=null,oe={a:1,b:0,c:0,d:1,tx:0,ty:0};function se(){return{...y.stroke}}function ae(t){y.stroke={...t}}function le(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0!==e.vibration&&void 0===e.scatter&&(e.scatter=e.vibration),void 0!==e.definition&&void 0===e.sharpness&&(e.sharpness=e.definition),void 0!==e.quality&&void 0===e.grain&&(e.grain=e.quality),e.pressure=function(t){if(!t||"object"==typeof t&&!Array.isArray(t))return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t};if(Array.isArray(t)){const[e,r,i]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,n=Math.min(e,r,i),o=Math.max(e,r,i),s=o-n||1,[a,l,c]=[(e-n)/s,(r-n)/s,(i-n)/s];return{type:"custom",min_max:[n,o],curve:t=>t<.5?a+(l-a)*t*2:l+(c-l)*(t-.5)*2}}}(e.pressure),"image"===e.type){if(!e.image||!e.image.src)throw new Error(`Brush "${t}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return Le.add(e.image.src),e.tip=()=>{ne.image(Le.tips.get(pe.p.image.src),-pe.p.weight/2,-pe.p.weight/2,pe.p.weight,pe.p.weight)},ie.set(t,{param:e,colors:[],buffers:[]}),Le.load()}ie.set(t,{param:e,colors:[],buffers:[]})}function ce(t){if(!ie.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...ie.keys()].join(", ")}.`);y.stroke.type=t}function he(t,e,r){p(),y.stroke.color=n.color(...arguments),y.stroke.isActive=!0}function ue(t){y.stroke.weight=t}function fe(t,e,r=1){ce(t),he(e),ue(r)}function me(){return{a:et(),b:rt(),c:it(),d:nt(),tx:Q(),ty:tt()}}function ge(t,e,r){return{x:t.a*e+t.c*r+t.tx,y:t.b*e+t.d*r+t.ty}}function de(t){const[e,r,i,n]=t;return{minX:Math.min(e,i),minY:Math.min(r,n),maxX:Math.max(e,i),maxY:Math.max(r,n)}}function xe(t,i){const n=ge(oe,t-e/2,i-r/2);return{x:n.x+e/2,y:n.y+r/2}}const pe={};function ye(t,i,n,o=!1){Ft=et(),Gt=rt(),$t=it(),Wt=nt(),Ht=Q(),Ut=tt(),oe=me(),Qt=new at(t+e/2,i+r/2),te=n,ee=o,ee&&ee.calcIndex(0)}const ve=[];function be(t,i){i||(re=t),function(){pe.seed=999999*T();const{param:t}=ie.get(y.stroke.type)??{};if(!t)return;pe.p=t,ne=b.glMask;const{pressure:i}=t;if(pe.a="custom"!==i.type?T(-1,1):0,pe.b="custom"!==i.type?T(1,1.5):0,pe.cp="custom"!==i.type?T(3,3.5):T(-.2,.2),[pe.min,pe.max]=i.min_max,pe.noiseoffset=.03,!ee){const t=re*Math.PI/180;pe.cos=Math.cos(t),pe.sin=Math.sin(t)}!function(){v();const t=b.glMask.drawingContext,i=!zt||Ct!==t;(i||Xt!==e||Dt!==r)&&(Lt=new Float32Array([2/e,0,0,0,0,-2/r,0,0,0,0,1,0,-1,1,0,1]),Xt=e,Dt=r),i&&(Ct=t,Yt=(t=>{const e=t.createProgram();for(let[r,i]of[[t.VERTEX_SHADER,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}"],[t.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"]]){const n=t.createShader(r);t.shaderSource(n,i),t.compileShader(n),t.attachShader(e,n)}return t.linkProgram(e),e})(Ct),Ct.useProgram(Yt),Ct.enable(Ct.BLEND),Ct.blendFunc(Ct.ONE_MINUS_DST_ALPHA,Ct.ONE),["a_position","a_radius","a_alpha"].forEach(t=>Ot[t]=Ct.getAttribLocation(Yt,t)),["u_matrix","u_color"].forEach(t=>Bt[t]=Ct.getUniformLocation(Yt,t)),Tt=Ct.createVertexArray(),Ct.bindVertexArray(Tt),Nt=Ct.createBuffer(),Ct.bindBuffer(Ct.ARRAY_BUFFER,Nt),Ct.bufferData(Ct.ARRAY_BUFFER,jt.byteLength,Ct.DYNAMIC_DRAW),Kt=jt.byteLength,Ct.enableVertexAttribArray(Ot.a_position),Ct.vertexAttribPointer(Ot.a_position,2,Ct.FLOAT,!1,16,0),Ct.enableVertexAttribArray(Ot.a_radius),Ct.vertexAttribPointer(Ot.a_radius,1,Ct.FLOAT,!1,16,8),Ct.enableVertexAttribArray(Ot.a_alpha),Ct.vertexAttribPointer(Ot.a_alpha,1,Ct.FLOAT,!1,16,12),Ct.bindVertexArray(null),zt=!0)}();const n=!0!==b.isBrush;b.isBrush=!0,n&&(b.justChanged=!0),Me()&&b.blend(y.stroke.color),pe.alpha=Se(),Pe()}();const n=function(){const{param:t}=ie.get(y.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(te*(i?t:1)/n);for(let e=0;e<o;e++)ve.length<2*o&&ve.push(z()),_e(),i?Qt.plotTo(ee,n,n,t,e<10):Qt._moveToDegrees(t,n,n);Jt(),Pe()}function _e(t=!1){if(!Me())return;let e=t||we(),r=D(L(pe.seed+.002*Qt.plotted,0),0,1,1-pe.noiseoffset,1+pe.noiseoffset);switch(pe.p.type){case"spray":!function(t){const e=y.stroke.weight*pe.p.scatter*t+y.stroke.weight*N(ve)*pe.p.scatter/3,r=pe.p.weight*T(.9,1.1),i=Math.ceil(pe.p.grain/t);for(let t=0;t<i;t++){const t=T(.9,1.1),i=t*e*T(-1,1),n=T(-1,1),o=Math.sqrt((t*e)**2-i**2);qt(Qt.x+i,Qt.y+n*o,r,pe.alpha)}}(e*r);break;case"marker":Ee(e*r);break;case"custom":case"image":Ae(e*r,pe.alpha);break;default:!function(t,e=1){const r=(e=D(e,0,1,.9,1.05))*y.stroke.weight*pe.p.scatter*(pe.p.sharpness+(1-pe.p.sharpness)*N(ve)/t);if(T(0,pe.p.grain*t)>.4){let e,i;if(ee)e=.7*r*T(-1,1),i=r*T(-1,1);else{const t=r*T(-1,1),n=.3*r*T(-1,1);e=t*-pe.sin+n*pe.cos,i=t*pe.cos+n*pe.sin}qt(Qt.x+e,Qt.y+i,t*t*pe.p.weight*T(.85,1.15)*y.stroke.weight,Math.max(.9,t)*pe.alpha*T(.75,1.1))}}(e*r)}}function we(){return ee?Re()*ee.pressure(Qt.plotted):Re()}function Re(){return"custom"===pe.p.pressure.type?D(pe.p.pressure.curve(Qt.plotted/te)+pe.cp,0,1,pe.min,pe.max,!0):function(t=.5+pe.p.pressure.curve[0]*pe.a,e=1-pe.p.pressure.curve[1]*pe.b,r=pe.cp,i=pe.min,n=pe.max){const o=t*te,s=(Qt.plotted<o?1.2*e:.8*e)*(te/2);return D(1/(1+Math.pow(Math.abs((Qt.plotted-o)/s),2*r)),0,1,i,n)}()}function Se(){return["default","spray"].includes(pe.p.type)?pe.p.opacity:pe.p.opacity/Math.min(y.stroke.weight,1.3)}function Me(){const t=ge(oe,Qt.x-e/2,Qt.y-r/2);if(y.stroke.clipWindow){const e=ge(y.stroke.clipWindow.inverse,t.x,t.y),{bounds:r}=y.stroke.clipWindow;return e.x>=r.minX&&e.x<=r.maxX&&e.y>=r.minY&&e.y<=r.maxY}let i=.05*e;return t.x>=-e/2-i&&t.x<=e/2+i&&t.y>=-r/2-i&&t.y<=r/2+i}function Ee(t,e=!0,r=pe.alpha){const i=e?y.stroke.weight*pe.p.scatter:0,n=e?i*T(-1,1):0,o=e?i*T(-1,1):0;qt(Qt.x+n,Qt.y+o,y.stroke.weight*pe.p.weight*t,r)}function Ae(t,i,o=!0){b.glMask.isDrawn=!0,ne.push(),ne.noStroke(),y.stroke.color.setAlpha(i),ne.fill(y.stroke.color);const s=o?y.stroke.weight*pe.p.scatter:0,a=o?s*T(-1,1):0,l=o?s*T(-1,1):0;ne.translate(Qt.x+a-e,Qt.y+l-r);const c=y.stroke.weight*t,h=function(t,e){ne.scale(t),"image"===pe.p.type&&ne.tint(255,0,0,e/2);let r=0;return"random"===pe.p.rotate?r=Y(0,360):"natural"===pe.p.rotate&&(r=(ee?-ee.angle(Qt.plotted):-re)+Qt.angle()),ne.rotate(r),r}(c,i);pe.p.tip(ne),ne.pop(),"image"===pe.p.type?function(t,e,r,i){const o=pe.p.weight/2,s=i*Math.PI/180,a=Math.cos(s),l=Math.sin(s),c=Qt.x+t,h=Qt.y+e,u=[[-o,-o],[o,-o],[o,o],[-o,o]];let f=Infinity,m=Infinity,g=-Infinity,d=-Infinity;for(const[t,e]of u){const i=xe(c+r*(a*t-l*e),h+r*(l*t+a*e));f=Math.min(f,i.x*n.pixelDensity()),m=Math.min(m,i.y*n.pixelDensity()),g=Math.max(g,i.x*n.pixelDensity()),d=Math.max(d,i.y*n.pixelDensity())}b.markDirtyRect(b.glMask,{minX:f-2,minY:m-2,maxX:g+2,maxY:d+2})}(a,l,c,h):b.markFull(b.glMask)}function Pe(){if(Me()){let t=we(),e=Se();if("marker"===pe.p.type){for(let r=1;r<10;r++)Ee(t*r/10,!1,5*e);Jt()}else if("custom"===pe.p.type||"image"===pe.p.type)for(let r=1;r<5;r++)Ae(t*r/5,e,!1)}}function ke(t,e,r,i){if(!y.stroke.isActive||!y.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");st();let n=K(t,e,r,i);0!=n&&(ye(t,e,n),be(q(t,e,r,i),!1))}C(()=>{ve.length=0});const Ie=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],Ce=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of Ce){let e={};for(let r=0;r<t[1].length;r++)e[Ie[r]]=t[1][r];le(t[0],e)}le("diamond",{type:"custom",weight:.78,scatter:.1,opacity:17,spacing:1.3,pressure:[1.2,.82],rotate:"none",tip:t=>{t.rotate(45),t.rect(-4,-4,8,8),t.rect(2,2,3,3)}}),bt.prototype.draw=function(t=!1,e,r){let i=se();if(t&&fe(t,e,r),i.isActive)for(let t of this.sides)ke(t[0].x,t[0].y,t[1].x,t[1].y);ae(i)},_t.prototype.draw=function(t,e,r){se().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,i){st(),ye(e,r,t.length,t),be(i,!0)}(this,t,e,r))};const Le={tips:new Map,add(t){this.tips.set(t,!1)},imageToWhite(t){t.loadPixels();for(let e=0;e<4*t.width*t.height;e+=4){let r=(t.pixels[e]+t.pixels[e+1]+t.pixels[e+2])/3;t.pixels[e]=t.pixels[e+1]=t.pixels[e+2]=255,t.pixels[e+3]=255-r}t.updatePixels()},async load(){const t=[...this.tips.keys()].filter(t=>!this.tips.get(t));await Promise.all(t.map(t=>new Promise((e,r)=>{const i=new window.Image;i.onload=()=>{const r=n.createImage(i.naturalWidth,i.naturalHeight);r.drawingContext.drawImage(i,0,0),Le.imageToWhite(r),this.tips.set(t,r),e()},i.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),i.src=t})))}};function Te(){return{...y.hatch}}function Ne(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let i=y.hatch;i.isActive=!0,i.dist=t,i.angle=Z(e),i.options=r}function Ye(t){let e=y.hatch.dist,r=(y.hatch.angle%180+180)%180,i=y.hatch.options,n=se();y.hatch.hBrush&&fe(...Object.values(y.hatch.hBrush)),Array.isArray(t)||(t=[t]);const o=function(t){let e={minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity};for(let r of t){const t=ze(r);e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY)}return e}(t);let s=new bt([[o.minX,o.minY],[o.maxX,o.minY],[o.maxX,o.maxY],[o.minX,o.maxY]]),a=r<=90&&r>=0?o.minY:o.maxY,l=i.gradient?D(i.gradient,0,1,1,1.1,!0):1,c=[],h=0,u=e,f=t=>({point1:{x:o.minX+u*t*H(90-r),y:a+u*t*U(90-r)},point2:{x:o.minX+u*t*H(90-r)+H(-r),y:a+u*t*U(90-r)+U(-r)}});for(;s.intersect(f(h)).length>0;){let e=[];for(let r of t)e.push(r.intersect(f(h)));c[h]=e.flat().sort((t,e)=>t.x===e.x?t.y-e.y:t.x-e.x),u*=l,h++}let m=c.filter(t=>void 0!==t[0]),g=i.rand||0;for(let t=0;t<m.length;t++){let r=m[t],n=t>0&&i.continuous;for(let i=0;i<r.length-1;i+=2)0!==g&&(r[i].x+=g*e*T(-1,1),r[i].y+=g*e*T(-1,1),r[i+1].x+=g*e*T(-1,1),r[i+1].y+=g*e*T(-1,1)),ke(r[i].x,r[i].y,r[i+1].x,r[i+1].y),n&&ke(m[t-1][1].x,m[t-1][1].y,r[i].x,r[i].y)}ae(n)}function ze(t){if(t._boundingBox)return t._boundingBox;let e=Infinity,r=Infinity,i=-Infinity,n=-Infinity;for(let o=0;o<t.a.length;o++){const[s,a]=t.a[o];s<e&&(e=s),s>i&&(i=s),a<r&&(r=a),a>n&&(n=a)}return t._boundingBox={minX:e,minY:r,maxX:i,maxY:n},t._boundingBox}function Xe(t,e,r){return{x:t.a*e+t.c*r+t.e,y:t.b*e+t.d*r+t.f}}function De(t,e){const r=t.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(e.a,e.c),Math.hypot(e.b,e.d))/2}function Oe(t,e,r){const i=2*Math.PI,n=b.ctx,o=n.getTransform(),s=r/2,a=Xe(o,t,e),l=s*Math.hypot(o.a,o.c),c=s*Math.hypot(o.b,o.d),h=De(n,o);b.markDirtyRect(b.mask,{minX:a.x-l-h,minY:a.y-c-h,maxX:a.x+l+h,maxY:a.y+c+h}),n.moveTo(t+s,e),n.arc(t,e,s,0,i)}y.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},bt.prototype.hatch=function(t=!1,e,r){let i=Te();t&&Ne(t,e,r),i.isActive&&Ye(this),function(t){y.hatch={...t}}(i)},_t.prototype.hatch=function(t,e,r){Te().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},y.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Be=()=>({...y.fill});function Fe(t,e,r,i){y.fill.opacity=(arguments.length<4?e:i)||150,y.fill.color=arguments.length<3?n.color(t):n.color(t,e,r),y.fill.isActive=!0}function Ge(t,e="out"){y.fill.bleed_strength=O(t,0,1),y.fill.direction=e}function $e(t=.4,e=.4){y.fill.texture_strength=O(t,0,1),y.fill.border_strength=O(e,0,1)}let We;const He=[[],[]];function Ue(){for(let t=0;t<512;t++)He[0][t]=z(.5,.2),He[1][t]=z(0,.02)}function je(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}C(Ue);class Ze{constructor(t,e,r,i=[],n=!1,o,s){if(this.v=t,this.m=e,this.dir=i,this.midP=r,n){let e=0,i=0;const n=[];for(let o=0;o<t.length;o++){const s=Math.abs(r.x-t[o].x),a=Math.abs(r.y-t[o].y);e=Math.max(e,s),i=Math.max(i,a);const l=t[o],c=t[(o+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=V(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};n.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=i,this.dir=Array(t.length),n.forEach((t,e)=>{let r=0;for(const e of We.intersect(t.ray))je(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=T(-.6,.6)*e,s=T(-.6,.6)*i;this.midP={x:r.x+o,y:r.y+s}}else this.sizeX=o,this.sizeY=s}trim(t=1){if(t>=1||t<0||this.v.length<=8)return{v:[...this.v],m:[...this.m],dir:[...this.dir]};const e=~~((1-t)*this.v.length),r=~~(this.v.length/2-e/2),i=[...this.v],n=[...this.m],o=[...this.dir];return i.splice(r,e),n.splice(r,e),o.splice(r,e),{v:i,m:n,dir:o}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),i=[],n=e/r;for(let t=0;t<r;t++)i.push(~~(t*n+T(0,.8*n)));const o=[],s=[],a=[],l=this.midP,c=We.sides;for(const t of i){const r=t%e;let i=this.v[r],n=0;for(const[t,e]of c){const r=t.y,o=e.y;if(r>i.y==o>i.y)continue;const s=(i.y-r)/(o-r);i.x<t.x+s*(e.x-t.x)&&n++}n%2==0&&(i={x:l.x+(i.x-l.x)*T(.3,.6),y:l.y+(i.y-l.y)*T(.3,.6)}),o.push(i),s.push(this.m[r]),a.push(!this.dir[r])}return new Ze(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new Ze(this.v,this.m,this.midP,this.dir.map(t=>!t),!1,this.sizeX,this.sizeY)}grow(t=1){const{v:e,m:r,dir:i}=this.trim(t),n=e.length,o=2*n,s=new Array(o),a=new Array(o),l=new Array(o),c="out"===y.fill.direction?-90:90;0===He[0].length&&Ue();const h=He[0],u=h.length,f=He[1],m=f.length;let g=0,d=999===t?T(.6,.8):y.fill.bleed_strength;for(let o=0;o<n;o++){const x=e[o],p=e[o+1<n?o+1:0],y=r[o],v=i[o];t<997&&(d=y);const b=(v?c:-c)+5*T(-1,1),_=H(b),w=U(b),R=p.x-x.x,S=p.y-x.y,M=_*R+w*S,E=_*S-w*R,A=h[~~(T(0,1)*u)]*T(.65,1.35)*d;s[g]=x,a[g]=y,l[g]=v,g++,s[g]={x:x.x+.5*R+M*A,y:x.y+.5*S+E*A},a[g]=y+f[~~(T(0,1)*m)],l[g]=v,g++}let x=s,p=a,v=l,b=1024/y.fill.texture_strength;if(b&&g>b){const t=Math.ceil(g/b);x=[],p=[],v=[];for(let e=0;e<g;e+=t)x.push(s[e]),p.push(a[e]),v.push(l[e])}else x.length=g,p.length=g,v.length=g;return new Ze(x,p,this.midP,v,!1,this.sizeX,this.sizeY)}fill(t,i,n){const s=3*n,a=2*i*(1+n/2),l=!1!==b.isBrush;b.isBrush=!1,l&&(b.justChanged=!0),b.blend(t),b.ctx.save(),b.ctx.setTransform(o*et(),o*rt(),o*it(),o*nt(),o*(Q()+e/2),o*(tt()+r/2)),b.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*y.fill.border_strength})`,b.ctx.lineCap="round";const c=Math.max(this.sizeX,this.sizeY),h=T(.15,.7);let u=this.grow();const f=this.scatter(.1).grow().scatter(.75).flipDirs();let m;for(let e=0;e<20;e++){e%4==0&&(u=u.grow()),e%2==0&&(m=[u.grow(1-.0125*e),u.grow(.7-.0125*e),u.grow(.4-.0125*e)]);for(const r of m)r.grow(999).grow(997).layer(e,c,a,t);f.grow(999).flipDirs().grow(997).layer(e,c,1.5*a*s,t),e%2==0&&u.grow(h).grow(999).layer(e,c,2*a,t),e%5!=0&&19!==e||(0!==s&&u.erase(3*s,i),b.blend(t,!0,!1,!0))}b.ctx.restore()}layer(t,e,r,i){b.ctx.lineWidth=D(t,0,24,e/25,e/30,!0),b.ctx.fillStyle=`rgb(${i._getRed()} ${i._getGreen()} ${i._getBlue()} / ${r}%)`,function(t){const e=b.ctx,r=e.getTransform();let i=Infinity,n=Infinity,o=-Infinity,s=-Infinity;e.beginPath(),t.forEach((t,a)=>{const l=Xe(r,t.x,t.y);i=Math.min(i,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),s=Math.max(s,l.y),0===a?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.closePath();const a=De(e,r);b.markDirtyRect(b.mask,{minX:i-a,minY:n-a,maxX:o+a,maxY:s+a})}(this.v),b.ctx.fill(),b.ctx.stroke()}erase(t,e){b.ctx.save();const r=~~(T(80,110)*D(t,0,1,2,3.5)),i=this.sizeX/1.3,n=this.sizeY/1.3,o=Math.min(this.sizeX,this.sizeY)*(1.4-y.fill.bleed_strength),s=.05*o,a=.4*o,{x:l,y:c}=this.midP;b.ctx.globalCompositeOperation="destination-out";const h=(5-D(e,80,100,.3,.7,!0))*t/255;b.ctx.fillStyle=`rgb(255 0 0 / ${h})`,b.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+z(0,i),r=c+z(0,n),o=T(s,a);b.ctx.beginPath(),Oe(e,r,o),t%5!=0&&b.ctx.fill()}b.ctx.globalCompositeOperation="source-over",b.ctx.restore()}}bt.prototype.fill=function(t=!1,e,r,i,n,o){let s=Be();t&&(Fe(t,e),Ge(r,o),$e(i,n)),s.isActive&&(st(),function(t){if(!y.fill.isActive||!y.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");We=t;const e=[...t.vertices],r=~~(.25*e.length*X({1:5,2:10,3:60})),i=y.fill.bleed_strength,n=e.map((t,e)=>(e>r?1:.3)*T(.85,1.2)*i),o=Y(0,e.length),s=[...e.slice(o),...e.slice(0,o)],a=function(t){if(t.length<8)return t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0}).map(e=>e/t.length);const e=[...t];e[0].x===e[e.length-1].x&&e[0].y===e[e.length-1].y||e.push(e[0]);let r=0,i=0,n=0;for(let t=0;t<e.length-1;t++){const o=e[t].x*e[t+1].y-e[t+1].x*e[t].y;r+=o,i+=(e[t].x+e[t+1].x)*o,n+=(e[t].y+e[t+1].y)*o}return r*=.5,r?{x:i/(6*r),y:n/(6*r)}:{x:e[0].x,y:e[0].y}}(s);new Ze(s,n,a,[],!0).fill(y.fill.color,D(y.fill.opacity,0,255,0,1,!0),y.fill.texture_strength)}(this)),(t=>{y.fill={...t}})(s)},_t.prototype.fill=function(t,e,r){Be().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,D(y.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const Ve=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>b.blend(!1,!0),r.postdraw=()=>b.blend(!1,!0);const i=e.push,n=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){i.call(this),st(),Ve.push({fill:{...y.fill},stroke:{...y.stroke},hatch:{...y.hatch},field:{...y.field}})},e.pop=function(){n.call(this),function(){const t=Ve.pop();t&&(y.stroke={...t.stroke},y.field={...t.field},y.hatch={...t.hatch},y.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{k=A(t);for(const t of I)t()})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{L=E(A(t))})(t)}}),t.Plot=_t,t.Polygon=bt,t.Position=at,t.add=le,t.addField=yt,t.arc=function(t,e,r,i,n){const o=Z(i),s=((Z(n)-o)%360+360)%360;if(0===s)return;const a=new _t("curve"),l=Math.max(1,Math.ceil(s/90)),c=s/l,h=Math.PI*r*c/180;for(let t=0;t<l;t++)a.addSegment(o+t*c+90,h,1,!0);a.endPlot(o+s+90,1,!0);const u=t+r*H(o),f=e-r*U(o);a.draw(u,f,1)},t.beginShape=At,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Mt=[e,r],St=new _t(t)},t.box=function(){return[...ie.keys()]},t.circle=function(t,e,r,i=!1){const n=new _t("curve"),o=Math.PI*r,s=T(0,360),a=i?()=>1+.2*i*T():()=>1;for(let t=0;t<4;t++){const e=-90*t+s;n.addSegment(e*a(),o/2*a(),1,!0)}if(i){const t=i*Y(-5,5);n.addSegment(s,Math.abs(t)*(Math.PI/180)*r,1,!0),n.endPlot(t+s,1,!0)}else n.endPlot(s,1,!0);const l=t-r*U(s),c=e-r*H(-s);n.show(l,c,1)},t.clip=function(t){p();const e=function(t){const e=t.a*t.d-t.b*t.c;return Math.abs(e)<1e-12?null:{a:t.d/e,b:-t.b/e,c:-t.c/e,d:t.a/e,tx:(t.c*t.ty-t.d*t.tx)/e,ty:(t.b*t.tx-t.a*t.ty)/e}}(me());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");y.stroke.clipWindow={bounds:de(t),inverse:e}},t.endShape=kt,t.endStroke=function(t,e){if(!St)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");St.endPlot(t,e),St.draw(Mt[0],Mt[1],1),St=!1},t.field=pt,t.fill=Fe,t.fillBleed=Ge,t.fillTexture=$e,t.flowLine=function(t,e,r,i){if(!y.stroke.isActive||!y.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");st(),ye(t,e,r),be(j(i),!1)},t.hatch=Ne,t.hatchArray=Ye,t.hatchStyle=function(t,e="black",r=1){y.hatch.hBrush={brush:t,color:e,weight:r}},t.instance=t=>{x=!0,i=t},t.line=ke,t.listFields=function(){return st(),Array.from(mt.keys())},t.load=g,t.move=function(t,e,r){if(!St)throw new Error("move() called without beginStroke(). Call beginStroke() first.");St.addSegment(t,e,r)},t.noClip=function(){y.stroke.clipWindow=null},t.noField=function(){st(),y.field.isActive=!1},t.noFill=function(){y.fill.isActive=!1},t.noHatch=function(){y.hatch.isActive=!1,y.hatch.hBrush=!1},t.noStroke=function(){y.stroke.isActive=!1},t.pick=ce,t.polygon=function(t){new bt(t).show()},t.rect=function(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),At(0),Pt(t,e),Pt(t+r,e),Pt(t+r,e+i),Pt(t,e+i),kt(!0)},t.refreshField=function(t=0){if(!y.field.isActive||!y.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=mt.get(y.field.current);e.field=xt(e,t)},t.scaleBrushes=function(t){for(const{param:e}of ie.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.set=fe,t.spline=function(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");It(t,e).draw()},t.stroke=he,t.strokeWeight=ue,t.vertex=Pt,t.wRand=X,t.wiggle=function(t=1){pt("hand"),y.field.wiggle=t}},"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).brush={});
+var t,e;t=this,e=function(t){let e,r,i,n,o;const s=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,a=()=>x?i:window.self.p5.instance,l=t=>{t&&"function"==typeof t.remove&&t.remove()},c=()=>n&&n._renderer&&"function"==typeof n._renderer.activeFramebuffer?n._renderer.activeFramebuffer():null,h=()=>({width:Math.max(1,Math.round(e*o)),height:Math.max(1,Math.round(r*o))}),u=t=>{if(!t)return null;const{width:e,height:r}=h(),i=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),n=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),o=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),s=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return o<=i||s<=n?null:{minX:i,minY:n,maxX:o,maxY:s}},f=()=>{const{width:t,height:e}=h();return{minX:0,minY:0,maxX:t,maxY:e}},m=(t,e,r)=>{const i=(t=>{const e=u(t);if(!e)return null;const{height:r}=h();return{x:e.minX,y:r-e.maxY,width:e.maxX-e.minX,height:e.maxY-e.minY}})(e);if(!i)return!1;const n=t.isEnabled(t.SCISSOR_TEST),o=t.getParameter(t.SCISSOR_BOX);t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{r()}finally{n?t.scissor(o[0],o[1],o[2],o[3]):t.disable(t.SCISSOR_TEST)}return!0},g=(t=!1)=>{const o=((t=!1)=>{if(x&&!t)return{renderer:i,width:i.width,height:i.height};if(!t){const t=a();return{renderer:t,width:t.width,height:t.height}}if(s(t)){if(!s(e=t)||e.renderer._pInst!==a())throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.");return{renderer:a(),width:t.width,height:t.height}}var e;return{renderer:t,width:t.width,height:t.height}})(t);if(n=o.renderer,"webgl2"!==n.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");e=o.width,r=o.height,d=!0,n.loaded&&b.load()};let d=!1,x=!1;const p=()=>{d||g()},y={},v=()=>{n?.loaded||(p(),b.load())},b={isBlending:!1,cachedColor:new Object,markDirtyRect(t,e){const r=u(e);var i,n;t&&r&&(t.dirtyRect=(n=r,(i=t.dirtyRect)?n?{minX:Math.min(i.minX,n.minX),minY:Math.min(i.minY,n.minY),maxX:Math.max(i.maxX,n.maxX),maxY:Math.max(i.maxY,n.maxY)}:i:n),t.isDrawn=!0)},markFull(t){t&&(t.dirtyRect=f(),t.isDrawn=!0)},clearMask(t){t&&(t.clear(),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:(t,e)=>t?t.dirtyRect?u(((t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null)(t.dirtyRect,e?2:4)):f():null,captureBlendSource(t){const i=c();if(!i)return n._renderer;var s;(!(s=n.blendSourceFramebuffer)||s.width!==e||s.height!==r||"function"==typeof s.pixelDensity&&s.pixelDensity()!==o)&&(l(n.blendSourceFramebuffer),n.blendSourceFramebuffer=n.createFramebuffer({width:e,height:r,density:o,antialias:!1,depth:!1,stencil:!1}));const a=n.blendSourceFramebuffer;return a.draw(()=>{m(n.drawingContext,t,()=>{n.clear(),n.push(),"function"==typeof n.imageMode&&n.imageMode(n.CENTER??n._renderer?._pInst?.CENTER),n.image(i,0,0,e,r),n.pop()})}),a},load(){o=n.pixelDensity();const t="function"==typeof n.createGraphics?n:n._pInst,i=t.P2D??n.P2D,s=t.WEBGL??n.WEBGL;n.loaded&&n.mask&&n.glMask&&n.mask.width===e&&n.mask.height===r&&n.glMask.width===e&&n.glMask.height===r?(this.mask=n.mask,this.glMask=n.glMask,this.ctx=this.mask.drawingContext,this.mask.dirtyRect??=null,this.mask.isDrawn??=!1,this.glMask.dirtyRect??=null,this.glMask.isDrawn??=!1):(l(n.mask),l(n.glMask),n.mask=t.createGraphics(e,r,i),n.glMask=t.createGraphics(e,r,s),n.loaded=!0,n.shaderProgram??=n.createShader("#version 300 es\n#define GLSLIFY 1\nuniform bool u_flipOutputY;out vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,u_flipOutputY ?-v.y : v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 uv1=vec2(uv.x,1.0-uv.y);vec4 source=texture(u_source,uv1);vec4 maskColor=texture(u_mask,uv1);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=uv1+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.0);}"),this.mask=n.mask,this.mask.pixelDensity(o),this.mask.clear(),this.mask.angleMode(n.DEGREES),this.mask.dirtyRect=null,this.mask.isDrawn=!1,this.ctx=this.mask.drawingContext,this.glMask=n.glMask,this.glMask.pixelDensity(o),this.glMask.clear(),this.glMask.angleMode(this.glMask.DEGREES),this.glMask.drawingContext.lineWidth=0,this.glMask.dirtyRect=null,this.glMask.isDrawn=!1),this.glMask._renderer.uModelMatrix=n._renderer.uModelMatrix},blend(t=!1,e=!1){v();const r=!0===this.isBrush,i=r?this.glMask:this.mask,n=r?this.mask:this.glMask,o=t?._array,s=!!o&&(this.cachedColor[0]!==o[0]||this.cachedColor[1]!==o[1]||this.cachedColor[2]!==o[2]||this.cachedColor[3]!==o[3]);!this.isBlending&&o&&(this.isBlending=!0,this.cachedColor=o,this.glMask.clear()),(e||s)&&(this.justChanged&&(this.applyShader(n,!r),this.justChanged=!1),this.isBlending&&this.applyShader(i,r),o&&(this.cachedColor=o),e&&(this.isBlending=!1))},applyShader(t,i){if(!t?.isDrawn)return;const o=this.getCompositeRect(t,i);if(!o)return void this.clearMask(t);let s=n.shaderProgram;const a=n.drawingContext,l=!!c(),h=this.captureBlendSource(o),u=a.getParameter(a.DEPTH_TEST);a.disable(a.DEPTH_TEST),n.push(),n.translate(0,0),n.shader(s),s.setUniform("u_source",h),s.setUniform("u_isBrush",i),s.setUniform("u_flipOutputY",l),s.setUniform("u_mask",t),s.setUniform("u_color",this.cachedColor),m(a,o,()=>{n.fill(0,0,0,0),n.noStroke(),n.rect(-e/2,-r/2,e,r)}),n.pop(),n.resetShader(),u&&a.enable(a.DEPTH_TEST),this.clearMask(t)}},_=Math.sqrt(3),w=.5*(_-1),R=(3-_)/6,S=t=>0|Math.floor(t),M=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]);function E(t=Math.random){const e=function(t){const e=new Uint8Array(512);for(let t=0;t<256;t++)e[t]=t;for(let r=0;r<255;r++){const i=r+~~(t()*(256-r)),n=e[r];e[r]=e[i],e[i]=n}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>M[t%12*2]),i=new Float64Array(e).map(t=>M[t%12*2+1]);return function(t,n){let o=0,s=0,a=0;const l=(t+n)*w,c=S(t+l),h=S(n+l),u=(c+h)*R,f=t-(c-u),m=n-(h-u);let g,d;f>m?(g=1,d=0):(g=0,d=1);const x=f-g+R,p=m-d+R,y=f-1+2*R,v=m-1+2*R,b=255&c,_=255&h;let M=.5-f*f-m*m;if(M>=0){const t=b+e[_];M*=M,o=M*M*(r[t]*f+i[t]*m)}let E=.5-x*x-p*p;if(E>=0){const t=b+g+e[_+d];E*=E,s=E*E*(r[t]*x+i[t]*p)}let A=.5-y*y-v*v;if(A>=0){const t=b+1+e[_+1];A*=A,a=A*A*(r[t]*y+i[t]*v)}return 70*(o+s+a)}}function A(t,e){let r=new P(t),i=()=>r.next();return i.double=()=>i()+11102230246251565e-32*(2097152*i()|0),i.int32=()=>4294967296*r.next()|0,i.quick=i,i}class P{constructor(t){null==t&&(t=+new Date);let e=4022871197;function r(t){t=String(t);for(let r=0;r<t.length;r++){e+=t.charCodeAt(r);let i=.02519603282416938*e;e=i>>>0,i-=e,i*=e,e=i>>>0,i-=e,e+=4294967296*i}return 2.3283064365386963e-10*(e>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(t),this.s0<0&&(this.s0+=1),this.s1-=r(t),this.s1<0&&(this.s1+=1),this.s2-=r(t),this.s2<0&&(this.s2+=1)}next(){let{c:t,s0:e,s1:r,s2:i}=this,n=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=i,this.s2=n-(this.c=0|n)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let k=A(Math.random());const I=[],C=t=>I.push(t);let L=E(A(Math.random()));const T=(t=0,e=1)=>t+k()*(e-t),N=t=>t[~~(k()*t.length)],Y=(t,e)=>~~T(t,e),z=(t=0,e=1)=>{const r=1-k(),i=k();return Math.sqrt(-2*Math.log(r))*H(360*i)*e+t},X=t=>{let e=0;const r=[];for(const i in t)e+=t[i],r.push({key:i,cumulative:e});const i=k()*e;for(const{key:t,cumulative:e}of r)if(i<e)return isNaN(t)?t:parseInt(t)},D=(t,e,r,i,n,o=!1)=>{let s=i+(t-e)/(r-e)*(n-i);return o?i<n?O(s,i,n):O(s,n,i):s},O=(t,e,r)=>Math.max(Math.min(t,r),e),B=t=>(t%=360)<0?t+360:t,F=1440,G=2*Math.PI/F,$=new Float32Array(F).fill(NaN),W=new Float32Array(F).fill(NaN),H=t=>{const e=~~(4*B(t));let r=$[e];return isNaN(r)&&(r=Math.cos(e*G),$[e]=r),r},U=t=>{const e=~~(4*B(t));let r=W[e];return isNaN(r)&&(r=Math.sin(e*G),W[e]=r),r},j=(t,e=!1)=>{if(e||n&&"function"==typeof n.angleMode&&n.angleMode()===n.RADIANS){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},Z=(t,e=!1)=>e||n&&"function"==typeof n.angleMode&&n.angleMode()===n.RADIANS?180*t/Math.PI:t,V=(t,e,r,i,n)=>{let o=H(n),s=U(n);return{x:o*(r-t)+s*(i-e)+t,y:o*(i-e)-s*(r-t)+e}},K=(t,e,r,i)=>Math.hypot(r-t,i-e),q=(t,e,r,i)=>j(Math.atan2(-(i-e),r-t),!0),J=(t,e,r,i,n=!1)=>{let o=t.x,s=t.y,a=e.x,l=e.y,c=r.x,h=r.y,u=i.x,f=i.y;if(o===a&&s===l||c===u&&h===f)return!1;let m=a-o,g=l-s,d=u-c,x=f-h,p=x*m-d*g;if(0===p)return!1;let y=(d*(s-h)-x*(o-c))/p,v=(m*(s-h)-g*(o-c))/p;return!(!n&&(v<0||v>1))&&{x:o+y*m,y:s+y*g}},Q=()=>n._renderer.uModelMatrix.mat4[12],tt=()=>n._renderer.uModelMatrix.mat4[13],et=()=>n._renderer.uModelMatrix.mat4[0],rt=()=>n._renderer.uModelMatrix.mat4[1],it=()=>n._renderer.uModelMatrix.mat4[4],nt=()=>n._renderer.uModelMatrix.mat4[5];let ot=!1;function st(){ot||(v(),lt=.01*e,ct=-.5*e,ht=-.5*r,ut=Math.round(2*e/lt),ft=Math.round(2*r/lt),yt("hand",(t,e)=>{const r=T(.2,.8),i=Y(5,10);return vt(e,(e,n)=>.5*i*U(r*n*e+Y(15,25))*.2*H(t)+L(e,n)*i*.7)}),yt("curved",(t,e)=>{let r=Y(-10,10);return Y(0,100)%2==0&&(r*=-1),vt(e,(e,i)=>3*D(L(.02*e+.03*t,.02*i+.03*t),0,1,-r,r))}),yt("zigzag",(t,e)=>{let r=Y(-30,-15)+Math.abs(44*U(t));Y(0,100)%2==0&&(r*=-1);let i=r,n=0;for(let t=0;t<ut;t++){for(let r=0;r<ft;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e}),yt("waves",(t,e)=>{const r=Y(10,15)+5*U(t),i=Y(3,6)+3*H(t),n=Y(20,35);return vt(e,(t,e)=>U(r*t)*n*H(e*i)+Y(-3,3))}),yt("seabed",(t,e)=>{const r=T(.4,.8),i=Y(18,26);return vt(e,(e,n)=>1.1*i*U(r*n*e+Y(15,20))*H(t))}),yt("spiral",(t,e)=>{const r=Y(5,10),i=2*Y(0,2)-1,n=Y(65,80),o=Array.from({length:r},()=>({x:T(.1,.9)*ut,y:T(.1,.9)*ft}));return vt(e,(t,e)=>{let r=0,s=0;for(const a of o){const o=t-a.x,l=e-a.y,c=1/(o*o+l*l+1),h=Math.atan2(l,o)*(180/Math.PI),u=i*(h+n)*Math.PI/180;r+=c*Math.cos(u),s+=c*Math.sin(u)}return Math.atan2(s,r)*(180/Math.PI)})}),yt("columns",(t,e)=>{const r=Y(3,8),i=Y(25,45);return vt(e,(t,e)=>U(t*r)*i)}),ot=!0)}class at{constructor(t,e){st(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=at.getColIndex(t),this.rowIdx=at.getRowIndex(e)}reset(){this.plotted=0}isIn(){return y.field.isActive?at.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,i=r,n=this.x+Q(),o=this.y+tt();return n>=-.3*t&&n<=1.3*t&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&y.field.isActive?mt.get(y.field.current).field[this.colIdx][this.rowIdx]*y.field.wiggle:0}moveTo(t,e,r=1){this.movePos(Z(t),e,r)}_moveToDegrees(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,i=1){this.movePos(t,e,r,i)}movePos(t,e,r,i=!1){const n=i||1;if(this.isIn())for(let o=0;o<e/r;o++){const e=this.angle()-(i?t.angle(this.plotted):t);this.update(this.x+r*H(e),this.y+r*U(e)),this.plotted+=r/n}else this.plotted+=r/n}static getRowIndex(t,e=1){const r=t+tt()-ht;return Math.round(r/lt/e)}static getColIndex(t,e=1){const r=t+Q()-ct;return Math.round(r/lt/e)}static isIn(t,e){return t>=0&&e>=0&&t<ut&&e<ft}}y.field={isActive:!1,current:null,wiggle:1};let lt,ct,ht,ut,ft,mt=new Map;const gt=new Set(["degrees","radians"]);function dt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!gt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function xt(t,e){return function(t,e){if("radians"!==e)return t;for(let e=0;e<t.length;e++)for(let r=0;r<t[e].length;r++)t[e][r]=Z(t[e][r],!0);return t}(t.gen(e,new Array(ut).fill(null).map(()=>new Float32Array(ft))),t.angleMode)}function pt(t){if(y.field.wiggle||(y.field.wiggle=1),st(),!mt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(mt.keys()).join(", ")}.`);y.field.isActive=!0,y.field.current=t;const e=mt.get(t);e.field||(e.field=xt(e,0))}function yt(t,e,r={}){mt.set(t,{gen:e,field:null,angleMode:dt(r)})}function vt(t,e){for(let r=0;r<ut;r++)for(let i=0;i<ft;i++)t[r][i]=e(r,i);return t}class bt{constructor(t,e=!1){this.a=t,this.vertices=e?t:t.map(([t,e])=>({x:t,y:e})),this.sides=this.vertices.map((t,e,r)=>[t,r[(e+1)%r.length]]),this._intersectionCache={}}intersect(t){const e=`${t.point1.x},${t.point1.y}-${t.point2.x},${t.point2.y}`;if(this._intersectionCache[e])return this._intersectionCache[e];const r=[];for(const[e,i]of this.sides){const n=J(t.point1,t.point2,e,i);n&&r.push(n)}return this._intersectionCache[e]=r,r}show(){y.stroke&&this.draw(),y.hatch&&this.hatch(),y.fill&&this.fill()}}class _t{constructor(t){this.segments=[],this.angles=[],this.pres=[],this.type=t,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(t=0,e=0,r=1,i=!1){this.angles.length>0&&this.angles.pop(),t=i?(t%360+360)%360:j(t),this.angles.push(t,t),this.pres.push(r),this.segments.push(e),this.length=this.segments.reduce((t,e)=>t+e,0)}endPlot(t=0,e=1,r=!1){t=r?(t%360+360)%360:j(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=j(t)}pressure(t){return t>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,t)}angle(t){return t>this.length?this.angles[this.angles.length-1]:(this.calcIndex(t),"curve"===this.type?this.curving(this.angles,t)+this.dir:this.angles[this.index]+this.dir)}curving(t,e){let r=t[this.index],i=t[this.index+1]??r;return Math.abs(i-r)>180&&(i>r?i=-(360-i):r=-(360-r)),D(e-this.suma,0,this.segments[this.index],r,i,!0)}calcIndex(t){this.index=-1,this.suma=0;let e=0;for(;e<=t;)this.suma=e,e+=this.segments[this.index+1],this.index++;return this.index}genPol(t,i,n=1,o){st();const s=.5,a=[],l=Math.round(this.length/s),c=new at(t+e/2,i+r/2);let h=0,u=0;for(let t=0;t<l;t++){c.plotTo(this,s,s);const t=this.calcIndex(c.plotted);h+=s,(h>=Math.max(this.segments[t]*o*T(.7,1.3),10)||t>=u)&&c.x&&(a.push([c.x-e/2,c.y-r/2]),h=0,t>=u&&u++)}return new bt(a)}show(t,e,r=1){y.stroke&&this.draw(t,e,r),y.hatch&&this.hatch(t,e,r),y.fill&&this.fill(t,e,r)}}let wt,Rt,St,Mt;class Et{constructor(){this.isClosed=!1,this.curvature=Rt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){It(this.vert,this.curvature,this.isClosed).show()}}function At(t=0){Rt=O(t,0,1),wt=new Et}function Pt(t,e,r=1){if(!wt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");wt.vertex(t,e,r)}function kt(t=!1){if(!wt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(wt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(wt.vertex(...wt.vert[0]),wt.isClosed=!0),wt.show(),wt=!1}function It(t,e=.5,r=!1){const i=new _t(0===e?"segments":"curve"),n=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let o,s,a,l=0;for(let c=0;c<t.length-1;c++)if(e>0&&c<t.length-2){const h=t[c],u=t[c+1],f=t[c+2],m=K(h[0],h[1],u[0],u[1]),g=K(u[0],u[1],f[0],f[1]),d=q(h[0],h[1],u[0],u[1]),x=q(u[0],u[1],f[0],f[1]),p=e*Math.min(m,g,.5*Math.min(m,g)),y=Math.max(m,g),v=m-p,b=g-p;if(Math.floor(d)===Math.floor(x)){const e=r&&0===c?0:m-l,n=r?0===c?0:g-a:g;i.addSegment(d,e,h[2],!0),c===t.length-3&&i.addSegment(x,n,u[2],!0),l=0,0===c&&(o=m,a=p,s=t[1],l=0)}else{const e={x:u[0]-p*H(-d),y:u[1]-p*U(-d)},f={x:e.x+y*H(90-d),y:e.y+y*U(90-d)},m={x:u[0]+p*H(-x),y:u[1]+p*U(-x)},g={x:m.x+y*H(90-x),y:m.y+y*U(90-x)},_=J(e,f,m,g,!0),w=K(e.x,e.y,_.x,_.y),R=K(e.x,e.y,m.x,m.y)/2,S=n*w*(2*Math.asin(R/w)*(180/Math.PI))/360,M=r&&0===c?0:v-l,E=c===t.length-3?r?o-p:b:0;i.addSegment(d,M,h[2],!0),i.addSegment(d,isNaN(S)?0:S,h[2],!0),i.addSegment(x,E,u[2],!0),l=p,0===c&&(o=v,a=p,s=[e.x,e.y])}c===t.length-3&&i.endPlot(x,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],n=K(e[0],e[1],r[0],r[1]),o=q(e[0],e[1],r[0],r[1]);i.addSegment(o,n,r[2],!0),c===t.length-2&&i.endPlot(o,1,!0)}i.origin=r&&0!==e?s:t[0]}return i}let Ct,Lt,Tt,Nt,Yt,zt=!1,Xt=0,Dt=0;const Ot={},Bt={};let Ft=1,Gt=0,$t=0,Wt=1,Ht=0,Ut=0,jt=new Float32Array(8192),Zt=0,Vt=2048,Kt=32768;function qt(t,i,n,s){if(Zt>=Vt){Vt*=2;const t=new Float32Array(4*Vt);t.set(jt),jt=t}const a=t-e/2,l=i-r/2,c=4*Zt,h=Ft*a+$t*l+Ht+e/2,u=Gt*a+Wt*l+Ut+r/2,f=o*n*Math.sqrt(Ft*Ft+Gt*Gt)/2;jt[c]=h,jt[c+1]=u,jt[c+2]=f,jt[c+3]=s/255,b.markDirtyRect(b.glMask,{minX:h*o-f-1,minY:u*o-f-1,maxX:h*o+f+1,maxY:u*o+f+1}),Zt++}function Jt(){if(0===Zt)return;b.glMask.isDrawn=!0;const t=y.stroke.color._array;Ct.useProgram(Yt),Ct.enable(Ct.BLEND),Ct.blendFunc(Ct.ONE_MINUS_DST_ALPHA,Ct.ONE),Ct.bindVertexArray(Tt),Ct.bindBuffer(Ct.ARRAY_BUFFER,Nt);const e=16*Zt,r=jt.subarray(0,4*Zt);e>Kt?(Ct.bufferData(Ct.ARRAY_BUFFER,jt,Ct.DYNAMIC_DRAW),Kt=jt.byteLength):Ct.bufferSubData(Ct.ARRAY_BUFFER,0,r),Ct.uniform4f(Bt.u_color,...t),Ct.uniformMatrix4fv(Bt.u_matrix,!1,Lt),Ct.drawArrays(Ct.POINTS,0,Zt),Ct.bindVertexArray(null),Zt=0,b.glMask._renderer._curShader=null}y.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let Qt,te,ee,re,ie=new Map,ne=null,oe={a:1,b:0,c:0,d:1,tx:0,ty:0};function se(){return{...y.stroke}}function ae(t){y.stroke={...t}}function le(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0!==e.vibration&&void 0===e.scatter&&(e.scatter=e.vibration),void 0!==e.definition&&void 0===e.sharpness&&(e.sharpness=e.definition),void 0!==e.quality&&void 0===e.grain&&(e.grain=e.quality),e.pressure=function(t){if(!t||"object"==typeof t&&!Array.isArray(t))return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t};if(Array.isArray(t)){const[e,r,i]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,n=Math.min(e,r,i),o=Math.max(e,r,i),s=o-n||1,[a,l,c]=[(e-n)/s,(r-n)/s,(i-n)/s];return{type:"custom",min_max:[n,o],curve:t=>t<.5?a+(l-a)*t*2:l+(c-l)*(t-.5)*2}}}(e.pressure),"image"===e.type){if(!e.image||!e.image.src)throw new Error(`Brush "${t}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return Le.add(e.image.src),e.tip=()=>{ne.image(Le.tips.get(pe.p.image.src),-pe.p.weight/2,-pe.p.weight/2,pe.p.weight,pe.p.weight)},ie.set(t,{param:e,colors:[],buffers:[]}),Le.load()}ie.set(t,{param:e,colors:[],buffers:[]})}function ce(t){if(!ie.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...ie.keys()].join(", ")}.`);y.stroke.type=t}function he(t,e,r){p(),y.stroke.color=n.color(...arguments),y.stroke.isActive=!0}function ue(t){y.stroke.weight=t}function fe(t,e,r=1){ce(t),he(e),ue(r)}function me(){return{a:et(),b:rt(),c:it(),d:nt(),tx:Q(),ty:tt()}}function ge(t,e,r){return{x:t.a*e+t.c*r+t.tx,y:t.b*e+t.d*r+t.ty}}function de(t){const[e,r,i,n]=t;return{minX:Math.min(e,i),minY:Math.min(r,n),maxX:Math.max(e,i),maxY:Math.max(r,n)}}function xe(t,i){const n=ge(oe,t-e/2,i-r/2);return{x:n.x+e/2,y:n.y+r/2}}const pe={};function ye(t,i,n,o=!1){Ft=et(),Gt=rt(),$t=it(),Wt=nt(),Ht=Q(),Ut=tt(),oe=me(),Qt=new at(t+e/2,i+r/2),te=n,ee=o,ee&&ee.calcIndex(0)}const ve=[];function be(t,i){i||(re=t),function(){pe.seed=999999*T();const{param:t}=ie.get(y.stroke.type)??{};if(!t)return;pe.p=t,ne=b.glMask;const{pressure:i}=t;if(pe.a="custom"!==i.type?T(-1,1):0,pe.b="custom"!==i.type?T(1,1.5):0,pe.cp="custom"!==i.type?T(3,3.5):T(-.2,.2),[pe.min,pe.max]=i.min_max,pe.noiseoffset=.03,!ee){const t=re*Math.PI/180;pe.cos=Math.cos(t),pe.sin=Math.sin(t)}!function(){v();const t=b.glMask.drawingContext,i=!zt||Ct!==t;(i||Xt!==e||Dt!==r)&&(Lt=new Float32Array([2/e,0,0,0,0,-2/r,0,0,0,0,1,0,-1,1,0,1]),Xt=e,Dt=r),i&&(Ct=t,Yt=(t=>{const e=t.createProgram();for(let[r,i]of[[t.VERTEX_SHADER,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}"],[t.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"]]){const n=t.createShader(r);t.shaderSource(n,i),t.compileShader(n),t.attachShader(e,n)}return t.linkProgram(e),e})(Ct),Ct.useProgram(Yt),Ct.enable(Ct.BLEND),Ct.blendFunc(Ct.ONE_MINUS_DST_ALPHA,Ct.ONE),["a_position","a_radius","a_alpha"].forEach(t=>Ot[t]=Ct.getAttribLocation(Yt,t)),["u_matrix","u_color"].forEach(t=>Bt[t]=Ct.getUniformLocation(Yt,t)),Tt=Ct.createVertexArray(),Ct.bindVertexArray(Tt),Nt=Ct.createBuffer(),Ct.bindBuffer(Ct.ARRAY_BUFFER,Nt),Ct.bufferData(Ct.ARRAY_BUFFER,jt.byteLength,Ct.DYNAMIC_DRAW),Kt=jt.byteLength,Ct.enableVertexAttribArray(Ot.a_position),Ct.vertexAttribPointer(Ot.a_position,2,Ct.FLOAT,!1,16,0),Ct.enableVertexAttribArray(Ot.a_radius),Ct.vertexAttribPointer(Ot.a_radius,1,Ct.FLOAT,!1,16,8),Ct.enableVertexAttribArray(Ot.a_alpha),Ct.vertexAttribPointer(Ot.a_alpha,1,Ct.FLOAT,!1,16,12),Ct.bindVertexArray(null),zt=!0)}();const n=!0!==b.isBrush;b.isBrush=!0,n&&(b.justChanged=!0),Me()&&b.blend(y.stroke.color),pe.alpha=Se(),Pe()}();const n=function(){const{param:t}=ie.get(y.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(te*(i?t:1)/n);for(let e=0;e<o;e++)ve.length<2*o&&ve.push(z()),_e(),i?Qt.plotTo(ee,n,n,t,e<10):Qt._moveToDegrees(t,n,n);Jt(),Pe()}function _e(t=!1){if(!Me())return;let e=t||we(),r=D(L(pe.seed+.002*Qt.plotted,0),0,1,1-pe.noiseoffset,1+pe.noiseoffset);switch(pe.p.type){case"spray":!function(t){const e=y.stroke.weight*pe.p.scatter*t+y.stroke.weight*N(ve)*pe.p.scatter/3,r=pe.p.weight*T(.9,1.1),i=Math.ceil(pe.p.grain/t);for(let t=0;t<i;t++){const t=T(.9,1.1),i=t*e*T(-1,1),n=T(-1,1),o=Math.sqrt((t*e)**2-i**2);qt(Qt.x+i,Qt.y+n*o,r,pe.alpha)}}(e*r);break;case"marker":Ee(e*r);break;case"custom":case"image":Ae(e*r,pe.alpha);break;default:!function(t,e=1){const r=(e=D(e,0,1,.9,1.05))*y.stroke.weight*pe.p.scatter*(pe.p.sharpness+(1-pe.p.sharpness)*N(ve)/t);if(T(0,pe.p.grain*t)>.4){let e,i;if(ee)e=.7*r*T(-1,1),i=r*T(-1,1);else{const t=r*T(-1,1),n=.3*r*T(-1,1);e=t*-pe.sin+n*pe.cos,i=t*pe.cos+n*pe.sin}qt(Qt.x+e,Qt.y+i,t*t*pe.p.weight*T(.85,1.15)*y.stroke.weight,Math.max(.9,t)*pe.alpha*T(.75,1.1))}}(e*r)}}function we(){return ee?Re()*ee.pressure(Qt.plotted):Re()}function Re(){return"custom"===pe.p.pressure.type?D(pe.p.pressure.curve(Qt.plotted/te)+pe.cp,0,1,pe.min,pe.max,!0):function(t=.5+pe.p.pressure.curve[0]*pe.a,e=1-pe.p.pressure.curve[1]*pe.b,r=pe.cp,i=pe.min,n=pe.max){const o=t*te,s=(Qt.plotted<o?1.2*e:.8*e)*(te/2);return D(1/(1+Math.pow(Math.abs((Qt.plotted-o)/s),2*r)),0,1,i,n)}()}function Se(){return["default","spray"].includes(pe.p.type)?pe.p.opacity:pe.p.opacity/Math.min(y.stroke.weight,1.3)}function Me(){const t=ge(oe,Qt.x-e/2,Qt.y-r/2);if(y.stroke.clipWindow){const e=ge(y.stroke.clipWindow.inverse,t.x,t.y),{bounds:r}=y.stroke.clipWindow;return e.x>=r.minX&&e.x<=r.maxX&&e.y>=r.minY&&e.y<=r.maxY}let i=.05*e;return t.x>=-e/2-i&&t.x<=e/2+i&&t.y>=-r/2-i&&t.y<=r/2+i}function Ee(t,e=!0,r=pe.alpha){const i=e?y.stroke.weight*pe.p.scatter:0,n=e?i*T(-1,1):0,o=e?i*T(-1,1):0;qt(Qt.x+n,Qt.y+o,y.stroke.weight*pe.p.weight*t,r)}function Ae(t,i,o=!0){b.glMask.isDrawn=!0,ne.push(),ne.noStroke(),y.stroke.color.setAlpha(i),ne.fill(y.stroke.color);const s=o?y.stroke.weight*pe.p.scatter:0,a=o?s*T(-1,1):0,l=o?s*T(-1,1):0;ne.translate(Qt.x+a-e,Qt.y+l-r);const c=y.stroke.weight*t,h=function(t,e){ne.scale(t),"image"===pe.p.type&&ne.tint(255,0,0,e/2);let r=0;return"random"===pe.p.rotate?r=Y(0,360):"natural"===pe.p.rotate&&(r=(ee?-ee.angle(Qt.plotted):-re)+Qt.angle()),ne.rotate(r),r}(c,i);pe.p.tip(ne),ne.pop(),"image"===pe.p.type?function(t,e,r,i){const o=pe.p.weight/2,s=i*Math.PI/180,a=Math.cos(s),l=Math.sin(s),c=Qt.x+t,h=Qt.y+e,u=[[-o,-o],[o,-o],[o,o],[-o,o]];let f=Infinity,m=Infinity,g=-Infinity,d=-Infinity;for(const[t,e]of u){const i=xe(c+r*(a*t-l*e),h+r*(l*t+a*e));f=Math.min(f,i.x*n.pixelDensity()),m=Math.min(m,i.y*n.pixelDensity()),g=Math.max(g,i.x*n.pixelDensity()),d=Math.max(d,i.y*n.pixelDensity())}b.markDirtyRect(b.glMask,{minX:f-2,minY:m-2,maxX:g+2,maxY:d+2})}(a,l,c,h):b.markFull(b.glMask)}function Pe(){if(Me()){let t=we(),e=Se();if("marker"===pe.p.type){for(let r=1;r<10;r++)Ee(t*r/10,!1,5*e);Jt()}else if("custom"===pe.p.type||"image"===pe.p.type)for(let r=1;r<5;r++)Ae(t*r/5,e,!1)}}function ke(t,e,r,i){if(!y.stroke.isActive||!y.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");st();let n=K(t,e,r,i);0!=n&&(ye(t,e,n),be(q(t,e,r,i),!1))}C(()=>{ve.length=0});const Ie=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],Ce=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of Ce){let e={};for(let r=0;r<t[1].length;r++)e[Ie[r]]=t[1][r];le(t[0],e)}le("diamond",{type:"custom",weight:.78,scatter:.1,opacity:17,spacing:1.3,pressure:[1.2,.82],rotate:"none",tip:t=>{t.rotate(45),t.rect(-4,-4,8,8),t.rect(2,2,3,3)}}),bt.prototype.draw=function(t=!1,e,r){let i=se();if(t&&fe(t,e,r),i.isActive)for(let t of this.sides)ke(t[0].x,t[0].y,t[1].x,t[1].y);ae(i)},_t.prototype.draw=function(t,e,r){se().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,i){st(),ye(e,r,t.length,t),be(i,!0)}(this,t,e,r))};const Le={tips:new Map,add(t){this.tips.set(t,!1)},imageToWhite(t){t.loadPixels();for(let e=0;e<4*t.width*t.height;e+=4){let r=(t.pixels[e]+t.pixels[e+1]+t.pixels[e+2])/3;t.pixels[e]=t.pixels[e+1]=t.pixels[e+2]=255,t.pixels[e+3]=255-r}t.updatePixels()},async load(){const t=[...this.tips.keys()].filter(t=>!this.tips.get(t));await Promise.all(t.map(t=>new Promise((e,r)=>{const i=new window.Image;i.onload=()=>{const r=n.createImage(i.naturalWidth,i.naturalHeight);r.drawingContext.drawImage(i,0,0),Le.imageToWhite(r),this.tips.set(t,r),e()},i.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),i.src=t})))}};function Te(){return{...y.hatch}}function Ne(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let i=y.hatch;i.isActive=!0,i.dist=t,i.angle=Z(e),i.options=r}function Ye(t){let e=y.hatch.dist,r=(y.hatch.angle%180+180)%180,i=y.hatch.options,n=se();y.hatch.hBrush&&fe(...Object.values(y.hatch.hBrush)),Array.isArray(t)||(t=[t]);const o=function(t){let e={minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity};for(let r of t){const t=ze(r);e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY)}return e}(t);let s=new bt([[o.minX,o.minY],[o.maxX,o.minY],[o.maxX,o.maxY],[o.minX,o.maxY]]),a=r<=90&&r>=0?o.minY:o.maxY,l=i.gradient?D(i.gradient,0,1,1,1.1,!0):1,c=[],h=0,u=e,f=t=>({point1:{x:o.minX+u*t*H(90-r),y:a+u*t*U(90-r)},point2:{x:o.minX+u*t*H(90-r)+H(-r),y:a+u*t*U(90-r)+U(-r)}});for(;s.intersect(f(h)).length>0;){let e=[];for(let r of t)e.push(r.intersect(f(h)));c[h]=e.flat().sort((t,e)=>t.x===e.x?t.y-e.y:t.x-e.x),u*=l,h++}let m=c.filter(t=>void 0!==t[0]),g=i.rand||0;for(let t=0;t<m.length;t++){let r=m[t],n=t>0&&i.continuous;for(let i=0;i<r.length-1;i+=2)0!==g&&(r[i].x+=g*e*T(-1,1),r[i].y+=g*e*T(-1,1),r[i+1].x+=g*e*T(-1,1),r[i+1].y+=g*e*T(-1,1)),ke(r[i].x,r[i].y,r[i+1].x,r[i+1].y),n&&ke(m[t-1][1].x,m[t-1][1].y,r[i].x,r[i].y)}ae(n)}function ze(t){if(t._boundingBox)return t._boundingBox;let e=Infinity,r=Infinity,i=-Infinity,n=-Infinity;for(let o=0;o<t.a.length;o++){const[s,a]=t.a[o];s<e&&(e=s),s>i&&(i=s),a<r&&(r=a),a>n&&(n=a)}return t._boundingBox={minX:e,minY:r,maxX:i,maxY:n},t._boundingBox}function Xe(t,e,r){return{x:t.a*e+t.c*r+t.e,y:t.b*e+t.d*r+t.f}}function De(t,e){const r=t.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(e.a,e.c),Math.hypot(e.b,e.d))/2}function Oe(t,e,r){const i=2*Math.PI,n=b.ctx,o=n.getTransform(),s=r/2,a=Xe(o,t,e),l=s*Math.hypot(o.a,o.c),c=s*Math.hypot(o.b,o.d),h=De(n,o);b.markDirtyRect(b.mask,{minX:a.x-l-h,minY:a.y-c-h,maxX:a.x+l+h,maxY:a.y+c+h}),n.moveTo(t+s,e),n.arc(t,e,s,0,i)}y.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},bt.prototype.hatch=function(t=!1,e,r){let i=Te();t&&Ne(t,e,r),i.isActive&&Ye(this),function(t){y.hatch={...t}}(i)},_t.prototype.hatch=function(t,e,r){Te().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},y.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Be=()=>({...y.fill});function Fe(t,e,r,i){y.fill.opacity=(arguments.length<4?e:i)||150,y.fill.color=arguments.length<3?n.color(t):n.color(t,e,r),y.fill.isActive=!0}function Ge(t,e="out"){y.fill.bleed_strength=O(t,0,1),y.fill.direction=e}function $e(t=.4,e=.4){y.fill.texture_strength=O(t,0,1),y.fill.border_strength=O(e,0,1)}let We;const He=[[],[]];function Ue(){for(let t=0;t<512;t++)He[0][t]=z(.5,.2),He[1][t]=z(0,.02)}function je(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}C(Ue);class Ze{constructor(t,e,r,i=[],n=!1,o,s){if(this.v=t,this.m=e,this.dir=i,this.midP=r,n){let e=0,i=0;const n=[];for(let o=0;o<t.length;o++){const s=Math.abs(r.x-t[o].x),a=Math.abs(r.y-t[o].y);e=Math.max(e,s),i=Math.max(i,a);const l=t[o],c=t[(o+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=V(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};n.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=i,this.dir=Array(t.length),n.forEach((t,e)=>{let r=0;for(const e of We.intersect(t.ray))je(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=T(-.6,.6)*e,s=T(-.6,.6)*i;this.midP={x:r.x+o,y:r.y+s}}else this.sizeX=o,this.sizeY=s}trim(t=1){if(t>=1||t<0||this.v.length<=8)return{v:[...this.v],m:[...this.m],dir:[...this.dir]};const e=~~((1-t)*this.v.length),r=~~(this.v.length/2-e/2),i=[...this.v],n=[...this.m],o=[...this.dir];return i.splice(r,e),n.splice(r,e),o.splice(r,e),{v:i,m:n,dir:o}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),i=[],n=e/r;for(let t=0;t<r;t++)i.push(~~(t*n+T(0,.8*n)));const o=[],s=[],a=[],l=this.midP,c=We.sides;for(const t of i){const r=t%e;let i=this.v[r],n=0;for(const[t,e]of c){const r=t.y,o=e.y;if(r>i.y==o>i.y)continue;const s=(i.y-r)/(o-r);i.x<t.x+s*(e.x-t.x)&&n++}n%2==0&&(i={x:l.x+(i.x-l.x)*T(.3,.6),y:l.y+(i.y-l.y)*T(.3,.6)}),o.push(i),s.push(this.m[r]),a.push(!this.dir[r])}return new Ze(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new Ze(this.v,this.m,this.midP,this.dir.map(t=>!t),!1,this.sizeX,this.sizeY)}grow(t=1){const{v:e,m:r,dir:i}=this.trim(t),n=e.length,o=2*n,s=new Array(o),a=new Array(o),l=new Array(o),c="out"===y.fill.direction?-90:90;0===He[0].length&&Ue();const h=He[0],u=h.length,f=He[1],m=f.length;let g=0,d=999===t?T(.6,.8):y.fill.bleed_strength;for(let o=0;o<n;o++){const x=e[o],p=e[o+1<n?o+1:0],y=r[o],v=i[o];t<997&&(d=y);const b=(v?c:-c)+5*T(-1,1),_=H(b),w=U(b),R=p.x-x.x,S=p.y-x.y,M=_*R+w*S,E=_*S-w*R,A=h[~~(T(0,1)*u)]*T(.65,1.35)*d;s[g]=x,a[g]=y,l[g]=v,g++,s[g]={x:x.x+.5*R+M*A,y:x.y+.5*S+E*A},a[g]=y+f[~~(T(0,1)*m)],l[g]=v,g++}let x=s,p=a,v=l,b=1024/y.fill.texture_strength;if(b&&g>b){const t=Math.ceil(g/b);x=[],p=[],v=[];for(let e=0;e<g;e+=t)x.push(s[e]),p.push(a[e]),v.push(l[e])}else x.length=g,p.length=g,v.length=g;return new Ze(x,p,this.midP,v,!1,this.sizeX,this.sizeY)}fill(t,i,n){const s=3*n,a=2*i*(1+n/2),l=!1!==b.isBrush;b.isBrush=!1,l&&(b.justChanged=!0),b.blend(t),b.ctx.save(),b.ctx.setTransform(o*et(),o*rt(),o*it(),o*nt(),o*(Q()+e/2),o*(tt()+r/2)),b.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*y.fill.border_strength})`,b.ctx.lineCap="round";const c=Math.max(this.sizeX,this.sizeY),h=T(.15,.7);let u=this.grow();const f=this.scatter(.1).grow().scatter(.75).flipDirs();let m;for(let e=0;e<20;e++){e%4==0&&(u=u.grow()),e%2==0&&(m=[u.grow(1-.0125*e),u.grow(.7-.0125*e),u.grow(.4-.0125*e)]);for(const r of m)r.grow(999).grow(997).layer(e,c,a,t);f.grow(999).flipDirs().grow(997).layer(e,c,1.5*a*s,t),e%2==0&&u.grow(h).grow(999).layer(e,c,2*a,t),e%5!=0&&19!==e||(0!==s&&u.erase(3*s,i),b.blend(t,!0,!1,!0))}b.ctx.restore()}layer(t,e,r,i){b.ctx.lineWidth=D(t,0,24,e/25,e/30,!0),b.ctx.fillStyle=`rgb(${i._getRed()} ${i._getGreen()} ${i._getBlue()} / ${r}%)`,function(t){const e=b.ctx,r=e.getTransform();let i=Infinity,n=Infinity,o=-Infinity,s=-Infinity;e.beginPath(),t.forEach((t,a)=>{const l=Xe(r,t.x,t.y);i=Math.min(i,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),s=Math.max(s,l.y),0===a?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.closePath();const a=De(e,r);b.markDirtyRect(b.mask,{minX:i-a,minY:n-a,maxX:o+a,maxY:s+a})}(this.v),b.ctx.fill(),b.ctx.stroke()}erase(t,e){b.ctx.save();const r=~~(T(80,110)*D(t,0,1,2,3.5)),i=this.sizeX/1.3,n=this.sizeY/1.3,o=Math.min(this.sizeX,this.sizeY)*(1.4-y.fill.bleed_strength),s=.05*o,a=.4*o,{x:l,y:c}=this.midP;b.ctx.globalCompositeOperation="destination-out";const h=(5-D(e,80,100,.3,.7,!0))*t/255;b.ctx.fillStyle=`rgb(255 0 0 / ${h})`,b.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+z(0,i),r=c+z(0,n),o=T(s,a);b.ctx.beginPath(),Oe(e,r,o),t%5!=0&&b.ctx.fill()}b.ctx.globalCompositeOperation="source-over",b.ctx.restore()}}bt.prototype.fill=function(t=!1,e,r,i,n,o){let s=Be();t&&(Fe(t,e),Ge(r,o),$e(i,n)),s.isActive&&(st(),function(t){if(!y.fill.isActive||!y.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");We=t;const e=[...t.vertices],r=~~(.25*e.length*X({1:5,2:10,3:60})),i=y.fill.bleed_strength,n=e.map((t,e)=>(e>r?1:.3)*T(.85,1.2)*i),o=Y(0,e.length),s=[...e.slice(o),...e.slice(0,o)],a=function(t){if(t.length<8)return t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0}).map(e=>e/t.length);const e=[...t];e[0].x===e[e.length-1].x&&e[0].y===e[e.length-1].y||e.push(e[0]);let r=0,i=0,n=0;for(let t=0;t<e.length-1;t++){const o=e[t].x*e[t+1].y-e[t+1].x*e[t].y;r+=o,i+=(e[t].x+e[t+1].x)*o,n+=(e[t].y+e[t+1].y)*o}return r*=.5,r?{x:i/(6*r),y:n/(6*r)}:{x:e[0].x,y:e[0].y}}(s);new Ze(s,n,a,[],!0).fill(y.fill.color,D(y.fill.opacity,0,255,0,1,!0),y.fill.texture_strength)}(this)),(t=>{y.fill={...t}})(s)},_t.prototype.fill=function(t,e,r){Be().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,D(y.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const Ve=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>b.blend(!1,!0),r.postdraw=()=>b.blend(!1,!0);const i=e.push,n=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){i.call(this),st(),Ve.push({fill:{...y.fill},stroke:{...y.stroke},hatch:{...y.hatch},field:{...y.field}})},e.pop=function(){n.call(this),function(){const t=Ve.pop();t&&(y.stroke={...t.stroke},y.field={...t.field},y.hatch={...t.hatch},y.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{k=A(t);for(const t of I)t()})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{L=E(A(t))})(t)}}),t.Plot=_t,t.Polygon=bt,t.Position=at,t.add=le,t.addField=yt,t.arc=function(t,e,r,i,n){const o=Z(i),s=((Z(n)-o)%360+360)%360;if(0===s)return;const a=new _t("curve"),l=Math.max(1,Math.ceil(s/90)),c=s/l,h=Math.PI*r*c/180;for(let t=0;t<l;t++)a.addSegment(o+t*c+90,h,1,!0);a.endPlot(o+s+90,1,!0);const u=t+r*H(o),f=e-r*U(o);a.draw(u,f,1)},t.beginShape=At,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Mt=[e,r],St=new _t(t)},t.box=function(){return[...ie.keys()]},t.circle=function(t,e,r,i=!1){const n=new _t("curve"),o=Math.PI*r,s=T(0,360),a=i?()=>1+.2*i*T():()=>1;for(let t=0;t<4;t++){const e=-90*t+s;n.addSegment(e*a(),o/2*a(),1,!0)}if(i){const t=i*Y(-5,5);n.addSegment(s,Math.abs(t)*(Math.PI/180)*r,1,!0),n.endPlot(t+s,1,!0)}else n.endPlot(s,1,!0);const l=t-r*U(s),c=e-r*H(-s);n.show(l,c,1)},t.clip=function(t){p();const e=function(t){const e=t.a*t.d-t.b*t.c;return Math.abs(e)<1e-12?null:{a:t.d/e,b:-t.b/e,c:-t.c/e,d:t.a/e,tx:(t.c*t.ty-t.d*t.tx)/e,ty:(t.b*t.tx-t.a*t.ty)/e}}(me());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");y.stroke.clipWindow={bounds:de(t),inverse:e}},t.endShape=kt,t.endStroke=function(t,e){if(!St)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");St.endPlot(t,e),St.draw(Mt[0],Mt[1],1),St=!1},t.field=pt,t.fill=Fe,t.fillBleed=Ge,t.fillTexture=$e,t.flowLine=function(t,e,r,i){if(!y.stroke.isActive||!y.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");st(),ye(t,e,r),be(j(i),!1)},t.hatch=Ne,t.hatchArray=Ye,t.hatchStyle=function(t,e="black",r=1){y.hatch.hBrush={brush:t,color:e,weight:r}},t.instance=t=>{x=!0,i=t},t.line=ke,t.listFields=function(){return st(),Array.from(mt.keys())},t.load=g,t.move=function(t,e,r){if(!St)throw new Error("move() called without beginStroke(). Call beginStroke() first.");St.addSegment(t,e,r)},t.noClip=function(){y.stroke.clipWindow=null},t.noField=function(){st(),y.field.isActive=!1},t.noFill=function(){y.fill.isActive=!1},t.noHatch=function(){y.hatch.isActive=!1,y.hatch.hBrush=!1},t.noStroke=function(){y.stroke.isActive=!1},t.pick=ce,t.polygon=function(t){new bt(t).show()},t.rect=function(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),At(0),Pt(t,e),Pt(t+r,e),Pt(t+r,e+i),Pt(t,e+i),kt(!0)},t.refreshField=function(t=0){if(!y.field.isActive||!y.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=mt.get(y.field.current);e.field=xt(e,t)},t.scaleBrushes=function(t){for(const{param:e}of ie.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.set=fe,t.spline=function(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");It(t,e).draw()},t.stroke=he,t.strokeWeight=ue,t.vertex=Pt,t.wRand=X,t.wiggle=function(t=1){pt("hand"),y.field.wiggle=t}},"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).brush={});
//# sourceMappingURL=p5.brush.js.map
diff --git a/dist/p5.brush.js.map b/dist/p5.brush.js.map
index 7ea3e49..6b5db67 100644
--- a/dist/p5.brush.js.map
+++ b/dist/p5.brush.js.map
@@ -1 +1 @@
-{"version":3,"file":"p5.brush.js","sources":["../src/core/color.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/flowfield.js","../src/core/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/core/gl/utils.js","../src/hatch/hatch.js","../src/core/mask.js","../src/fill/fill.js","../src/core/save.js","../src/index.js"],"sourcesContent":["import vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Section: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties\n\nconst isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\nconst getSketchRenderer = () =>\n _isInstanced ? Instance : window.self.p5.instance;\n\nconst isSupportedFramebufferTarget = (target) =>\n isFramebufferTarget(target) && target.renderer._pInst === getSketchRenderer();\n\nconst resolveTarget = (buffer = false) => {\n if (_isInstanced && !buffer) {\n return {\n renderer: Instance,\n width: Instance.width,\n height: Instance.height,\n };\n }\n\n if (!buffer) {\n const renderer = getSketchRenderer();\n return {\n renderer,\n width: renderer.width,\n height: renderer.height,\n };\n }\n\n if (isFramebufferTarget(buffer)) {\n if (!isSupportedFramebufferTarget(buffer)) {\n throw new Error(\n \"p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.\",\n );\n }\n\n return {\n renderer: getSketchRenderer(),\n width: buffer.width,\n height: buffer.height,\n };\n }\n\n return {\n renderer: buffer,\n width: buffer.width,\n height: buffer.height,\n };\n};\n\nconst removeTargetBuffer = (buffer) => {\n if (buffer && typeof buffer.remove === \"function\") {\n buffer.remove();\n }\n};\n\nconst getGraphicsFactory = () =>\n typeof Renderer.createGraphics === \"function\" ? Renderer : Renderer._pInst;\n\nconst getActiveFramebuffer = () =>\n Renderer &&\n Renderer._renderer &&\n typeof Renderer._renderer.activeFramebuffer === \"function\"\n ? Renderer._renderer.activeFramebuffer()\n : null;\n\nconst needsBlendSourceFramebuffer = (framebuffer) =>\n !framebuffer ||\n framebuffer.width !== Cwidth ||\n framebuffer.height !== Cheight ||\n (typeof framebuffer.pixelDensity === \"function\" &&\n framebuffer.pixelDensity() !== Density);\n\nconst needsMixBuffers = () =>\n !Renderer.mask ||\n !Renderer.glMask ||\n Renderer.mask.width !== Cwidth ||\n Renderer.mask.height !== Cheight ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight;\n\nconst DIRTY_BRUSH_PADDING = 2;\nconst DIRTY_FILL_PADDING = 4;\n\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n\n const { width, height } = getTargetPixelSize();\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\nconst unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return { minX: 0, minY: 0, maxX: width, maxY: height };\n};\n\nconst toScissorBox = (rect) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: height - normalized.maxY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\nconst withScissor = (gl, rect, draw) => {\n const box = toScissorBox(rect);\n if (!box) return false;\n\n const wasEnabled = gl.isEnabled(gl.SCISSOR_TEST);\n const prevBox = gl.getParameter(gl.SCISSOR_BOX);\n\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n if (wasEnabled) {\n gl.scissor(prevBox[0], prevBox[1], prevBox[2], prevBox[3]);\n } else {\n gl.disable(gl.SCISSOR_TEST);\n }\n }\n\n return true;\n};\n\n/**\n * Loads and initializes a canvas for the drawing system.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.\n * Pass a framebuffer only while drawing inside its begin()/end() or draw() scope.\n * Framebuffers created from p5.Graphics are not supported.\n */\nexport const load = (buffer = false) => {\n const target = resolveTarget(buffer);\n Renderer = target.renderer;\n\n // Check if Rendrer is webgl and throw error if it's not\n\n if (Renderer.webglVersion !== \"webgl2\") {\n throw new Error(\"p5.brush requires a WEBGL canvas\");\n }\n\n Cwidth = target.width;\n Cheight = target.height;\n\n _isReady = true;\n if (Renderer.loaded) Mix.load();\n};\n\nlet _isReady = false;\nlet _isInstanced = false;\n\n/**\n * Ensures the drawing system is ready before any operation.\n */\nexport const isCanvasReady = () => {\n if (!_isReady) load();\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n\nexport const instance = (inst) => {\n _isInstanced = true;\n Instance = inst;\n};\n\n\n// =============================================================================\n// Section: Color Blending\n// =============================================================================\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\nconst disable = false;\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: new Object(),\n\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n markFull(target) {\n if (!target) return;\n\n target.dirtyRect = getFullDirtyRect();\n target.isDrawn = true;\n },\n\n clearMask(target) {\n if (!target) return;\n\n target.clear();\n target.isDrawn = false;\n target.dirtyRect = null;\n },\n\n getCompositeRect(target, isBrushMask) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n\n return normalizeDirtyRect(\n expandDirtyRect(\n target.dirtyRect,\n isBrushMask ? DIRTY_BRUSH_PADDING : DIRTY_FILL_PADDING,\n ),\n );\n },\n\n captureBlendSource(dirtyRect) {\n const activeFramebuffer = getActiveFramebuffer();\n\n if (!activeFramebuffer) return Renderer._renderer;\n\n if (needsBlendSourceFramebuffer(Renderer.blendSourceFramebuffer)) {\n removeTargetBuffer(Renderer.blendSourceFramebuffer);\n Renderer.blendSourceFramebuffer = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n const source = Renderer.blendSourceFramebuffer;\n\n source.draw(() => {\n withScissor(Renderer.drawingContext, dirtyRect, () => {\n Renderer.clear();\n Renderer.push();\n if (typeof Renderer.imageMode === \"function\") {\n Renderer.imageMode(\n Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER,\n );\n }\n Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n });\n });\n\n return source;\n },\n\n /**\n * Loads necessary resources and prepares the mask buffer and shader for colour blending.\n */\n load() {\n Density = Renderer.pixelDensity();\n const graphicsFactory = getGraphicsFactory();\n const p2dMode = graphicsFactory.P2D ?? Renderer.P2D;\n const webglMode = graphicsFactory.WEBGL ?? Renderer.WEBGL;\n\n if (!Renderer.loaded || needsMixBuffers()) {\n removeTargetBuffer(Renderer.mask);\n removeTargetBuffer(Renderer.glMask);\n\n Renderer.mask = graphicsFactory.createGraphics(Cwidth, Cheight, p2dMode);\n Renderer.glMask = graphicsFactory.createGraphics(\n Cwidth,\n Cheight,\n webglMode,\n );\n Renderer.loaded = true;\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n\n this.mask = Renderer.mask;\n this.mask.pixelDensity(Density);\n this.mask.clear();\n this.mask.angleMode(Renderer.DEGREES);\n this.mask.dirtyRect = null;\n this.mask.isDrawn = false;\n\n this.ctx = this.mask.drawingContext;\n\n this.glMask = Renderer.glMask;\n this.glMask.pixelDensity(Density);\n this.glMask.clear();\n this.glMask.angleMode(this.glMask.DEGREES);\n this.glMask.drawingContext.lineWidth = 0;\n this.glMask.dirtyRect = null;\n this.glMask.isDrawn = false;\n } else {\n this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\n this.mask.dirtyRect ??= null;\n this.mask.isDrawn ??= false;\n this.glMask.dirtyRect ??= null;\n this.glMask.isDrawn ??= false;\n }\n\n // Link Matrix of GL mask to main Renderer\n this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;\n },\n\n /**\n * Applies blending effects using the current color and mask.\n * @param {Color} _color - Color to blend.\n * @param {boolean} _isLast - If this is the final blend operation.\n * @param {boolean} _isImg - If blending an image.\n * @param {boolean} _isFillLayer - If this is a special case.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n\n const activeIsBrush = this.isBrush === true;\n const mask = activeIsBrush ? this.glMask : this.mask;\n const no_mask = activeIsBrush ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor[0] !== nextColor[0] ||\n this.cachedColor[1] !== nextColor[1] ||\n this.cachedColor[2] !== nextColor[2] ||\n this.cachedColor[3] !== nextColor[3]);\n\n // Perf gains are minimal but let's keep it for now\n if (disable) {\n if (_isLast && mask.isDrawn) {\n Renderer.push();\n Renderer.translate(0, 0);\n Renderer.image(mask, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n mask.isDrawn = false;\n }\n return;\n }\n\n // Initialize blending if not already active\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Force p5 to bind its internal render target for glMask,\n // so the first glDraw() writes to the correct framebuffer.\n this.glMask.clear();\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(no_mask, !activeIsBrush);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, activeIsBrush);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) this.isBlending = false;\n }\n },\n\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n let shader = Renderer.shaderProgram;\n const gl = Renderer.drawingContext;\n const targetIsFramebuffer = !!getActiveFramebuffer();\n const source = this.captureBlendSource(dirtyRect);\n\n // Disable depth test for this compositing draw so the fullscreen rect\n // does not write Z=0 into the depth buffer — which would cause any\n // subsequent p5 geometry drawn at the same depth to fail depth testing\n // and become invisible.\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n gl.disable(gl.DEPTH_TEST);\n\n Renderer.push();\n Renderer.translate(0, 0);\n\n // Use the blend shader for rendering\n Renderer.shader(shader);\n\n // Set shader uniforms\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n shader.setUniform(\"u_flipOutputY\", targetIsFramebuffer);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", this.cachedColor);\n\n // Draw a rectangle covering the whole canvas to apply the shader\n withScissor(gl, dirtyRect, () => {\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n });\n\n // Finish and clear mask\n Renderer.pop();\n Renderer.resetShader();\n\n // Restore depth test state\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n this.clearMask(mask);\n },\n};\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { Renderer } from \"./color.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n const usesRadians =\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS);\n // Only if Renderer.angleMode() is set to radians\n if (usesRadians) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS)\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","import { isMixReady, Cwidth, Cheight, State, Renderer } from \"./color.js\";\nimport { randInt, noise, rr, sin, cos, map, toDegreesSigned } from \"./utils.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n/**\n * The `Matrix` object exposes the current 2D affine transform from p5's model matrix.\n * mat4 layout (column-major 4x4):\n * [0]=a [1]=b [4]=c [5]=d [12]=tx [13]=ty\n * where the 2D transform of a point (x,y) is: (a*x + c*y + tx, b*x + d*y + ty)\n */\nexport const Matrix = {\n x: () => Renderer._renderer.uModelMatrix.mat4[12],\n y: () => Renderer._renderer.uModelMatrix.mat4[13],\n a: () => Renderer._renderer.uModelMatrix.mat4[0],\n b: () => Renderer._renderer.uModelMatrix.mat4[1],\n c: () => Renderer._renderer.uModelMatrix.mat4[4],\n d: () => Renderer._renderer.uModelMatrix.mat4[5],\n};\n\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n this.colIdx = Position.getColIndex(x);\n this.rowIdx = Position.getRowIndex(y);\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + Matrix.x();\n const y = this.y + Matrix.y();\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle() {\n return this.isIn() && State.field.isActive\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current p5 angle mode.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1) {\n this.movePos(_plot, _length, _step_length, _scale);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n for (let i = 0; i < _length / _step; i++) {\n const angle =\n this.angle() - (_scale ? _dirPlot.angle(this.plotted) : _dirPlot);\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + Matrix.y() - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + Matrix.x() - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr(0.2, 0.8),\n ba = randInt(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt(15, 25));\n return 0.2 * angle * cos(t) + noise(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt(-10, 10);\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt(-30, -15) + Math.abs(44 * sin(t));\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt(10, 15) + 5 * sin(t),\n cr = randInt(3, 6) + 3 * cos(t),\n ba = randInt(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr(0.4, 0.8),\n ba = randInt(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt(5, 10);\n const dir = randInt(0, 2) * 2 - 1;\n const offset = randInt(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr(0.1, 0.9) * num_columns,\n y: rr(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt(3, 8),\n amp = randInt(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.stroke) this.draw();\n if (State.hatch) this.hatch();\n if (State.fill) this.fill();\n }\n}\n","import { State, Cwidth, Cheight } from \"./color.js\";\nimport { toDegrees, map, rr } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = 0.5;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n const maxSize = Math.max(this.segments[idx] * _side * rr(0.7, 1.3), 10);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.stroke) this.draw(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n }\n}\n","import {\n rr,\n randInt,\n sin,\n cos,\n toDegrees,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current p5 angle mode.\n * @param {number} end - End angle in the current p5 angle mode.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module provides functions for rendering shapes (circles and squares)\n * using WebGL2. It initializes the WebGL context and shader programs, prepares buffers,\n * and implements drawing routines based on queued drawing primitives. The module uses\n * an orthographic projection to map canvas coordinates to clip space and supports adjustable\n * blending for translucent effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\n State,\n} from \"../core/color.js\";\nimport { Matrix } from \"../core/flowfield.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n projMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0;\n\n/**\n * Snapshots the current p5 model matrix. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n _ma = Matrix.a();\n _mb = Matrix.b();\n _mc = Matrix.c();\n _md = Matrix.d();\n _mx = Matrix.x();\n _my = Matrix.y();\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n\n const nextGl = Mix.glMask.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n projMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n -2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * p5's current model matrix so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - Cwidth / 2;\n const py = y - Cheight / 2;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + Cwidth / 2;\n const screenY = _mb * px + _md * py + _my + Cheight / 2;\n const radius =\n (Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n Mix.markDirtyRect(Mix.glMask, {\n minX: screenX * Density - radius - 1,\n minY: screenY * Density - radius - 1,\n maxX: screenX * Density + radius + 1,\n maxY: screenY * Density + radius + 1,\n });\n\n circleCount++;\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader (p5 drawing may have switched programs)\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, projMatrix);\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing p5's _curShader tracking.\n // Reset it to null so p5 is forced to re-activate its own shader next time\n // it draws — otherwise p5 skips gl.useProgram() and sets uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n Mix.glMask._renderer._curShader = null;\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n State,\n Renderer,\n isCanvasReady,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed,\n} from \"../core/utils.js\";\nimport { Position, Matrix, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { isReady, glDraw, circle, snapshotMatrix } from \"./gl_draw.js\";\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n clipWindow: null,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nlet Mask = null;\nlet _strokeTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n tx: 0,\n ty: 0,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { type, min_max, curve } — old internal format, passed through unchanged\n */\nfunction normalizePressure(p) {\n if (!p || (typeof p === \"object\" && !Array.isArray(p))) return p;\n if (typeof p === \"function\")\n return { type: \"custom\", min_max: [0, 1], curve: p };\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n params.tip = () => {\n Mask.image(\n T.tips.get(current.p.image.src),\n -current.p.weight / 2,\n -current.p.weight / 2,\n current.p.weight,\n current.p.weight,\n );\n };\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = Renderer.color(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\nfunction snapshotTransform() {\n return {\n a: Matrix.a(),\n b: Matrix.b(),\n c: Matrix.c(),\n d: Matrix.d(),\n tx: Matrix.x(),\n ty: Matrix.y(),\n };\n}\n\nfunction invertTransform(transform) {\n const det = transform.a * transform.d - transform.b * transform.c;\n if (Math.abs(det) < 1e-12) return null;\n\n return {\n a: transform.d / det,\n b: -transform.b / det,\n c: -transform.c / det,\n d: transform.a / det,\n tx: (transform.c * transform.ty - transform.d * transform.tx) / det,\n ty: (transform.b * transform.tx - transform.a * transform.ty) / det,\n };\n}\n\nfunction transformPoint(transform, x, y) {\n return {\n x: transform.a * x + transform.c * y + transform.tx,\n y: transform.b * x + transform.d * y + transform.ty,\n };\n}\n\nfunction normalizeRegion(region) {\n const [x1, y1, x2, y2] = region;\n return {\n minX: Math.min(x1, x2),\n minY: Math.min(y1, y2),\n maxX: Math.max(x1, x2),\n maxY: Math.max(y1, y2),\n };\n}\n\nfunction currentPointInUserSpace() {\n return transformPoint(\n _strokeTransform,\n _position.x - Cwidth / 2,\n _position.y - Cheight / 2,\n );\n}\n\nfunction screenPointFromPosition(x, y) {\n const point = transformPoint(_strokeTransform, x - Cwidth / 2, y - Cheight / 2);\n return {\n x: point.x + Cwidth / 2,\n y: point.y + Cheight / 2,\n };\n}\n\nfunction markImageTipDirty(rx, ry, scale, angle) {\n const halfWeight = current.p.weight / 2;\n const radians = (angle * Math.PI) / 180;\n const cosAngle = Math.cos(radians);\n const sinAngle = Math.sin(radians);\n const userCenterX = _position.x + rx;\n const userCenterY = _position.y + ry;\n const corners = [\n [-halfWeight, -halfWeight],\n [halfWeight, -halfWeight],\n [halfWeight, halfWeight],\n [-halfWeight, halfWeight],\n ];\n\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n for (const [x, y] of corners) {\n const lx = scale * (cosAngle * x - sinAngle * y);\n const ly = scale * (sinAngle * x + cosAngle * y);\n const point = screenPointFromPosition(userCenterX + lx, userCenterY + ly);\n\n minX = Math.min(minX, point.x * Renderer.pixelDensity());\n minY = Math.min(minY, point.y * Renderer.pixelDensity());\n maxX = Math.max(maxX, point.x * Renderer.pixelDensity());\n maxY = Math.max(maxY, point.y * Renderer.pixelDensity());\n }\n\n Mix.markDirtyRect(Mix.glMask, {\n minX: minX - 2,\n minY: minY - 2,\n maxX: maxX + 2,\n maxY: maxY + 2,\n });\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current p5 transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n const inverse = invertTransform(snapshotTransform());\n if (!inverse) {\n throw new Error(\n \"brush.clip() cannot be used with a non-invertible transform.\",\n );\n }\n State.stroke.clipWindow = {\n bounds: normalizeRegion(region),\n inverse,\n };\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n State.stroke.clipWindow = null;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {boolean} flow - Flag for vector-field following.\n * @param {Object|boolean} plot - Plot object or false.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _strokeTransform = snapshotTransform();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n isPlot\n ? _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n )\n : _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n Mask = Mix.glMask;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.a = pressure.type !== \"custom\" ? rr(-1, 1) : 0;\n current.b = pressure.type !== \"custom\" ? rr(1, 1.5) : 0;\n current.cp = pressure.type !== \"custom\" ? rr(3, 3.5) : rr(-0.2, 0.2);\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.03;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n const dirRad = (_dir * Math.PI) / 180;\n current.cos = Math.cos(dirRad);\n current.sin = Math.sin(dirRad);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n if (isInsideClippingArea()) Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n glDraw();\n markerTip();\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n * @param {number} [customPressure=false] - Optional custom pressure.\n */\nfunction tip(customPressure = false) {\n if (!isInsideClippingArea()) return;\n let pressure = customPressure || calculatePressure();\n\n let lineNoise = map(\n noise(current.seed + _position.plotted * 0.002, 0),\n 0,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n\n switch (current.p.type) {\n case \"spray\":\n drawSpray(pressure * lineNoise);\n break;\n case \"marker\":\n drawMarker(pressure * lineNoise);\n break;\n case \"custom\":\n case \"image\":\n drawTip(pressure * lineNoise, current.alpha);\n break;\n default:\n drawDefault(pressure * lineNoise);\n break;\n }\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n return _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n return current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(_position.plotted / _length) + current.cp,\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Checks if the current drawing position is within the clipping region.\n * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n const point = currentPointInUserSpace();\n\n if (State.stroke.clipWindow) {\n const local = transformPoint(\n State.stroke.clipWindow.inverse,\n point.x,\n point.y,\n );\n const { bounds } = State.stroke.clipWindow;\n return (\n local.x >= bounds.minX &&\n local.x <= bounds.maxX &&\n local.y >= bounds.minY &&\n local.y <= bounds.maxY\n );\n }\n\n let o = Cwidth * 0.05;\n return (\n point.x >= -Cwidth / 2 - o &&\n point.x <= Cwidth / 2 + o &&\n point.y >= -Cheight / 2 - o &&\n point.y <= Cheight / 2 + o\n );\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return 1;\n return param.spacing;\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha,\n );\n}\n\n/**\n * Draws a custom or image-based brush tip.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Alpha (opacity) for drawing.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawTip(pressure, alpha, vibrate = true) {\n Mix.glMask.isDrawn = true;\n Mask.push();\n Mask.noStroke();\n let color = State.stroke.color;\n color.setAlpha(alpha);\n Mask.fill(State.stroke.color);\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n Mask.translate(_position.x + rx - Cwidth, _position.y + ry - Cheight);\n const scale = State.stroke.weight * pressure;\n const angle = adjustSizeAndRotation(scale, alpha);\n current.p.tip(Mask);\n Mask.pop();\n\n if (current.p.type === \"image\") {\n markImageTipDirty(rx, ry, scale, angle);\n } else {\n Mix.markFull(Mix.glMask);\n }\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n if (rr(0, current.p.grain * pressure) > 0.4) {\n let dx, dy;\n if (_plot) {\n dx = 0.7 * vibration * rr(-1, 1);\n dy = vibration * rr(-1, 1);\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * -current.sin + along * current.cos;\n dy = perp * current.cos + along * current.sin;\n }\n circle(\n _position.x + dx,\n _position.y + dy,\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight,\n Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1),\n );\n }\n}\n\n/**\n * Adjusts the size and rotation of the brush tip before rendering.\n * @param {number} pressure - Pressure-based scaling factor.\n * @param {number} alpha - Opacity value.\n */\nfunction adjustSizeAndRotation(pressure, alpha) {\n Mask.scale(pressure);\n if (current.p.type === \"image\") {\n Mask.tint(255, 0, 0, alpha / 2);\n }\n let angle = 0;\n if (current.p.rotate === \"random\") angle = randInt(0, 360);\n else if (current.p.rotate === \"natural\") {\n angle =\n (_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle();\n }\n Mask.rotate(angle);\n return angle;\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (isInsideClippingArea()) {\n let pressure = calculatePressure();\n let alpha = calculateAlpha(pressure);\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, false, alpha * 5);\n }\n glDraw();\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawTip((pressure * s) / 5, alpha, false);\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current p5 angle mode.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, vibration, definition, quality, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\nadd(\"diamond\", {\n type: \"custom\",\n weight: 0.78,\n scatter: 0.1,\n opacity: 17,\n spacing: 1.3,\n pressure: [1.2, 0.82],\n rotate: \"none\",\n tip: (_m) => {\n _m.rotate(45);\n _m.rect(-4, -4, 8, 8);\n _m.rect(2, 2, 3, 3);\n },\n});\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the p5.js graphics library.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The p5.Image to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const p5img = Renderer.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n T.imageToWhite(p5img);\n this.tips.set(src, p5img);\n resolve();\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.src = src;\n }),\n ),\n );\n },\n};\n\n/**\n * Loads all registered image tips. Must be awaited before setup/draw.\n * @returns {Promise}\n *\n * @example\n * // In your sketch:\n * await brush.preload();\n */\nexport async function preload() {\n await T.load();\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};","// =============================================================================\n// Module: Hatch\n// =============================================================================\n/**\n * The Hatch module contains functions and classes dedicated to applying\n * hatch patterns over shapes and polygons. It enables the simulation of\n * cross-hatching and shading effects by drawing parallel lines or strokes\n * across a geometry. The module supports adjustable spacing, angle, and\n * optional style parameters (such as randomness, continuity, and gradient),\n * giving an artistic representation similar to hand-drawn hatching techniques.\n *\n * The implementation allows for hatching to be applied either to a Polygon\n * directly or via a Plot, extending the drawing capabilities with layered,\n * stylized textures.\n */\n\nimport { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, cos, sin, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// ---------------------------------------------------------------------------\n// Hatch State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global hatch state settings.\n */\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow copy of the current hatch state.\n * @returns {object} The current hatch state.\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Updates the global hatch state.\n * @param {object} state - The new hatch state.\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Activates hatching for subsequent geometries.\n *\n * @param {number} dist - The distance between hatching lines.\n * @param {number} angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} options - Optional parameters to affect the hatching style:\n * - rand: Number value to introduce randomness.\n * - continuous: Boolean to connect adjacent lines.\n * - gradient: Number to gradually change spacing.\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Sets the hatch brush style for subsequent hatching.\n *\n * @param {string} brush - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} weight - The brush weight (size).\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Disables hatching.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a hatching pattern over the given polygon(s).\n *\n * @param {Polygon|Polygon[]} polygons - A polygon or an array of polygons.\n */\nexport function createHatch(polygons) {\n let dist = State.hatch.dist;\n let angle = ((State.hatch.angle % 180) + 180) % 180;\n let options = State.hatch.options;\n\n // Save current stroke state\n let save = BrushState();\n // If a hatch brush is set, override with those parameters.\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n\n // Compute overall bounding box for all polygons.\n if (!Array.isArray(polygons)) polygons = [polygons];\n const overallBB = computeOverallBoundingBox(polygons);\n\n // Build a bounding polygon based on the overall bounding box.\n let ventana = new Polygon([\n [overallBB.minX, overallBB.minY],\n [overallBB.maxX, overallBB.minY],\n [overallBB.maxX, overallBB.maxY],\n [overallBB.minX, overallBB.maxY],\n ]);\n\n // Determine starting y coordinate based on angle.\n let startY = angle <= 90 && angle >= 0 ? overallBB.minY : overallBB.maxY;\n let gradient = options.gradient\n ? map(options.gradient, 0, 1, 1, 1.1, true)\n : 1;\n let dots = [];\n let i = 0;\n let dist1 = dist;\n\n // Function to generate a line for index i.\n let linea = (i) => {\n return {\n point1: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90),\n y: startY + dist1 * i * sin(-angle + 90),\n },\n point2: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90) + cos(-angle),\n y: startY + dist1 * i * sin(-angle + 90) + sin(-angle),\n },\n };\n };\n\n // Generate lines and calculate intersections with polygons\n // Loop through the lines based on the distance and angle to calculate intersections with the polygons\n // The loop continues until a line does not intersect with the bounding window polygon\n // Each iteration accounts for the gradient effect by adjusting the distance between lines\n while (ventana.intersect(linea(i)).length > 0) {\n let tempArray = [];\n for (let p of polygons) {\n tempArray.push(p.intersect(linea(i)));\n }\n dots[i] = tempArray\n .flat()\n .sort((a, b) => (a.x === b.x ? a.y - b.y : a.x - b.x));\n dist1 *= gradient;\n i++;\n }\n\n // Filter out empty intersection sets.\n let gdots = dots.filter((dd) => typeof dd[0] !== \"undefined\");\n\n // Draw the hatching lines using the calculated intersections\n // If the 'rand' option is enabled, add randomness to the start and end points of the lines\n // If the 'continuous' option is set, connect the end of one line to the start of the next\n let r = options.rand || 0;\n for (let j = 0; j < gdots.length; j++) {\n let dd = gdots[j];\n let continuousLine = j > 0 && options.continuous;\n for (let i = 0; i < dd.length - 1; i += 2) {\n if (r !== 0) {\n dd[i].x += r * dist * rr(-1, 1);\n dd[i].y += r * dist * rr(-1, 1);\n dd[i + 1].x += r * dist * rr(-1, 1);\n dd[i + 1].y += r * dist * rr(-1, 1);\n }\n line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);\n if (continuousLine) {\n line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);\n }\n }\n }\n\n // Restore previous brush state.\n BrushSetState(save);\n}\n\n/**\n * Computes the bounding box for a single polygon.\n * @param {Polygon} polygon - The polygon to evaluate.\n * @returns {object} The bounding box as {minX, minY, maxX, maxY}.\n */\nfunction computeBoundingBoxForPolygon(polygon) {\n if (polygon._boundingBox) return polygon._boundingBox;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n for (let i = 0; i < polygon.a.length; i++) {\n const [x, y] = polygon.a[i];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n polygon._boundingBox = { minX, minY, maxX, maxY };\n return polygon._boundingBox;\n}\n\n/**\n * Computes an overall bounding box for an array of polygons.\n * @param {Array} polygons - Array of Polygon objects.\n * @returns {object} The overall bounding box {minX, minY, maxX, maxY}.\n */\nfunction computeOverallBoundingBox(polygons) {\n let overall = {\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity,\n };\n for (let poly of polygons) {\n const bb = computeBoundingBoxForPolygon(poly);\n overall.minX = Math.min(overall.minX, bb.minX);\n overall.minY = Math.min(overall.minY, bb.minY);\n overall.maxX = Math.max(overall.maxX, bb.maxX);\n overall.maxY = Math.max(overall.maxY, bb.maxY);\n }\n return overall;\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Adds a hatch effect to the polygon.\n *\n * If a distance is provided, activates hatching with the given parameters.\n * Then, if hatch is active, applies the hatching pattern.\n *\n * @param {number} [_dist] - The distance between hatch lines.\n * @param {number} _angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} _options - Optional hatch options.\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) {\n createHatch(this);\n }\n HatchSetState(state);\n};\n\n/**\n * Applies hatching to a plot.\n *\n * If hatching is active, generates a polygon from the plot and applies hatch.\n *\n * @param {number} x - The x-coordinate to draw at.\n * @param {number} y - The y-coordinate to draw at.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.25);\n this.pol.hatch();\n }\n};\n","import { Mix } from \"./color.js\";\n\nfunction transformPoint(matrix, x, y) {\n return {\n x: matrix.a * x + matrix.c * y + matrix.e,\n y: matrix.b * x + matrix.d * y + matrix.f,\n };\n}\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices) {\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n vertices.forEach((v, i) => {\n const point = transformPoint(matrix, v.x, v.y);\n minX = Math.min(minX, point.x);\n minY = Math.min(minY, point.y);\n maxX = Math.max(maxX, point.x);\n maxY = Math.max(maxY, point.y);\n\n if (i === 0) ctx.moveTo(v.x, v.y);\n else ctx.lineTo(v.x, v.y);\n });\n ctx.closePath();\n\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n const radius = d / 2;\n const center = transformPoint(matrix, x, y);\n const rx = radius * Math.hypot(matrix.a, matrix.c);\n const ry = radius * Math.hypot(matrix.b, matrix.d);\n const padding = strokePadding(ctx, matrix);\n\n Mix.markDirtyRect(Mix.mask, {\n minX: center.x - rx - padding,\n minY: center.y - ry - padding,\n maxX: center.x + rx + padding,\n maxY: center.y + ry + padding,\n });\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\nimport { Renderer, Mix, State, Cwidth, Cheight, Density } from \"../core/color.js\";\nimport { drawPolygon, circle } from \"../core/mask.js\";\nimport {\n constrain,\n weightedRand,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady, Matrix } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 1024;\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color =\n arguments.length < 3 ? Renderer.color(a) : Renderer.color(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length < 8) {\n // Simple average for small polygons\n return pts\n .reduce((c, p) => ({ x: c.x + p.x, y: c.y + p.y }), { x: 0, y: 0 })\n .map((v) => v / pts.length);\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n const v = [...polygon.vertices];\n\n // Map vertices\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n\n // Create bleed modifiers\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.2) * strength,\n );\n\n // Randomize starting point\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n\n // Calculate center and create FillPolygon\n const center = _center(shifted);\n new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions\n this.dir = Array(v.length);\n rayCalc.forEach((rc, i) => {\n let count = 0;\n for (const isect of _polygon.intersect(rc.ray)) {\n if (_isLeft(rc.v1, rc.v2, isect)) count++;\n }\n this.dir[i] = count % 2 === 0;\n });\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: [...this.v], m: [...this.m], dir: [...this.dir] };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Clone and splice\n const v = [...this.v],\n m = [...this.m],\n dir = [...this.dir];\n v.splice(s, n);\n m.splice(s, n);\n dir.splice(s, n);\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n\n // Build sorted random indices\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [], sm = [], sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n\n // Ray-cast: count intersections from p to far right\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y, by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n // If outside (even crossings), pull toward center\n if (crossings % 2 === 0) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]); // flip direction → grow inward\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n // Get trimmed vertices\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n \n // Pre-allocate output arrays\n const outLen = len * 2;\n const newVerts = new Array(outLen);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\n \n // Determine bleed direction\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n \n // Ensure gaussian pool is filled\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0], gPoolLen = gPool.length;\n const g2Pool = _gaussians[1], g2PoolLen = g2Pool.length;\n \n let idx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n \n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n \n if (f < 997) mod = mi;\n \n // Inline rotate: rotDeg = ±bleedDirDeg + small jitter\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n \n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n \n // Outward distance: inline rArray + rr\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n \n // First vertex: original\n newVerts[idx] = cv;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n \n // Second vertex: midpoint + outward push\n newVerts[idx] = {\n x: cv.x + sideX * 0.5 + dirX * d,\n y: cv.y + sideY * 0.5 + dirY * d,\n };\n newMods[idx] = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n newDirs[idx] = di;\n idx++;\n }\n \n // Cap vertex count to prevent exponential blowup.\n let fv = newVerts, fm = newMods, fd = newDirs;\n let growe = GROW_MAX_VERTS / (State.fill.texture_strength);\n if (growe && idx > growe) {\n const step = Math.ceil(idx / growe);\n fv = []; fm = []; fd = [];\n for (let j = 0; j < idx; j += step) {\n fv.push(newVerts[j]);\n fm.push(newMods[j]);\n fd.push(newDirs[j]);\n }\n } else {\n // Trim pre-allocated arrays to actual size\n fv.length = idx;\n fm.length = idx;\n fd.length = idx;\n }\n \n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n // Precalculate stuff\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n // Perform initial setup only once\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(), Density * Matrix.b(),\n Density * Matrix.c(), Density * Matrix.d(),\n Density * (Matrix.x() + Cwidth / 2),\n Density * (Matrix.y() + Cheight / 2),\n );\n\n Mix.ctx.strokeStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${\n 0.005 * State.fill.border_strength\n })`;\n Mix.ctx.lineCap = \"round\";\n\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n\n // Create initial polygon\n let pol = this.grow();\n // Create sparse inner polygon from original (pre-grow) vertices\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n // Grow polygon every 4 layers\n if (i % 4 === 0) pol = pol.grow();\n\n // Create variant polygons\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n // Draw layers\n for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);\n sparse.grow(999).flipDirs().grow(997).layer(i, size, int * 1.5 * texture, color);\n if (i % 2 === 0)\n pol\n .grow(darker)\n .grow(999)\n .layer(i, size, int * 2, color);\n\n // Apply texture and blend periodically\n if (i % 5 === 0 || i === numLayers - 1) {\n if (texture !== 0) pol.erase(texture * 3, intensity);\n Mix.blend(color, true, false, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, color) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\n drawPolygon(this.v);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n // Optimize by pre-calculating values\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.4 - State.fill.bleed_strength);\n const minSizeFactor = 0.05 * minSize;\n const maxSizeFactor = 0.4 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n // Set up erase mode\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n // Calculate transparency\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n // Draw erase circles\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const size = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, size);\n if (i % 5 !== 0) Mix.ctx.fill();\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n map(State.fill.bleed_strength, 0, 0.6, 0.3, 0.45, true),\n );\n this.pol.fill();\n }\n};\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n}\n","/**\n * @fileoverview p5.brush - A comprehensive toolset for brush management in p5.js.\n * @version 2.0.0-alpha\n * @license MIT\n * @author Alejandro Campos Uribe\n *\n * @description\n * p5.brush is a p5.js library dedicated to the creation and management of custom brushes.\n * It extends the drawing capabilities of p5.js by allowing users to simulate a wide range\n * of brush strokes, vector fields, hatching patterns, and fill textures. These features\n * are essential for emulating the nuanced effects found in traditional sketching and painting.\n * Whether for digital art applications or procedural generation of graphics, p5.brush provides\n * a robust framework for artists and developers to create rich, dynamic, and textured visuals.\n *\n * @example\n * // Basic usage:\n * brush.pick('marker'); // Select brush type\n * brush.stroke(255, 0, 0); // Set brush color\n * brush.strokeWeight(10); // Set brush size\n * brush.line(25, 25, 75, 75); // Draw a line\n *\n * // Add a new brush type:\n * brush.add('customBrush', { /* parameters for the brush *\\/ });\n * brush.pick('customBrush');\n *\n * // Use the custom brush for a vector-field line:\n * brush.field('field_name') // Pick a flowfield\n * brush.flowLine(50, 50, 100, PI / 4); // Draw a line within the vector-field; angle follows p5 angleMode()\n *\n * // Fill textures:\n * brush.noStroke();\n * brush.fill('#FF0000', 90); // Set fill color to red and opacity to 90\n * brush.bleed(0.3); // Set bleed effect for a watercolor-like appearance\n * brush.rect(100, 100, 50, 50); // Fill a rectangle with the bleed effect\n *\n * @license\n * MIT License\n *\n * Copyright (c) 2023-2024 Alejandro Campos Uribe\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n// Randomness and other auxiliary functions\nexport { weightedRand as wRand } from \"./core/utils.js\";\n\n// Color Blending\nexport { load, instance } from \"./core/color.js\";\n\n// Matrix transformations, FlowField and Position Class\nexport {\n field,\n noField,\n addField,\n refreshField,\n listFields,\n Position,\n wiggle,\n} from \"./core/flowfield.js\";\n\n// Polygon and Plot classes\nexport { Polygon } from \"./core/polygon.js\";\nexport { Plot } from \"./core/plot.js\";\n\n// Primitives\nexport {\n rect,\n circle,\n arc,\n beginShape,\n vertex,\n endShape,\n beginStroke,\n move,\n endStroke,\n spline,\n polygon,\n} from \"./core/primitives.js\";\n\n// Brushes\nexport {\n add,\n box,\n scaleBrushes,\n pick,\n stroke,\n strokeWeight,\n set,\n noStroke,\n clip,\n noClip,\n line,\n flowLine,\n} from \"./stroke/stroke.js\";\n\n// Section: Hatching\nexport {\n hatch,\n hatchStyle,\n noHatch,\n createHatch as hatchArray,\n} from \"./hatch/hatch.js\";\n\n// Fill\nexport { fill, noFill, fillTexture, fillBleed } from \"./fill/fill.js\";\n\n// p5 addon registration\nimport { Mix } from \"./core/color.js\";\nimport { push as brushPush, pop as brushPop } from \"./core/save.js\";\nimport { seed as brushSeed, noiseSeed as brushNoiseSeed } from \"./core/utils.js\";\n\nfunction registerAddon(_p5, fn, lifecycles) {\n lifecycles.postsetup = () => Mix.blend(false, true);\n lifecycles.postdraw = () => Mix.blend(false, true);\n\n const _push = fn.push;\n const _pop = fn.pop;\n const _randomSeed = fn.randomSeed;\n const _noiseSeed = fn.noiseSeed;\n\n fn.push = function () {\n _push.call(this);\n brushPush();\n };\n\n fn.pop = function () {\n _pop.call(this);\n brushPop();\n };\n\n fn.randomSeed = function (s) {\n _randomSeed.call(this, s);\n brushSeed(s);\n };\n\n fn.noiseSeed = function (s) {\n _noiseSeed.call(this, s);\n brushNoiseSeed(s);\n };\n}\n\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerAddon);\n"],"names":["Cwidth","Cheight","Instance","Renderer","Density","isFramebufferTarget","target","begin","end","renderer","_pInst","getSketchRenderer","_isInstanced","window","self","p5","instance","removeTargetBuffer","buffer","remove","getActiveFramebuffer","_renderer","activeFramebuffer","getTargetPixelSize","width","Math","max","round","height","normalizeDirtyRect","rect","minX","floor","min","maxX","minY","maxY","ceil","getFullDirtyRect","withScissor","gl","draw","box","normalized","x","y","toScissorBox","wasEnabled","isEnabled","SCISSOR_TEST","prevBox","getParameter","SCISSOR_BOX","enable","scissor","disable","load","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","isMixReady","isBlending","cachedColor","Object","markDirtyRect","a","b","dirtyRect","isDrawn","markFull","clearMask","clear","getCompositeRect","isBrushMask","padding","expandDirtyRect","captureBlendSource","framebuffer","blendSourceFramebuffer","pixelDensity","createFramebuffer","density","antialias","depth","stencil","source","drawingContext","push","imageMode","CENTER","image","pop","graphicsFactory","createGraphics","p2dMode","P2D","webglMode","WEBGL","mask","glMask","this","ctx","shaderProgram","createShader","angleMode","DEGREES","lineWidth","uModelMatrix","blend","_color","_isLast","activeIsBrush","isBrush","no_mask","nextColor","_array","colorChanged","justChanged","applyShader","shader","targetIsFramebuffer","hadDepthTest","DEPTH_TEST","translate","setUniform","fill","noStroke","resetShader","SQRT3","sqrt","F2","G2","fastFloor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","c","s0","s1","s2","copy","f","rng","_seedCallbacks","_onSeed","cb","noise","rr","e","rArray","array","randInt","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","d","withinBounds","constrain","low","high","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","NaN","sLookup","idx","sin","toDegrees","rad","isRad","RADIANS","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","Matrix","mat4","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","update","plotted","colIdx","getColIndex","rowIdx","getRowIndex","reset","isIn","isActive","isInCanvas","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","y_offset","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","has","generateField","entry","normalizeFieldAngles","gen","keys","join","name","funct","set","fn","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","intersection","show","stroke","hatch","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","_current","_curvature","_strokeArray","_strokeOrigin","SubPath","isClosed","curvature","vert","vertex","_createSpline","beginShape","endShape","close","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","radius","halfDist","arcLength","asin","origin","projMatrix","vao","buf","program","loadedWidth","loadedHeight","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circle","diameter","alpha","newData","px","py","screenX","screenY","glDraw","color","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","uniform4f","u_color","uniformMatrix4fv","u_matrix","drawArrays","POINTS","_curShader","weight","clipWindow","opacity","_position","Mask","_strokeTransform","tx","ty","BrushState","BrushSetState","state","add","params","includes","undefined","vibration","scatter","definition","sharpness","quality","grain","isArray","min_max","curve","m","range","ns","nm","ne","normalizePressure","src","T","tip","tips","param","colors","buffers","pick","brushName","g","arguments","strokeWeight","snapshotTransform","transformPoint","transform","normalizeRegion","region","screenPointFromPosition","point","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","noiseoffset","dirRad","nextGl","needsContextRefresh","createProgram","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","isReady","switchingToBrush","isInsideClippingArea","calculateAlpha","markerTip","saveState","stepSize","spacing","totalSteps","customPressure","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","local","inverse","bounds","o","vibrate","rx","ry","setAlpha","tint","adjustSizeAndRotation","halfWeight","radians","cosAngle","sinAngle","userCenterX","userCenterY","corners","Infinity","markImageTipDirty","_vals","_standard_brushes","obj","_m","prototype","_brush","_weight","imageToWhite","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","p5img","createImage","naturalWidth","naturalHeight","drawImage","onerror","HatchState","rand","continuous","gradient","createHatch","polygons","save","hBrush","values","overallBB","overall","poly","bb","computeBoundingBoxForPolygon","computeOverallBoundingBox","ventana","startY","dots","dist1","linea","tempArray","flat","sort","gdots","dd","continuousLine","polygon","_boundingBox","matrix","strokePadding","getTransform","center","arc","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","sx","sy","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","splice","ratio","L","keep","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","newVerts","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","fv","fm","fd","growe","intensity","tex","texture","int","switchingToFill","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","size","darker","sparse","pols","layer","numLayers","erase","restore","fillStyle","beginPath","lineTo","closePath","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","_opacity","_bleed","fluid","strength","modifiers","_","shift","shifted","slice","pts","area","cross","_center","createFill","FillSetState","_stateStack","registerAddon","_p5","lifecycles","postsetup","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","callback","brushSeed","brushNoiseSeed","startDeg","sweepDeg","segmentCount","segmentSweep","startX","angleOffset","randomFactor","randomAngle","offsetX","offsetY","det","invertTransform","brush","inst","mode","currentField","_array_points"],"mappings":"6BAYO,IAAIA,EAAQC,EAASC,EAAUC,EAAUC,EA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3B,IAAK,MAAMkM,MAAEA,KAAWjN,GAAK8U,SACvB7H,IACFA,EAAMlC,QAAUhK,EAChBkM,EAAMlB,SAAWhL,EACjBkM,EAAMkD,SAAWpP,EAGvB,oBF4EO,SAAgBsf,EAAe7a,EAAa,IACjD,IAAK6a,GAAiBA,EAAcpoB,OAAS,EAC3C,MAAM,IAAIvI,MACR,+EAGIsW,GAAcqa,EAAe7a,GACnC9W,MACJ,+DHmFO,SAAgB6B,EAAI,GACzBsN,GAAM,QACN5N,EAAM4N,MAAMsC,OAAS5P,CACvB","x_google_ignoreList":[1,2]}
\ No newline at end of file
+{"version":3,"file":"p5.brush.js","sources":["../src/core/color.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/flowfield.js","../src/core/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/core/gl/utils.js","../src/hatch/hatch.js","../src/core/mask.js","../src/fill/fill.js","../src/core/save.js","../src/index.js"],"sourcesContent":["import vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Section: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties\n\nconst isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\nconst getSketchRenderer = () =>\n _isInstanced ? Instance : window.self.p5.instance;\n\nconst isSupportedFramebufferTarget = (target) =>\n isFramebufferTarget(target) && target.renderer._pInst === getSketchRenderer();\n\nconst resolveTarget = (buffer = false) => {\n if (_isInstanced && !buffer) {\n return {\n renderer: Instance,\n width: Instance.width,\n height: Instance.height,\n };\n }\n\n if (!buffer) {\n const renderer = getSketchRenderer();\n return {\n renderer,\n width: renderer.width,\n height: renderer.height,\n };\n }\n\n if (isFramebufferTarget(buffer)) {\n if (!isSupportedFramebufferTarget(buffer)) {\n throw new Error(\n \"p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.\",\n );\n }\n\n return {\n renderer: getSketchRenderer(),\n width: buffer.width,\n height: buffer.height,\n };\n }\n\n return {\n renderer: buffer,\n width: buffer.width,\n height: buffer.height,\n };\n};\n\nconst removeTargetBuffer = (buffer) => {\n if (buffer && typeof buffer.remove === \"function\") {\n buffer.remove();\n }\n};\n\nconst getGraphicsFactory = () =>\n typeof Renderer.createGraphics === \"function\" ? Renderer : Renderer._pInst;\n\nconst getActiveFramebuffer = () =>\n Renderer &&\n Renderer._renderer &&\n typeof Renderer._renderer.activeFramebuffer === \"function\"\n ? Renderer._renderer.activeFramebuffer()\n : null;\n\nconst needsBlendSourceFramebuffer = (framebuffer) =>\n !framebuffer ||\n framebuffer.width !== Cwidth ||\n framebuffer.height !== Cheight ||\n (typeof framebuffer.pixelDensity === \"function\" &&\n framebuffer.pixelDensity() !== Density);\n\nconst needsMixBuffers = () =>\n !Renderer.mask ||\n !Renderer.glMask ||\n Renderer.mask.width !== Cwidth ||\n Renderer.mask.height !== Cheight ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight;\n\nconst DIRTY_BRUSH_PADDING = 2;\nconst DIRTY_FILL_PADDING = 4;\n\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n\n const { width, height } = getTargetPixelSize();\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\nconst unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return { minX: 0, minY: 0, maxX: width, maxY: height };\n};\n\nconst toScissorBox = (rect) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: height - normalized.maxY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\nconst withScissor = (gl, rect, draw) => {\n const box = toScissorBox(rect);\n if (!box) return false;\n\n const wasEnabled = gl.isEnabled(gl.SCISSOR_TEST);\n const prevBox = gl.getParameter(gl.SCISSOR_BOX);\n\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n if (wasEnabled) {\n gl.scissor(prevBox[0], prevBox[1], prevBox[2], prevBox[3]);\n } else {\n gl.disable(gl.SCISSOR_TEST);\n }\n }\n\n return true;\n};\n\n/**\n * Loads and initializes a canvas for the drawing system.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.\n * Pass a framebuffer only while drawing inside its begin()/end() or draw() scope.\n * Framebuffers created from p5.Graphics are not supported.\n */\nexport const load = (buffer = false) => {\n const target = resolveTarget(buffer);\n Renderer = target.renderer;\n\n // Check if Rendrer is webgl and throw error if it's not\n\n if (Renderer.webglVersion !== \"webgl2\") {\n throw new Error(\"p5.brush requires a WEBGL canvas\");\n }\n\n Cwidth = target.width;\n Cheight = target.height;\n\n _isReady = true;\n if (Renderer.loaded) Mix.load();\n};\n\nlet _isReady = false;\nlet _isInstanced = false;\n\n/**\n * Ensures the drawing system is ready before any operation.\n */\nexport const isCanvasReady = () => {\n if (!_isReady) load();\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n\nexport const instance = (inst) => {\n _isInstanced = true;\n Instance = inst;\n};\n\n\n// =============================================================================\n// Section: Color Blending\n// =============================================================================\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer?.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\nconst disable = false;\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: new Object(),\n\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n markFull(target) {\n if (!target) return;\n\n target.dirtyRect = getFullDirtyRect();\n target.isDrawn = true;\n },\n\n clearMask(target) {\n if (!target) return;\n\n target.clear();\n target.isDrawn = false;\n target.dirtyRect = null;\n },\n\n getCompositeRect(target, isBrushMask) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n\n return normalizeDirtyRect(\n expandDirtyRect(\n target.dirtyRect,\n isBrushMask ? DIRTY_BRUSH_PADDING : DIRTY_FILL_PADDING,\n ),\n );\n },\n\n captureBlendSource(dirtyRect) {\n const activeFramebuffer = getActiveFramebuffer();\n\n if (!activeFramebuffer) return Renderer._renderer;\n\n if (needsBlendSourceFramebuffer(Renderer.blendSourceFramebuffer)) {\n removeTargetBuffer(Renderer.blendSourceFramebuffer);\n Renderer.blendSourceFramebuffer = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n const source = Renderer.blendSourceFramebuffer;\n\n source.draw(() => {\n withScissor(Renderer.drawingContext, dirtyRect, () => {\n Renderer.clear();\n Renderer.push();\n if (typeof Renderer.imageMode === \"function\") {\n Renderer.imageMode(\n Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER,\n );\n }\n Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n });\n });\n\n return source;\n },\n\n /**\n * Loads necessary resources and prepares the mask buffer and shader for colour blending.\n */\n load() {\n Density = Renderer.pixelDensity();\n const graphicsFactory = getGraphicsFactory();\n const p2dMode = graphicsFactory.P2D ?? Renderer.P2D;\n const webglMode = graphicsFactory.WEBGL ?? Renderer.WEBGL;\n\n if (!Renderer.loaded || needsMixBuffers()) {\n removeTargetBuffer(Renderer.mask);\n removeTargetBuffer(Renderer.glMask);\n\n Renderer.mask = graphicsFactory.createGraphics(Cwidth, Cheight, p2dMode);\n Renderer.glMask = graphicsFactory.createGraphics(\n Cwidth,\n Cheight,\n webglMode,\n );\n Renderer.loaded = true;\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n\n this.mask = Renderer.mask;\n this.mask.pixelDensity(Density);\n this.mask.clear();\n this.mask.angleMode(Renderer.DEGREES);\n this.mask.dirtyRect = null;\n this.mask.isDrawn = false;\n\n this.ctx = this.mask.drawingContext;\n\n this.glMask = Renderer.glMask;\n this.glMask.pixelDensity(Density);\n this.glMask.clear();\n this.glMask.angleMode(this.glMask.DEGREES);\n this.glMask.drawingContext.lineWidth = 0;\n this.glMask.dirtyRect = null;\n this.glMask.isDrawn = false;\n } else {\n this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\n this.mask.dirtyRect ??= null;\n this.mask.isDrawn ??= false;\n this.glMask.dirtyRect ??= null;\n this.glMask.isDrawn ??= false;\n }\n\n // Link Matrix of GL mask to main Renderer\n this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;\n },\n\n /**\n * Applies blending effects using the current color and mask.\n * @param {Color} _color - Color to blend.\n * @param {boolean} _isLast - If this is the final blend operation.\n * @param {boolean} _isImg - If blending an image.\n * @param {boolean} _isFillLayer - If this is a special case.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n\n const activeIsBrush = this.isBrush === true;\n const mask = activeIsBrush ? this.glMask : this.mask;\n const no_mask = activeIsBrush ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor[0] !== nextColor[0] ||\n this.cachedColor[1] !== nextColor[1] ||\n this.cachedColor[2] !== nextColor[2] ||\n this.cachedColor[3] !== nextColor[3]);\n\n // Perf gains are minimal but let's keep it for now\n if (disable) {\n if (_isLast && mask.isDrawn) {\n Renderer.push();\n Renderer.translate(0, 0);\n Renderer.image(mask, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n mask.isDrawn = false;\n }\n return;\n }\n\n // Initialize blending if not already active\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Force p5 to bind its internal render target for glMask,\n // so the first glDraw() writes to the correct framebuffer.\n this.glMask.clear();\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(no_mask, !activeIsBrush);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, activeIsBrush);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) this.isBlending = false;\n }\n },\n\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n let shader = Renderer.shaderProgram;\n const gl = Renderer.drawingContext;\n const targetIsFramebuffer = !!getActiveFramebuffer();\n const source = this.captureBlendSource(dirtyRect);\n\n // Disable depth test for this compositing draw so the fullscreen rect\n // does not write Z=0 into the depth buffer — which would cause any\n // subsequent p5 geometry drawn at the same depth to fail depth testing\n // and become invisible.\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n gl.disable(gl.DEPTH_TEST);\n\n Renderer.push();\n Renderer.translate(0, 0);\n\n // Use the blend shader for rendering\n Renderer.shader(shader);\n\n // Set shader uniforms\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n shader.setUniform(\"u_flipOutputY\", targetIsFramebuffer);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", this.cachedColor);\n\n // Draw a rectangle covering the whole canvas to apply the shader\n withScissor(gl, dirtyRect, () => {\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n });\n\n // Finish and clear mask\n Renderer.pop();\n Renderer.resetShader();\n\n // Restore depth test state\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n this.clearMask(mask);\n },\n};\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { Renderer } from \"./color.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n const usesRadians =\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS);\n // Only if Renderer.angleMode() is set to radians\n if (usesRadians) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS)\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","import { isMixReady, Cwidth, Cheight, State, Renderer } from \"./color.js\";\nimport { randInt, noise, rr, sin, cos, map, toDegreesSigned } from \"./utils.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n/**\n * The `Matrix` object exposes the current 2D affine transform from p5's model matrix.\n * mat4 layout (column-major 4x4):\n * [0]=a [1]=b [4]=c [5]=d [12]=tx [13]=ty\n * where the 2D transform of a point (x,y) is: (a*x + c*y + tx, b*x + d*y + ty)\n */\nexport const Matrix = {\n x: () => Renderer._renderer.uModelMatrix.mat4[12],\n y: () => Renderer._renderer.uModelMatrix.mat4[13],\n a: () => Renderer._renderer.uModelMatrix.mat4[0],\n b: () => Renderer._renderer.uModelMatrix.mat4[1],\n c: () => Renderer._renderer.uModelMatrix.mat4[4],\n d: () => Renderer._renderer.uModelMatrix.mat4[5],\n};\n\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n this.colIdx = Position.getColIndex(x);\n this.rowIdx = Position.getRowIndex(y);\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + Matrix.x();\n const y = this.y + Matrix.y();\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle() {\n return this.isIn() && State.field.isActive\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current p5 angle mode.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1) {\n this.movePos(_plot, _length, _step_length, _scale);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n for (let i = 0; i < _length / _step; i++) {\n const angle =\n this.angle() - (_scale ? _dirPlot.angle(this.plotted) : _dirPlot);\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + Matrix.y() - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + Matrix.x() - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr(0.2, 0.8),\n ba = randInt(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt(15, 25));\n return 0.2 * angle * cos(t) + noise(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt(-10, 10);\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt(-30, -15) + Math.abs(44 * sin(t));\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt(10, 15) + 5 * sin(t),\n cr = randInt(3, 6) + 3 * cos(t),\n ba = randInt(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr(0.4, 0.8),\n ba = randInt(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt(5, 10);\n const dir = randInt(0, 2) * 2 - 1;\n const offset = randInt(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr(0.1, 0.9) * num_columns,\n y: rr(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt(3, 8),\n amp = randInt(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.stroke) this.draw();\n if (State.hatch) this.hatch();\n if (State.fill) this.fill();\n }\n}\n","import { State, Cwidth, Cheight } from \"./color.js\";\nimport { toDegrees, map, rr } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = 0.5;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n const maxSize = Math.max(this.segments[idx] * _side * rr(0.7, 1.3), 10);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.stroke) this.draw(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n }\n}\n","import {\n rr,\n randInt,\n sin,\n cos,\n toDegrees,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current p5 angle mode.\n * @param {number} end - End angle in the current p5 angle mode.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module provides functions for rendering shapes (circles and squares)\n * using WebGL2. It initializes the WebGL context and shader programs, prepares buffers,\n * and implements drawing routines based on queued drawing primitives. The module uses\n * an orthographic projection to map canvas coordinates to clip space and supports adjustable\n * blending for translucent effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\n State,\n} from \"../core/color.js\";\nimport { Matrix } from \"../core/flowfield.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n projMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0;\n\n/**\n * Snapshots the current p5 model matrix. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n _ma = Matrix.a();\n _mb = Matrix.b();\n _mc = Matrix.c();\n _md = Matrix.d();\n _mx = Matrix.x();\n _my = Matrix.y();\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n\n const nextGl = Mix.glMask.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n projMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n -2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * p5's current model matrix so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - Cwidth / 2;\n const py = y - Cheight / 2;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + Cwidth / 2;\n const screenY = _mb * px + _md * py + _my + Cheight / 2;\n const radius =\n (Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n Mix.markDirtyRect(Mix.glMask, {\n minX: screenX * Density - radius - 1,\n minY: screenY * Density - radius - 1,\n maxX: screenX * Density + radius + 1,\n maxY: screenY * Density + radius + 1,\n });\n\n circleCount++;\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader (p5 drawing may have switched programs)\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, projMatrix);\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing p5's _curShader tracking.\n // Reset it to null so p5 is forced to re-activate its own shader next time\n // it draws — otherwise p5 skips gl.useProgram() and sets uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n Mix.glMask._renderer._curShader = null;\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n State,\n Renderer,\n isCanvasReady,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed,\n} from \"../core/utils.js\";\nimport { Position, Matrix, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { isReady, glDraw, circle, snapshotMatrix } from \"./gl_draw.js\";\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n clipWindow: null,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nlet Mask = null;\nlet _strokeTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n tx: 0,\n ty: 0,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { type, min_max, curve } — old internal format, passed through unchanged\n */\nfunction normalizePressure(p) {\n if (!p || (typeof p === \"object\" && !Array.isArray(p))) return p;\n if (typeof p === \"function\")\n return { type: \"custom\", min_max: [0, 1], curve: p };\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n params.tip = () => {\n Mask.image(\n T.tips.get(current.p.image.src),\n -current.p.weight / 2,\n -current.p.weight / 2,\n current.p.weight,\n current.p.weight,\n );\n };\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = Renderer.color(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\nfunction snapshotTransform() {\n return {\n a: Matrix.a(),\n b: Matrix.b(),\n c: Matrix.c(),\n d: Matrix.d(),\n tx: Matrix.x(),\n ty: Matrix.y(),\n };\n}\n\nfunction invertTransform(transform) {\n const det = transform.a * transform.d - transform.b * transform.c;\n if (Math.abs(det) < 1e-12) return null;\n\n return {\n a: transform.d / det,\n b: -transform.b / det,\n c: -transform.c / det,\n d: transform.a / det,\n tx: (transform.c * transform.ty - transform.d * transform.tx) / det,\n ty: (transform.b * transform.tx - transform.a * transform.ty) / det,\n };\n}\n\nfunction transformPoint(transform, x, y) {\n return {\n x: transform.a * x + transform.c * y + transform.tx,\n y: transform.b * x + transform.d * y + transform.ty,\n };\n}\n\nfunction normalizeRegion(region) {\n const [x1, y1, x2, y2] = region;\n return {\n minX: Math.min(x1, x2),\n minY: Math.min(y1, y2),\n maxX: Math.max(x1, x2),\n maxY: Math.max(y1, y2),\n };\n}\n\nfunction currentPointInUserSpace() {\n return transformPoint(\n _strokeTransform,\n _position.x - Cwidth / 2,\n _position.y - Cheight / 2,\n );\n}\n\nfunction screenPointFromPosition(x, y) {\n const point = transformPoint(_strokeTransform, x - Cwidth / 2, y - Cheight / 2);\n return {\n x: point.x + Cwidth / 2,\n y: point.y + Cheight / 2,\n };\n}\n\nfunction markImageTipDirty(rx, ry, scale, angle) {\n const halfWeight = current.p.weight / 2;\n const radians = (angle * Math.PI) / 180;\n const cosAngle = Math.cos(radians);\n const sinAngle = Math.sin(radians);\n const userCenterX = _position.x + rx;\n const userCenterY = _position.y + ry;\n const corners = [\n [-halfWeight, -halfWeight],\n [halfWeight, -halfWeight],\n [halfWeight, halfWeight],\n [-halfWeight, halfWeight],\n ];\n\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n for (const [x, y] of corners) {\n const lx = scale * (cosAngle * x - sinAngle * y);\n const ly = scale * (sinAngle * x + cosAngle * y);\n const point = screenPointFromPosition(userCenterX + lx, userCenterY + ly);\n\n minX = Math.min(minX, point.x * Renderer.pixelDensity());\n minY = Math.min(minY, point.y * Renderer.pixelDensity());\n maxX = Math.max(maxX, point.x * Renderer.pixelDensity());\n maxY = Math.max(maxY, point.y * Renderer.pixelDensity());\n }\n\n Mix.markDirtyRect(Mix.glMask, {\n minX: minX - 2,\n minY: minY - 2,\n maxX: maxX + 2,\n maxY: maxY + 2,\n });\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current p5 transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n const inverse = invertTransform(snapshotTransform());\n if (!inverse) {\n throw new Error(\n \"brush.clip() cannot be used with a non-invertible transform.\",\n );\n }\n State.stroke.clipWindow = {\n bounds: normalizeRegion(region),\n inverse,\n };\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n State.stroke.clipWindow = null;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {boolean} flow - Flag for vector-field following.\n * @param {Object|boolean} plot - Plot object or false.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _strokeTransform = snapshotTransform();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n isPlot\n ? _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n )\n : _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n Mask = Mix.glMask;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.a = pressure.type !== \"custom\" ? rr(-1, 1) : 0;\n current.b = pressure.type !== \"custom\" ? rr(1, 1.5) : 0;\n current.cp = pressure.type !== \"custom\" ? rr(3, 3.5) : rr(-0.2, 0.2);\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.03;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n const dirRad = (_dir * Math.PI) / 180;\n current.cos = Math.cos(dirRad);\n current.sin = Math.sin(dirRad);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n if (isInsideClippingArea()) Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n glDraw();\n markerTip();\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n * @param {number} [customPressure=false] - Optional custom pressure.\n */\nfunction tip(customPressure = false) {\n if (!isInsideClippingArea()) return;\n let pressure = customPressure || calculatePressure();\n\n let lineNoise = map(\n noise(current.seed + _position.plotted * 0.002, 0),\n 0,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n\n switch (current.p.type) {\n case \"spray\":\n drawSpray(pressure * lineNoise);\n break;\n case \"marker\":\n drawMarker(pressure * lineNoise);\n break;\n case \"custom\":\n case \"image\":\n drawTip(pressure * lineNoise, current.alpha);\n break;\n default:\n drawDefault(pressure * lineNoise);\n break;\n }\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n return _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n return current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(_position.plotted / _length) + current.cp,\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Checks if the current drawing position is within the clipping region.\n * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n const point = currentPointInUserSpace();\n\n if (State.stroke.clipWindow) {\n const local = transformPoint(\n State.stroke.clipWindow.inverse,\n point.x,\n point.y,\n );\n const { bounds } = State.stroke.clipWindow;\n return (\n local.x >= bounds.minX &&\n local.x <= bounds.maxX &&\n local.y >= bounds.minY &&\n local.y <= bounds.maxY\n );\n }\n\n let o = Cwidth * 0.05;\n return (\n point.x >= -Cwidth / 2 - o &&\n point.x <= Cwidth / 2 + o &&\n point.y >= -Cheight / 2 - o &&\n point.y <= Cheight / 2 + o\n );\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return 1;\n return param.spacing;\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha,\n );\n}\n\n/**\n * Draws a custom or image-based brush tip.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Alpha (opacity) for drawing.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawTip(pressure, alpha, vibrate = true) {\n Mix.glMask.isDrawn = true;\n Mask.push();\n Mask.noStroke();\n let color = State.stroke.color;\n color.setAlpha(alpha);\n Mask.fill(State.stroke.color);\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n Mask.translate(_position.x + rx - Cwidth, _position.y + ry - Cheight);\n const scale = State.stroke.weight * pressure;\n const angle = adjustSizeAndRotation(scale, alpha);\n current.p.tip(Mask);\n Mask.pop();\n\n if (current.p.type === \"image\") {\n markImageTipDirty(rx, ry, scale, angle);\n } else {\n Mix.markFull(Mix.glMask);\n }\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n if (rr(0, current.p.grain * pressure) > 0.4) {\n let dx, dy;\n if (_plot) {\n dx = 0.7 * vibration * rr(-1, 1);\n dy = vibration * rr(-1, 1);\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * -current.sin + along * current.cos;\n dy = perp * current.cos + along * current.sin;\n }\n circle(\n _position.x + dx,\n _position.y + dy,\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight,\n Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1),\n );\n }\n}\n\n/**\n * Adjusts the size and rotation of the brush tip before rendering.\n * @param {number} pressure - Pressure-based scaling factor.\n * @param {number} alpha - Opacity value.\n */\nfunction adjustSizeAndRotation(pressure, alpha) {\n Mask.scale(pressure);\n if (current.p.type === \"image\") {\n Mask.tint(255, 0, 0, alpha / 2);\n }\n let angle = 0;\n if (current.p.rotate === \"random\") angle = randInt(0, 360);\n else if (current.p.rotate === \"natural\") {\n angle =\n (_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle();\n }\n Mask.rotate(angle);\n return angle;\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (isInsideClippingArea()) {\n let pressure = calculatePressure();\n let alpha = calculateAlpha(pressure);\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, false, alpha * 5);\n }\n glDraw();\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawTip((pressure * s) / 5, alpha, false);\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current p5 angle mode.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, vibration, definition, quality, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\nadd(\"diamond\", {\n type: \"custom\",\n weight: 0.78,\n scatter: 0.1,\n opacity: 17,\n spacing: 1.3,\n pressure: [1.2, 0.82],\n rotate: \"none\",\n tip: (_m) => {\n _m.rotate(45);\n _m.rect(-4, -4, 8, 8);\n _m.rect(2, 2, 3, 3);\n },\n});\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the p5.js graphics library.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The p5.Image to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const p5img = Renderer.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n T.imageToWhite(p5img);\n this.tips.set(src, p5img);\n resolve();\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.src = src;\n }),\n ),\n );\n },\n};\n\n/**\n * Loads all registered image tips. Must be awaited before setup/draw.\n * @returns {Promise}\n *\n * @example\n * // In your sketch:\n * await brush.preload();\n */\nexport async function preload() {\n await T.load();\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};","// =============================================================================\n// Module: Hatch\n// =============================================================================\n/**\n * The Hatch module contains functions and classes dedicated to applying\n * hatch patterns over shapes and polygons. It enables the simulation of\n * cross-hatching and shading effects by drawing parallel lines or strokes\n * across a geometry. The module supports adjustable spacing, angle, and\n * optional style parameters (such as randomness, continuity, and gradient),\n * giving an artistic representation similar to hand-drawn hatching techniques.\n *\n * The implementation allows for hatching to be applied either to a Polygon\n * directly or via a Plot, extending the drawing capabilities with layered,\n * stylized textures.\n */\n\nimport { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, cos, sin, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// ---------------------------------------------------------------------------\n// Hatch State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global hatch state settings.\n */\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow copy of the current hatch state.\n * @returns {object} The current hatch state.\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Updates the global hatch state.\n * @param {object} state - The new hatch state.\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Activates hatching for subsequent geometries.\n *\n * @param {number} dist - The distance between hatching lines.\n * @param {number} angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} options - Optional parameters to affect the hatching style:\n * - rand: Number value to introduce randomness.\n * - continuous: Boolean to connect adjacent lines.\n * - gradient: Number to gradually change spacing.\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Sets the hatch brush style for subsequent hatching.\n *\n * @param {string} brush - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} weight - The brush weight (size).\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Disables hatching.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a hatching pattern over the given polygon(s).\n *\n * @param {Polygon|Polygon[]} polygons - A polygon or an array of polygons.\n */\nexport function createHatch(polygons) {\n let dist = State.hatch.dist;\n let angle = ((State.hatch.angle % 180) + 180) % 180;\n let options = State.hatch.options;\n\n // Save current stroke state\n let save = BrushState();\n // If a hatch brush is set, override with those parameters.\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n\n // Compute overall bounding box for all polygons.\n if (!Array.isArray(polygons)) polygons = [polygons];\n const overallBB = computeOverallBoundingBox(polygons);\n\n // Build a bounding polygon based on the overall bounding box.\n let ventana = new Polygon([\n [overallBB.minX, overallBB.minY],\n [overallBB.maxX, overallBB.minY],\n [overallBB.maxX, overallBB.maxY],\n [overallBB.minX, overallBB.maxY],\n ]);\n\n // Determine starting y coordinate based on angle.\n let startY = angle <= 90 && angle >= 0 ? overallBB.minY : overallBB.maxY;\n let gradient = options.gradient\n ? map(options.gradient, 0, 1, 1, 1.1, true)\n : 1;\n let dots = [];\n let i = 0;\n let dist1 = dist;\n\n // Function to generate a line for index i.\n let linea = (i) => {\n return {\n point1: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90),\n y: startY + dist1 * i * sin(-angle + 90),\n },\n point2: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90) + cos(-angle),\n y: startY + dist1 * i * sin(-angle + 90) + sin(-angle),\n },\n };\n };\n\n // Generate lines and calculate intersections with polygons\n // Loop through the lines based on the distance and angle to calculate intersections with the polygons\n // The loop continues until a line does not intersect with the bounding window polygon\n // Each iteration accounts for the gradient effect by adjusting the distance between lines\n while (ventana.intersect(linea(i)).length > 0) {\n let tempArray = [];\n for (let p of polygons) {\n tempArray.push(p.intersect(linea(i)));\n }\n dots[i] = tempArray\n .flat()\n .sort((a, b) => (a.x === b.x ? a.y - b.y : a.x - b.x));\n dist1 *= gradient;\n i++;\n }\n\n // Filter out empty intersection sets.\n let gdots = dots.filter((dd) => typeof dd[0] !== \"undefined\");\n\n // Draw the hatching lines using the calculated intersections\n // If the 'rand' option is enabled, add randomness to the start and end points of the lines\n // If the 'continuous' option is set, connect the end of one line to the start of the next\n let r = options.rand || 0;\n for (let j = 0; j < gdots.length; j++) {\n let dd = gdots[j];\n let continuousLine = j > 0 && options.continuous;\n for (let i = 0; i < dd.length - 1; i += 2) {\n if (r !== 0) {\n dd[i].x += r * dist * rr(-1, 1);\n dd[i].y += r * dist * rr(-1, 1);\n dd[i + 1].x += r * dist * rr(-1, 1);\n dd[i + 1].y += r * dist * rr(-1, 1);\n }\n line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);\n if (continuousLine) {\n line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);\n }\n }\n }\n\n // Restore previous brush state.\n BrushSetState(save);\n}\n\n/**\n * Computes the bounding box for a single polygon.\n * @param {Polygon} polygon - The polygon to evaluate.\n * @returns {object} The bounding box as {minX, minY, maxX, maxY}.\n */\nfunction computeBoundingBoxForPolygon(polygon) {\n if (polygon._boundingBox) return polygon._boundingBox;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n for (let i = 0; i < polygon.a.length; i++) {\n const [x, y] = polygon.a[i];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n polygon._boundingBox = { minX, minY, maxX, maxY };\n return polygon._boundingBox;\n}\n\n/**\n * Computes an overall bounding box for an array of polygons.\n * @param {Array} polygons - Array of Polygon objects.\n * @returns {object} The overall bounding box {minX, minY, maxX, maxY}.\n */\nfunction computeOverallBoundingBox(polygons) {\n let overall = {\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity,\n };\n for (let poly of polygons) {\n const bb = computeBoundingBoxForPolygon(poly);\n overall.minX = Math.min(overall.minX, bb.minX);\n overall.minY = Math.min(overall.minY, bb.minY);\n overall.maxX = Math.max(overall.maxX, bb.maxX);\n overall.maxY = Math.max(overall.maxY, bb.maxY);\n }\n return overall;\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Adds a hatch effect to the polygon.\n *\n * If a distance is provided, activates hatching with the given parameters.\n * Then, if hatch is active, applies the hatching pattern.\n *\n * @param {number} [_dist] - The distance between hatch lines.\n * @param {number} _angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} _options - Optional hatch options.\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) {\n createHatch(this);\n }\n HatchSetState(state);\n};\n\n/**\n * Applies hatching to a plot.\n *\n * If hatching is active, generates a polygon from the plot and applies hatch.\n *\n * @param {number} x - The x-coordinate to draw at.\n * @param {number} y - The y-coordinate to draw at.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.25);\n this.pol.hatch();\n }\n};\n","import { Mix } from \"./color.js\";\n\nfunction transformPoint(matrix, x, y) {\n return {\n x: matrix.a * x + matrix.c * y + matrix.e,\n y: matrix.b * x + matrix.d * y + matrix.f,\n };\n}\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices) {\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n vertices.forEach((v, i) => {\n const point = transformPoint(matrix, v.x, v.y);\n minX = Math.min(minX, point.x);\n minY = Math.min(minY, point.y);\n maxX = Math.max(maxX, point.x);\n maxY = Math.max(maxY, point.y);\n\n if (i === 0) ctx.moveTo(v.x, v.y);\n else ctx.lineTo(v.x, v.y);\n });\n ctx.closePath();\n\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n const radius = d / 2;\n const center = transformPoint(matrix, x, y);\n const rx = radius * Math.hypot(matrix.a, matrix.c);\n const ry = radius * Math.hypot(matrix.b, matrix.d);\n const padding = strokePadding(ctx, matrix);\n\n Mix.markDirtyRect(Mix.mask, {\n minX: center.x - rx - padding,\n minY: center.y - ry - padding,\n maxX: center.x + rx + padding,\n maxY: center.y + ry + padding,\n });\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\nimport { Renderer, Mix, State, Cwidth, Cheight, Density } from \"../core/color.js\";\nimport { drawPolygon, circle } from \"../core/mask.js\";\nimport {\n constrain,\n weightedRand,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady, Matrix } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 1024;\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color =\n arguments.length < 3 ? Renderer.color(a) : Renderer.color(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length < 8) {\n // Simple average for small polygons\n return pts\n .reduce((c, p) => ({ x: c.x + p.x, y: c.y + p.y }), { x: 0, y: 0 })\n .map((v) => v / pts.length);\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n const v = [...polygon.vertices];\n\n // Map vertices\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n\n // Create bleed modifiers\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.2) * strength,\n );\n\n // Randomize starting point\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n\n // Calculate center and create FillPolygon\n const center = _center(shifted);\n new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions\n this.dir = Array(v.length);\n rayCalc.forEach((rc, i) => {\n let count = 0;\n for (const isect of _polygon.intersect(rc.ray)) {\n if (_isLeft(rc.v1, rc.v2, isect)) count++;\n }\n this.dir[i] = count % 2 === 0;\n });\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: [...this.v], m: [...this.m], dir: [...this.dir] };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Clone and splice\n const v = [...this.v],\n m = [...this.m],\n dir = [...this.dir];\n v.splice(s, n);\n m.splice(s, n);\n dir.splice(s, n);\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n\n // Build sorted random indices\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [], sm = [], sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n\n // Ray-cast: count intersections from p to far right\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y, by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n // If outside (even crossings), pull toward center\n if (crossings % 2 === 0) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]); // flip direction → grow inward\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n // Get trimmed vertices\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n \n // Pre-allocate output arrays\n const outLen = len * 2;\n const newVerts = new Array(outLen);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\n \n // Determine bleed direction\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n \n // Ensure gaussian pool is filled\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0], gPoolLen = gPool.length;\n const g2Pool = _gaussians[1], g2PoolLen = g2Pool.length;\n \n let idx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n \n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n \n if (f < 997) mod = mi;\n \n // Inline rotate: rotDeg = ±bleedDirDeg + small jitter\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n \n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n \n // Outward distance: inline rArray + rr\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n \n // First vertex: original\n newVerts[idx] = cv;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n \n // Second vertex: midpoint + outward push\n newVerts[idx] = {\n x: cv.x + sideX * 0.5 + dirX * d,\n y: cv.y + sideY * 0.5 + dirY * d,\n };\n newMods[idx] = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n newDirs[idx] = di;\n idx++;\n }\n \n // Cap vertex count to prevent exponential blowup.\n let fv = newVerts, fm = newMods, fd = newDirs;\n let growe = GROW_MAX_VERTS / (State.fill.texture_strength);\n if (growe && idx > growe) {\n const step = Math.ceil(idx / growe);\n fv = []; fm = []; fd = [];\n for (let j = 0; j < idx; j += step) {\n fv.push(newVerts[j]);\n fm.push(newMods[j]);\n fd.push(newDirs[j]);\n }\n } else {\n // Trim pre-allocated arrays to actual size\n fv.length = idx;\n fm.length = idx;\n fd.length = idx;\n }\n \n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n // Precalculate stuff\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n // Perform initial setup only once\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(), Density * Matrix.b(),\n Density * Matrix.c(), Density * Matrix.d(),\n Density * (Matrix.x() + Cwidth / 2),\n Density * (Matrix.y() + Cheight / 2),\n );\n\n Mix.ctx.strokeStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${\n 0.005 * State.fill.border_strength\n })`;\n Mix.ctx.lineCap = \"round\";\n\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n\n // Create initial polygon\n let pol = this.grow();\n // Create sparse inner polygon from original (pre-grow) vertices\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n // Grow polygon every 4 layers\n if (i % 4 === 0) pol = pol.grow();\n\n // Create variant polygons\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n // Draw layers\n for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);\n sparse.grow(999).flipDirs().grow(997).layer(i, size, int * 1.5 * texture, color);\n if (i % 2 === 0)\n pol\n .grow(darker)\n .grow(999)\n .layer(i, size, int * 2, color);\n\n // Apply texture and blend periodically\n if (i % 5 === 0 || i === numLayers - 1) {\n if (texture !== 0) pol.erase(texture * 3, intensity);\n Mix.blend(color, true, false, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, color) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\n drawPolygon(this.v);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n // Optimize by pre-calculating values\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.4 - State.fill.bleed_strength);\n const minSizeFactor = 0.05 * minSize;\n const maxSizeFactor = 0.4 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n // Set up erase mode\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n // Calculate transparency\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n // Draw erase circles\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const size = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, size);\n if (i % 5 !== 0) Mix.ctx.fill();\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n map(State.fill.bleed_strength, 0, 0.6, 0.3, 0.45, true),\n );\n this.pol.fill();\n }\n};\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n}\n","/**\n * @fileoverview p5.brush - A comprehensive toolset for brush management in p5.js.\n * @version 2.0.0-alpha\n * @license MIT\n * @author Alejandro Campos Uribe\n *\n * @description\n * p5.brush is a p5.js library dedicated to the creation and management of custom brushes.\n * It extends the drawing capabilities of p5.js by allowing users to simulate a wide range\n * of brush strokes, vector fields, hatching patterns, and fill textures. These features\n * are essential for emulating the nuanced effects found in traditional sketching and painting.\n * Whether for digital art applications or procedural generation of graphics, p5.brush provides\n * a robust framework for artists and developers to create rich, dynamic, and textured visuals.\n *\n * @example\n * // Basic usage:\n * brush.pick('marker'); // Select brush type\n * brush.stroke(255, 0, 0); // Set brush color\n * brush.strokeWeight(10); // Set brush size\n * brush.line(25, 25, 75, 75); // Draw a line\n *\n * // Add a new brush type:\n * brush.add('customBrush', { /* parameters for the brush *\\/ });\n * brush.pick('customBrush');\n *\n * // Use the custom brush for a vector-field line:\n * brush.field('field_name') // Pick a flowfield\n * brush.flowLine(50, 50, 100, PI / 4); // Draw a line within the vector-field; angle follows p5 angleMode()\n *\n * // Fill textures:\n * brush.noStroke();\n * brush.fill('#FF0000', 90); // Set fill color to red and opacity to 90\n * brush.bleed(0.3); // Set bleed effect for a watercolor-like appearance\n * brush.rect(100, 100, 50, 50); // Fill a rectangle with the bleed effect\n *\n * @license\n * MIT License\n *\n * Copyright (c) 2023-2024 Alejandro Campos Uribe\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n// Randomness and other auxiliary functions\nexport { weightedRand as wRand } from \"./core/utils.js\";\n\n// Color Blending\nexport { load, instance } from \"./core/color.js\";\n\n// Matrix transformations, FlowField and Position Class\nexport {\n field,\n noField,\n addField,\n refreshField,\n listFields,\n Position,\n wiggle,\n} from \"./core/flowfield.js\";\n\n// Polygon and Plot classes\nexport { Polygon } from \"./core/polygon.js\";\nexport { Plot } from \"./core/plot.js\";\n\n// Primitives\nexport {\n rect,\n circle,\n arc,\n beginShape,\n vertex,\n endShape,\n beginStroke,\n move,\n endStroke,\n spline,\n polygon,\n} from \"./core/primitives.js\";\n\n// Brushes\nexport {\n add,\n box,\n scaleBrushes,\n pick,\n stroke,\n strokeWeight,\n set,\n noStroke,\n clip,\n noClip,\n line,\n flowLine,\n} from \"./stroke/stroke.js\";\n\n// Section: Hatching\nexport {\n hatch,\n hatchStyle,\n noHatch,\n createHatch as hatchArray,\n} from \"./hatch/hatch.js\";\n\n// Fill\nexport { fill, noFill, fillTexture, fillBleed } from \"./fill/fill.js\";\n\n// p5 addon registration\nimport { Mix } from \"./core/color.js\";\nimport { push as brushPush, pop as brushPop } from \"./core/save.js\";\nimport { seed as brushSeed, noiseSeed as brushNoiseSeed } from \"./core/utils.js\";\n\nfunction registerAddon(_p5, fn, lifecycles) {\n lifecycles.postsetup = () => Mix.blend(false, true);\n lifecycles.postdraw = () => Mix.blend(false, true);\n\n const _push = fn.push;\n const _pop = fn.pop;\n const _randomSeed = fn.randomSeed;\n const _noiseSeed = fn.noiseSeed;\n\n fn.push = function () {\n _push.call(this);\n brushPush();\n };\n\n fn.pop = function () {\n _pop.call(this);\n brushPop();\n };\n\n fn.randomSeed = function (s) {\n _randomSeed.call(this, s);\n brushSeed(s);\n };\n\n fn.noiseSeed = function (s) {\n _noiseSeed.call(this, s);\n brushNoiseSeed(s);\n };\n}\n\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerAddon);\n"],"names":["Cwidth","Cheight","Instance","Renderer","Density","isFramebufferTarget","target","begin","end","renderer","_pInst","getSketchRenderer","_isInstanced","window","self","p5","instance","removeTargetBuffer","buffer","remove","getActiveFramebuffer","_renderer","activeFramebuffer","getTargetPixelSize","width","Math","max","round","height","normalizeDirtyRect","rect","minX","floor","min","maxX","minY","maxY","ceil","getFullDirtyRect","withScissor","gl","draw","box","normalized","x","y","toScissorBox","wasEnabled","isEnabled","SCISSOR_TEST","prevBox","getParameter","SCISSOR_BOX","enable","scissor","disable","load","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","isMixReady","isBlending","cachedColor","Object","markDirtyRect","a","b","dirtyRect","isDrawn","markFull","clearMask","clear","getCompositeRect","isBrushMask","padding","expandDirtyRect","captureBlendSource","framebuffer","blendSourceFramebuffer","pixelDensity","createFramebuffer","density","antialias","depth","stencil","source","drawingContext","push","imageMode","CENTER","image","pop","graphicsFactory","createGraphics","p2dMode","P2D","webglMode","WEBGL","mask","glMask","this","ctx","shaderProgram","createShader","angleMode","DEGREES","lineWidth","uModelMatrix","blend","_color","_isLast","activeIsBrush","isBrush","no_mask","nextColor","_array","colorChanged","justChanged","applyShader","shader","targetIsFramebuffer","hadDepthTest","DEPTH_TEST","translate","setUniform","fill","noStroke","resetShader","SQRT3","sqrt","F2","G2","fastFloor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","c","s0","s1","s2","copy","f","rng","_seedCallbacks","_onSeed","cb","noise","rr","e","rArray","array","randInt","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","d","withinBounds","constrain","low","high","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","NaN","sLookup","idx","sin","toDegrees","rad","isRad","RADIANS","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","Matrix","mat4","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","update","plotted","colIdx","getColIndex","rowIdx","getRowIndex","reset","isIn","isActive","isInCanvas","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","y_offset","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","has","generateField","entry","normalizeFieldAngles","gen","keys","join","name","funct","set","fn","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","intersection","show","stroke","hatch","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","_current","_curvature","_strokeArray","_strokeOrigin","SubPath","isClosed","curvature","vert","vertex","_createSpline","beginShape","endShape","close","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","radius","halfDist","arcLength","asin","origin","projMatrix","vao","buf","program","loadedWidth","loadedHeight","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circle","diameter","alpha","newData","px","py","screenX","screenY","glDraw","color","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","uniform4f","u_color","uniformMatrix4fv","u_matrix","drawArrays","POINTS","_curShader","weight","clipWindow","opacity","_position","Mask","_strokeTransform","tx","ty","BrushState","BrushSetState","state","add","params","includes","undefined","vibration","scatter","definition","sharpness","quality","grain","isArray","min_max","curve","m","range","ns","nm","ne","normalizePressure","src","T","tip","tips","param","colors","buffers","pick","brushName","g","arguments","strokeWeight","snapshotTransform","transformPoint","transform","normalizeRegion","region","screenPointFromPosition","point","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","noiseoffset","dirRad","nextGl","needsContextRefresh","createProgram","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","isReady","switchingToBrush","isInsideClippingArea","calculateAlpha","markerTip","saveState","stepSize","spacing","totalSteps","customPressure","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","local","inverse","bounds","o","vibrate","rx","ry","setAlpha","tint","adjustSizeAndRotation","halfWeight","radians","cosAngle","sinAngle","userCenterX","userCenterY","corners","Infinity","markImageTipDirty","_vals","_standard_brushes","obj","_m","prototype","_brush","_weight","imageToWhite","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","p5img","createImage","naturalWidth","naturalHeight","drawImage","onerror","HatchState","rand","continuous","gradient","createHatch","polygons","save","hBrush","values","overallBB","overall","poly","bb","computeBoundingBoxForPolygon","computeOverallBoundingBox","ventana","startY","dots","dist1","linea","tempArray","flat","sort","gdots","dd","continuousLine","polygon","_boundingBox","matrix","strokePadding","getTransform","center","arc","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","sx","sy","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","splice","ratio","L","keep","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","newVerts","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","fv","fm","fd","growe","intensity","tex","texture","int","switchingToFill","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","size","darker","sparse","pols","layer","numLayers","erase","restore","fillStyle","beginPath","lineTo","closePath","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","_opacity","_bleed","fluid","strength","modifiers","_","shift","shifted","slice","pts","area","cross","_center","createFill","FillSetState","_stateStack","registerAddon","_p5","lifecycles","postsetup","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","callback","brushSeed","brushNoiseSeed","startDeg","sweepDeg","segmentCount","segmentSweep","startX","angleOffset","randomFactor","randomAngle","offsetX","offsetY","det","invertTransform","brush","inst","mode","currentField","_array_points"],"mappings":"6BAYO,IAAIA,EAAQC,EAASC,EAAUC,EAAUC,EAEhD,MAAMC,EAAuBC,KACzBA,GACsB,mBAAjBA,EAAOC,OACQ,mBAAfD,EAAOE,OACZF,EAAOG,YACPH,EAAOG,SAASC,OAEdC,EAAoB,IACxBC,EAAeV,EAAWW,OAAOC,KAAKC,GAAGC,SA4CrCC,EAAsBC,IACtBA,GAAmC,mBAAlBA,EAAOC,QAC1BD,EAAOC,UAOLC,EAAuB,IAC3BjB,GACAA,EAASkB,WACuC,mBAAzClB,EAASkB,UAAUC,kBACtBnB,EAASkB,UAAUC,oBACnB,KAoBAC,EAAqB,KAAA,CACzBC,MAAOC,KAAKC,IAAI,EAAGD,KAAKE,MAAM3B,EAASI,IACvCwB,OAAQH,KAAKC,IAAI,EAAGD,KAAKE,MAAM1B,EAAUG,MAarCyB,EAAsBC,I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iC,UAAW,CACzB,WS1NO,WACL7P,EAAMkE,KAAK2L,UAAW,CACxB,YFPO,WACL7P,EAAMoT,MAAMvD,UAAW,EACvB7P,EAAMoT,MAAMwR,QAAS,CACvB,aFiIO,WACL5kB,EAAMmT,OAAOtD,UAAW,CAC1B,sBF5MO,SAAiBuC,GAEN,IAAID,GAAQC,GACpBc,MACV,SAUO,SAActU,EAAGC,EAAGmQ,EAAG9G,EAAGgoB,EAAO,UACzB,WAATA,IACFtxB,GAAKoQ,EAAI,EACTnQ,GAAKqJ,EAAI,GAEX8N,GAAW,GACXF,GAAOlX,EAAGC,GACViX,GAAOlX,EAAIoQ,EAAGnQ,GACdiX,GAAOlX,EAAIoQ,EAAGnQ,EAAIqJ,GAClB4N,GAAOlX,EAAGC,EAAIqJ,GACd+N,IAAS,EACX,iBH6NO,SAAsBlQ,EAAI,GAC/B,IAAK/F,EAAM4N,MAAMiC,WAAa7P,EAAM4N,MAAMqC,QACxC,MAAM,IAAIxQ,MACR,6FAGJ,MAAM0wB,EAAepgB,GAAKC,IAAIhQ,EAAM4N,MAAMqC,SAC1CkgB,EAAaviB,MAAQ6D,GAAc0e,EAAcpqB,EACnD,iBK9GO,SAAsB+K,GAC3B,IAAK,MAAMkM,MAAEA,KAAWjN,GAAK8U,SACvB7H,IACFA,EAAMlC,QAAUhK,EAChBkM,EAAMlB,SAAWhL,EACjBkM,EAAMkD,SAAWpP,EAGvB,oBF4EO,SAAgBsf,EAAe7a,EAAa,IACjD,IAAK6a,GAAiBA,EAAcpoB,OAAS,EAC3C,MAAM,IAAIvI,MACR,+EAGIsW,GAAcqa,EAAe7a,GACnC9W,MACJ,+DHmFO,SAAgB6B,EAAI,GACzBsN,GAAM,QACN5N,EAAM4N,MAAMsC,OAAS5P,CACvB","x_google_ignoreList":[1,2]}
\ No newline at end of file
diff --git a/example/sketch.js b/example/sketch.js
index 7130063..2574f6a 100644
--- a/example/sketch.js
+++ b/example/sketch.js
@@ -1,256 +1,353 @@
-//////////////////////////////////////////////////
+// =============================================================================
+// p5.brush — Live Tutorial Sketch
+//
+// This sketch cycles through 6 scenes, each demonstrating a core feature
+// of the p5.brush library. Click anywhere to pause on the current scene.
+//
+// Scenes:
+// 0 · Brush Rain — brush.flowLine() with a vector field
+// 1 · Fields — every built-in vector field cycling in sequence
+// 2 · Strokes — brush types, brush.set(), brush.pick()
+// 3 · Hatches — brush.hatch() inside polygons
+// 4 · Watercolor — brush.fill(), fillBleed(), fillTexture()
+// 5 · Splines — brush.spline() with per-point pressure
+// =============================================================================
+
+
+// ── Responsive canvas ────────────────────────────────────────────────────────
+// Fits the canvas to the browser window while preserving its aspect ratio.
function adjustCanvas(id) {
- let canvas = document.getElementById(id);
- canvas.style.maxWidth = "100vw";
- canvas.style.maxHeight = "100vh";
- canvas.style.width = "auto";
- canvas.style.height = "auto";
- canvas.style.objectFit = "contain";
+ let canvas = document.getElementById(id);
+ canvas.style.maxWidth = "100vw";
+ canvas.style.maxHeight = "100vh";
+ canvas.style.width = "auto";
+ canvas.style.height = "auto";
+ canvas.style.objectFit = "contain";
}
-//////////////////////////////////////////////////
-let palette = ["#002185", "#003c32", "#fcd300", "#ff2702", "#6b9404"]
-let seeds = []
-let isBackgroundDrawn = false;
-let rrr = 213123;
+// ── Globals ───────────────────────────────────────────────────────────────────
-let font;
+// A hand-picked colour palette used across all scenes.
+let palette = ["#002185", "#003c32", "#fcd300", "#ff2702", "#6b9404"];
+// Pre-generated random seeds — one per element — so each frame redraws
+// identically (deterministic randomness prevents shimmering).
+let seeds = [];
+
+let isBackgroundDrawn = false; // prevents background() wiping accumulating scenes
+let rrr = 213123; // seed that can be refreshed mid-scene
+
+let font; // loaded in setup(), used for scene labels
+
+
+// ── Setup ─────────────────────────────────────────────────────────────────────
async function setup() {
-
+
+ // p5.brush requires a WEBGL canvas.
let c = createCanvas(600, 600, WEBGL);
c.id("main");
adjustCanvas("main");
-
- // In p5 2.x, loadFont must be awaited in an async setup()
- font = await loadFont('https://fonts.gstatic.com/s/inter/v3/UcCO3FwrK3iLTeHuS_fvQtMwCp50KnMw2boKoduKmMEVuGKYMZhrib2Bg-4.ttf')
+
+ // In p5 2.x, loadFont must be awaited inside an async setup().
+ font = await loadFont("https://fonts.gstatic.com/s/inter/v3/UcCO3FwrK3iLTeHuS_fvQtMwCp50KnMw2boKoduKmMEVuGKYMZhrib2Bg-4.ttf");
angleMode(DEGREES);
- brush.load()
- brush.scaleBrushes(3.5)
- // Custom watercolor brush
+ // brush.scaleBrushes() multiplies the weight and scatter of every
+ // built-in brush by the given factor — handy for high-resolution canvases.
+ brush.scaleBrushes(3.5);
+
+ // ── Custom brush ──────────────────────────────────────────────────────────
+ // brush.add() registers a new brush you can use anywhere in your sketch.
+ // "custom" type means you supply a tip function that draws the stamp shape.
+ // Each line of the tip receives a graphics context (_m) with full p5 2D API.
+ //
+ // Try the interactive Brush Maker to design your own:
+ // https://acamposuribe.github.io/p5.brush/tools/brush-maker.html
brush.add("watercolor", {
- type: "custom",
- weight: 5,
- scatter: 1,
- sharpness: 0.5,
- grain: 8,
- opacity: 10,
- spacing: 0.4,
- blend: true,
- pressure: [0.78, 1.3],
- tip: (_m) => { _m.rect(-5, -5, 10, 10); _m.rect(5, 5, 4, 4); },
- rotate: "natural"
- })
-
- for (let i = 0; i < 150; i++) seeds.push(random())
- background("#fffceb")
-
- frameRate(30)
+ type: "custom",
+ weight: 5,
+ scatter: 1, // sideways spread of each stamp
+ opacity: 10, // very transparent — builds up like real watercolour
+ spacing: 0.4, // stamps placed close together for a smooth wash
+ pressure: [0.78, 1.3],// stroke grows from start to end
+ tip: (_m) => { _m.rect(-5, -5, 10, 10); _m.rect(5, 5, 4, 4); },
+ rotate: "natural" // tip rotates to follow the stroke direction
+ });
+
+ // Fill the seeds array with stable randoms for deterministic drawing.
+ for (let i = 0; i < 150; i++) seeds.push(random());
+ background("#fffceb");
+ frameRate(30);
}
+
+// ── Draw loop ─────────────────────────────────────────────────────────────────
function draw() {
-
- const t = frameCount / 30
- let scene = floor(t / 5) % 6
- textFont(font)
- translate(-width / 2, -height / 2)
+ // t advances once per second; scene changes every 5 seconds, cycling 0–5.
+ const t = frameCount / 30;
+ const scene = floor(t / 5) % 6;
+
+ textFont(font);
- // --- Scene 0: Brush Rain ---
+ // In WEBGL mode the origin is at the canvas centre. Shifting it to the
+ // top-left lets us use the same coordinate system as 2D mode (0,0 = top-left).
+ translate(-width / 2, -height / 2);
+
+
+ // ── Scene 0 · Brush Rain ──────────────────────────────────────────────────
+ // Demonstrates: brush.field(), brush.set(), brush.flowLine()
+ //
+ // flowLine() draws a single stroke that follows the active vector field.
+ // Here every frame adds a new line, building up a layered composition.
if (scene === 0) {
if (!isBackgroundDrawn) {
- background("#fffceb"), isBackgroundDrawn = true;
+ background("#fffceb");
+ isBackgroundDrawn = true;
}
- // Title
- push()
- noStroke()
- fill(0)
- translate(-20 + width / 2, -5 + height / 2)
- textAlign(CENTER, CENTER)
- textSize(50)
- text('*p5.brush', 0, 0)
- pop()
-
- let colores = ["#2c695a", "#4ad6af", "#7facc6", "#4e93cc", "#f6684f", "#ffd300"]
- let brushes = ["marker", "watercolor", "spray", "charcoal", "HB", "2B", "cpencil", "2H", "rotring"]
-
- brush.field("seabed")
- brush.set(random(brushes), random(colores), random(0.7, 1.6))
- brush.flowLine(random(width), random(height), random(140, 240), random(360))
+ // Scene label — drawn with native p5 text on top of brush strokes.
+ push();
+ noStroke(); fill(0);
+ translate(-20 + width / 2, -5 + height / 2);
+ textAlign(CENTER, CENTER); textSize(50);
+ text("*p5.brush", 0, 0);
+ pop();
+
+ const colores = ["#2c695a", "#4ad6af", "#7facc6", "#4e93cc", "#f6684f", "#ffd300"];
+ const brushes = ["marker", "watercolor", "spray", "charcoal", "HB", "2B", "cpencil", "2H", "rotring"];
+
+ // Activate a vector field. "seabed" produces gentle organic curves.
+ // While a field is active, every flowLine() bends to follow it.
+ brush.field("seabed");
+
+ // brush.set(name, color, weight) picks the brush, colour, and size in one call.
+ brush.set(random(brushes), random(colores), random(0.7, 1.6));
+
+ // brush.flowLine(x, y, length, direction) — the stroke starts at (x,y),
+ // travels `length` canvas units, and bends along the current vector field.
+ brush.flowLine(random(width), random(height), random(140, 240), random(360));
}
- // --- Scene 1: Vector Fields ---
+
+ // ── Scene 1 · Vector Fields ───────────────────────────────────────────────
+ // Demonstrates: brush.listFields(), brush.field(), brush.pick(), brush.circle()
+ //
+ // Every built-in field is shown in turn so you can compare them.
if (scene === 1) {
isBackgroundDrawn = false;
background("#080f15");
- let flowfields = brush.listFields()
- if (t % 1 == 0) brush.field(flowfields[floor(t % flowfields.length)])
+ // brush.listFields() returns an array of every registered field name.
+ const flowfields = brush.listFields();
- randomSeed(33213 * seeds[67])
- brush.set("charcoal", "white", 1)
- brush.circle(300, 300, 180, true)
+ // Rotate through all fields once per second.
+ if (t % 1 === 0) brush.field(flowfields[floor(t % flowfields.length)]);
- brush.pick("HB")
- randomSeed(33213 * seeds[97])
+ // brush.circle() is affected by the active field — its outline bends
+ // organically. The last argument (0–1) controls hand-drawn irregularity.
+ randomSeed(33213 * seeds[67]);
+ brush.set("charcoal", "white", 1);
+ brush.circle(300, 300, 180, 0.3);
+
+ // brush.pick() swaps the brush type while keeping the current colour and weight.
+ brush.pick("HB");
+ randomSeed(33213 * seeds[97]);
for (let i = 0; i < 30; i++) {
- brush.flowLine(random(width), random(height), 75, 0)
+ brush.flowLine(random(width), random(height), 75, 0);
}
- push()
- noStroke()
- fill(210)
- textAlign(CENTER, CENTER)
- textSize(40)
- text('*field()', 300, 300)
- pop()
+ push();
+ noStroke(); fill(210);
+ textAlign(CENTER, CENTER); textSize(40);
+ text("*field()", 300, 300);
+ pop();
}
- // --- Scene 2: Brush Wheel ---
+
+ // ── Scene 2 · Brush Wheel ─────────────────────────────────────────────────
+ // Demonstrates: brush.flowLine() radiating from a centre, brush.noField()
+ //
+ // Lines are fired outward from a point on a rotating circle,
+ // flowing along the "seabed" field to produce a spinning bloom.
if (scene === 2) {
isBackgroundDrawn = false;
background("#e2e7dc");
- let brushes = ["marker", "marker", "watercolor", "watercolor", "charcoal", "HB", "2B", "rotring"]
- brush.field("seabed")
+ const brushes = ["marker", "marker", "watercolor", "watercolor", "charcoal", "HB", "2B", "rotring"];
+ brush.field("seabed");
- let cx = 300, cy = 300;
+ const cx = 300, cy = 300;
for (let i = 0; i < 20; i++) {
- let angle = (i * 18 + t * 30)
- randomSeed(33213 * seeds[i])
- brush.set(random(brushes), random(palette), 1)
- brush.flowLine(cx + 100 * cos(-angle), cy + 100 * sin(-angle), 320, angle)
+ const angle = i * 18 + t * 30;
+ randomSeed(33213 * seeds[i]);
+ brush.set(random(brushes), random(palette), 1);
+ // Start each flowLine on a circle of radius 100 around the centre,
+ // firing outward at the same angle — field bending does the rest.
+ brush.flowLine(cx + 100 * cos(-angle), cy + 100 * sin(-angle), 320, angle);
}
- brush.noField()
- if ((t * 10) % 5 == 0) { rrr = Math.random() * 23122 }
- randomSeed(rrr)
- brush.set(random(brushes), random(palette), 1)
- brush.circle(300, 300, 100, 0.2)
-
- push()
- noStroke()
- fill(40)
- textAlign(CENTER, CENTER)
- textSize(40)
- text('*stroke()', 300, 300)
- pop()
+ // brush.noField() deactivates the field so the centre circle
+ // is drawn without bending.
+ brush.noField();
+ if ((t * 10) % 5 === 0) rrr = Math.random() * 23122;
+ randomSeed(rrr);
+ brush.set(random(brushes), random(palette), 1);
+ brush.circle(300, 300, 100, 0.2);
+
+ push();
+ noStroke(); fill(40);
+ textAlign(CENTER, CENTER); textSize(40);
+ text("*stroke()", 300, 300);
+ pop();
}
- // --- Scene 3: Hatches ---
+
+ // ── Scene 3 · Hatches ─────────────────────────────────────────────────────
+ // Demonstrates: brush.hatchStyle(), brush.hatch(), brush.polygon(), brush.noHatch()
+ //
+ // Hatching fills a shape with parallel lines drawn by a brush.
+ // The polygon vertices jitter each frame, making the shape feel alive.
if (scene === 3) {
isBackgroundDrawn = false;
background("#ffe6d4");
- randomSeed(33213 * seeds[56])
- brush.set("pen", "#000000", 1)
-
- randomSeed(33213 * seeds[35])
- brush.hatchStyle("HB", "#c76282", 1.3)
- brush.hatch(15, 45)
+ // brush.hatchStyle() sets the brush, colour, and weight used for the hatch lines.
+ // brush.hatch(spacing, angle) activates hatching — every shape drawn
+ // after this call will be filled with parallel lines at `angle` degrees,
+ // spaced `spacing` canvas units apart.
+ randomSeed(33213 * seeds[35]);
+ brush.hatchStyle("HB", "#c76282", 1.3);
+ brush.hatch(15, 45);
brush.polygon([
- [80 + 20 * sin(random(0, 360) + t * 150), 150 + 20 * sin(random(0, 360) + t * 150)],
+ [80 + 20 * sin(random(0, 360) + t * 150), 150 + 20 * sin(random(0, 360) + t * 150)],
[180 + 20 * sin(random(0, 360) + t * 150), 150 + 20 * sin(random(0, 360) + t * 150)],
[420 + 20 * sin(random(0, 360) + t * 150), 150 + 20 * sin(random(0, 360) + t * 150)],
[480 + 20 * sin(random(0, 360) + t * 150), 450 + 20 * sin(random(0, 360) + t * 150)],
[280 + 20 * sin(random(0, 360) + t * 150), 450 + 20 * sin(random(0, 360) + t * 150)],
[130 + 20 * sin(random(0, 360) + t * 150), 450 + 20 * sin(random(0, 360) + t * 150)],
- ])
+ ]);
- randomSeed(33213 * seeds[75])
- brush.hatchStyle("marker", "#e0b411", 1.3)
- brush.hatch(10, 130, { rand: 0.1 })
+ // A second hatch style on the overlapping triangle — different brush and angle.
+ // The { rand } option adds slight randomness to line spacing for a looser look.
+ randomSeed(33213 * seeds[75]);
+ brush.hatchStyle("marker", "#e0b411", 1.3);
+ brush.hatch(10, 130, { rand: 0.1 });
brush.polygon([
[250 + 20 * cos(360 * sin(random(0, 360) + t * 120)), 250 + 20 * sin(random(0, 360) + t * 120)],
[500 + 40 * cos(360 * sin(random(0, 360) + t * 120)), 300 + 50 * sin(random(0, 360) + t * 120)],
[300 + 10 * cos(360 * sin(random(0, 360) + t * 120)), 520 + 30 * sin(random(0, 360) + t * 120)],
- ])
+ ]);
- push()
- noStroke()
- fill(50)
- textAlign(CENTER, CENTER)
- textSize(40)
- text('*hatch()', 300, 300)
- pop()
+ push();
+ noStroke(); fill(50);
+ textAlign(CENTER, CENTER); textSize(40);
+ text("*hatch()", 300, 300);
+ pop();
- brush.noHatch()
+ // Always call noHatch() when you are done so subsequent shapes are not hatched.
+ brush.noHatch();
}
- // --- Scene 4: Fill ---
+
+ // ── Scene 4 · Watercolor Fill ─────────────────────────────────────────────
+ // Demonstrates: brush.fill(), brush.fillBleed(), brush.fillTexture(), brush.noFill()
+ //
+ // p5.brush simulates watercolour washes: soft edges, bleed, and paper texture.
+ // Shapes accumulate on a fixed background, building up layers over time.
if (scene === 4) {
if (!isBackgroundDrawn) {
- background("#fffceb"), isBackgroundDrawn = true;
- push()
- noStroke()
- fill(0)
- translate(-20 + width / 2, -5 + height / 2)
- textAlign(CENTER, CENTER)
- textSize(40)
- text('*fill()', 0, 0)
- pop()
+ background("#fffceb");
+ isBackgroundDrawn = true;
+
+ push();
+ noStroke(); fill(0);
+ translate(-20 + width / 2, -5 + height / 2);
+ textAlign(CENTER, CENTER); textSize(40);
+ text("*fill()", 0, 0);
+ pop();
}
- brush.set("marker", "#e0b411", 1.1)
- let colores = ["#7b4800", "#002185", "#003c32", "#fcd300", "#ff2702", "#6b9404"];
- if ((10 * t) % 3 == 0) {
- brush.fill(random(colores), random(60, 110))
- brush.fillBleed(random(0.1, 0.55))
- brush.fillTexture(0.4, 0.4)
- brush.rect(random(width), random(height), random(50, 140), random(50, 140), "center")
- brush.noFill()
+
+ const colores = ["#7b4800", "#002185", "#003c32", "#fcd300", "#ff2702", "#6b9404"];
+ brush.set("marker", "#e0b411", 1.1);
+
+ if ((10 * t) % 3 === 0) {
+ // brush.fill(color, opacity) enables watercolour fill for the next shape.
+ // Opacity works on a 0–255 scale — low values let washes build up in layers.
+ brush.fill(random(colores), random(60, 110));
+
+ // fillBleed controls how much colour bleeds outside the shape edge (0–1).
+ brush.fillBleed(random(0.1, 0.55));
+
+ // fillTexture adds paper grain and a darker border (both 0–1).
+ brush.fillTexture(0.4, 0.4);
+
+ brush.rect(random(width), random(height), random(50, 140), random(50, 140), "center");
+
+ // brush.noFill() disables fill so subsequent shapes are stroke-only.
+ brush.noFill();
}
}
- // --- Scene 5: Splines ---
+
+ // ── Scene 5 · Splines ────────────────────────────────────────────────────
+ // Demonstrates: brush.spline(), per-point pressure, multiple overlapping curves
+ //
+ // brush.spline() draws a smooth curve through an array of [x, y, pressure] points.
+ // Pressure (0–2) controls stroke thickness at each point along the path.
if (scene === 5) {
isBackgroundDrawn = false;
background("#445e87");
- brush.noField()
+ brush.noField();
- brush.set("2B", "#0e2d58", 2)
- randomSeed(33213 * seeds[67])
- brush.circle(155, 140, 50)
+ // A circle drawn with the "2B" brush — notice the soft charcoal-like edge.
+ randomSeed(33213 * seeds[67]);
+ brush.set("2B", "#0e2d58", 2);
+ brush.circle(155, 140, 50);
- randomSeed(33213 * seeds[67])
+ randomSeed(33213 * seeds[67]);
- let points = [
- [30, 30, 1],
+ // Control points as [x, y, pressure]. The third point animates over time,
+ // making the family of curves ripple smoothly.
+ const points = [
+ [30, 30, 1],
[250, 100, random(0.8, 1.5)],
[280 - 150 * cos(360 * sin(random(0, 360) + t * 90)), 300 + 50 * sin(random(0, 360) + t * 90), random(0.8, 1.5)],
- [570, 570, 1]
- ]
+ [570, 570, 1],
+ ];
if (points[1][0] === points[1][1]) points[1][0] += 1;
- brush.set("charcoal", "white", 1)
- brush.spline(points, 1)
- brush.set("2H", "white", 1)
+ // The main spine in charcoal white, then four offset copies in lighter pencil
+ // — stacking curves builds the sense of a hand-drawn bundle of lines.
+ brush.set("charcoal", "white", 1);
+ brush.spline(points, 1);
+
+ brush.set("2H", "white", 1);
for (let i = 1; i <= 4; i++) {
- let p = [
+ const p = [
[points[0][0] + 55 * i, points[0][1], 1],
- [points[1][0] - 3 * i, points[1][1] + 5 * i, 1],
+ [points[1][0] - 3 * i, points[1][1] + 5 * i, 1],
points[2],
[points[3][0] - 100 * i, points[3][1], 1],
- ]
- randomSeed(33213 * seeds[62])
- brush.spline(p, 1)
+ ];
+ randomSeed(33213 * seeds[62]);
+ brush.spline(p, 1);
}
- push()
- noStroke()
- fill(210)
- translate(points[2][0], points[2][1])
- textAlign(LEFT, CENTER)
- textSize(40)
- text('*spline()', 0, 0)
- pop()
+ push();
+ noStroke(); fill(210);
+ translate(points[2][0], points[2][1]);
+ textAlign(LEFT, CENTER); textSize(40);
+ text("*spline()", 0, 0);
+ pop();
}
}
+
+// Click anywhere to pause the animation on the current scene.
function mouseClicked() {
- noLoop()
+ noLoop();
}
diff --git a/llms.txt b/llms.txt
index 70fbd83..169018e 100644
--- a/llms.txt
+++ b/llms.txt
@@ -16,22 +16,21 @@ import * as brush from 'p5.brush'
## Setup
-The canvas **must use WEBGL mode**. Call `brush.load()` after `createCanvas()`.
+The canvas **must use WEBGL mode**. The library initializes automatically when `createCanvas()` is called — no `brush.load()` needed for the main canvas.
```js
async function setup() {
createCanvas(600, 600, WEBGL)
- brush.load()
brush.scaleBrushes(1.5) // optional: scale all default brushes
}
```
-In **instance mode**, call `brush.instance(p)` before setup:
+In **instance mode**, call `brush.instance(p)` before setup — auto-initialization still applies:
```js
const sketch = (p) => {
brush.instance(p)
- p.setup = () => { p.createCanvas(600, 600, p.WEBGL); brush.load() }
+ p.setup = () => { p.createCanvas(600, 600, p.WEBGL) }
}
new p5(sketch)
```
@@ -54,7 +53,7 @@ Exception: `brush.addField(name, fn, { angleMode })` lets custom field generator
### Configuration
-- `brush.load(buffer?)` — Initialize on the current canvas, on a `p5.Graphics` buffer, or on an active `p5.Framebuffer` from the current sketch. For `p5.Graphics`, create the buffer in `WEBGL`, call `brush.load(pg)`, draw, then call `brush.load()` before presenting it with `image(pg, ...)`. For framebuffers, call `brush.load(framebuffer)` only while that framebuffer is active inside `begin()` / `end()` or `draw()`, then call `brush.load()` again after leaving that scope. `brush.load(...)` only changes p5.brush's target; native p5 drawing calls still need to be directed at the same target explicitly. Framebuffers created from `p5.Graphics` are not supported. Call again with no args to return to the main canvas.
+- `brush.load(buffer?)` — Only needed when targeting a secondary canvas. Pass a `p5.Graphics` buffer or an active `p5.Framebuffer` to redirect all brush drawing to that target. Call `brush.load()` with no args to return to the main canvas. For `p5.Graphics`, create the buffer in `WEBGL`, call `brush.load(pg)`, draw, then call `brush.load()` before presenting it with `image(pg, ...)`. For framebuffers, call `brush.load(framebuffer)` only while that framebuffer is active inside `begin()` / `end()` or `draw()`, then call `brush.load()` again after leaving that scope. `brush.load(...)` only changes p5.brush's target; native p5 drawing calls still need to be directed at the same target explicitly. Framebuffers created from `p5.Graphics` are not supported.
- `brush.scaleBrushes(scale)` — Scale all currently registered brushes by `scale`. Call once in setup; if you only want the built-ins scaled, call it before adding custom brushes.
- `brush.instance(p)` — Use when p5 is in instance mode. Call before setup/draw.
- `brush.preload()` — Compatibility helper for preloading image tips. Usually unnecessary in v2 if you `await brush.add(...)` for image brushes.
@@ -239,7 +238,6 @@ pos.plotTo(plot, length, stepLength, scale)
```js
async function setup() {
createCanvas(600, 600, WEBGL)
- brush.load()
brush.scaleBrushes(2)
angleMode(DEGREES)
background("#fffceb")
@@ -297,7 +295,7 @@ pop()
- Canvas **must be WEBGL** — `createCanvas(w, h, WEBGL)`.
- In WEBGL mode the origin is at the center. Use `translate(-width/2, -height/2)` at the start of `draw()` to work in top-left coordinates.
- `brush.circle()` can be stroked, hatched, and filled. `brush.arc()` is stroke-only.
-- `brush.load()` must be called after `createCanvas()`, not before.
+- `brush.load()` is **not needed** for the main canvas — it initializes automatically on `createCanvas()`. Only call it when switching to a `p5.Graphics` or `p5.Framebuffer` target.
- For image brushes, `setup()` must be `async` and you must `await brush.add(...)`.
- `randomSeed()` and `noiseSeed()` seed the library automatically — no separate brush seed call needed.
- `brush.flowLine()` direction and `brush.hatch()` angles follow the current `angleMode()`.
diff --git a/src/core/color.js b/src/core/color.js
index dafe185..814219a 100644
--- a/src/core/color.js
+++ b/src/core/color.js
@@ -237,7 +237,7 @@ export const instance = (inst) => {
* Ensures the Mix object is initialized and ready for blending.
*/
export const isMixReady = () => {
- if (!Renderer.loaded) {
+ if (!Renderer?.loaded) {
isCanvasReady();
Mix.load();
}
diff --git a/tools/brush-maker.html b/tools/brush-maker.html
index 6f10d23..9853e70 100644
--- a/tools/brush-maker.html
+++ b/tools/brush-maker.html
@@ -903,7 +903,6 @@ const sketch = (p) => {
cnv.parent('canvas-wrap');
p.pixelDensity(2);
p.angleMode(p.DEGREES);
- brush.load();
brush.scaleBrushes(3);
p.frameRate(30);
};