Unlock custom brushes, natural fill effects and intuitive hatching in p5.js
New tool: brush maker
acamposuribeb30134b0d33c
diff --git a/README.md b/README.mdindex c3778b8..f48972f 100644--- a/README.md+++ b/README.md@@ -291,7 +291,6 @@ Functions for managing brush behaviors and properties.- `grain`: Controls how dense the texture is. Higher = smoother, more continuous line. Only matters for `"default"` type.- `opacity`: How opaque each mark is, from 0 to 255. Pressure also affects this.- `spacing`: Gap between brush tip stamps along the stroke. `1` means no overlap, lower values create denser strokes.- - `blend`: `true` or `false`. Enables realistic paint mixing. On by default for `"marker"`, `"custom"`, and `"image"` types.- `pressure`: Controls how the brush size changes from start to end of a stroke. Use a simple array — the easiest way:- `[start, end]` — e.g. `[2, 0.5]` starts thick and gets thin.- `[start, middle, end]` — e.g. `[0.5, 2, 0.5]` starts thin, swells in the middle, ends thin.@@ -314,7 +313,6 @@ Functions for managing brush behaviors and properties.scatter: 2,opacity: 30,spacing: 1.5,- blend: true,pressure: [1, 0.5], // starts thick, ends thinimage: { src: "./brush_tips/brush.jpg" },rotate: "random",@@ -332,7 +330,6 @@ Functions for managing brush behaviors and properties.scatter: 0.08,opacity: 23,spacing: 0.6,- blend: true,pressure: [0.5, 1.5, 0.5], // thin → thick → thintip: (_m) => {// Draw inside _m using normal p5.js drawing commandsdiff --git a/dist/p5.brush.esm.js b/dist/p5.brush.esm.jsindex a4956e0..1a00495 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=()=>u?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=(n=!1)=>{const a=((t=!1)=>{if(u&&!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,h=!0,i.loaded&&p.load()};let h=!1,u=!1;const f=()=>{h||c()},g={},d=t=>{u=!0,r=t},m=()=>{i.loaded||(f(),p.load())},p={isBlending:!1,cachedColor:new Object,captureBlendSource(){const r=l();if(!r)return i._renderer;var o;(!(o=i.blendSourceFramebuffer)||o.width!==t||o.height!==e||"function"==typeof o.pixelDensity&&o.pixelDensity()!==n)&&(a(i.blendSourceFramebuffer),i.blendSourceFramebuffer=i.createFramebuffer({width:t,height:e,density:n,antialias:!1,depth:!1,stencil:!1}));const s=i.blendSourceFramebuffer;return s.draw(()=>{i.clear(),i.push(),"function"==typeof i.imageMode&&i.imageMode(i.CENTER??i._renderer?._pInst?.CENTER),i.image(r,0,0,t,e),i.pop()}),s},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):(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.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._renderer.uModelMatrix=i._renderer.uModelMatrix},blend(t=!1,e=!1){m();const r=this.isBrush?this.glMask:this.mask,i=this.isBrush?this.mask:this.glMask;!this.isBlending&&t&&(this.isBlending=!0,this.cachedColor=t._array,this.glMask.clear()),(e||this.cachedColor[0]!==t._array[0]||this.cachedColor[1]!==t._array[1]||this.cachedColor[2]!==t._array[2]||this.cachedColor[3]!==t._array[3])&&(this.justChanged&&(this.applyShader(i),this.justChanged=!1),this.isBlending&&this.applyShader(r),this.cachedColor=t._array,e&&(this.isBlending=!1))},applyShader(r){let n=i.shaderProgram;const o=i.drawingContext,s=!!l(),a=this.captureBlendSource(),c=o.getParameter(o.DEPTH_TEST);o.disable(o.DEPTH_TEST),i.push(),i.translate(0,0),i.shader(n),n.setUniform("u_source",a),n.setUniform("u_isBrush",this.isBrush),n.setUniform("u_flipOutputY",s),n.setUniform("u_mask",r),n.setUniform("u_color",this.cachedColor),i.fill(0,0,0,0),i.noStroke(),i.rect(-t/2,-e/2,t,e),i.pop(),i.resetShader(),c&&o.enable(o.DEPTH_TEST),r.clear(),r.isDrawn=!1}},x=Math.sqrt(3),y=.5*(x-1),v=(3-x)/6,_=t=>0|Math.floor(t),b=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 w(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=>b[t%12*2]),i=new Float64Array(e).map(t=>b[t%12*2+1]);return function(t,n){let o=0,s=0,a=0;const l=(t+n)*y,c=_(t+l),h=_(n+l),u=(c+h)*v,f=t-(c-u),g=n-(h-u);let d,m;f>g?(d=1,m=0):(d=0,m=1);const p=f-d+v,x=g-m+v,b=f-1+2*v,w=g-1+2*v,R=255&c,S=255&h;let E=.5-f*f-g*g;if(E>=0){const t=R+e[S];E*=E,o=E*E*(r[t]*f+i[t]*g)}let A=.5-p*p-x*x;if(A>=0){const t=R+d+e[S+m];A*=A,s=A*A*(r[t]*p+i[t]*x)}let M=.5-b*b-w*w;if(M>=0){const t=R+1+e[S+1];M*=M,a=M*M*(r[t]*b+i[t]*w)}return 70*(o+s+a)}}function R(t,e){let r=new S(t),i=()=>r.next();return i.double=()=>i()+11102230246251565e-32*(2097152*i()|0),i.int32=()=>4294967296*r.next()|0,i.quick=i,i}class S{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 E=R(Math.random());const A=[],M=t=>A.push(t);let P=w(R(Math.random()));const k=(t=0,e=1)=>t+E()*(e-t),I=t=>t[~~(E()*t.length)],L=(t,e)=>~~k(t,e),C=(t=0,e=1)=>{const r=1-E(),i=E();return Math.sqrt(-2*Math.log(r))*X(360*i)*e+t},T=t=>{let e=0;const r=[];for(const i in t)e+=t[i],r.push({key:i,cumulative:e});const i=E()*e;for(const{key:t,cumulative:e}of r)if(i<e)return isNaN(t)?t:parseInt(t)},N=(t,e,r,i,n,o=!1)=>{let s=i+(t-e)/(r-e)*(n-i);return o?i<n?z(s,i,n):z(s,n,i):s},z=(t,e,r)=>Math.max(Math.min(t,r),e),O=t=>(t%=360)<0?t+360:t,B=1440,D=2*Math.PI/B,Y=new Float32Array(B).fill(NaN),F=new Float32Array(B).fill(NaN),X=t=>{const e=~~(4*O(t));let r=Y[e];return isNaN(r)&&(r=Math.cos(e*D),Y[e]=r),r},G=t=>{const e=~~(4*O(t));let r=F[e];return isNaN(r)&&(r=Math.sin(e*D),F[e]=r),r},$=(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},H=(t,e=!1)=>e||i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS?180*t/Math.PI:t,U=(t,e,r,i,n)=>{let o=X(n),s=G(n);return{x:o*(r-t)+s*(i-e)+t,y:o*(i-e)-s*(r-t)+e}},W=(t,e,r,i)=>Math.hypot(r-t,i-e),j=(t,e,r,i)=>$(Math.atan2(-(i-e),r-t),!0),Z=(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 g=a-o,d=l-s,m=u-c,p=f-h,x=p*g-m*d;if(0===x)return!1;let y=(m*(s-h)-p*(o-c))/x,v=(g*(s-h)-d*(o-c))/x;return!(!n&&(v<0||v>1))&&{x:o+y*g,y:s+y*d}},V=()=>i._renderer.uModelMatrix.mat4[12],K=()=>i._renderer.uModelMatrix.mat4[13],q=()=>i._renderer.uModelMatrix.mat4[0],J=()=>i._renderer.uModelMatrix.mat4[1],Q=()=>i._renderer.uModelMatrix.mat4[4],tt=()=>i._renderer.uModelMatrix.mat4[5];let et=!1;function rt(){et||(m(),nt=.01*t,ot=-.5*t,st=-.5*e,at=Math.round(2*t/nt),lt=Math.round(2*e/nt),pt("hand",(t,e)=>{const r=k(.2,.8),i=L(5,10);return vt(e,(e,n)=>.5*i*G(r*n*e+L(15,25))*.2*X(t)+P(e,n)*i*.7)}),pt("curved",(t,e)=>{let r=L(-10,10);return L(0,100)%2==0&&(r*=-1),vt(e,(e,i)=>3*N(P(.02*e+.03*t,.02*i+.03*t),0,1,-r,r))}),pt("zigzag",(t,e)=>{let r=L(-30,-15)+Math.abs(44*G(t));L(0,100)%2==0&&(r*=-1);let i=r,n=0;for(let t=0;t<at;t++){for(let r=0;r<lt;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e}),pt("waves",(t,e)=>{const r=L(10,15)+5*G(t),i=L(3,6)+3*X(t),n=L(20,35);return vt(e,(t,e)=>G(r*t)*n*X(e*i)+L(-3,3))}),pt("seabed",(t,e)=>{const r=k(.4,.8),i=L(18,26);return vt(e,(e,n)=>1.1*i*G(r*n*e+L(15,20))*X(t))}),pt("spiral",(t,e)=>{const r=L(5,10),i=2*L(0,2)-1,n=L(65,80),o=Array.from({length:r},()=>({x:k(.1,.9)*at,y:k(.1,.9)*lt}));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)})}),pt("columns",(t,e)=>{const r=L(3,8),i=L(25,45);return vt(e,(t,e)=>G(t*r)*i)}),et=!0)}class it{constructor(t,e){rt(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=it.getColIndex(t),this.rowIdx=it.getRowIndex(e)}reset(){this.plotted=0}isIn(){return g.field.isActive?it.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const r=t,i=e,n=this.x+V(),o=this.y+K();return n>=-.3*r&&n<=1.3*r&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&g.field.isActive?ct.get(g.field.current).field[this.colIdx][this.rowIdx]*g.field.wiggle:0}moveTo(t,e,r=1){this.movePos(H(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*X(e),this.y+r*G(e)),this.plotted+=r/n}else this.plotted+=r/n}static getRowIndex(t,e=1){const r=t+K()-st;return Math.round(r/nt/e)}static getColIndex(t,e=1){const r=t+V()-ot;return Math.round(r/nt/e)}static isIn(t,e){return t>=0&&e>=0&&t<at&&e<lt}}g.field={isActive:!1,current:null,wiggle:1};let nt,ot,st,at,lt,ct=new Map;const ht=new Set(["degrees","radians"]);function ut(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!ht.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function ft(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]=H(t[e][r],!0);return t}(t.gen(e,new Array(at).fill(null).map(()=>new Float32Array(lt))),t.angleMode)}function gt(t=0){if(!g.field.isActive||!g.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=ct.get(g.field.current);e.field=ft(e,t)}function dt(t){if(g.field.wiggle||(g.field.wiggle=1),rt(),!ct.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(ct.keys()).join(", ")}.`);g.field.isActive=!0,g.field.current=t;const e=ct.get(t);e.field||(e.field=ft(e,0))}function mt(){rt(),g.field.isActive=!1}function pt(t,e,r={}){ct.set(t,{gen:e,field:null,angleMode:ut(r)})}function xt(){return rt(),Array.from(ct.keys())}function yt(t=1){dt("hand"),g.field.wiggle=t}function vt(t,e){for(let r=0;r<at;r++)for(let i=0;i<lt;i++)t[r][i]=e(r,i);return t}class _t{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=Z(t.point1,t.point2,e,i);n&&r.push(n)}return this._intersectionCache[e]=r,r}show(){g.stroke&&this.draw(),g.hatch&&this.hatch(),g.fill&&this.fill()}}class bt{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:$(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:$(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=$(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)),N(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){rt();const s=.5,a=[],l=Math.round(this.length/s),c=new it(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*k(.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 _t(a)}show(t,e,r=1){g.stroke&&this.draw(t,e,r),g.hatch&&this.hatch(t,e,r),g.fill&&this.fill(t,e,r)}}function wt(t){new _t(t).show()}function Rt(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),Lt(0),Ct(t,e),Ct(t+r,e),Ct(t+r,e+i),Ct(t,e+i),Tt(!0)}function St(t,e,r,i=!1){const n=new bt("curve"),o=Math.PI*r,s=k(0,360),a=i?()=>1+.2*i*k():()=>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*L(-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*G(s),c=e-r*X(-s);n.show(l,c,1)}function Et(t,e,r,i,n){const o=H(i),s=((H(n)-o)%360+360)%360;if(0===s)return;const a=new bt("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*X(o),f=e-r*G(o);a.draw(u,f,1)}let At,Mt,Pt,kt;class It{constructor(){this.isClosed=!1,this.curvature=Mt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){Dt(this.vert,this.curvature,this.isClosed).show()}}function Lt(t=0){Mt=z(t,0,1),At=new It}function Ct(t,e,r=1){if(!At)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");At.vertex(t,e,r)}function Tt(t=!1){if(!At)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(At.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(At.vertex(...At.vert[0]),At.isClosed=!0),At.show(),At=!1}function Nt(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);kt=[e,r],Pt=new bt(t)}function zt(t,e,r){if(!Pt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Pt.addSegment(t,e,r)}function Ot(t,e){if(!Pt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Pt.endPlot(t,e),Pt.draw(kt[0],kt[1],1),Pt=!1}function Bt(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");Dt(t,e).draw()}function Dt(t,e=.5,r=!1){const i=new bt(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],g=W(h[0],h[1],u[0],u[1]),d=W(u[0],u[1],f[0],f[1]),m=j(h[0],h[1],u[0],u[1]),p=j(u[0],u[1],f[0],f[1]),x=e*Math.min(g,d,.5*Math.min(g,d)),y=Math.max(g,d),v=g-x,_=d-x;if(Math.floor(m)===Math.floor(p)){const e=r&&0===c?0:g-l,n=r?0===c?0:d-a:d;i.addSegment(m,e,h[2],!0),c===t.length-3&&i.addSegment(p,n,u[2],!0),l=0,0===c&&(o=g,a=x,s=t[1],l=0)}else{const e={x:u[0]-x*X(-m),y:u[1]-x*G(-m)},f={x:e.x+y*X(90-m),y:e.y+y*G(90-m)},g={x:u[0]+x*X(-p),y:u[1]+x*G(-p)},d={x:g.x+y*X(90-p),y:g.y+y*G(90-p)},b=Z(e,f,g,d,!0),w=W(e.x,e.y,b.x,b.y),R=W(e.x,e.y,g.x,g.y)/2,S=n*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=r&&0===c?0:v-l,A=c===t.length-3?r?o-x:_:0;i.addSegment(m,E,h[2],!0),i.addSegment(m,isNaN(S)?0:S,h[2],!0),i.addSegment(p,A,u[2],!0),l=x,0===c&&(o=v,a=x,s=[e.x,e.y])}c===t.length-3&&i.endPlot(p,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],n=W(e[0],e[1],r[0],r[1]),o=j(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 Yt,Ft,Xt,Gt,$t,Ht=!1,Ut=0,Wt=0;const jt={},Zt={};let Vt=1,Kt=0,qt=0,Jt=1,Qt=0,te=0,ee=new Float32Array(8192),re=0,ie=2048,ne=32768;function oe(r,i,o,s){if(re>=ie){ie*=2;const t=new Float32Array(4*ie);t.set(ee),ee=t}const a=r-t/2,l=i-e/2,c=4*re;ee[c]=Vt*a+qt*l+Qt+t/2,ee[c+1]=Kt*a+Jt*l+te+e/2,ee[c+2]=n*o*Math.sqrt(Vt*Vt+Kt*Kt)/2,ee[c+3]=s/255,re++}function se(){if(0===re)return;p.glMask.isDrawn=!0;const t=g.stroke.color._array;Yt.useProgram($t),Yt.enable(Yt.BLEND),Yt.blendFunc(Yt.ONE_MINUS_DST_ALPHA,Yt.ONE),Yt.bindVertexArray(Xt),Yt.bindBuffer(Yt.ARRAY_BUFFER,Gt);const e=16*re,r=ee.subarray(0,4*re);e>ne?(Yt.bufferData(Yt.ARRAY_BUFFER,ee,Yt.DYNAMIC_DRAW),ne=ee.byteLength):Yt.bufferSubData(Yt.ARRAY_BUFFER,0,r),Yt.uniform4f(Zt.u_color,...t),Yt.uniformMatrix4fv(Zt.u_matrix,!1,Ft),Yt.drawArrays(Yt.POINTS,0,re),Yt.bindVertexArray(null),re=0,p.glMask._renderer._curShader=null}g.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let ae,le,ce,he,ue=new Map,fe=null,ge={a:1,b:0,c:0,d:1,tx:0,ty:0};function de(){return{...g.stroke}}function me(t){g.stroke={...t}}function pe(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 Ue.add(e.image.src),e.tip=()=>{fe.image(Ue.tips.get(ke.p.image.src),-ke.p.weight/2,-ke.p.weight/2,ke.p.weight,ke.p.weight)},ue.set(t,{param:e,colors:[],buffers:[]}),Ue.load()}ue.set(t,{param:e,colors:[],buffers:[]})}function xe(){return[...ue.keys()]}function ye(t){for(const{param:e}of ue.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function ve(t){if(!ue.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...ue.keys()].join(", ")}.`);g.stroke.type=t}function _e(t,e,r){f(),g.stroke.color=i.color(...arguments),g.stroke.isActive=!0}function be(t){g.stroke.weight=t}function we(t,e,r=1){ve(t),_e(e),be(r)}function Re(){g.stroke.isActive=!1}function Se(){return{a:q(),b:J(),c:Q(),d:tt(),tx:V(),ty:K()}}function Ee(t,e,r){return{x:t.a*e+t.c*r+t.tx,y:t.b*e+t.d*r+t.ty}}function Ae(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 Me(t){f();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}}(Se());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");g.stroke.clipWindow={bounds:Ae(t),inverse:e}}function Pe(){g.stroke.clipWindow=null}const ke={};function Ie(r,i,n,o=!1){Vt=q(),Kt=J(),qt=Q(),Jt=tt(),Qt=V(),te=K(),ge=Se(),ae=new it(r+t/2,i+e/2),le=n,ce=o,ce&&ce.calcIndex(0)}const Le=[];function Ce(r,i){i||(he=r),function(){ke.seed=999999*k();const{param:r}=ue.get(g.stroke.type)??{};if(!r)return;ke.p=r,fe=p.glMask;const{pressure:i}=r;if(ke.a="custom"!==i.type?k(-1,1):0,ke.b="custom"!==i.type?k(1,1.5):0,ke.cp="custom"!==i.type?k(3,3.5):k(-.2,.2),[ke.min,ke.max]=i.min_max,ke.noiseoffset=.03,!ce){const t=he*Math.PI/180;ke.cos=Math.cos(t),ke.sin=Math.sin(t)}(function(){m();const r=p.glMask.drawingContext,i=!Ht||Yt!==r;(i||Ut!==t||Wt!==e)&&(Ft=new Float32Array([2/t,0,0,0,0,-2/e,0,0,0,0,1,0,-1,1,0,1]),Ut=t,Wt=e),i&&(Yt=r,$t=(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})(Yt),Yt.useProgram($t),Yt.enable(Yt.BLEND),Yt.blendFunc(Yt.ONE_MINUS_DST_ALPHA,Yt.ONE),["a_position","a_radius","a_alpha"].forEach(t=>jt[t]=Yt.getAttribLocation($t,t)),["u_matrix","u_color"].forEach(t=>Zt[t]=Yt.getUniformLocation($t,t)),Xt=Yt.createVertexArray(),Yt.bindVertexArray(Xt),Gt=Yt.createBuffer(),Yt.bindBuffer(Yt.ARRAY_BUFFER,Gt),Yt.bufferData(Yt.ARRAY_BUFFER,ee.byteLength,Yt.DYNAMIC_DRAW),ne=ee.byteLength,Yt.enableVertexAttribArray(jt.a_position),Yt.vertexAttribPointer(jt.a_position,2,Yt.FLOAT,!1,16,0),Yt.enableVertexAttribArray(jt.a_radius),Yt.vertexAttribPointer(jt.a_radius,1,Yt.FLOAT,!1,16,8),Yt.enableVertexAttribArray(jt.a_alpha),Yt.vertexAttribPointer(jt.a_alpha,1,Yt.FLOAT,!1,16,12),Yt.bindVertexArray(null),Ht=!0)})(),Be()&&p.blend(g.stroke.color),!1===p.isBrush&&(p.justChanged=!0),p.isBrush=!0,ke.alpha=Oe(),Fe()}();const n=function(){const{param:t}=ue.get(g.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(le*(i?r:1)/n);for(let t=0;t<o;t++)Le.length<2*o&&Le.push(C()),Te(),i?ae.plotTo(ce,n,n,r,t<10):ae._moveToDegrees(r,n,n);se(),Fe()}function Te(t=!1){if(!Be())return;let e=t||Ne(),r=N(P(ke.seed+.002*ae.plotted,0),0,1,1-ke.noiseoffset,1+ke.noiseoffset);switch(ke.p.type){case"spray":!function(t){const e=g.stroke.weight*ke.p.scatter*t+g.stroke.weight*I(Le)*ke.p.scatter/3,r=ke.p.weight*k(.9,1.1),i=Math.ceil(ke.p.grain/t);for(let t=0;t<i;t++){const t=k(.9,1.1),i=t*e*k(-1,1),n=k(-1,1),o=Math.sqrt((t*e)**2-i**2);oe(ae.x+i,ae.y+n*o,r,ke.alpha)}}(e*r);break;case"marker":De(e*r);break;case"custom":case"image":Ye(e*r,ke.alpha);break;default:!function(t,e=1){const r=(e=N(e,0,1,.9,1.05))*g.stroke.weight*ke.p.scatter*(ke.p.sharpness+(1-ke.p.sharpness)*I(Le)/t);if(k(0,ke.p.grain*t)>.4){let e,i;if(ce)e=.7*r*k(-1,1),i=r*k(-1,1);else{const t=r*k(-1,1),n=.3*r*k(-1,1);e=t*-ke.sin+n*ke.cos,i=t*ke.cos+n*ke.sin}oe(ae.x+e,ae.y+i,t*t*ke.p.weight*k(.85,1.15)*g.stroke.weight,Math.max(.9,t)*ke.alpha*k(.75,1.1))}}(e*r)}}function Ne(){return ce?ze()*ce.pressure(ae.plotted):ze()}function ze(){return"custom"===ke.p.pressure.type?N(ke.p.pressure.curve(ae.plotted/le)+ke.cp,0,1,ke.min,ke.max,!0):function(t=.5+ke.p.pressure.curve[0]*ke.a,e=1-ke.p.pressure.curve[1]*ke.b,r=ke.cp,i=ke.min,n=ke.max){const o=t*le,s=(ae.plotted<o?1.2*e:.8*e)*(le/2);return N(1/(1+Math.pow(Math.abs((ae.plotted-o)/s),2*r)),0,1,i,n)}()}function Oe(){return["default","spray"].includes(ke.p.type)?ke.p.opacity:ke.p.opacity/Math.min(g.stroke.weight,1.3)}function Be(){const r=Ee(ge,ae.x-t/2,ae.y-e/2);if(g.stroke.clipWindow){const t=Ee(g.stroke.clipWindow.inverse,r.x,r.y),{bounds:e}=g.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 De(t,e=!0,r=ke.alpha){const i=e?g.stroke.weight*ke.p.scatter:0,n=e?i*k(-1,1):0,o=e?i*k(-1,1):0;oe(ae.x+n,ae.y+o,g.stroke.weight*ke.p.weight*t,r)}function Ye(r,i,n=!0){p.glMask.isDrawn=!0,fe.push(),fe.noStroke(),g.stroke.color.setAlpha(i),fe.fill(g.stroke.color);const o=n?g.stroke.weight*ke.p.scatter:0,s=n?o*k(-1,1):0,a=n?o*k(-1,1):0;fe.translate(ae.x+s-t,ae.y+a-e),function(t,e){fe.scale(t),"image"===ke.p.type&&fe.tint(255,0,0,e/2);let r=0;"random"===ke.p.rotate?r=L(0,360):"natural"===ke.p.rotate&&(r=(ce?-ce.angle(ae.plotted):-he)+ae.angle()),fe.rotate(r)}(g.stroke.weight*r,i),ke.p.tip(fe),fe.pop()}function Fe(){if(Be()){let t=Ne(),e=Oe();if("marker"===ke.p.type){for(let r=1;r<10;r++)De(t*r/10,!1,5*e);se()}else if("custom"===ke.p.type||"image"===ke.p.type)for(let r=1;r<5;r++)Ye(t*r/5,e,!1)}}function Xe(t,e,r,i){if(!g.stroke.isActive||!g.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");rt();let n=W(t,e,r,i);0!=n&&(Ie(t,e,n),Ce(j(t,e,r,i),!1))}function Ge(t,e,r,i){if(!g.stroke.isActive||!g.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");rt(),Ie(t,e,r),Ce($(i),!1)}M(()=>{Le.length=0});const $e=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],He=[["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,.12,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of He){let e={};for(let r=0;r<t[1].length;r++)e[$e[r]]=t[1][r];pe(t[0],e)}_t.prototype.draw=function(t=!1,e,r){let i=de();if(t&&we(t,e,r),i.isActive)for(let t of this.sides)Xe(t[0].x,t[0].y,t[1].x,t[1].y);me(i)},bt.prototype.draw=function(t,e,r){de().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,i){rt(),Ie(e,r,t.length,t),Ce(i,!0)}(this,t,e,r))};const Ue={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),Ue.imageToWhite(r),this.tips.set(t,r),e()},n.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),n.src=t})))}};function We(){return{...g.hatch}}function je(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let i=g.hatch;i.isActive=!0,i.dist=t,i.angle=H(e),i.options=r}function Ze(t,e="black",r=1){g.hatch.hBrush={brush:t,color:e,weight:r}}function Ve(){g.hatch.isActive=!1,g.hatch.hBrush=!1}function Ke(t){let e=g.hatch.dist,r=(g.hatch.angle%180+180)%180,i=g.hatch.options,n=de();g.hatch.hBrush&&we(...Object.values(g.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=qe(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 _t([[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?N(i.gradient,0,1,1,1.1,!0):1,c=[],h=0,u=e,f=t=>({point1:{x:o.minX+u*t*X(90-r),y:a+u*t*G(90-r)},point2:{x:o.minX+u*t*X(90-r)+X(-r),y:a+u*t*G(90-r)+G(-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 d=c.filter(t=>void 0!==t[0]),m=i.rand||0;for(let t=0;t<d.length;t++){let r=d[t],n=t>0&&i.continuous;for(let i=0;i<r.length-1;i+=2)0!==m&&(r[i].x+=m*e*k(-1,1),r[i].y+=m*e*k(-1,1),r[i+1].x+=m*e*k(-1,1),r[i+1].y+=m*e*k(-1,1)),Xe(r[i].x,r[i].y,r[i+1].x,r[i+1].y),n&&Xe(d[t-1][1].x,d[t-1][1].y,r[i].x,r[i].y)}me(n)}function qe(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 Je(t,e,r){const i=2*Math.PI,n=r/2;p.ctx.moveTo(t+n,e),p.ctx.arc(t,e,n,0,i)}g.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},_t.prototype.hatch=function(t=!1,e,r){let i=We();t&&je(t,e,r),i.isActive&&Ke(this),function(t){g.hatch={...t}}(i)},bt.prototype.hatch=function(t,e,r){We().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},g.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Qe=()=>({...g.fill});function tr(t,e,r,n){g.fill.opacity=(arguments.length<4?e:n)||150,g.fill.color=arguments.length<3?i.color(t):i.color(t,e,r),g.fill.isActive=!0}function er(t,e="out"){g.fill.bleed_strength=z(t,0,1),g.fill.direction=e}function rr(t=.4,e=.4){g.fill.texture_strength=z(t,0,1),g.fill.border_strength=z(e,0,1)}function ir(){g.fill.isActive=!1}let nr;const or=[[],[]];function sr(){for(let t=0;t<512;t++)or[0][t]=C(.5,.2),or[1][t]=C(0,.02)}function ar(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}M(sr);class lr{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=U(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 nr.intersect(t.ray))ar(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=k(-.6,.6)*e,s=k(-.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+k(0,.8*n)));const o=[],s=[],a=[],l=this.midP,c=nr.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)*k(.3,.6),y:l.y+(i.y-l.y)*k(.3,.6)}),o.push(i),s.push(this.m[r]),a.push(!this.dir[r])}return new lr(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new lr(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"===g.fill.direction?-90:90;0===or[0].length&&sr();const h=or[0],u=h.length,f=or[1],d=f.length;let m=0,p=999===t?k(.6,.8):g.fill.bleed_strength;for(let o=0;o<n;o++){const g=e[o],x=e[o+1<n?o+1:0],y=r[o],v=i[o];t<997&&(p=y);const _=(v?c:-c)+5*k(-1,1),b=X(_),w=G(_),R=x.x-g.x,S=x.y-g.y,E=b*R+w*S,A=b*S-w*R,M=h[~~(k(0,1)*u)]*k(.65,1.35)*p;s[m]=g,a[m]=y,l[m]=v,m++,s[m]={x:g.x+.5*R+E*M,y:g.y+.5*S+A*M},a[m]=y+f[~~(k(0,1)*d)],l[m]=v,m++}let x=s,y=a,v=l,_=1024/g.fill.texture_strength;if(_&&m>_){const t=Math.ceil(m/_);x=[],y=[],v=[];for(let e=0;e<m;e+=t)x.push(s[e]),y.push(a[e]),v.push(l[e])}else x.length=m,y.length=m,v.length=m;return new lr(x,y,this.midP,v,!1,this.sizeX,this.sizeY)}fill(r,i,o){const s=3*o,a=2*i*(1+o/2);p.blend(r),p.justChanged=!0,p.isBrush=!1,p.ctx.save(),p.ctx.setTransform(n*q(),n*J(),n*Q(),n*tt(),n*(V()+t/2),n*(K()+e/2)),p.ctx.strokeStyle=`rgb(${r._getRed()} ${r._getGreen()} ${r._getBlue()} / ${.005*g.fill.border_strength})`,p.ctx.lineCap="round";const l=Math.max(this.sizeX,this.sizeY),c=k(.15,.7);let h=this.grow();const u=this.scatter(.1).grow().scatter(.75).flipDirs();let f;for(let t=0;t<20;t++){t%4==0&&(h=h.grow()),t%2==0&&(f=[h.grow(1-.0125*t),h.grow(.7-.0125*t),h.grow(.4-.0125*t)]);for(const e of f)e.grow(999).grow(997).layer(t,l,a,r);u.grow(999).flipDirs().grow(997).layer(t,l,1.5*a*s,r),t%2==0&&h.grow(c).grow(999).layer(t,l,2*a,r),t%5!=0&&19!==t||(0!==s&&h.erase(3*s,i),p.blend(r,!0,!1,!0))}p.ctx.restore()}layer(t,e,r,i){var n;p.ctx.lineWidth=N(t,0,24,e/25,e/30,!0),p.ctx.fillStyle=`rgb(${i._getRed()} ${i._getGreen()} ${i._getBlue()} / ${r}%)`,n=this.v,p.ctx.beginPath(),n.forEach((t,e)=>{0===e?p.ctx.moveTo(t.x,t.y):p.ctx.lineTo(t.x,t.y)}),p.ctx.closePath(),p.ctx.fill(),p.ctx.stroke()}erase(t,e){p.ctx.save();const r=~~(k(80,110)*N(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-g.fill.bleed_strength),s=.05*o,a=.4*o,{x:l,y:c}=this.midP;p.ctx.globalCompositeOperation="destination-out";const h=(5-N(e,80,100,.3,.7,!0))*t/255;p.ctx.fillStyle=`rgb(255 0 0 / ${h})`,p.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+C(0,i),r=c+C(0,n),o=k(s,a);p.ctx.beginPath(),Je(e,r,o),t%5!=0&&p.ctx.fill()}p.ctx.globalCompositeOperation="source-over",p.ctx.restore()}}_t.prototype.fill=function(t=!1,e,r,i,n,o){let s=Qe();t&&(tr(t,e),er(r,o),rr(i,n)),s.isActive&&(rt(),function(t){if(!g.fill.isActive||!g.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");nr=t;const e=[...t.vertices],r=~~(.25*e.length*T({1:5,2:10,3:60})),i=g.fill.bleed_strength,n=e.map((t,e)=>(e>r?1:.3)*k(.85,1.2)*i),o=L(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 lr(s,n,a,[],!0).fill(g.fill.color,N(g.fill.opacity,0,255,0,1,!0),g.fill.texture_strength)}(this)),(t=>{g.fill={...t}})(s)},bt.prototype.fill=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,N(g.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const cr=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>p.blend(!1,!0),r.postdraw=()=>p.blend(!1,!0);const i=e.push,n=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){i.call(this),rt(),cr.push({fill:{...g.fill},stroke:{...g.stroke},hatch:{...g.hatch},field:{...g.field}})},e.pop=function(){n.call(this),function(){const t=cr.pop();t&&(g.stroke={...t.stroke},g.field={...t.field},g.hatch={...t.hatch},g.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{E=R(t);for(const t of A)t()})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{P=w(R(t))})(t)}});export{bt as Plot,_t as Polygon,it as Position,pe as add,pt as addField,Et as arc,Lt as beginShape,Nt as beginStroke,xe as box,St as circle,Me as clip,Tt as endShape,Ot as endStroke,dt as field,tr as fill,er as fillBleed,rr as fillTexture,Ge as flowLine,je as hatch,Ke as hatchArray,Ze as hatchStyle,d as instance,Xe as line,xt as listFields,c as load,zt as move,Pe as noClip,mt as noField,ir as noFill,Ve as noHatch,Re as noStroke,ve as pick,wt as polygon,Rt as rect,gt as refreshField,ye as scaleBrushes,we as set,Bt as spline,_e as stroke,be as strokeWeight,Ct as vertex,T as wRand,yt 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.mapdiff --git a/dist/p5.brush.esm.js.map b/dist/p5.brush.esm.js.mapindex d9a2dfc..350e1c8 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\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 captureBlendSource() {\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 Renderer.clear();\n Renderer.push();\n if (typeof Renderer.imageMode === \"function\") {\n Renderer.imageMode(Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER);\n }\n Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);\n Renderer.pop();\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\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 } else {\n this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\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 mask = this.isBrush ? this.glMask : this.mask;\n const no_mask = this.isBrush ? this.mask : this.glMask;\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 && _color) {\n this.isBlending = true;\n this.cachedColor = _color._array;\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 || this.cachedColor[0] !== _color._array[0] || this.cachedColor[1] !== _color._array[1] || this.cachedColor[2] !== _color._array[2] || this.cachedColor[3] !== _color._array[3]) {\n if (this.justChanged) {\n this.applyShader(no_mask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask);\n }\n this.cachedColor = _color._array;\n if (_isLast) this.isBlending = false;\n }\n },\n\n applyShader(mask) {\n let shader = Renderer.shaderProgram;\n const gl = Renderer.drawingContext;\n const targetIsFramebuffer = !!getActiveFramebuffer();\n const source = this.captureBlendSource();\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\", this.isBrush);\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 Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\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 mask.clear();\n mask.isDrawn = false;\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 circleData[offset] = _ma * px + _mc * py + _mx + Cwidth / 2;\n circleData[offset + 1] = _mb * px + _md * py + _my + Cheight / 2;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] =\n (Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;\n circleData[offset + 3] = alpha / 255;\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\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 if (isInsideClippingArea()) Mix.blend(State.stroke.color);\n if (Mix.isBrush === false) Mix.justChanged = true;\n Mix.isBrush = true;\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 adjustSizeAndRotation(State.stroke.weight * pressure, alpha);\n current.p.tip(Mask);\n Mask.pop();\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}\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.12,\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\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\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 Mix.ctx.beginPath();\n vertices.forEach((v, i) => {\n if (i === 0) Mix.ctx.moveTo(v.x, v.y);\n else Mix.ctx.lineTo(v.x, v.y);\n });\n Mix.ctx.closePath();\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 radius = d / 2;\n Mix.ctx.moveTo(x + radius, y);\n Mix.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 Mix.blend(color);\n Mix.justChanged = true;\n Mix.isBrush = false;\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","load","width","height","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","inst","isMixReady","isBlending","cachedColor","Object","captureBlendSource","framebuffer","blendSourceFramebuffer","pixelDensity","createFramebuffer","density","antialias","depth","stencil","source","draw","clear","push","imageMode","CENTER","image","pop","graphicsFactory","createGraphics","p2dMode","P2D","webglMode","WEBGL","mask","glMask","this","ctx","drawingContext","shaderProgram","createShader","angleMode","DEGREES","lineWidth","uModelMatrix","blend","_color","_isLast","isBrush","no_mask","_array","justChanged","applyShader","shader","gl","targetIsFramebuffer","hadDepthTest","getParameter","DEPTH_TEST","disable","translate","setUniform","fill","noStroke","rect","resetShader","enable","isDrawn","SQRT3","Math","sqrt","F2","G2","fastFloor","x","floor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","y","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","a","b","d","withinBounds","constrain","low","high","max","min","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","round","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","ceil","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","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","box","scaleBrushes","values","spacing","pick","brushName","g","arguments","strokeWeight","snapshotTransform","transformPoint","transform","normalizeRegion","region","minX","minY","maxX","maxY","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","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","point","local","o","vibrate","rx","ry","setAlpha","tint","adjustSizeAndRotation","flowLine","_vals","_standard_brushes","obj","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","Infinity","poly","bb","computeBoundingBoxForPolygon","computeOverallBoundingBox","ventana","dots","dist1","linea","tempArray","flat","sort","gdots","dd","continuousLine","_boundingBox","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","noFill","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","center","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","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","size","darker","sparse","pols","layer","numLayers","erase","restore","fillStyle","beginPath","lineTo","closePath","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,KAuBOC,EAAO,CAACL,GAAS,KAC5B,MAAMZ,EA7Ec,EAACY,GAAS,KAC9B,GAAIN,IAAiBM,EACnB,MAAO,CACLT,SAAUP,EACVsB,MAAOtB,EAASsB,MAChBC,OAAQvB,EAASuB,QAIrB,IAAKP,EAAQ,CACX,MAAMT,EAAWE,IACjB,MAAO,CACLF,WACAe,MAAOf,EAASe,MAChBC,OAAQhB,EAASgB,OAErB,CAEA,GAAIpB,EAAoBa,GAAS,CAC/B,IArBFb,EADoCC,EAsBAY,IArBLZ,EAAOG,SAASC,SAAWC,IAsBtD,MAAM,IAAIe,MACR,0IAIJ,MAAO,CACLjB,SAAUE,IACVa,MAAON,EAAOM,MACdC,OAAQP,EAAOO,OAEnB,CAjCmC,IAACnB,EAmCpC,MAAO,CACLG,SAAUS,EACVM,MAAON,EAAOM,MACdC,OAAQP,EAAOO,SA0CFE,CAAcT,GAK7B,GAJAf,EAAWG,EAAOG,SAIY,WAA1BN,EAASyB,a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GAAYjuB,MACrB8uB,IACLpwB,EAAM0T,OAAS,IAAK0c,EAAM1c,QAC1B1T,EAAM+N,MAAQ,IAAKqiB,EAAMriB,OACzB/N,EAAM2T,MAAQ,IAAKyc,EAAMzc,OACzB3T,EAAMyD,KAAO,IAAK2sB,EAAM3sB,MAC1B,CCyGI4sB,EACF,EAEA5d,EAAGud,WAAa,SAAUrqB,GACxBoqB,EAAYI,KAAKpuB,KAAM4D,GZpHP,CAACA,IACnB4C,EAAMzB,EAAUnB,GAChB,IAAK,MAAM2qB,KAAY9nB,EACrB8nB,KYkHAC,CAAU5qB,EACZ,EAEA8M,EAAGyd,UAAY,SAAUvqB,GACvBsqB,EAAWE,KAAKpuB,KAAM4D,GZvGD,CAACA,IACxBgD,EAAQlE,EAAcqC,EAAUnB,KYuG9B6qB,CAAe7qB,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,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,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B,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 filediff --git a/dist/p5.brush.js b/dist/p5.brush.jsindex c83bd38..1fe5fce 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=()=>f?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=(t=!1)=>{const o=((t=!1)=>{if(f&&!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,u=!0,n.loaded&&p.load()};let u=!1,f=!1;const g=()=>{u||h()},d={},m=()=>{n.loaded||(g(),p.load())},p={isBlending:!1,cachedColor:new Object,captureBlendSource(){const t=c();if(!t)return n._renderer;var i;(!(i=n.blendSourceFramebuffer)||i.width!==e||i.height!==r||"function"==typeof i.pixelDensity&&i.pixelDensity()!==o)&&(l(n.blendSourceFramebuffer),n.blendSourceFramebuffer=n.createFramebuffer({width:e,height:r,density:o,antialias:!1,depth:!1,stencil:!1}));const s=n.blendSourceFramebuffer;return s.draw(()=>{n.clear(),n.push(),"function"==typeof n.imageMode&&n.imageMode(n.CENTER??n._renderer?._pInst?.CENTER),n.image(t,0,0,e,r),n.pop()}),s},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):(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.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._renderer.uModelMatrix=n._renderer.uModelMatrix},blend(t=!1,e=!1){m();const r=this.isBrush?this.glMask:this.mask,i=this.isBrush?this.mask:this.glMask;!this.isBlending&&t&&(this.isBlending=!0,this.cachedColor=t._array,this.glMask.clear()),(e||this.cachedColor[0]!==t._array[0]||this.cachedColor[1]!==t._array[1]||this.cachedColor[2]!==t._array[2]||this.cachedColor[3]!==t._array[3])&&(this.justChanged&&(this.applyShader(i),this.justChanged=!1),this.isBlending&&this.applyShader(r),this.cachedColor=t._array,e&&(this.isBlending=!1))},applyShader(t){let i=n.shaderProgram;const o=n.drawingContext,s=!!c(),a=this.captureBlendSource(),l=o.getParameter(o.DEPTH_TEST);o.disable(o.DEPTH_TEST),n.push(),n.translate(0,0),n.shader(i),i.setUniform("u_source",a),i.setUniform("u_isBrush",this.isBrush),i.setUniform("u_flipOutputY",s),i.setUniform("u_mask",t),i.setUniform("u_color",this.cachedColor),n.fill(0,0,0,0),n.noStroke(),n.rect(-e/2,-r/2,e,r),n.pop(),n.resetShader(),l&&o.enable(o.DEPTH_TEST),t.clear(),t.isDrawn=!1}},x=Math.sqrt(3),y=.5*(x-1),v=(3-x)/6,b=t=>0|Math.floor(t),_=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 w(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=>_[t%12*2]),i=new Float64Array(e).map(t=>_[t%12*2+1]);return function(t,n){let o=0,s=0,a=0;const l=(t+n)*y,c=b(t+l),h=b(n+l),u=(c+h)*v,f=t-(c-u),g=n-(h-u);let d,m;f>g?(d=1,m=0):(d=0,m=1);const p=f-d+v,x=g-m+v,_=f-1+2*v,w=g-1+2*v,S=255&c,R=255&h;let E=.5-f*f-g*g;if(E>=0){const t=S+e[R];E*=E,o=E*E*(r[t]*f+i[t]*g)}let A=.5-p*p-x*x;if(A>=0){const t=S+d+e[R+m];A*=A,s=A*A*(r[t]*p+i[t]*x)}let P=.5-_*_-w*w;if(P>=0){const t=S+1+e[R+1];P*=P,a=P*P*(r[t]*_+i[t]*w)}return 70*(o+s+a)}}function S(t,e){let r=new R(t),i=()=>r.next();return i.double=()=>i()+11102230246251565e-32*(2097152*i()|0),i.int32=()=>4294967296*r.next()|0,i.quick=i,i}class R{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 E=S(Math.random());const A=[],P=t=>A.push(t);let M=w(S(Math.random()));const k=(t=0,e=1)=>t+E()*(e-t),I=t=>t[~~(E()*t.length)],L=(t,e)=>~~k(t,e),C=(t=0,e=1)=>{const r=1-E(),i=E();return Math.sqrt(-2*Math.log(r))*X(360*i)*e+t},T=t=>{let e=0;const r=[];for(const i in t)e+=t[i],r.push({key:i,cumulative:e});const i=E()*e;for(const{key:t,cumulative:e}of r)if(i<e)return isNaN(t)?t:parseInt(t)},N=(t,e,r,i,n,o=!1)=>{let s=i+(t-e)/(r-e)*(n-i);return o?i<n?z(s,i,n):z(s,n,i):s},z=(t,e,r)=>Math.max(Math.min(t,r),e),O=t=>(t%=360)<0?t+360:t,B=1440,D=2*Math.PI/B,Y=new Float32Array(B).fill(NaN),F=new Float32Array(B).fill(NaN),X=t=>{const e=~~(4*O(t));let r=Y[e];return isNaN(r)&&(r=Math.cos(e*D),Y[e]=r),r},G=t=>{const e=~~(4*O(t));let r=F[e];return isNaN(r)&&(r=Math.sin(e*D),F[e]=r),r},$=(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},H=(t,e=!1)=>e||n&&"function"==typeof n.angleMode&&n.angleMode()===n.RADIANS?180*t/Math.PI:t,W=(t,e,r,i,n)=>{let o=X(n),s=G(n);return{x:o*(r-t)+s*(i-e)+t,y:o*(i-e)-s*(r-t)+e}},U=(t,e,r,i)=>Math.hypot(r-t,i-e),j=(t,e,r,i)=>$(Math.atan2(-(i-e),r-t),!0),Z=(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 g=a-o,d=l-s,m=u-c,p=f-h,x=p*g-m*d;if(0===x)return!1;let y=(m*(s-h)-p*(o-c))/x,v=(g*(s-h)-d*(o-c))/x;return!(!n&&(v<0||v>1))&&{x:o+y*g,y:s+y*d}},V=()=>n._renderer.uModelMatrix.mat4[12],K=()=>n._renderer.uModelMatrix.mat4[13],q=()=>n._renderer.uModelMatrix.mat4[0],J=()=>n._renderer.uModelMatrix.mat4[1],Q=()=>n._renderer.uModelMatrix.mat4[4],tt=()=>n._renderer.uModelMatrix.mat4[5];let et=!1;function rt(){et||(m(),nt=.01*e,ot=-.5*e,st=-.5*r,at=Math.round(2*e/nt),lt=Math.round(2*r/nt),dt("hand",(t,e)=>{const r=k(.2,.8),i=L(5,10);return mt(e,(e,n)=>.5*i*G(r*n*e+L(15,25))*.2*X(t)+M(e,n)*i*.7)}),dt("curved",(t,e)=>{let r=L(-10,10);return L(0,100)%2==0&&(r*=-1),mt(e,(e,i)=>3*N(M(.02*e+.03*t,.02*i+.03*t),0,1,-r,r))}),dt("zigzag",(t,e)=>{let r=L(-30,-15)+Math.abs(44*G(t));L(0,100)%2==0&&(r*=-1);let i=r,n=0;for(let t=0;t<at;t++){for(let r=0;r<lt;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e}),dt("waves",(t,e)=>{const r=L(10,15)+5*G(t),i=L(3,6)+3*X(t),n=L(20,35);return mt(e,(t,e)=>G(r*t)*n*X(e*i)+L(-3,3))}),dt("seabed",(t,e)=>{const r=k(.4,.8),i=L(18,26);return mt(e,(e,n)=>1.1*i*G(r*n*e+L(15,20))*X(t))}),dt("spiral",(t,e)=>{const r=L(5,10),i=2*L(0,2)-1,n=L(65,80),o=Array.from({length:r},()=>({x:k(.1,.9)*at,y:k(.1,.9)*lt}));return mt(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)})}),dt("columns",(t,e)=>{const r=L(3,8),i=L(25,45);return mt(e,(t,e)=>G(t*r)*i)}),et=!0)}class it{constructor(t,e){rt(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=it.getColIndex(t),this.rowIdx=it.getRowIndex(e)}reset(){this.plotted=0}isIn(){return d.field.isActive?it.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,i=r,n=this.x+V(),o=this.y+K();return n>=-.3*t&&n<=1.3*t&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&d.field.isActive?ct.get(d.field.current).field[this.colIdx][this.rowIdx]*d.field.wiggle:0}moveTo(t,e,r=1){this.movePos(H(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*X(e),this.y+r*G(e)),this.plotted+=r/n}else this.plotted+=r/n}static getRowIndex(t,e=1){const r=t+K()-st;return Math.round(r/nt/e)}static getColIndex(t,e=1){const r=t+V()-ot;return Math.round(r/nt/e)}static isIn(t,e){return t>=0&&e>=0&&t<at&&e<lt}}d.field={isActive:!1,current:null,wiggle:1};let nt,ot,st,at,lt,ct=new Map;const ht=new Set(["degrees","radians"]);function ut(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!ht.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function ft(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]=H(t[e][r],!0);return t}(t.gen(e,new Array(at).fill(null).map(()=>new Float32Array(lt))),t.angleMode)}function gt(t){if(d.field.wiggle||(d.field.wiggle=1),rt(),!ct.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(ct.keys()).join(", ")}.`);d.field.isActive=!0,d.field.current=t;const e=ct.get(t);e.field||(e.field=ft(e,0))}function dt(t,e,r={}){ct.set(t,{gen:e,field:null,angleMode:ut(r)})}function mt(t,e){for(let r=0;r<at;r++)for(let i=0;i<lt;i++)t[r][i]=e(r,i);return t}class pt{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=Z(t.point1,t.point2,e,i);n&&r.push(n)}return this._intersectionCache[e]=r,r}show(){d.stroke&&this.draw(),d.hatch&&this.hatch(),d.fill&&this.fill()}}class xt{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:$(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:$(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=$(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)),N(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){rt();const s=.5,a=[],l=Math.round(this.length/s),c=new it(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*k(.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 pt(a)}show(t,e,r=1){d.stroke&&this.draw(t,e,r),d.hatch&&this.hatch(t,e,r),d.fill&&this.fill(t,e,r)}}let yt,vt,bt,_t;class wt{constructor(){this.isClosed=!1,this.curvature=vt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){At(this.vert,this.curvature,this.isClosed).show()}}function St(t=0){vt=z(t,0,1),yt=new wt}function Rt(t,e,r=1){if(!yt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");yt.vertex(t,e,r)}function Et(t=!1){if(!yt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(yt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(yt.vertex(...yt.vert[0]),yt.isClosed=!0),yt.show(),yt=!1}function At(t,e=.5,r=!1){const i=new xt(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],g=U(h[0],h[1],u[0],u[1]),d=U(u[0],u[1],f[0],f[1]),m=j(h[0],h[1],u[0],u[1]),p=j(u[0],u[1],f[0],f[1]),x=e*Math.min(g,d,.5*Math.min(g,d)),y=Math.max(g,d),v=g-x,b=d-x;if(Math.floor(m)===Math.floor(p)){const e=r&&0===c?0:g-l,n=r?0===c?0:d-a:d;i.addSegment(m,e,h[2],!0),c===t.length-3&&i.addSegment(p,n,u[2],!0),l=0,0===c&&(o=g,a=x,s=t[1],l=0)}else{const e={x:u[0]-x*X(-m),y:u[1]-x*G(-m)},f={x:e.x+y*X(90-m),y:e.y+y*G(90-m)},g={x:u[0]+x*X(-p),y:u[1]+x*G(-p)},d={x:g.x+y*X(90-p),y:g.y+y*G(90-p)},_=Z(e,f,g,d,!0),w=U(e.x,e.y,_.x,_.y),S=U(e.x,e.y,g.x,g.y)/2,R=n*w*(2*Math.asin(S/w)*(180/Math.PI))/360,E=r&&0===c?0:v-l,A=c===t.length-3?r?o-x:b:0;i.addSegment(m,E,h[2],!0),i.addSegment(m,isNaN(R)?0:R,h[2],!0),i.addSegment(p,A,u[2],!0),l=x,0===c&&(o=v,a=x,s=[e.x,e.y])}c===t.length-3&&i.endPlot(p,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],n=U(e[0],e[1],r[0],r[1]),o=j(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 Pt,Mt,kt,It,Lt,Ct=!1,Tt=0,Nt=0;const zt={},Ot={};let Bt=1,Dt=0,Yt=0,Ft=1,Xt=0,Gt=0,$t=new Float32Array(8192),Ht=0,Wt=2048,Ut=32768;function jt(t,i,n,s){if(Ht>=Wt){Wt*=2;const t=new Float32Array(4*Wt);t.set($t),$t=t}const a=t-e/2,l=i-r/2,c=4*Ht;$t[c]=Bt*a+Yt*l+Xt+e/2,$t[c+1]=Dt*a+Ft*l+Gt+r/2,$t[c+2]=o*n*Math.sqrt(Bt*Bt+Dt*Dt)/2,$t[c+3]=s/255,Ht++}function Zt(){if(0===Ht)return;p.glMask.isDrawn=!0;const t=d.stroke.color._array;Pt.useProgram(Lt),Pt.enable(Pt.BLEND),Pt.blendFunc(Pt.ONE_MINUS_DST_ALPHA,Pt.ONE),Pt.bindVertexArray(kt),Pt.bindBuffer(Pt.ARRAY_BUFFER,It);const e=16*Ht,r=$t.subarray(0,4*Ht);e>Ut?(Pt.bufferData(Pt.ARRAY_BUFFER,$t,Pt.DYNAMIC_DRAW),Ut=$t.byteLength):Pt.bufferSubData(Pt.ARRAY_BUFFER,0,r),Pt.uniform4f(Ot.u_color,...t),Pt.uniformMatrix4fv(Ot.u_matrix,!1,Mt),Pt.drawArrays(Pt.POINTS,0,Ht),Pt.bindVertexArray(null),Ht=0,p.glMask._renderer._curShader=null}d.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let Vt,Kt,qt,Jt,Qt=new Map,te=null,ee={a:1,b:0,c:0,d:1,tx:0,ty:0};function re(){return{...d.stroke}}function ie(t){d.stroke={...t}}function ne(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 Pe.add(e.image.src),e.tip=()=>{te.image(Pe.tips.get(fe.p.image.src),-fe.p.weight/2,-fe.p.weight/2,fe.p.weight,fe.p.weight)},Qt.set(t,{param:e,colors:[],buffers:[]}),Pe.load()}Qt.set(t,{param:e,colors:[],buffers:[]})}function oe(t){if(!Qt.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...Qt.keys()].join(", ")}.`);d.stroke.type=t}function se(t,e,r){g(),d.stroke.color=n.color(...arguments),d.stroke.isActive=!0}function ae(t){d.stroke.weight=t}function le(t,e,r=1){oe(t),se(e),ae(r)}function ce(){return{a:q(),b:J(),c:Q(),d:tt(),tx:V(),ty:K()}}function he(t,e,r){return{x:t.a*e+t.c*r+t.tx,y:t.b*e+t.d*r+t.ty}}function ue(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)}}const fe={};function ge(t,i,n,o=!1){Bt=q(),Dt=J(),Yt=Q(),Ft=tt(),Xt=V(),Gt=K(),ee=ce(),Vt=new it(t+e/2,i+r/2),Kt=n,qt=o,qt&&qt.calcIndex(0)}const de=[];function me(t,i){i||(Jt=t),function(){fe.seed=999999*k();const{param:t}=Qt.get(d.stroke.type)??{};if(!t)return;fe.p=t,te=p.glMask;const{pressure:i}=t;if(fe.a="custom"!==i.type?k(-1,1):0,fe.b="custom"!==i.type?k(1,1.5):0,fe.cp="custom"!==i.type?k(3,3.5):k(-.2,.2),[fe.min,fe.max]=i.min_max,fe.noiseoffset=.03,!qt){const t=Jt*Math.PI/180;fe.cos=Math.cos(t),fe.sin=Math.sin(t)}(function(){m();const t=p.glMask.drawingContext,i=!Ct||Pt!==t;(i||Tt!==e||Nt!==r)&&(Mt=new Float32Array([2/e,0,0,0,0,-2/r,0,0,0,0,1,0,-1,1,0,1]),Tt=e,Nt=r),i&&(Pt=t,Lt=(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})(Pt),Pt.useProgram(Lt),Pt.enable(Pt.BLEND),Pt.blendFunc(Pt.ONE_MINUS_DST_ALPHA,Pt.ONE),["a_position","a_radius","a_alpha"].forEach(t=>zt[t]=Pt.getAttribLocation(Lt,t)),["u_matrix","u_color"].forEach(t=>Ot[t]=Pt.getUniformLocation(Lt,t)),kt=Pt.createVertexArray(),Pt.bindVertexArray(kt),It=Pt.createBuffer(),Pt.bindBuffer(Pt.ARRAY_BUFFER,It),Pt.bufferData(Pt.ARRAY_BUFFER,$t.byteLength,Pt.DYNAMIC_DRAW),Ut=$t.byteLength,Pt.enableVertexAttribArray(zt.a_position),Pt.vertexAttribPointer(zt.a_position,2,Pt.FLOAT,!1,16,0),Pt.enableVertexAttribArray(zt.a_radius),Pt.vertexAttribPointer(zt.a_radius,1,Pt.FLOAT,!1,16,8),Pt.enableVertexAttribArray(zt.a_alpha),Pt.vertexAttribPointer(zt.a_alpha,1,Pt.FLOAT,!1,16,12),Pt.bindVertexArray(null),Ct=!0)})(),be()&&p.blend(d.stroke.color),!1===p.isBrush&&(p.justChanged=!0),p.isBrush=!0,fe.alpha=ve(),Se()}();const n=function(){const{param:t}=Qt.get(d.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(Kt*(i?t:1)/n);for(let e=0;e<o;e++)de.length<2*o&&de.push(C()),pe(),i?Vt.plotTo(qt,n,n,t,e<10):Vt._moveToDegrees(t,n,n);Zt(),Se()}function pe(t=!1){if(!be())return;let e=t||xe(),r=N(M(fe.seed+.002*Vt.plotted,0),0,1,1-fe.noiseoffset,1+fe.noiseoffset);switch(fe.p.type){case"spray":!function(t){const e=d.stroke.weight*fe.p.scatter*t+d.stroke.weight*I(de)*fe.p.scatter/3,r=fe.p.weight*k(.9,1.1),i=Math.ceil(fe.p.grain/t);for(let t=0;t<i;t++){const t=k(.9,1.1),i=t*e*k(-1,1),n=k(-1,1),o=Math.sqrt((t*e)**2-i**2);jt(Vt.x+i,Vt.y+n*o,r,fe.alpha)}}(e*r);break;case"marker":_e(e*r);break;case"custom":case"image":we(e*r,fe.alpha);break;default:!function(t,e=1){const r=(e=N(e,0,1,.9,1.05))*d.stroke.weight*fe.p.scatter*(fe.p.sharpness+(1-fe.p.sharpness)*I(de)/t);if(k(0,fe.p.grain*t)>.4){let e,i;if(qt)e=.7*r*k(-1,1),i=r*k(-1,1);else{const t=r*k(-1,1),n=.3*r*k(-1,1);e=t*-fe.sin+n*fe.cos,i=t*fe.cos+n*fe.sin}jt(Vt.x+e,Vt.y+i,t*t*fe.p.weight*k(.85,1.15)*d.stroke.weight,Math.max(.9,t)*fe.alpha*k(.75,1.1))}}(e*r)}}function xe(){return qt?ye()*qt.pressure(Vt.plotted):ye()}function ye(){return"custom"===fe.p.pressure.type?N(fe.p.pressure.curve(Vt.plotted/Kt)+fe.cp,0,1,fe.min,fe.max,!0):function(t=.5+fe.p.pressure.curve[0]*fe.a,e=1-fe.p.pressure.curve[1]*fe.b,r=fe.cp,i=fe.min,n=fe.max){const o=t*Kt,s=(Vt.plotted<o?1.2*e:.8*e)*(Kt/2);return N(1/(1+Math.pow(Math.abs((Vt.plotted-o)/s),2*r)),0,1,i,n)}()}function ve(){return["default","spray"].includes(fe.p.type)?fe.p.opacity:fe.p.opacity/Math.min(d.stroke.weight,1.3)}function be(){const t=he(ee,Vt.x-e/2,Vt.y-r/2);if(d.stroke.clipWindow){const e=he(d.stroke.clipWindow.inverse,t.x,t.y),{bounds:r}=d.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 _e(t,e=!0,r=fe.alpha){const i=e?d.stroke.weight*fe.p.scatter:0,n=e?i*k(-1,1):0,o=e?i*k(-1,1):0;jt(Vt.x+n,Vt.y+o,d.stroke.weight*fe.p.weight*t,r)}function we(t,i,n=!0){p.glMask.isDrawn=!0,te.push(),te.noStroke(),d.stroke.color.setAlpha(i),te.fill(d.stroke.color);const o=n?d.stroke.weight*fe.p.scatter:0,s=n?o*k(-1,1):0,a=n?o*k(-1,1):0;te.translate(Vt.x+s-e,Vt.y+a-r),function(t,e){te.scale(t),"image"===fe.p.type&&te.tint(255,0,0,e/2);let r=0;"random"===fe.p.rotate?r=L(0,360):"natural"===fe.p.rotate&&(r=(qt?-qt.angle(Vt.plotted):-Jt)+Vt.angle()),te.rotate(r)}(d.stroke.weight*t,i),fe.p.tip(te),te.pop()}function Se(){if(be()){let t=xe(),e=ve();if("marker"===fe.p.type){for(let r=1;r<10;r++)_e(t*r/10,!1,5*e);Zt()}else if("custom"===fe.p.type||"image"===fe.p.type)for(let r=1;r<5;r++)we(t*r/5,e,!1)}}function Re(t,e,r,i){if(!d.stroke.isActive||!d.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");rt();let n=U(t,e,r,i);0!=n&&(ge(t,e,n),me(j(t,e,r,i),!1))}P(()=>{de.length=0});const Ee=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],Ae=[["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,.12,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of Ae){let e={};for(let r=0;r<t[1].length;r++)e[Ee[r]]=t[1][r];ne(t[0],e)}pt.prototype.draw=function(t=!1,e,r){let i=re();if(t&&le(t,e,r),i.isActive)for(let t of this.sides)Re(t[0].x,t[0].y,t[1].x,t[1].y);ie(i)},xt.prototype.draw=function(t,e,r){re().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,i){rt(),ge(e,r,t.length,t),me(i,!0)}(this,t,e,r))};const Pe={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),Pe.imageToWhite(r),this.tips.set(t,r),e()},i.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),i.src=t})))}};function Me(){return{...d.hatch}}function ke(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let i=d.hatch;i.isActive=!0,i.dist=t,i.angle=H(e),i.options=r}function Ie(t){let e=d.hatch.dist,r=(d.hatch.angle%180+180)%180,i=d.hatch.options,n=re();d.hatch.hBrush&&le(...Object.values(d.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=Le(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 pt([[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?N(i.gradient,0,1,1,1.1,!0):1,c=[],h=0,u=e,f=t=>({point1:{x:o.minX+u*t*X(90-r),y:a+u*t*G(90-r)},point2:{x:o.minX+u*t*X(90-r)+X(-r),y:a+u*t*G(90-r)+G(-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 g=c.filter(t=>void 0!==t[0]),m=i.rand||0;for(let t=0;t<g.length;t++){let r=g[t],n=t>0&&i.continuous;for(let i=0;i<r.length-1;i+=2)0!==m&&(r[i].x+=m*e*k(-1,1),r[i].y+=m*e*k(-1,1),r[i+1].x+=m*e*k(-1,1),r[i+1].y+=m*e*k(-1,1)),Re(r[i].x,r[i].y,r[i+1].x,r[i+1].y),n&&Re(g[t-1][1].x,g[t-1][1].y,r[i].x,r[i].y)}ie(n)}function Le(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 Ce(t,e,r){const i=2*Math.PI,n=r/2;p.ctx.moveTo(t+n,e),p.ctx.arc(t,e,n,0,i)}d.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},pt.prototype.hatch=function(t=!1,e,r){let i=Me();t&&ke(t,e,r),i.isActive&&Ie(this),function(t){d.hatch={...t}}(i)},xt.prototype.hatch=function(t,e,r){Me().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},d.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Te=()=>({...d.fill});function Ne(t,e,r,i){d.fill.opacity=(arguments.length<4?e:i)||150,d.fill.color=arguments.length<3?n.color(t):n.color(t,e,r),d.fill.isActive=!0}function ze(t,e="out"){d.fill.bleed_strength=z(t,0,1),d.fill.direction=e}function Oe(t=.4,e=.4){d.fill.texture_strength=z(t,0,1),d.fill.border_strength=z(e,0,1)}let Be;const De=[[],[]];function Ye(){for(let t=0;t<512;t++)De[0][t]=C(.5,.2),De[1][t]=C(0,.02)}function Fe(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}P(Ye);class Xe{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=W(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 Be.intersect(t.ray))Fe(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=k(-.6,.6)*e,s=k(-.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+k(0,.8*n)));const o=[],s=[],a=[],l=this.midP,c=Be.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)*k(.3,.6),y:l.y+(i.y-l.y)*k(.3,.6)}),o.push(i),s.push(this.m[r]),a.push(!this.dir[r])}return new Xe(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new Xe(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"===d.fill.direction?-90:90;0===De[0].length&&Ye();const h=De[0],u=h.length,f=De[1],g=f.length;let m=0,p=999===t?k(.6,.8):d.fill.bleed_strength;for(let o=0;o<n;o++){const d=e[o],x=e[o+1<n?o+1:0],y=r[o],v=i[o];t<997&&(p=y);const b=(v?c:-c)+5*k(-1,1),_=X(b),w=G(b),S=x.x-d.x,R=x.y-d.y,E=_*S+w*R,A=_*R-w*S,P=h[~~(k(0,1)*u)]*k(.65,1.35)*p;s[m]=d,a[m]=y,l[m]=v,m++,s[m]={x:d.x+.5*S+E*P,y:d.y+.5*R+A*P},a[m]=y+f[~~(k(0,1)*g)],l[m]=v,m++}let x=s,y=a,v=l,b=1024/d.fill.texture_strength;if(b&&m>b){const t=Math.ceil(m/b);x=[],y=[],v=[];for(let e=0;e<m;e+=t)x.push(s[e]),y.push(a[e]),v.push(l[e])}else x.length=m,y.length=m,v.length=m;return new Xe(x,y,this.midP,v,!1,this.sizeX,this.sizeY)}fill(t,i,n){const s=3*n,a=2*i*(1+n/2);p.blend(t),p.justChanged=!0,p.isBrush=!1,p.ctx.save(),p.ctx.setTransform(o*q(),o*J(),o*Q(),o*tt(),o*(V()+e/2),o*(K()+r/2)),p.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*d.fill.border_strength})`,p.ctx.lineCap="round";const l=Math.max(this.sizeX,this.sizeY),c=k(.15,.7);let h=this.grow();const u=this.scatter(.1).grow().scatter(.75).flipDirs();let f;for(let e=0;e<20;e++){e%4==0&&(h=h.grow()),e%2==0&&(f=[h.grow(1-.0125*e),h.grow(.7-.0125*e),h.grow(.4-.0125*e)]);for(const r of f)r.grow(999).grow(997).layer(e,l,a,t);u.grow(999).flipDirs().grow(997).layer(e,l,1.5*a*s,t),e%2==0&&h.grow(c).grow(999).layer(e,l,2*a,t),e%5!=0&&19!==e||(0!==s&&h.erase(3*s,i),p.blend(t,!0,!1,!0))}p.ctx.restore()}layer(t,e,r,i){var n;p.ctx.lineWidth=N(t,0,24,e/25,e/30,!0),p.ctx.fillStyle=`rgb(${i._getRed()} ${i._getGreen()} ${i._getBlue()} / ${r}%)`,n=this.v,p.ctx.beginPath(),n.forEach((t,e)=>{0===e?p.ctx.moveTo(t.x,t.y):p.ctx.lineTo(t.x,t.y)}),p.ctx.closePath(),p.ctx.fill(),p.ctx.stroke()}erase(t,e){p.ctx.save();const r=~~(k(80,110)*N(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-d.fill.bleed_strength),s=.05*o,a=.4*o,{x:l,y:c}=this.midP;p.ctx.globalCompositeOperation="destination-out";const h=(5-N(e,80,100,.3,.7,!0))*t/255;p.ctx.fillStyle=`rgb(255 0 0 / ${h})`,p.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+C(0,i),r=c+C(0,n),o=k(s,a);p.ctx.beginPath(),Ce(e,r,o),t%5!=0&&p.ctx.fill()}p.ctx.globalCompositeOperation="source-over",p.ctx.restore()}}pt.prototype.fill=function(t=!1,e,r,i,n,o){let s=Te();t&&(Ne(t,e),ze(r,o),Oe(i,n)),s.isActive&&(rt(),function(t){if(!d.fill.isActive||!d.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Be=t;const e=[...t.vertices],r=~~(.25*e.length*T({1:5,2:10,3:60})),i=d.fill.bleed_strength,n=e.map((t,e)=>(e>r?1:.3)*k(.85,1.2)*i),o=L(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 Xe(s,n,a,[],!0).fill(d.fill.color,N(d.fill.opacity,0,255,0,1,!0),d.fill.texture_strength)}(this)),(t=>{d.fill={...t}})(s)},xt.prototype.fill=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,N(d.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const Ge=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>p.blend(!1,!0),r.postdraw=()=>p.blend(!1,!0);const i=e.push,n=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){i.call(this),rt(),Ge.push({fill:{...d.fill},stroke:{...d.stroke},hatch:{...d.hatch},field:{...d.field}})},e.pop=function(){n.call(this),function(){const t=Ge.pop();t&&(d.stroke={...t.stroke},d.field={...t.field},d.hatch={...t.hatch},d.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{E=S(t);for(const t of A)t()})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{M=w(S(t))})(t)}}),t.Plot=xt,t.Polygon=pt,t.Position=it,t.add=ne,t.addField=dt,t.arc=function(t,e,r,i,n){const o=H(i),s=((H(n)-o)%360+360)%360;if(0===s)return;const a=new xt("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*X(o),f=e-r*G(o);a.draw(u,f,1)},t.beginShape=St,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);_t=[e,r],bt=new xt(t)},t.box=function(){return[...Qt.keys()]},t.circle=function(t,e,r,i=!1){const n=new xt("curve"),o=Math.PI*r,s=k(0,360),a=i?()=>1+.2*i*k():()=>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*L(-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*G(s),c=e-r*X(-s);n.show(l,c,1)},t.clip=function(t){g();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}}(ce());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");d.stroke.clipWindow={bounds:ue(t),inverse:e}},t.endShape=Et,t.endStroke=function(t,e){if(!bt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");bt.endPlot(t,e),bt.draw(_t[0],_t[1],1),bt=!1},t.field=gt,t.fill=Ne,t.fillBleed=ze,t.fillTexture=Oe,t.flowLine=function(t,e,r,i){if(!d.stroke.isActive||!d.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");rt(),ge(t,e,r),me($(i),!1)},t.hatch=ke,t.hatchArray=Ie,t.hatchStyle=function(t,e="black",r=1){d.hatch.hBrush={brush:t,color:e,weight:r}},t.instance=t=>{f=!0,i=t},t.line=Re,t.listFields=function(){return rt(),Array.from(ct.keys())},t.load=h,t.move=function(t,e,r){if(!bt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");bt.addSegment(t,e,r)},t.noClip=function(){d.stroke.clipWindow=null},t.noField=function(){rt(),d.field.isActive=!1},t.noFill=function(){d.fill.isActive=!1},t.noHatch=function(){d.hatch.isActive=!1,d.hatch.hBrush=!1},t.noStroke=function(){d.stroke.isActive=!1},t.pick=oe,t.polygon=function(t){new pt(t).show()},t.rect=function(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),St(0),Rt(t,e),Rt(t+r,e),Rt(t+r,e+i),Rt(t,e+i),Et(!0)},t.refreshField=function(t=0){if(!d.field.isActive||!d.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=ct.get(d.field.current);e.field=ft(e,t)},t.scaleBrushes=function(t){for(const{param:e}of Qt.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.set=le,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].");At(t,e).draw()},t.stroke=se,t.strokeWeight=ae,t.vertex=Rt,t.wRand=T,t.wiggle=function(t=1){gt("hand"),d.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.mapdiff --git a/dist/p5.brush.js.map b/dist/p5.brush.js.mapindex 967a88c..7ea3e49 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\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 captureBlendSource() {\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 Renderer.clear();\n Renderer.push();\n if (typeof Renderer.imageMode === \"function\") {\n Renderer.imageMode(Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER);\n }\n Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);\n Renderer.pop();\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\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 } else {\n this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\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 mask = this.isBrush ? this.glMask : this.mask;\n const no_mask = this.isBrush ? this.mask : this.glMask;\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 && _color) {\n this.isBlending = true;\n this.cachedColor = _color._array;\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 || this.cachedColor[0] !== _color._array[0] || this.cachedColor[1] !== _color._array[1] || this.cachedColor[2] !== _color._array[2] || this.cachedColor[3] !== _color._array[3]) {\n if (this.justChanged) {\n this.applyShader(no_mask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask);\n }\n this.cachedColor = _color._array;\n if (_isLast) this.isBlending = false;\n }\n },\n\n applyShader(mask) {\n let shader = Renderer.shaderProgram;\n const gl = Renderer.drawingContext;\n const targetIsFramebuffer = !!getActiveFramebuffer();\n const source = this.captureBlendSource();\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\", this.isBrush);\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 Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\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 mask.clear();\n mask.isDrawn = false;\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 circleData[offset] = _ma * px + _mc * py + _mx + Cwidth / 2;\n circleData[offset + 1] = _mb * px + _md * py + _my + Cheight / 2;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] =\n (Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;\n circleData[offset + 3] = alpha / 255;\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\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 if (isInsideClippingArea()) Mix.blend(State.stroke.color);\n if (Mix.isBrush === false) Mix.justChanged = true;\n Mix.isBrush = true;\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 adjustSizeAndRotation(State.stroke.weight * pressure, alpha);\n current.p.tip(Mask);\n Mask.pop();\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}\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.12,\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\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\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 Mix.ctx.beginPath();\n vertices.forEach((v, i) => {\n if (i === 0) Mix.ctx.moveTo(v.x, v.y);\n else Mix.ctx.lineTo(v.x, v.y);\n });\n Mix.ctx.closePath();\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 radius = d / 2;\n Mix.ctx.moveTo(x + radius, y);\n Mix.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 Mix.blend(color);\n Mix.justChanged = true;\n Mix.isBrush = false;\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","load","width","height","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","isMixReady","isBlending","cachedColor","Object","captureBlendSource","framebuffer","blendSourceFramebuffer","pixelDensity","createFramebuffer","density","antialias","depth","stencil","source","draw","clear","push","imageMode","CENTER","image","pop","graphicsFactory","createGraphics","p2dMode","P2D","webglMode","WEBGL","mask","glMask","this","ctx","drawingContext","shaderProgram","createShader","angleMode","DEGREES","lineWidth","uModelMatrix","blend","_color","_isLast","isBrush","no_mask","_array","justChanged","applyShader","shader","gl","targetIsFramebuffer","hadDepthTest","getParameter","DEPTH_TEST","disable","translate","setUniform","fill","noStroke","rect","resetShader","enable","isDrawn","SQRT3","Math","sqrt","F2","G2","fastFloor","x","floor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","y","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","a","b","d","withinBounds","constrain","low","high","max","min","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","round","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","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","minX","minY","maxX","maxY","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","isInsideClippingArea","calculateAlpha","markerTip","saveState","stepSize","spacing","totalSteps","customPressure","calculatePressure","lineNoise","sw","iterations","ceil","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","point","local","inverse","bounds","o","vibrate","rx","ry","setAlpha","tint","adjustSizeAndRotation","_vals","_standard_brushes","obj","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","Infinity","poly","bb","computeBoundingBoxForPolygon","computeOverallBoundingBox","ventana","startY","dots","dist1","linea","tempArray","flat","sort","gdots","dd","continuousLine","polygon","_boundingBox","arc","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","center","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","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","size","darker","sparse","pols","layer","numLayers","erase","restore","fillStyle","beginPath","lineTo","closePath","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,OAEd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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,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,EA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Q,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 filediff --git a/llms.txt b/llms.txtindex 12688fd..70fbd83 100644--- a/llms.txt+++ b/llms.txt@@ -163,7 +163,6 @@ brush.endStroke(angle, pressure)| `grain` | Texture density (`"default"` type only) || `opacity` | Mark opacity 0–255 || `spacing` | Stamp gap along stroke (1 = no overlap) |-| `blend` | Paint mixing on/off || `pressure` | `[start, end]` or `[start, mid, end]` or `(t) => value` || `tip` | `"custom"` type: `(_m) => { _m.rect(...) }` || `image` | `"image"` type: `{ src: "./tip.jpg" }` |@@ -176,7 +175,7 @@ Image brushes return a Promise — use `await brush.add(...)` inside `async setubrush.add("diamond", {type: "custom",weight: 5, scatter: 0.08, opacity: 23, spacing: 0.6,- blend: true, pressure: [0.5, 1.5, 0.5],+ pressure: [0.5, 1.5, 0.5],tip: (_m) => { _m.rotate(45); _m.rect(-1.5, -1.5, 3, 3) },rotate: "natural"})@@ -185,7 +184,7 @@ brush.add("diamond", {await brush.add("photo", {type: "image",weight: 10, scatter: 2, opacity: 30, spacing: 1.5,- blend: true, pressure: [1, 0.5],+ pressure: [1, 0.5],image: { src: "./tip.jpg" },rotate: "random"})diff --git a/src/core/color.js b/src/core/color.jsindex 7bd6d4e..dafe185 100644--- a/src/core/color.js+++ b/src/core/color.js@@ -95,6 +95,91 @@ const needsMixBuffers = () =>Renderer.glMask.width !== Cwidth ||Renderer.glMask.height !== Cheight;+const DIRTY_BRUSH_PADDING = 2;+const DIRTY_FILL_PADDING = 4;++const getTargetPixelSize = () => ({+ width: Math.max(1, Math.round(Cwidth * Density)),+ height: Math.max(1, Math.round(Cheight * Density)),+});++const expandDirtyRect = (rect, padding = 0) =>+ rect+ ? {+ minX: rect.minX - padding,+ minY: rect.minY - padding,+ maxX: rect.maxX + padding,+ maxY: rect.maxY + padding,+ }+ : null;++const normalizeDirtyRect = (rect) => {+ if (!rect) return null;++ const { width, height } = getTargetPixelSize();+ const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));+ const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));+ const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));+ const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));++ if (maxX <= minX || maxY <= minY) return null;++ return { minX, minY, maxX, maxY };+};++const unionDirtyRect = (a, b) => {+ if (!a) return b;+ if (!b) return a;++ return {+ minX: Math.min(a.minX, b.minX),+ minY: Math.min(a.minY, b.minY),+ maxX: Math.max(a.maxX, b.maxX),+ maxY: Math.max(a.maxY, b.maxY),+ };+};++const getFullDirtyRect = () => {+ const { width, height } = getTargetPixelSize();+ return { minX: 0, minY: 0, maxX: width, maxY: height };+};++const toScissorBox = (rect) => {+ const normalized = normalizeDirtyRect(rect);+ if (!normalized) return null;++ const { height } = getTargetPixelSize();+ return {+ x: normalized.minX,+ y: height - normalized.maxY,+ width: normalized.maxX - normalized.minX,+ height: normalized.maxY - normalized.minY,+ };+};++const withScissor = (gl, rect, draw) => {+ const box = toScissorBox(rect);+ if (!box) return false;++ const wasEnabled = gl.isEnabled(gl.SCISSOR_TEST);+ const prevBox = gl.getParameter(gl.SCISSOR_BOX);++ gl.enable(gl.SCISSOR_TEST);+ gl.scissor(box.x, box.y, box.width, box.height);++ try {+ draw();+ } finally {+ if (wasEnabled) {+ gl.scissor(prevBox[0], prevBox[1], prevBox[2], prevBox[3]);+ } else {+ gl.disable(gl.SCISSOR_TEST);+ }+ }++ return true;+};+/*** Loads and initializes a canvas for the drawing system.* @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.@@ -172,7 +257,42 @@ export const Mix = {isBlending: false,cachedColor: new Object(),- captureBlendSource() {+ markDirtyRect(target, rect) {+ const normalized = normalizeDirtyRect(rect);+ if (!target || !normalized) return;++ target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);+ target.isDrawn = true;+ },++ markFull(target) {+ if (!target) return;++ target.dirtyRect = getFullDirtyRect();+ target.isDrawn = true;+ },++ clearMask(target) {+ if (!target) return;++ target.clear();+ target.isDrawn = false;+ target.dirtyRect = null;+ },++ getCompositeRect(target, isBrushMask) {+ if (!target) return null;+ if (!target.dirtyRect) return getFullDirtyRect();++ return normalizeDirtyRect(+ expandDirtyRect(+ target.dirtyRect,+ isBrushMask ? DIRTY_BRUSH_PADDING : DIRTY_FILL_PADDING,+ ),+ );+ },++ captureBlendSource(dirtyRect) {const activeFramebuffer = getActiveFramebuffer();if (!activeFramebuffer) return Renderer._renderer;@@ -192,13 +312,17 @@ export const Mix = {const source = Renderer.blendSourceFramebuffer;source.draw(() => {- Renderer.clear();- Renderer.push();- if (typeof Renderer.imageMode === "function") {- Renderer.imageMode(Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER);- }- Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);- Renderer.pop();+ withScissor(Renderer.drawingContext, dirtyRect, () => {+ Renderer.clear();+ Renderer.push();+ if (typeof Renderer.imageMode === "function") {+ Renderer.imageMode(+ Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER,+ );+ }+ Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);+ Renderer.pop();+ });});return source;@@ -230,6 +354,8 @@ export const Mix = {this.mask.pixelDensity(Density);this.mask.clear();this.mask.angleMode(Renderer.DEGREES);+ this.mask.dirtyRect = null;+ this.mask.isDrawn = false;this.ctx = this.mask.drawingContext;@@ -238,10 +364,16 @@ export const Mix = {this.glMask.clear();this.glMask.angleMode(this.glMask.DEGREES);this.glMask.drawingContext.lineWidth = 0;+ this.glMask.dirtyRect = null;+ this.glMask.isDrawn = false;} else {this.mask = Renderer.mask;this.glMask = Renderer.glMask;this.ctx = this.mask.drawingContext;+ this.mask.dirtyRect ??= null;+ this.mask.isDrawn ??= false;+ this.glMask.dirtyRect ??= null;+ this.glMask.isDrawn ??= false;}// Link Matrix of GL mask to main Renderer@@ -258,8 +390,16 @@ export const Mix = {blend(_color = false, _isLast = false) {isMixReady();- const mask = this.isBrush ? this.glMask : this.mask;- const no_mask = this.isBrush ? this.mask : this.glMask;+ const activeIsBrush = this.isBrush === true;+ const mask = activeIsBrush ? this.glMask : this.mask;+ const no_mask = activeIsBrush ? this.mask : this.glMask;+ const nextColor = _color?._array;+ const colorChanged =+ !!nextColor &&+ (this.cachedColor[0] !== nextColor[0] ||+ this.cachedColor[1] !== nextColor[1] ||+ this.cachedColor[2] !== nextColor[2] ||+ this.cachedColor[3] !== nextColor[3]);// Perf gains are minimal but let's keep it for nowif (disable) {@@ -274,32 +414,40 @@ export const Mix = {}// Initialize blending if not already active- if (!this.isBlending && _color) {+ if (!this.isBlending && nextColor) {this.isBlending = true;- this.cachedColor = _color._array;+ this.cachedColor = nextColor;// Force p5 to bind its internal render target for glMask,// so the first glDraw() writes to the correct framebuffer.this.glMask.clear();}- if (_isLast || this.cachedColor[0] !== _color._array[0] || this.cachedColor[1] !== _color._array[1] || this.cachedColor[2] !== _color._array[2] || this.cachedColor[3] !== _color._array[3]) {+ if (_isLast || colorChanged) {if (this.justChanged) {- this.applyShader(no_mask);+ this.applyShader(no_mask, !activeIsBrush);this.justChanged = false;}if (this.isBlending) {- this.applyShader(mask);+ this.applyShader(mask, activeIsBrush);}- this.cachedColor = _color._array;+ if (nextColor) this.cachedColor = nextColor;if (_isLast) this.isBlending = false;}},- applyShader(mask) {+ applyShader(mask, isBrushMask) {+ if (!mask?.isDrawn) return;++ const dirtyRect = this.getCompositeRect(mask, isBrushMask);+ if (!dirtyRect) {+ this.clearMask(mask);+ return;+ }+let shader = Renderer.shaderProgram;const gl = Renderer.drawingContext;const targetIsFramebuffer = !!getActiveFramebuffer();- const source = this.captureBlendSource();+ const source = this.captureBlendSource(dirtyRect);// Disable depth test for this compositing draw so the fullscreen rect// does not write Z=0 into the depth buffer — which would cause any@@ -316,15 +464,17 @@ export const Mix = {// Set shader uniformsshader.setUniform("u_source", source);- shader.setUniform("u_isBrush", this.isBrush);+ shader.setUniform("u_isBrush", isBrushMask);shader.setUniform("u_flipOutputY", targetIsFramebuffer);shader.setUniform("u_mask", mask);shader.setUniform("u_color", this.cachedColor);// Draw a rectangle covering the whole canvas to apply the shader- Renderer.fill(0, 0, 0, 0);- Renderer.noStroke();- Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);+ withScissor(gl, dirtyRect, () => {+ Renderer.fill(0, 0, 0, 0);+ Renderer.noStroke();+ Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);+ });// Finish and clear maskRenderer.pop();@@ -333,7 +483,6 @@ export const Mix = {// Restore depth test stateif (hadDepthTest) gl.enable(gl.DEPTH_TEST);- mask.clear();- mask.isDrawn = false;+ this.clearMask(mask);},};diff --git a/src/core/mask.js b/src/core/mask.jsindex 8ed0cdc..dece51f 100644--- a/src/core/mask.js+++ b/src/core/mask.js@@ -1,5 +1,23 @@import { Mix } from "./color.js";+function transformPoint(matrix, x, y) {+ return {+ x: matrix.a * x + matrix.c * y + matrix.e,+ y: matrix.b * x + matrix.d * y + matrix.f,+ };+}++function strokePadding(ctx, matrix) {+ const lineWidth = ctx.lineWidth || 0;+ if (lineWidth <= 0) return 1;++ return (+ 1 ++ (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /+ 2+ );+}+// =============================================================================// Section: Draw shapes to Mask Buffers// =============================================================================@@ -9,12 +27,33 @@ import { Mix } from "./color.js";* @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.*/export function drawPolygon(vertices) {- Mix.ctx.beginPath();+ const ctx = Mix.ctx;+ const matrix = ctx.getTransform();+ let minX = Infinity,+ minY = Infinity,+ maxX = -Infinity,+ maxY = -Infinity;++ ctx.beginPath();vertices.forEach((v, i) => {- if (i === 0) Mix.ctx.moveTo(v.x, v.y);- else Mix.ctx.lineTo(v.x, v.y);+ const point = transformPoint(matrix, v.x, v.y);+ minX = Math.min(minX, point.x);+ minY = Math.min(minY, point.y);+ maxX = Math.max(maxX, point.x);+ maxY = Math.max(maxY, point.y);++ if (i === 0) ctx.moveTo(v.x, v.y);+ else ctx.lineTo(v.x, v.y);+ });+ ctx.closePath();++ const padding = strokePadding(ctx, matrix);+ Mix.markDirtyRect(Mix.mask, {+ minX: minX - padding,+ minY: minY - padding,+ maxX: maxX + padding,+ maxY: maxY + padding,});- Mix.ctx.closePath();}/**@@ -25,7 +64,21 @@ export function drawPolygon(vertices) {*/export function circle(x, y, d) {const PI2 = Math.PI * 2;+ const ctx = Mix.ctx;+ const matrix = ctx.getTransform();const radius = d / 2;- Mix.ctx.moveTo(x + radius, y);- Mix.ctx.arc(x, y, radius, 0, PI2);+ const center = transformPoint(matrix, x, y);+ const rx = radius * Math.hypot(matrix.a, matrix.c);+ const ry = radius * Math.hypot(matrix.b, matrix.d);+ const padding = strokePadding(ctx, matrix);++ Mix.markDirtyRect(Mix.mask, {+ minX: center.x - rx - padding,+ minY: center.y - ry - padding,+ maxX: center.x + rx + padding,+ maxY: center.y + ry + padding,+ });++ ctx.moveTo(x + radius, y);+ ctx.arc(x, y, radius, 0, PI2);}diff --git a/src/fill/fill.js b/src/fill/fill.jsindex 0af8c04..a750c05 100644--- a/src/fill/fill.js+++ b/src/fill/fill.js@@ -454,9 +454,10 @@ class FillPoly {const int = 2 * intensity * (1 + tex / 2);// Perform initial setup only once- Mix.blend(color);- Mix.justChanged = true;+ const switchingToFill = Mix.isBrush !== false;Mix.isBrush = false;+ if (switchingToFill) Mix.justChanged = true;+ Mix.blend(color);Mix.ctx.save();Mix.ctx.setTransform(diff --git a/src/stroke/gl_draw.js b/src/stroke/gl_draw.jsindex 9a143eb..718ea09 100644--- a/src/stroke/gl_draw.js+++ b/src/stroke/gl_draw.js@@ -166,12 +166,24 @@ export function circle(x, y, diameter, alpha) {const py = y - Cheight / 2;const offset = circleCount * 4;- circleData[offset] = _ma * px + _mc * py + _mx + Cwidth / 2;- circleData[offset + 1] = _mb * px + _md * py + _my + Cheight / 2;- // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)- circleData[offset + 2] =+ const screenX = _ma * px + _mc * py + _mx + Cwidth / 2;+ const screenY = _mb * px + _md * py + _my + Cheight / 2;+ const radius =(Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;++ circleData[offset] = screenX;+ circleData[offset + 1] = screenY;+ // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)+ circleData[offset + 2] = radius;circleData[offset + 3] = alpha / 255;++ Mix.markDirtyRect(Mix.glMask, {+ minX: screenX * Density - radius - 1,+ minY: screenY * Density - radius - 1,+ maxX: screenX * Density + radius + 1,+ maxY: screenY * Density + radius + 1,+ });+circleCount++;}diff --git a/src/stroke/stroke.js b/src/stroke/stroke.jsindex 1480cb4..4f9a868 100644--- a/src/stroke/stroke.js+++ b/src/stroke/stroke.js@@ -277,6 +277,52 @@ function currentPointInUserSpace() {);}+function screenPointFromPosition(x, y) {+ const point = transformPoint(_strokeTransform, x - Cwidth / 2, y - Cheight / 2);+ return {+ x: point.x + Cwidth / 2,+ y: point.y + Cheight / 2,+ };+}++function markImageTipDirty(rx, ry, scale, angle) {+ const halfWeight = current.p.weight / 2;+ const radians = (angle * Math.PI) / 180;+ const cosAngle = Math.cos(radians);+ const sinAngle = Math.sin(radians);+ const userCenterX = _position.x + rx;+ const userCenterY = _position.y + ry;+ const corners = [+ [-halfWeight, -halfWeight],+ [halfWeight, -halfWeight],+ [halfWeight, halfWeight],+ [-halfWeight, halfWeight],+ ];++ let minX = Infinity,+ minY = Infinity,+ maxX = -Infinity,+ maxY = -Infinity;++ for (const [x, y] of corners) {+ const lx = scale * (cosAngle * x - sinAngle * y);+ const ly = scale * (sinAngle * x + cosAngle * y);+ const point = screenPointFromPosition(userCenterX + lx, userCenterY + ly);++ minX = Math.min(minX, point.x * Renderer.pixelDensity());+ minY = Math.min(minY, point.y * Renderer.pixelDensity());+ maxX = Math.max(maxX, point.x * Renderer.pixelDensity());+ maxY = Math.max(maxY, point.y * Renderer.pixelDensity());+ }++ Mix.markDirtyRect(Mix.glMask, {+ minX: minX - 2,+ minY: minY - 2,+ maxX: maxX + 2,+ maxY: maxY + 2,+ });+}+/*** Defines a clipping region for strokes.* The region uses the same coordinate space as brush drawing commands,@@ -393,9 +439,10 @@ function saveState() {// Ensure GL is ready and blend stateisReady();- if (isInsideClippingArea()) Mix.blend(State.stroke.color);- if (Mix.isBrush === false) Mix.justChanged = true;+ const switchingToBrush = Mix.isBrush !== true;Mix.isBrush = true;+ if (switchingToBrush) Mix.justChanged = true;+ if (isInsideClippingArea()) Mix.blend(State.stroke.color);// Set additional state valuescurrent.alpha = calculateAlpha();@@ -613,9 +660,16 @@ function drawTip(pressure, alpha, vibrate = true) {const rx = vibrate ? vibration * rr(-1, 1) : 0;const ry = vibrate ? vibration * rr(-1, 1) : 0;Mask.translate(_position.x + rx - Cwidth, _position.y + ry - Cheight);- adjustSizeAndRotation(State.stroke.weight * pressure, alpha);+ const scale = State.stroke.weight * pressure;+ const angle = adjustSizeAndRotation(scale, alpha);current.p.tip(Mask);Mask.pop();++ if (current.p.type === "image") {+ markImageTipDirty(rx, ry, scale, angle);+ } else {+ Mix.markFull(Mix.glMask);+ }}/**@@ -671,6 +725,7 @@ function adjustSizeAndRotation(pressure, alpha) {(_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle();}Mask.rotate(angle);+ return angle;}/**@@ -824,7 +879,7 @@ const _standard_brushes = ["marker",[2,- 0.12,+ 0.2,null,null,1,@@ -841,6 +896,21 @@ for (let s of _standard_brushes) {add(s[0], obj);}+add("diamond", {+ type: "custom",+ weight: 0.78,+ scatter: 0.1,+ opacity: 17,+ spacing: 1.3,+ pressure: [1.2, 0.82],+ rotate: "none",+ tip: (_m) => {+ _m.rotate(45);+ _m.rect(-4, -4, 8, 8);+ _m.rect(2, 2, 3, 3);+ },+});+// ---------------------------------------------------------------------------// Extensions to Polygon and Plot Prototypes// ---------------------------------------------------------------------------diff --git a/test/sketch.js b/test/sketch.jsindex eb8038e..8021ac3 100644--- a/test/sketch.js+++ b/test/sketch.js@@ -182,6 +182,7 @@ async function setup() {tip: (_m) => {_m.rotate(45);_m.rect(-4, -4, 8, 8);+ _m.rect(1, 1, 2, 2);},});diff --git a/tools/brush-maker.html b/tools/brush-maker.htmlnew file mode 100644index 0000000..6f10d23--- /dev/null+++ b/tools/brush-maker.html@@ -0,0 +1,1024 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>p5.brush — Brush Maker</title>+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>+ <script src="../dist/p5.brush.js"></script>+ <style>+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }++ :root {+ --bg: #1a1a1a;+ --panel: #242424;+ --border: #333;+ --accent: #e8c547;+ --text: #d4d4d4;+ --text-dim: #777;+ --input-bg: #1a1a1a;+ --radius: 6px;+ --font: 'JetBrains Mono', 'Fira Code', 'Menlo', monospace;+ }++ body {+ background: var(--bg);+ color: var(--text);+ font-family: var(--font);+ font-size: 12px;+ display: flex;+ height: 100vh;+ overflow: hidden;+ }++ /* ── Left panel ─────────────────────────────────────────── */+ #panel {+ width: 280px;+ flex-shrink: 0;+ display: flex;+ flex-direction: column;+ border-right: 1px solid var(--border);+ overflow: hidden;+ }++ #panel-header {+ padding: 14px 16px 10px;+ border-bottom: 1px solid var(--border);+ flex-shrink: 0;+ }++ #panel-header h1 {+ font-size: 13px;+ font-weight: 600;+ color: var(--accent);+ letter-spacing: 0.04em;+ }++ #panel-header p {+ font-size: 10px;+ color: var(--text-dim);+ margin-top: 2px;+ }++ #controls {+ flex: 1;+ overflow-y: auto;+ padding: 12px 16px;+ scrollbar-width: thin;+ scrollbar-color: var(--border) transparent;+ }++ /* ── Section headings ────────────────────────────────────── */+ .section-label {+ font-size: 9px;+ font-weight: 700;+ letter-spacing: 0.12em;+ text-transform: uppercase;+ color: var(--text-dim);+ margin: 14px 0 8px;+ }+ .section-label:first-child { margin-top: 0; }++ /* ── Individual control rows ─────────────────────────────── */+ .control-row {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-bottom: 9px;+ }++ .control-row label {+ width: 68px;+ flex-shrink: 0;+ color: var(--text-dim);+ font-size: 11px;+ }++ .control-row input[type="range"] {+ flex: 1;+ accent-color: var(--accent);+ cursor: pointer;+ height: 3px;+ }++ .control-row .val {+ width: 36px;+ text-align: right;+ color: var(--text);+ font-size: 11px;+ flex-shrink: 0;+ }++ .control-row select,+ .control-row input[type="text"] {+ flex: 1;+ background: var(--input-bg);+ border: 1px solid var(--border);+ color: var(--text);+ font-family: var(--font);+ font-size: 11px;+ padding: 4px 6px;+ border-radius: var(--radius);+ outline: none;+ }++ .control-row select:focus,+ .control-row input[type="text"]:focus {+ border-color: var(--accent);+ }++ .control-row input[type="color"] {+ width: 32px;+ height: 22px;+ border: 1px solid var(--border);+ border-radius: var(--radius);+ padding: 1px;+ background: var(--input-bg);+ cursor: pointer;+ }++ /* Toggle switch */+ .toggle-wrap {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-bottom: 9px;+ }++ .toggle-wrap label {+ width: 68px;+ color: var(--text-dim);+ font-size: 11px;+ flex-shrink: 0;+ }++ .toggle {+ position: relative;+ width: 36px;+ height: 18px;+ }++ .toggle input { opacity: 0; width: 0; height: 0; }++ .toggle .slider-track {+ position: absolute;+ inset: 0;+ background: var(--border);+ border-radius: 18px;+ cursor: pointer;+ transition: background 0.2s;+ }++ .toggle input:checked + .slider-track { background: var(--accent); }++ .toggle .slider-track::before {+ content: '';+ position: absolute;+ width: 12px;+ height: 12px;+ left: 3px;+ top: 3px;+ background: white;+ border-radius: 50%;+ transition: transform 0.2s;+ }++ .toggle input:checked + .slider-track::before { transform: translateX(18px); }++ /* Pressure row */+ .pressure-group { margin-bottom: 9px; }+ .pressure-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 6px;+ }+ .pressure-header span { color: var(--text-dim); font-size: 11px; }+ .pressure-header .sub { font-size: 10px; color: var(--text-dim); }+ /* Separator */+ .sep {+ border: none;+ border-top: 1px solid var(--border);+ margin: 14px 0;+ }++ /* ── Code output ─────────────────────────────────────────── */+ #code-panel {+ flex-shrink: 0;+ border-top: 1px solid var(--border);+ background: var(--panel);+ }++ #code-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 8px 16px;+ border-bottom: 1px solid var(--border);+ }++ #code-header span {+ font-size: 10px;+ font-weight: 600;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--text-dim);+ }++ #copy-btn {+ background: var(--accent);+ color: #111;+ border: none;+ border-radius: var(--radius);+ font-family: var(--font);+ font-size: 10px;+ font-weight: 700;+ padding: 4px 10px;+ cursor: pointer;+ letter-spacing: 0.06em;+ }++ #copy-btn:hover { opacity: 0.85; }+ #copy-btn.copied { background: #5cb85c; color: white; }++ #code-output {+ margin: 0;+ padding: 12px 16px;+ font-family: var(--font);+ font-size: 10.5px;+ line-height: 1.6;+ color: #9cdcfe;+ background: transparent;+ white-space: pre;+ overflow-x: auto;+ max-height: 170px;+ }++ /* ── Right: viewport ─────────────────────────────────────── */+ #viewport {+ flex: 1;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }++ #viewport-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 10px 16px;+ border-bottom: 1px solid var(--border);+ flex-shrink: 0;+ }++ #viewport-header span {+ font-size: 10px;+ font-weight: 600;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--text-dim);+ }++ #viewport-controls {+ display: flex;+ gap: 10px;+ align-items: center;+ }++ #viewport-controls label { color: var(--text-dim); font-size: 11px; }++ #bg-color {+ width: 28px;+ height: 20px;+ border: 1px solid var(--border);+ border-radius: var(--radius);+ padding: 1px;+ background: var(--input-bg);+ cursor: pointer;+ }++ #stroke-color {+ width: 28px;+ height: 20px;+ border: 1px solid var(--border);+ border-radius: var(--radius);+ padding: 1px;+ background: var(--input-bg);+ cursor: pointer;+ }++ #canvas-wrap {+ flex: 1;+ display: flex;+ align-items: center;+ justify-content: center;+ overflow: hidden;+ background: #111;+ }++ #canvas-wrap canvas { display: block; }++ #multicolor-btn {+ background: transparent;+ border: 1px solid var(--border);+ color: var(--text-dim);+ font-family: var(--font);+ font-size: 10px;+ padding: 3px 8px;+ border-radius: var(--radius);+ cursor: pointer;+ letter-spacing: 0.06em;+ }+ #multicolor-btn:hover { border-color: var(--accent); color: var(--text); }+ #multicolor-btn.active { background: var(--accent); border-color: var(--accent); color: #111; font-weight: 700; }++ #tip-body {+ width: 100%;+ min-height: 80px;+ background: var(--input-bg);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ color: #9cdcfe;+ font-family: var(--font);+ font-size: 11px;+ line-height: 1.6;+ padding: 8px;+ resize: vertical;+ outline: none;+ }+ #tip-body:focus { border-color: var(--accent); }++ /* Upload zone */+ #upload-zone {+ border: 2px dashed var(--border);+ border-radius: var(--radius);+ padding: 14px 10px;+ text-align: center;+ cursor: pointer;+ transition: border-color 0.2s, background 0.2s;+ margin-bottom: 9px;+ user-select: none;+ }+ #upload-zone:hover, #upload-zone.drag-over {+ border-color: var(--accent);+ background: rgba(232, 197, 71, 0.05);+ }+ #upload-zone .upload-icon { font-size: 18px; color: var(--text-dim); line-height: 1; }+ #upload-zone p { font-size: 9px; color: var(--text-dim); margin-top: 4px; line-height: 1.4; }+ #upload-zone.has-image { border-color: #5cb85c; }+ #upload-zone.has-image p { color: #5cb85c; }+ #upload-zone.has-image .upload-icon { color: #5cb85c; }++ /* HTML label overlay */+ #canvas-wrap { position: relative; }+ #labels {+ position: absolute;+ inset: 0;+ pointer-events: none;+ }+ .lbl {+ position: absolute;+ font-size: 9px;+ font-family: var(--font);+ color: #888;+ letter-spacing: 0.04em;+ }+ </style>+</head>+<body>++<!-- ── Left panel ───────────────────────────────────────────── -->+<div id="panel">+ <div id="panel-header">+ <h1>p5.brush · Brush Maker</h1>+ <p>Adjust params — preview updates live</p>+ </div>++ <div id="controls">++ <!-- Identity -->+ <div class="section-label">Identity</div>++ <div class="control-row">+ <label>name</label>+ <input type="text" id="brush-name" value="myBrush" />+ </div>++ <div class="control-row">+ <label>type</label>+ <select id="brush-type">+ <option value="default">default</option>+ <option value="spray">spray</option>+ <option value="marker">marker</option>+ <option value="custom">custom</option>+ <option value="image">image</option>+ </select>+ </div>++ <!-- Geometry -->+ <div class="section-label">Geometry</div>++ <div class="control-row" id="weight-row">+ <label>weight</label>+ <input type="range" id="weight" min="0" max="3" step="0.01" value="0.9" />+ <span class="val" id="weight-val">0.9</span>+ </div>++ <div class="control-row">+ <label>scatter</label>+ <input type="range" id="scatter" min="0" max="15" step="0.05" value="1.8" />+ <span class="val" id="scatter-val">1.8</span>+ </div>++ <div class="control-row" id="sharpness-row">+ <label>sharpness</label>+ <input type="range" id="sharpness" min="0" max="1" step="0.01" value="0.3" />+ <span class="val" id="sharpness-val">0.3</span>+ </div>++ <!-- grain uses a non-linear internal mapping: pos 0–60 → grain 0–30 (step 0.5), pos 60–107 → grain 30–500 (step 10) -->+ <div class="control-row" id="grain-row">+ <label>grain</label>+ <input type="range" id="grain" min="0" max="107" step="1" value="20" />+ <span class="val" id="grain-val">10</span>+ </div>++ <!-- Appearance -->+ <div class="section-label">Appearance</div>++ <div class="control-row">+ <label>opacity</label>+ <input type="range" id="opacity" min="1" max="255" step="1" value="170" />+ <span class="val" id="opacity-val">170</span>+ </div>++ <div class="control-row">+ <label>spacing</label>+ <input type="range" id="spacing" min="0.01" max="2" step="0.01" value="0.3" />+ <span class="val" id="spacing-val">0.3</span>+ </div>++ <div class="control-row" id="rotate-row" style="display:none">+ <label>rotate</label>+ <select id="rotate">+ <option value="natural">natural</option>+ <option value="none">none</option>+ <option value="random">random</option>+ </select>+ </div>++ <!-- Pressure -->+ <div class="section-label">Pressure</div>+ <div class="pressure-group">+ <div class="control-row">+ <label>start</label>+ <input type="range" id="press-start" min="0.1" max="3" step="0.02" value="1.1" />+ <span class="val" id="press-start-val">1.1</span>+ </div>+ <div class="control-row" id="pressure-mid-row" style="display:none">+ <label>mid</label>+ <input type="range" id="press-mid" min="0.1" max="3" step="0.02" value="1.5" />+ <span class="val" id="press-mid-val">1.5</span>+ </div>+ <div class="control-row">+ <label>end</label>+ <input type="range" id="press-end" min="0.1" max="3" step="0.02" value="0.9" />+ <span class="val" id="press-end-val">0.9</span>+ </div>+ <div class="toggle-wrap" style="margin-top:4px">+ <label>3-point</label>+ <label class="toggle">+ <input type="checkbox" id="pressure-3pt" />+ <span class="slider-track"></span>+ </label>+ </div>+ </div>++ <!-- Tip function (custom type only) -->+ <div id="tip-section" style="display:none">+ <div class="section-label">Tip Function</div>+ <p style="font-size:9px;color:var(--text-dim);margin-bottom:6px;line-height:1.5">Write p5 commands. Each line becomes <span style="color:#9cdcfe">_m.command</span></p>+ <textarea id="tip-body" spellcheck="false">rotate(45);+rect(-4, -4, 8, 8);+rect(2, 2, 2, 2);</textarea>+ </div>++ <!-- Image upload (image type only) -->+ <div id="image-section" style="display:none">+ <div class="section-label">Image Tip</div>+ <div id="upload-zone">+ <div class="upload-icon">↑</div>+ <p id="upload-label">Click or drag an image here</p>+ <input type="file" id="image-file" accept="image/*" style="display:none" />+ </div>+ </div>++ </div><!-- /controls -->++ <!-- Code output -->+ <div id="code-panel">+ <div id="code-header">+ <span>Generated Code</span>+ <button id="copy-btn">COPY</button>+ </div>+ <pre id="code-output"></pre>+ </div>+</div><!-- /panel -->++<!-- ── Right viewport ────────────────────────────────────────── -->+<div id="viewport">+ <div id="viewport-header">+ <span>Preview</span>+ <div id="viewport-controls">+ <label>bg</label>+ <input type="color" id="bg-color" value="#fffceb" />+ <label>ink</label>+ <input type="color" id="stroke-color" value="#1a1a2e" />+ <button id="multicolor-btn">palette</button>+ </div>+ </div>+ <div id="canvas-wrap">+ <div id="labels"></div>+ </div>+</div>++<script>+// ─────────────────────────────────────────────+// State+// ─────────────────────────────────────────────+const params = {+ name: 'myBrush',+ type: 'default',+ weight: 0.9,+ scatter: 1.8,+ sharpness: 0.3,+ grain: 10,+ opacity: 170,+ spacing: 0.3,+ rotate: 'natural',+ pressStart: 1.1,+ pressMid: 1.5,+ pressEnd: 0.9,+ pressure3pt: false,+ multicolor: false,+ referenceBrush: 'HB',+ tipBody: 'rotate(45);\nrect(-4, -4, 8, 8);\nrect(2, 2, 2, 2);',+ imageDataUrl: null,+ imageSrc: './your-image.jpg',+ bgColor: '#fffceb',+ strokeColor: '#1a1a2e',+};++let needsRebuild = true;+let brushReady = true;++// ─────────────────────────────────────────────+// Code generator+// ─────────────────────────────────────────────+function generateCode() {+ const p = params;+ const pressure = p.pressure3pt+ ? `[${p.pressStart}, ${p.pressMid}, ${p.pressEnd}]`+ : `[${p.pressStart}, ${p.pressEnd}]`;++ const typeSpecific = p.type === 'default' || p.type === 'spray'+ ? ` sharpness: ${p.sharpness},\n grain: ${p.grain},\n`+ : '';++ const tipLines = p.tipBody.split('\n').map(l => l.trim()).filter(Boolean).map(l => ` _m.${l}`).join('\n');+ const tipField = p.type === 'custom'+ ? ` tip: (_m) => {\n${tipLines}\n },\n`+ : '';++ const imageField = p.type === 'image'+ ? ` image: { src: "${p.imageSrc}" },\n`+ : '';++ const prefix = p.type === 'image'+ ? '// Image brushes must be awaited inside async setup()\nawait '+ : '';++ return `${prefix}brush.add("${p.name}", {\n type: "${p.type}",\n weight: ${p.weight},\n scatter: ${p.scatter},\n${typeSpecific} opacity: ${p.opacity},\n spacing: ${p.spacing},\n pressure: ${pressure},\n rotate: "${p.rotate}",\n${imageField}${tipField}});`;+}++function updateCode() {+ document.getElementById('code-output').textContent = generateCode();+}++// ─────────────────────────────────────────────+// UI wiring+// ─────────────────────────────────────────────+function wire(id, key, transform = v => v) {+ const el = document.getElementById(id);+ const valEl = document.getElementById(id + '-val');+ el.addEventListener('input', () => {+ params[key] = transform(el.value);+ if (valEl) valEl.textContent = params[key];+ needsRebuild = true;+ updateCode();+ });+ if (valEl) valEl.textContent = params[key];+}++// Non-linear grain mapping: slider 0–60 → grain 0–30 (step 0.5), slider 60–107 → grain 30–500 (step 10)+function posToGrain(pos) {+ pos = parseFloat(pos);+ return pos <= 60 ? Math.round(pos * 0.5 * 10) / 10+ : Math.round((30 + (pos - 60) * 10) * 10) / 10;+}+function grainToPos(grain) {+ return grain <= 30 ? grain / 0.5 : 60 + (grain - 30) / 10;+}+// Set grain slider initial position+document.getElementById('grain').value = grainToPos(params.grain);++wire('weight', 'weight', v => Math.round(parseFloat(v) * 100) / 100);+wire('scatter', 'scatter', v => Math.round(parseFloat(v) * 100) / 100);+wire('sharpness', 'sharpness', v => Math.round(parseFloat(v) * 100) / 100);+wire('opacity', 'opacity', v => Math.round(parseFloat(v) * 100) / 100);+wire('spacing', 'spacing', v => Math.max(0.001, Math.round(parseFloat(v) * 1000) / 1000));+wire('press-start','pressStart', v => Math.round(parseFloat(v) * 100) / 100);+wire('press-mid', 'pressMid', v => Math.round(parseFloat(v) * 100) / 100);+wire('press-end', 'pressEnd', v => Math.round(parseFloat(v) * 100) / 100);++// Grain uses custom mapping+(function() {+ const el = document.getElementById('grain');+ const valEl = document.getElementById('grain-val');+ el.addEventListener('input', () => {+ params.grain = posToGrain(el.value);+ valEl.textContent = params.grain;+ needsRebuild = true;+ updateCode();+ });+ valEl.textContent = params.grain;+})();++// Per-type slider ranges+const SLIDER_RANGES = {+ default: {+ weight: { min: 0, max: 3, step: 0.01 },+ scatter: { min: 0, max: 15, step: 0.05 },+ opacity: { min: 1, max: 255, step: 1 },+ spacing: { min: 0.01, max: 2, step: 0.01 },+ },+ spray: {+ weight: { min: 0, max: 3, step: 0.01 },+ scatter: { min: 10, max: 50, step: 1 },+ opacity: { min: 1, max: 255, step: 1 },+ spacing: { min: 2, max: 50, step: 1 },+ },+ marker: {+ weight: { min: 0, max: 50, step: 1 },+ scatter: { min: 0, max: 15, step: 0.05 },+ opacity: { min: 0, max: 5, step: 0.01 },+ spacing: { min: 0.002, max: 0.5, step: 0.002 },+ },+ custom: {+ weight: { min: 0, max: 3, step: 0.01 },+ scatter: { min: 0, max: 15, step: 0.05 },+ opacity: { min: 1, max: 255, step: 1 },+ spacing: { min: 0.01, max: 2, step: 0.01 },+ },+ image: {+ weight: { min: 1, max: 60, step: 1 },+ scatter: { min: 0, max: 10, step: 0.05 },+ opacity: { min: 1, max: 50, step: 1 },+ spacing: { min: 2.5, max: 15, step: 0.1 },+ },+};++// Per-type starting values (effective after scaleBrushes(3))+const TYPE_PRESETS = {+ default: {+ weight: 0.9, scatter: 1.8, sharpness: 0.3, grain: 10,+ opacity: 170, spacing: 0.3, pressStart: 1.1, pressEnd: 0.9,+ rotate: 'natural', referenceBrush: 'HB',+ },+ spray: {+ weight: 0.6, scatter: 18, sharpness: null, grain: 40,+ opacity: 90, spacing: 5, pressStart: 0.7, pressEnd: 1,+ rotate: 'random', referenceBrush: 'spray',+ },+ marker: {+ weight: 6, scatter: 0.36, sharpness: null, grain: null,+ opacity: 1, spacing: 0.09, pressStart: 1.2, pressEnd: 0.85,+ rotate: 'none', referenceBrush: 'marker',+ },+ custom: {+ weight: 0.6, scatter: 0.15, sharpness: null, grain: null,+ opacity: 15, spacing: 1.4, pressStart: 1, pressEnd: 1,+ rotate: 'none', referenceBrush: 'HB',+ },+ image: {+ weight: 40, scatter: 0.15, sharpness: null, grain: null,+ opacity: 10, spacing: 2.5, pressStart: 0.8, pressEnd: 1.2,+ rotate: 'random', referenceBrush: 'HB',+ },+};++function applySliderRange(id, cfg) {+ const el = document.getElementById(id);+ const valEl = document.getElementById(id + '-val');+ el.min = cfg.min;+ el.max = cfg.max;+ el.step = cfg.step;+}++function applySliderValue(id, value) {+ const el = document.getElementById(id);+ const valEl = document.getElementById(id + '-val');+ el.value = value;+ if (valEl) valEl.textContent = value;+}++function applyTypePreset(type) {+ const preset = TYPE_PRESETS[type];+ const ranges = SLIDER_RANGES[type];++ // Update slider ranges+ applySliderRange('weight', ranges.weight);+ applySliderRange('opacity', ranges.opacity);+ applySliderRange('spacing', ranges.spacing);+ if (ranges.scatter) applySliderRange('scatter', ranges.scatter);++ // Update param values and slider positions+ params.weight = preset.weight; applySliderValue('weight', preset.weight);+ params.scatter = preset.scatter; applySliderValue('scatter', preset.scatter);+ params.opacity = preset.opacity; applySliderValue('opacity', preset.opacity);+ params.spacing = preset.spacing; applySliderValue('spacing', preset.spacing);+ params.pressStart = preset.pressStart; applySliderValue('press-start', preset.pressStart);+ params.pressEnd = preset.pressEnd; applySliderValue('press-end', preset.pressEnd);+ params.rotate = preset.rotate;+ params.referenceBrush = preset.referenceBrush;+ document.getElementById('rotate').value = preset.rotate;++ if (preset.sharpness !== null) {+ params.sharpness = preset.sharpness;+ applySliderValue('sharpness', preset.sharpness);+ }+ if (preset.grain !== null) {+ params.grain = preset.grain;+ document.getElementById('grain').value = grainToPos(preset.grain);+ document.getElementById('grain-val').textContent = preset.grain;+ }+}++document.getElementById('brush-type').addEventListener('change', e => {+ params.type = e.target.value;+ const isCustom = params.type === 'custom';+ const isImage = params.type === 'image';+ const showGrain = params.type === 'default' || params.type === 'spray';+ const showSharpness = params.type === 'default';+ document.getElementById('weight-row').style.display = isCustom ? 'none' : '';+ document.getElementById('rotate-row').style.display = (isCustom || isImage) ? '' : 'none';+ document.getElementById('sharpness-row').style.display = showSharpness ? '' : 'none';+ document.getElementById('grain-row').style.display = showGrain ? '' : 'none';+ document.getElementById('tip-section').style.display = isCustom ? '' : 'none';+ document.getElementById('image-section').style.display = isImage ? '' : 'none';+ applyTypePreset(params.type);+ needsRebuild = true;+ updateCode();+});++document.getElementById('tip-body').addEventListener('input', e => {+ params.tipBody = e.target.value;+ needsRebuild = true;+ updateCode();+});++document.getElementById('rotate').addEventListener('change', e => {+ params.rotate = e.target.value;+ needsRebuild = true;+ updateCode();+});+++document.getElementById('brush-name').addEventListener('input', e => {+ params.name = e.target.value || 'myBrush';+ needsRebuild = true;+ updateCode();+});++document.getElementById('pressure-3pt').addEventListener('change', e => {+ params.pressure3pt = e.target.checked;+ document.getElementById('pressure-mid-row').style.display = e.target.checked ? 'flex' : 'none';+ needsRebuild = true;+ updateCode();+});++const PALETTE = ["#002185", "#003c32", "#fcd300", "#ff2702", "#6b9404"];++document.getElementById('multicolor-btn').addEventListener('click', () => {+ params.multicolor = !params.multicolor;+ document.getElementById('multicolor-btn').classList.toggle('active', params.multicolor);+});++document.getElementById('bg-color').addEventListener('input', e => {+ params.bgColor = e.target.value;+});++document.getElementById('stroke-color').addEventListener('input', e => {+ params.strokeColor = e.target.value;+ needsRebuild = true;+});++document.getElementById('copy-btn').addEventListener('click', () => {+ navigator.clipboard.writeText(generateCode()).then(() => {+ const btn = document.getElementById('copy-btn');+ btn.textContent = 'COPIED!';+ btn.classList.add('copied');+ setTimeout(() => { btn.textContent = 'COPY'; btn.classList.remove('copied'); }, 1500);+ });+});++updateCode();++// ─────────────────────────────────────────────+// Image upload+// ─────────────────────────────────────────────+function handleImageFile(file) {+ if (!file || !file.type.startsWith('image/')) return;+ const reader = new FileReader();+ reader.onload = (e) => {+ params.imageDataUrl = e.target.result;+ params.imageSrc = file.name;+ document.getElementById('upload-label').textContent = file.name;+ const zone = document.getElementById('upload-zone');+ zone.classList.add('has-image');+ zone.querySelector('.upload-icon').textContent = '✓';+ needsRebuild = true;+ updateCode();+ };+ reader.readAsDataURL(file);+}++const uploadZone = document.getElementById('upload-zone');+const imageFileInput = document.getElementById('image-file');++uploadZone.addEventListener('click', () => imageFileInput.click());+imageFileInput.addEventListener('change', e => handleImageFile(e.target.files[0]));++uploadZone.addEventListener('dragover', e => {+ e.preventDefault();+ uploadZone.classList.add('drag-over');+});+uploadZone.addEventListener('dragleave', () => uploadZone.classList.remove('drag-over'));+uploadZone.addEventListener('drop', e => {+ e.preventDefault();+ uploadZone.classList.remove('drag-over');+ handleImageFile(e.dataTransfer.files[0]);+});++// Preload the bundled example brush tip so the image type works out of the box+fetch('../example/brush_tips/brush.jpg')+ .then(r => r.blob())+ .then(blob => {+ const reader = new FileReader();+ reader.onload = (e) => {+ params.imageDataUrl = e.target.result;+ params.imageSrc = './brush.jpg';+ document.getElementById('upload-label').textContent = 'brush.jpg (example — replace with yours)';+ const zone = document.getElementById('upload-zone');+ zone.classList.add('has-image');+ zone.querySelector('.upload-icon').textContent = '✓';+ // trigger rebuild if already in image mode+ if (params.type === 'image') { needsRebuild = true; updateCode(); }+ };+ reader.readAsDataURL(blob);+ })+ .catch(() => {}); // silently fail if served without the example asset++// ─────────────────────────────────────────────+// p5 sketch+// ─────────────────────────────────────────────+const CANVAS_W = 600;+const CANVAS_H = 600;++const sketch = (p) => {+ brush.instance(p);++ p.setup = () => {+ const cnv = p.createCanvas(CANVAS_W, CANVAS_H, p.WEBGL);+ cnv.parent('canvas-wrap');+ p.pixelDensity(2);+ p.angleMode(p.DEGREES);+ brush.load();+ brush.scaleBrushes(3);+ p.frameRate(30);+ };++ async function rebuildBrush() {+ const pr = params.pressure3pt+ ? [params.pressStart, params.pressMid, params.pressEnd]+ : [params.pressStart, params.pressEnd];++ const cfg = {+ type: params.type,+ weight: params.weight,+ scatter: params.scatter,+ opacity: params.opacity,+ spacing: params.spacing,+ pressure: pr,+ rotate: params.rotate,+ };++ if (params.type === 'default' || params.type === 'spray') {+ cfg.sharpness = params.sharpness;+ cfg.grain = params.grain;+ }++ if (params.type === 'custom') {+ const tipLines = params.tipBody.split('\n').map(l => l.trim()).filter(Boolean).map(l => `_m.${l}`).join('\n');+ try { cfg.tip = new Function('_m', tipLines); } catch(e) { cfg.tip = (_m) => {}; }+ }++ if (params.type === 'image') {+ if (!params.imageDataUrl) return; // no image yet, skip+ cfg.image = { src: params.imageDataUrl };+ brushReady = false;+ await brush.add(params.name, cfg);+ brushReady = true;+ } else {+ brush.add(params.name, cfg);+ }+ }++ p.draw = () => {+ p.randomSeed(42);+ p.noiseSeed(42);+ p.background(params.bgColor);+ p.translate(-CANVAS_W / 2, -CANVAS_H / 2);++ if (needsRebuild) {+ needsRebuild = false;+ rebuildBrush(); // async for image type; sets brushReady = false while loading+ }++ const W = CANVAS_W;+ const H = CANVAS_H;+ const mc = params.multicolor;+ const c = (i) => mc ? PALETTE[i % PALETTE.length] : params.strokeColor;++ brush.noField();+ brush.noFill();+ brush.noHatch();++ // For image type: skip brush strokes if no image uploaded or still loading+ const canDrawBrush = params.type !== 'image' || (params.imageDataUrl && brushReady);+ if (!canDrawBrush) {+ brush.set(params.referenceBrush, params.strokeColor, 1);+ brush.line(30, H - 30, W - 30, H - 30);+ return;+ }++ // ── 1. line() — top strip, full width ─────────+ for (let i = 0; i < 4; i++) {+ brush.set(params.name, c(i), 1);+ brush.line(30, 35 + i * 22, W - 30, 35 + i * 22);+ }+ brush.set(params.name, c(4), 1);+ brush.line(30, 32, W - 30, 125);++ // ── 2. circle() — left middle ─────────────────+ brush.set(params.name, c(0), 1);+ brush.noFill();+ brush.noHatch();+ brush.circle(110, 260, 130, 0.1);++ // ── 3. rect() stroked — right middle ──────────+ brush.set(params.name, c(1), 1);+ brush.noFill();+ brush.noHatch();+ brush.rect(270, 175, 240, 160);++ // ── 4. rect() hatched — left bottom ───────────+ brush.hatchStyle(params.name, c(2), 1);+ brush.hatch(9, 40, { rand: 0.08 });+ brush.noStroke();+ brush.rect(30, 365, 195, 90);+ brush.noHatch();++ // ── 5. spline() — right bottom ────────────────+ brush.set(params.name, c(3), 1);+ brush.noHatch();+ const sx = 270, sy = 365;+ brush.spline([+ [sx, sy + 70, 1],+ [sx + 50, sy + 15, 1],+ [sx + 100, sy + 75, 1],+ [sx + 160, sy + 20, 1],+ [sx + 215, sy + 70, 1],+ ], 1);++ // ── Reference line ────────────────────────────+ brush.set(params.referenceBrush, params.strokeColor, 1);+ brush.noHatch();+ brush.line(30, H - 30, W - 30, H - 30);+ };+};++new p5(sketch);+</script>+</body>+</html>