Skip to content

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

Snapshot: baseline before compositor experiments

acamposuribeeeb51d509603
diff --git a/README.md b/README.md
index 6ac6eec..e636605 100644
--- a/README.md
+++ b/README.md
@@ -296,6 +296,9 @@ Functions for managing brush behaviors and properties.
- `[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.
- Or a function `(t) => value` where `t` goes from 0 (start) to 1 (end), for full control.
+ - These simple/custom pressure modes include a subtle amount of per-stroke variation automatically, so repeated strokes feel less mechanical.
+ - Advanced option for power users: use the library's built-in Gaussian pressure profile explicitly with an object like `{ mode: "gaussian", curve: [0.15, 0.2], min_max: [1.1, 0.9] }`.
+ `curve` adjusts the wobble and asymmetry of the pressure envelope, while `min_max` sets the mapped pressure range. This is the same family of pressure logic used by the built-in brushes.
- `tip`: Only for `"custom"` type. A function where you draw the tip shape using p5.js commands inside a small graphics buffer `_m`.
- `image`: Only for `"image"` type. An object with a `src` property pointing to your image file: `{ src: "./tip.jpg" }`.
- `rotate`: How the tip rotates as it moves. `"none"` keeps it fixed, `"natural"` follows the stroke direction, `"random"` spins randomly.
@@ -339,6 +342,23 @@ Functions for managing brush behaviors and properties.
},
rotate: "natural",
});
+
+ // Advanced: explicitly use the built-in Gaussian pressure mode
+ brush.add("soft-pencil", {
+ type: "default",
+ weight: 0.3,
+ scatter: 0.6,
+ sharpness: 0.3,
+ grain: 10,
+ opacity: 170,
+ spacing: 0.1,
+ pressure: {
+ mode: "gaussian",
+ curve: [0.15, 0.2],
+ min_max: [1.1, 0.9],
+ },
+ rotate: "none",
+ });
```
**Image brushes only**: `brush.add()` returns a Promise when `type` is `"image"` — you must `await` it so the image finishes loading before you start drawing. For this to work, your `setup()` function must be declared `async`. For all other brush types, no `await` is needed.
@@ -803,7 +823,7 @@ These three functions perform similarly to the p5.js beginShape(), vertex(), and
<sub>[back to table](#table-of-functions)</sub>
### Optional: Configuration
-This section covers functions for initializing the drawing system, preloading required assets, and configuring system behavior. By default, the library works without executing these functions, but you might want to configure them to your liking.
+This section covers functions for initializing the drawing system and configuring system behavior. By default, the library works without executing these functions, but you might want to configure them to your liking.
> **Seeding**: p5.brush automatically hooks into p5's `randomSeed()` and `noiseSeed()`. Calling either of those functions seeds both p5 and the library simultaneously — no separate `brush.seed()` call is needed.
diff --git a/agents/memory.md b/agents/memory.md
new file mode 100644
index 0000000..6012b3f
--- /dev/null
+++ b/agents/memory.md
@@ -0,0 +1,39 @@
+# p5.brush — Agent Session Summary (March 2026)
+
+## Recent Focus
+- **Custom tip rasterization:** Custom brush tips are now rasterized to a 500×500 p5.Graphics buffer at `add()` time, using a 100×100 user coordinate space (origin at center). Dark = opaque, light = transparent.
+- **GL instancing:** Both image and custom tips are drawn via GPU instancing for performance. All tips are routed through the same `stampImage`/`glDrawImages` path.
+- **Brush-maker tool:** Added a real-time 100×100 preview for custom tips, improved slider logic, and moved generated code to a right column.
+- **UI/UX fixes:** Weight slider is now always visible for custom/image tips; slider ranges and defaults are unified; spacing min is 0.5 for both.
+- **Edge crispness:** Custom tips now use `noSmooth()` during rasterization to avoid blurred borders.
+
+## Key Files
+- `src/stroke/stroke.js`: Main brush logic, custom tip rasterization, instancing.
+- `src/stroke/gl_draw.js`: WebGL2 engine, instancing, texture cache.
+- `tools/brush-maker.html`: Brush design tool, preview, sliders, code output.
+
+## Custom Tip Convention
+- Draw in 100×100 units, origin at center.
+- Use plain p5 commands (fill, rect, ellipse, etc).
+- Dark = opaque ink; light/white = transparent.
+- Tip rasterized at 500×500 with `scale(5)` and `noSmooth()`.
+
+## UI Changes
+- Preview window for custom tips (100×100, real-time).
+- Weight slider always visible for custom/image.
+- Generated code panel moved to right column.
+
+## Performance
+- All tips (image/custom) use GPU instancing for fast drawing.
+- Texture cache prevents redundant uploads.
+
+## Outstanding Issues
+- None pending. All recent fixes verified.
+
+## How to Continue
+- For new custom tip features, update rasterization logic in `stroke.js`.
+- For UI changes, edit `brush-maker.html`.
+- For GL/instancing, update `gl_draw.js`.
+
+---
+This summary is for agent handoff. See code comments and recent commit history for details.
diff --git a/dist/p5.brush.esm.js b/dist/p5.brush.esm.js
index 7f1df41..e5ab2e1 100644
--- a/dist/p5.brush.esm.js
+++ b/dist/p5.brush.esm.js
@@ -1,2 +1,2 @@
-let t,e,r,i,n;const o=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,s=()=>d?r:window.self.p5.instance,a=t=>{t&&"function"==typeof t.remove&&t.remove()},l=()=>i&&i._renderer&&"function"==typeof i._renderer.activeFramebuffer?i._renderer.activeFramebuffer():null,c=()=>({width:Math.max(1,Math.round(t*n)),height:Math.max(1,Math.round(e*n))}),h=t=>{if(!t)return null;const{width:e,height:r}=c(),i=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),n=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),o=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),s=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return o<=i||s<=n?null:{minX:i,minY:n,maxX:o,maxY:s}},u=()=>{const{width:t,height:e}=c();return{minX:0,minY:0,maxX:t,maxY:e}},f=(t,e,r)=>{const i=(t=>{const e=h(t);if(!e)return null;const{height:r}=c();return{x:e.minX,y:r-e.maxY,width:e.maxX-e.minX,height:e.maxY-e.minY}})(e);if(!i)return!1;const n=t.isEnabled(t.SCISSOR_TEST),o=t.getParameter(t.SCISSOR_BOX);t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{r()}finally{n?t.scissor(o[0],o[1],o[2],o[3]):t.disable(t.SCISSOR_TEST)}return!0},m=(n=!1)=>{const a=((t=!1)=>{if(d&&!t)return{renderer:r,width:r.width,height:r.height};if(!t){const t=s();return{renderer:t,width:t.width,height:t.height}}if(o(t)){if(!o(e=t)||e.renderer._pInst!==s())throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.");return{renderer:s(),width:t.width,height:t.height}}var e;return{renderer:t,width:t.width,height:t.height}})(n);if(i=a.renderer,"webgl2"!==i.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");t=a.width,e=a.height,g=!0,i.loaded&&b.load()};let g=!1,d=!1;const x=()=>{g||m()},p={},y=t=>{d=!0,r=t},v=()=>{i?.loaded||(x(),b.load())},b={isBlending:!1,cachedColor:new Object,markDirtyRect(t,e){const r=h(e);var i,n;t&&r&&(t.dirtyRect=(n=r,(i=t.dirtyRect)?n?{minX:Math.min(i.minX,n.minX),minY:Math.min(i.minY,n.minY),maxX:Math.max(i.maxX,n.maxX),maxY:Math.max(i.maxY,n.maxY)}:i:n),t.isDrawn=!0)},markFull(t){t&&(t.dirtyRect=u(),t.isDrawn=!0)},clearMask(t){t&&(t.clear(),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:(t,e)=>t?t.dirtyRect?h(((t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null)(t.dirtyRect,e?2:4)):u():null,captureBlendSource(r){const o=l();if(!o)return i._renderer;var s;(!(s=i.blendSourceFramebuffer)||s.width!==t||s.height!==e||"function"==typeof s.pixelDensity&&s.pixelDensity()!==n)&&(a(i.blendSourceFramebuffer),i.blendSourceFramebuffer=i.createFramebuffer({width:t,height:e,density:n,antialias:!1,depth:!1,stencil:!1}));const c=i.blendSourceFramebuffer;return c.draw(()=>{f(i.drawingContext,r,()=>{i.clear(),i.push(),"function"==typeof i.imageMode&&i.imageMode(i.CENTER??i._renderer?._pInst?.CENTER),i.image(o,0,0,t,e),i.pop()})}),c},load(){n=i.pixelDensity();const r="function"==typeof i.createGraphics?i:i._pInst,o=r.P2D??i.P2D,s=r.WEBGL??i.WEBGL;i.loaded&&i.mask&&i.glMask&&i.mask.width===t&&i.mask.height===e&&i.glMask.width===t&&i.glMask.height===e?(this.mask=i.mask,this.glMask=i.glMask,this.ctx=this.mask.drawingContext,this.mask.dirtyRect??=null,this.mask.isDrawn??=!1,this.glMask.dirtyRect??=null,this.glMask.isDrawn??=!1):(a(i.mask),a(i.glMask),i.mask=r.createGraphics(t,e,o),i.glMask=r.createGraphics(t,e,s),i.loaded=!0,i.shaderProgram??=i.createShader("#version 300 es\n#define GLSLIFY 1\nuniform bool u_flipOutputY;out vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,u_flipOutputY ?-v.y : v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 uv1=vec2(uv.x,1.0-uv.y);vec4 source=texture(u_source,uv1);vec4 maskColor=texture(u_mask,uv1);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=uv1+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.0);}"),this.mask=i.mask,this.mask.pixelDensity(n),this.mask.clear(),this.mask.angleMode(i.DEGREES),this.mask.dirtyRect=null,this.mask.isDrawn=!1,this.ctx=this.mask.drawingContext,this.glMask=i.glMask,this.glMask.pixelDensity(n),this.glMask.clear(),this.glMask.angleMode(this.glMask.DEGREES),this.glMask.drawingContext.lineWidth=0,this.glMask.dirtyRect=null,this.glMask.isDrawn=!1),this.glMask._renderer.uModelMatrix=i._renderer.uModelMatrix},blend(t=!1,e=!1){v();const r=!0===this.isBrush,i=r?this.glMask:this.mask,n=r?this.mask:this.glMask,o=t?._array,s=!!o&&(this.cachedColor[0]!==o[0]||this.cachedColor[1]!==o[1]||this.cachedColor[2]!==o[2]||this.cachedColor[3]!==o[3]);!this.isBlending&&o&&(this.isBlending=!0,this.cachedColor=o,this.glMask.clear()),(e||s)&&(this.justChanged&&(this.applyShader(n,!r),this.justChanged=!1),this.isBlending&&this.applyShader(i,r),o&&(this.cachedColor=o),e&&(this.isBlending=!1))},applyShader(r,n){if(!r?.isDrawn)return;const o=this.getCompositeRect(r,n);if(!o)return void this.clearMask(r);let s=i.shaderProgram;const a=i.drawingContext,c=!!l(),h=this.captureBlendSource(o),u=a.getParameter(a.DEPTH_TEST);a.disable(a.DEPTH_TEST),i.push(),i.translate(0,0),i.shader(s),s.setUniform("u_source",h),s.setUniform("u_isBrush",n),s.setUniform("u_flipOutputY",c),s.setUniform("u_mask",r),s.setUniform("u_color",this.cachedColor),f(a,o,()=>{i.fill(0,0,0,0),i.noStroke(),i.rect(-t/2,-e/2,t,e)}),i.pop(),i.resetShader(),u&&a.enable(a.DEPTH_TEST),this.clearMask(r)}},_=Math.sqrt(3),w=.5*(_-1),R=(3-_)/6,M=t=>0|Math.floor(t),S=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);function E(t=Math.random){const e=function(t){const e=new Uint8Array(512);for(let t=0;t<256;t++)e[t]=t;for(let r=0;r<255;r++){const i=r+~~(t()*(256-r)),n=e[r];e[r]=e[i],e[i]=n}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>S[t%12*2]),i=new Float64Array(e).map(t=>S[t%12*2+1]);return function(t,n){let o=0,s=0,a=0;const l=(t+n)*w,c=M(t+l),h=M(n+l),u=(c+h)*R,f=t-(c-u),m=n-(h-u);let g,d;f>m?(g=1,d=0):(g=0,d=1);const x=f-g+R,p=m-d+R,y=f-1+2*R,v=m-1+2*R,b=255&c,_=255&h;let S=.5-f*f-m*m;if(S>=0){const t=b+e[_];S*=S,o=S*S*(r[t]*f+i[t]*m)}let E=.5-x*x-p*p;if(E>=0){const t=b+g+e[_+d];E*=E,s=E*E*(r[t]*x+i[t]*p)}let A=.5-y*y-v*v;if(A>=0){const t=b+1+e[_+1];A*=A,a=A*A*(r[t]*y+i[t]*v)}return 70*(o+s+a)}}function A(t,e){let r=new P(t),i=()=>r.next();return i.double=()=>i()+11102230246251565e-32*(2097152*i()|0),i.int32=()=>4294967296*r.next()|0,i.quick=i,i}class P{constructor(t){null==t&&(t=+new Date);let e=4022871197;function r(t){t=String(t);for(let r=0;r<t.length;r++){e+=t.charCodeAt(r);let i=.02519603282416938*e;e=i>>>0,i-=e,i*=e,e=i>>>0,i-=e,e+=4294967296*i}return 2.3283064365386963e-10*(e>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(t),this.s0<0&&(this.s0+=1),this.s1-=r(t),this.s1<0&&(this.s1+=1),this.s2-=r(t),this.s2<0&&(this.s2+=1)}next(){let{c:t,s0:e,s1:r,s2:i}=this,n=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=i,this.s2=n-(this.c=0|n)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let k=A(Math.random());const I=[],C=t=>I.push(t);let L=E(A(Math.random()));const T=(t=0,e=1)=>t+k()*(e-t),N=t=>t[~~(k()*t.length)],Y=(t,e)=>~~T(t,e),z=(t=0,e=1)=>{const r=1-k(),i=k();return Math.sqrt(-2*Math.log(r))*H(360*i)*e+t},X=t=>{let e=0;const r=[];for(const i in t)e+=t[i],r.push({key:i,cumulative:e});const i=k()*e;for(const{key:t,cumulative:e}of r)if(i<e)return isNaN(t)?t:parseInt(t)},D=(t,e,r,i,n,o=!1)=>{let s=i+(t-e)/(r-e)*(n-i);return o?i<n?O(s,i,n):O(s,n,i):s},O=(t,e,r)=>Math.max(Math.min(t,r),e),B=t=>(t%=360)<0?t+360:t,F=1440,G=2*Math.PI/F,$=new Float32Array(F).fill(NaN),W=new Float32Array(F).fill(NaN),H=t=>{const e=~~(4*B(t));let r=$[e];return isNaN(r)&&(r=Math.cos(e*G),$[e]=r),r},U=t=>{const e=~~(4*B(t));let r=W[e];return isNaN(r)&&(r=Math.sin(e*G),W[e]=r),r},j=(t,e=!1)=>{if(e||i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},Z=(t,e=!1)=>e||i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS?180*t/Math.PI:t,V=(t,e,r,i,n)=>{let o=H(n),s=U(n);return{x:o*(r-t)+s*(i-e)+t,y:o*(i-e)-s*(r-t)+e}},K=(t,e,r,i)=>Math.hypot(r-t,i-e),q=(t,e,r,i)=>j(Math.atan2(-(i-e),r-t),!0),J=(t,e,r,i,n=!1)=>{let o=t.x,s=t.y,a=e.x,l=e.y,c=r.x,h=r.y,u=i.x,f=i.y;if(o===a&&s===l||c===u&&h===f)return!1;let m=a-o,g=l-s,d=u-c,x=f-h,p=x*m-d*g;if(0===p)return!1;let y=(d*(s-h)-x*(o-c))/p,v=(m*(s-h)-g*(o-c))/p;return!(!n&&(v<0||v>1))&&{x:o+y*m,y:s+y*g}},Q=()=>i._renderer.uModelMatrix.mat4[12],tt=()=>i._renderer.uModelMatrix.mat4[13],et=()=>i._renderer.uModelMatrix.mat4[0],rt=()=>i._renderer.uModelMatrix.mat4[1],it=()=>i._renderer.uModelMatrix.mat4[4],nt=()=>i._renderer.uModelMatrix.mat4[5];let ot=!1;function st(){ot||(v(),lt=.01*t,ct=-.5*t,ht=-.5*e,ut=Math.round(2*t/lt),ft=Math.round(2*e/lt),bt("hand",(t,e)=>{const r=T(.2,.8),i=Y(5,10);return Rt(e,(e,n)=>.5*i*U(r*n*e+Y(15,25))*.2*H(t)+L(e,n)*i*.7)}),bt("curved",(t,e)=>{let r=Y(-10,10);return Y(0,100)%2==0&&(r*=-1),Rt(e,(e,i)=>3*D(L(.02*e+.03*t,.02*i+.03*t),0,1,-r,r))}),bt("zigzag",(t,e)=>{let r=Y(-30,-15)+Math.abs(44*U(t));Y(0,100)%2==0&&(r*=-1);let i=r,n=0;for(let t=0;t<ut;t++){for(let r=0;r<ft;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e}),bt("waves",(t,e)=>{const r=Y(10,15)+5*U(t),i=Y(3,6)+3*H(t),n=Y(20,35);return Rt(e,(t,e)=>U(r*t)*n*H(e*i)+Y(-3,3))}),bt("seabed",(t,e)=>{const r=T(.4,.8),i=Y(18,26);return Rt(e,(e,n)=>1.1*i*U(r*n*e+Y(15,20))*H(t))}),bt("spiral",(t,e)=>{const r=Y(5,10),i=2*Y(0,2)-1,n=Y(65,80),o=Array.from({length:r},()=>({x:T(.1,.9)*ut,y:T(.1,.9)*ft}));return Rt(e,(t,e)=>{let r=0,s=0;for(const a of o){const o=t-a.x,l=e-a.y,c=1/(o*o+l*l+1),h=Math.atan2(l,o)*(180/Math.PI),u=i*(h+n)*Math.PI/180;r+=c*Math.cos(u),s+=c*Math.sin(u)}return Math.atan2(s,r)*(180/Math.PI)})}),bt("columns",(t,e)=>{const r=Y(3,8),i=Y(25,45);return Rt(e,(t,e)=>U(t*r)*i)}),ot=!0)}class at{constructor(t,e){st(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=at.getColIndex(t),this.rowIdx=at.getRowIndex(e)}reset(){this.plotted=0}isIn(){return p.field.isActive?at.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const r=t,i=e,n=this.x+Q(),o=this.y+tt();return n>=-.3*r&&n<=1.3*r&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&p.field.isActive?mt.get(p.field.current).field[this.colIdx][this.rowIdx]*p.field.wiggle:0}moveTo(t,e,r=1){this.movePos(Z(t),e,r)}_moveToDegrees(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,i=1){this.movePos(t,e,r,i)}movePos(t,e,r,i=!1){const n=i||1;if(this.isIn())for(let o=0;o<e/r;o++){const e=this.angle()-(i?t.angle(this.plotted):t);this.update(this.x+r*H(e),this.y+r*U(e)),this.plotted+=r/n}else this.plotted+=r/n}static getRowIndex(t,e=1){const r=t+tt()-ht;return Math.round(r/lt/e)}static getColIndex(t,e=1){const r=t+Q()-ct;return Math.round(r/lt/e)}static isIn(t,e){return t>=0&&e>=0&&t<ut&&e<ft}}p.field={isActive:!1,current:null,wiggle:1};let lt,ct,ht,ut,ft,mt=new Map;const gt=new Set(["degrees","radians"]);function dt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!gt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function xt(t,e){return function(t,e){if("radians"!==e)return t;for(let e=0;e<t.length;e++)for(let r=0;r<t[e].length;r++)t[e][r]=Z(t[e][r],!0);return t}(t.gen(e,new Array(ut).fill(null).map(()=>new Float32Array(ft))),t.angleMode)}function pt(t=0){if(!p.field.isActive||!p.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=mt.get(p.field.current);e.field=xt(e,t)}function yt(t){if(p.field.wiggle||(p.field.wiggle=1),st(),!mt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(mt.keys()).join(", ")}.`);p.field.isActive=!0,p.field.current=t;const e=mt.get(t);e.field||(e.field=xt(e,0))}function vt(){st(),p.field.isActive=!1}function bt(t,e,r={}){mt.set(t,{gen:e,field:null,angleMode:dt(r)})}function _t(){return st(),Array.from(mt.keys())}function wt(t=1){yt("hand"),p.field.wiggle=t}function Rt(t,e){for(let r=0;r<ut;r++)for(let i=0;i<ft;i++)t[r][i]=e(r,i);return t}class Mt{constructor(t,e=!1){this.a=t,this.vertices=e?t:t.map(([t,e])=>({x:t,y:e})),this.sides=this.vertices.map((t,e,r)=>[t,r[(e+1)%r.length]]),this._intersectionCache={}}intersect(t){const e=`${t.point1.x},${t.point1.y}-${t.point2.x},${t.point2.y}`;if(this._intersectionCache[e])return this._intersectionCache[e];const r=[];for(const[e,i]of this.sides){const n=J(t.point1,t.point2,e,i);n&&r.push(n)}return this._intersectionCache[e]=r,r}show(){p.stroke&&this.draw(),p.hatch&&this.hatch(),p.fill&&this.fill()}}class St{constructor(t){this.segments=[],this.angles=[],this.pres=[],this.type=t,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(t=0,e=0,r=1,i=!1){this.angles.length>0&&this.angles.pop(),t=i?(t%360+360)%360:j(t),this.angles.push(t,t),this.pres.push(r),this.segments.push(e),this.length=this.segments.reduce((t,e)=>t+e,0)}endPlot(t=0,e=1,r=!1){t=r?(t%360+360)%360:j(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=j(t)}pressure(t){return t>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,t)}angle(t){return t>this.length?this.angles[this.angles.length-1]:(this.calcIndex(t),"curve"===this.type?this.curving(this.angles,t)+this.dir:this.angles[this.index]+this.dir)}curving(t,e){let r=t[this.index],i=t[this.index+1]??r;return Math.abs(i-r)>180&&(i>r?i=-(360-i):r=-(360-r)),D(e-this.suma,0,this.segments[this.index],r,i,!0)}calcIndex(t){this.index=-1,this.suma=0;let e=0;for(;e<=t;)this.suma=e,e+=this.segments[this.index+1],this.index++;return this.index}genPol(r,i,n=1,o){st();const s=.5,a=[],l=Math.round(this.length/s),c=new at(r+t/2,i+e/2);let h=0,u=0;for(let r=0;r<l;r++){c.plotTo(this,s,s);const r=this.calcIndex(c.plotted);h+=s,(h>=Math.max(this.segments[r]*o*T(.7,1.3),10)||r>=u)&&c.x&&(a.push([c.x-t/2,c.y-e/2]),h=0,r>=u&&u++)}return new Mt(a)}show(t,e,r=1){p.stroke&&this.draw(t,e,r),p.hatch&&this.hatch(t,e,r),p.fill&&this.fill(t,e,r)}}function Et(t){new Mt(t).show()}function At(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),Yt(0),zt(t,e),zt(t+r,e),zt(t+r,e+i),zt(t,e+i),Xt(!0)}function Pt(t,e,r,i=!1){const n=new St("curve"),o=Math.PI*r,s=T(0,360),a=i?()=>1+.2*i*T():()=>1;for(let t=0;t<4;t++){const e=-90*t+s;n.addSegment(e*a(),o/2*a(),1,!0)}if(i){const t=i*Y(-5,5);n.addSegment(s,Math.abs(t)*(Math.PI/180)*r,1,!0),n.endPlot(t+s,1,!0)}else n.endPlot(s,1,!0);const l=t-r*U(s),c=e-r*H(-s);n.show(l,c,1)}function kt(t,e,r,i,n){const o=Z(i),s=((Z(n)-o)%360+360)%360;if(0===s)return;const a=new St("curve"),l=Math.max(1,Math.ceil(s/90)),c=s/l,h=Math.PI*r*c/180;for(let t=0;t<l;t++)a.addSegment(o+t*c+90,h,1,!0);a.endPlot(o+s+90,1,!0);const u=t+r*H(o),f=e-r*U(o);a.draw(u,f,1)}let It,Ct,Lt,Tt;class Nt{constructor(){this.isClosed=!1,this.curvature=Ct,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){Gt(this.vert,this.curvature,this.isClosed).show()}}function Yt(t=0){Ct=O(t,0,1),It=new Nt}function zt(t,e,r=1){if(!It)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");It.vertex(t,e,r)}function Xt(t=!1){if(!It)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(It.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(It.vertex(...It.vert[0]),It.isClosed=!0),It.show(),It=!1}function Dt(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Tt=[e,r],Lt=new St(t)}function Ot(t,e,r){if(!Lt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Lt.addSegment(t,e,r)}function Bt(t,e){if(!Lt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Lt.endPlot(t,e),Lt.draw(Tt[0],Tt[1],1),Lt=!1}function Ft(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");Gt(t,e).draw()}function Gt(t,e=.5,r=!1){const i=new St(0===e?"segments":"curve"),n=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let o,s,a,l=0;for(let c=0;c<t.length-1;c++)if(e>0&&c<t.length-2){const h=t[c],u=t[c+1],f=t[c+2],m=K(h[0],h[1],u[0],u[1]),g=K(u[0],u[1],f[0],f[1]),d=q(h[0],h[1],u[0],u[1]),x=q(u[0],u[1],f[0],f[1]),p=e*Math.min(m,g,.5*Math.min(m,g)),y=Math.max(m,g),v=m-p,b=g-p;if(Math.floor(d)===Math.floor(x)){const e=r&&0===c?0:m-l,n=r?0===c?0:g-a:g;i.addSegment(d,e,h[2],!0),c===t.length-3&&i.addSegment(x,n,u[2],!0),l=0,0===c&&(o=m,a=p,s=t[1],l=0)}else{const e={x:u[0]-p*H(-d),y:u[1]-p*U(-d)},f={x:e.x+y*H(90-d),y:e.y+y*U(90-d)},m={x:u[0]+p*H(-x),y:u[1]+p*U(-x)},g={x:m.x+y*H(90-x),y:m.y+y*U(90-x)},_=J(e,f,m,g,!0),w=K(e.x,e.y,_.x,_.y),R=K(e.x,e.y,m.x,m.y)/2,M=n*w*(2*Math.asin(R/w)*(180/Math.PI))/360,S=r&&0===c?0:v-l,E=c===t.length-3?r?o-p:b:0;i.addSegment(d,S,h[2],!0),i.addSegment(d,isNaN(M)?0:M,h[2],!0),i.addSegment(x,E,u[2],!0),l=p,0===c&&(o=v,a=p,s=[e.x,e.y])}c===t.length-3&&i.endPlot(x,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],n=K(e[0],e[1],r[0],r[1]),o=q(e[0],e[1],r[0],r[1]);i.addSegment(o,n,r[2],!0),c===t.length-2&&i.endPlot(o,1,!0)}i.origin=r&&0!==e?s:t[0]}return i}let $t,Wt,Ht,Ut,jt,Zt=!1,Vt=0,Kt=0;const qt={},Jt={};let Qt=1,te=0,ee=0,re=1,ie=0,ne=0,oe=new Float32Array(8192),se=0,ae=2048,le=32768;function ce(r,i,o,s){if(se>=ae){ae*=2;const t=new Float32Array(4*ae);t.set(oe),oe=t}const a=r-t/2,l=i-e/2,c=4*se,h=Qt*a+ee*l+ie+t/2,u=te*a+re*l+ne+e/2,f=n*o*Math.sqrt(Qt*Qt+te*te)/2;oe[c]=h,oe[c+1]=u,oe[c+2]=f,oe[c+3]=s/255,b.markDirtyRect(b.glMask,{minX:h*n-f-1,minY:u*n-f-1,maxX:h*n+f+1,maxY:u*n+f+1}),se++}function he(){if(0===se)return;b.glMask.isDrawn=!0;const t=p.stroke.color._array;$t.useProgram(jt),$t.enable($t.BLEND),$t.blendFunc($t.ONE_MINUS_DST_ALPHA,$t.ONE),$t.bindVertexArray(Ht),$t.bindBuffer($t.ARRAY_BUFFER,Ut);const e=16*se,r=oe.subarray(0,4*se);e>le?($t.bufferData($t.ARRAY_BUFFER,oe,$t.DYNAMIC_DRAW),le=oe.byteLength):$t.bufferSubData($t.ARRAY_BUFFER,0,r),$t.uniform4f(Jt.u_color,...t),$t.uniformMatrix4fv(Jt.u_matrix,!1,Wt),$t.drawArrays($t.POINTS,0,se),$t.bindVertexArray(null),se=0,b.glMask._renderer._curShader=null}p.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let ue,fe,me,ge,de=new Map,xe=null,pe={a:1,b:0,c:0,d:1,tx:0,ty:0};function ye(){return{...p.stroke}}function ve(t){p.stroke={...t}}function be(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0!==e.vibration&&void 0===e.scatter&&(e.scatter=e.vibration),void 0!==e.definition&&void 0===e.sharpness&&(e.sharpness=e.definition),void 0!==e.quality&&void 0===e.grain&&(e.grain=e.quality),e.pressure=function(t){if(!t||"object"==typeof t&&!Array.isArray(t))return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t};if(Array.isArray(t)){const[e,r,i]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,n=Math.min(e,r,i),o=Math.max(e,r,i),s=o-n||1,[a,l,c]=[(e-n)/s,(r-n)/s,(i-n)/s];return{type:"custom",min_max:[n,o],curve:t=>t<.5?a+(l-a)*t*2:l+(c-l)*(t-.5)*2}}}(e.pressure),"image"===e.type){if(!e.image||!e.image.src)throw new Error(`Brush "${t}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return Ke.add(e.image.src),e.tip=()=>{xe.image(Ke.tips.get(Ne.p.image.src),-Ne.p.weight/2,-Ne.p.weight/2,Ne.p.weight,Ne.p.weight)},de.set(t,{param:e,colors:[],buffers:[]}),Ke.load()}de.set(t,{param:e,colors:[],buffers:[]})}function _e(){return[...de.keys()]}function we(t){for(const{param:e}of de.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function Re(t){if(!de.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...de.keys()].join(", ")}.`);p.stroke.type=t}function Me(t,e,r){x(),p.stroke.color=i.color(...arguments),p.stroke.isActive=!0}function Se(t){p.stroke.weight=t}function Ee(t,e,r=1){Re(t),Me(e),Se(r)}function Ae(){p.stroke.isActive=!1}function Pe(){return{a:et(),b:rt(),c:it(),d:nt(),tx:Q(),ty:tt()}}function ke(t,e,r){return{x:t.a*e+t.c*r+t.tx,y:t.b*e+t.d*r+t.ty}}function Ie(t){const[e,r,i,n]=t;return{minX:Math.min(e,i),minY:Math.min(r,n),maxX:Math.max(e,i),maxY:Math.max(r,n)}}function Ce(r,i){const n=ke(pe,r-t/2,i-e/2);return{x:n.x+t/2,y:n.y+e/2}}function Le(t){x();const e=function(t){const e=t.a*t.d-t.b*t.c;return Math.abs(e)<1e-12?null:{a:t.d/e,b:-t.b/e,c:-t.c/e,d:t.a/e,tx:(t.c*t.ty-t.d*t.tx)/e,ty:(t.b*t.tx-t.a*t.ty)/e}}(Pe());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");p.stroke.clipWindow={bounds:Ie(t),inverse:e}}function Te(){p.stroke.clipWindow=null}const Ne={};function Ye(r,i,n,o=!1){Qt=et(),te=rt(),ee=it(),re=nt(),ie=Q(),ne=tt(),pe=Pe(),ue=new at(r+t/2,i+e/2),fe=n,me=o,me&&me.calcIndex(0)}const ze=[];function Xe(r,i){i||(ge=r),function(){Ne.seed=999999*T();const{param:r}=de.get(p.stroke.type)??{};if(!r)return;Ne.p=r,xe=b.glMask;const{pressure:i}=r;if(Ne.a="custom"!==i.type?T(-1,1):0,Ne.b="custom"!==i.type?T(1,1.5):0,Ne.cp="custom"!==i.type?T(3,3.5):T(-.2,.2),[Ne.min,Ne.max]=i.min_max,Ne.noiseoffset=.03,!me){const t=ge*Math.PI/180;Ne.cos=Math.cos(t),Ne.sin=Math.sin(t)}!function(){v();const r=b.glMask.drawingContext,i=!Zt||$t!==r;(i||Vt!==t||Kt!==e)&&(Wt=new Float32Array([2/t,0,0,0,0,-2/e,0,0,0,0,1,0,-1,1,0,1]),Vt=t,Kt=e),i&&($t=r,jt=(t=>{const e=t.createProgram();for(let[r,i]of[[t.VERTEX_SHADER,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}"],[t.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"]]){const n=t.createShader(r);t.shaderSource(n,i),t.compileShader(n),t.attachShader(e,n)}return t.linkProgram(e),e})($t),$t.useProgram(jt),$t.enable($t.BLEND),$t.blendFunc($t.ONE_MINUS_DST_ALPHA,$t.ONE),["a_position","a_radius","a_alpha"].forEach(t=>qt[t]=$t.getAttribLocation(jt,t)),["u_matrix","u_color"].forEach(t=>Jt[t]=$t.getUniformLocation(jt,t)),Ht=$t.createVertexArray(),$t.bindVertexArray(Ht),Ut=$t.createBuffer(),$t.bindBuffer($t.ARRAY_BUFFER,Ut),$t.bufferData($t.ARRAY_BUFFER,oe.byteLength,$t.DYNAMIC_DRAW),le=oe.byteLength,$t.enableVertexAttribArray(qt.a_position),$t.vertexAttribPointer(qt.a_position,2,$t.FLOAT,!1,16,0),$t.enableVertexAttribArray(qt.a_radius),$t.vertexAttribPointer(qt.a_radius,1,$t.FLOAT,!1,16,8),$t.enableVertexAttribArray(qt.a_alpha),$t.vertexAttribPointer(qt.a_alpha,1,$t.FLOAT,!1,16,12),$t.bindVertexArray(null),Zt=!0)}();const n=!0!==b.isBrush;b.isBrush=!0,n&&(b.justChanged=!0),Ge()&&b.blend(p.stroke.color),Ne.alpha=Fe(),He()}();const n=function(){const{param:t}=de.get(p.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(fe*(i?r:1)/n);for(let t=0;t<o;t++)ze.length<2*o&&ze.push(z()),De(),i?ue.plotTo(me,n,n,r,t<10):ue._moveToDegrees(r,n,n);he(),He()}function De(t=!1){if(!Ge())return;let e=t||Oe(),r=D(L(Ne.seed+.002*ue.plotted,0),0,1,1-Ne.noiseoffset,1+Ne.noiseoffset);switch(Ne.p.type){case"spray":!function(t){const e=p.stroke.weight*Ne.p.scatter*t+p.stroke.weight*N(ze)*Ne.p.scatter/3,r=Ne.p.weight*T(.9,1.1),i=Math.ceil(Ne.p.grain/t);for(let t=0;t<i;t++){const t=T(.9,1.1),i=t*e*T(-1,1),n=T(-1,1),o=Math.sqrt((t*e)**2-i**2);ce(ue.x+i,ue.y+n*o,r,Ne.alpha)}}(e*r);break;case"marker":$e(e*r);break;case"custom":case"image":We(e*r,Ne.alpha);break;default:!function(t,e=1){const r=(e=D(e,0,1,.9,1.05))*p.stroke.weight*Ne.p.scatter*(Ne.p.sharpness+(1-Ne.p.sharpness)*N(ze)/t);if(T(0,Ne.p.grain*t)>.4){let e,i;if(me)e=.7*r*T(-1,1),i=r*T(-1,1);else{const t=r*T(-1,1),n=.3*r*T(-1,1);e=t*-Ne.sin+n*Ne.cos,i=t*Ne.cos+n*Ne.sin}ce(ue.x+e,ue.y+i,t*t*Ne.p.weight*T(.85,1.15)*p.stroke.weight,Math.max(.9,t)*Ne.alpha*T(.75,1.1))}}(e*r)}}function Oe(){return me?Be()*me.pressure(ue.plotted):Be()}function Be(){return"custom"===Ne.p.pressure.type?D(Ne.p.pressure.curve(ue.plotted/fe)+Ne.cp,0,1,Ne.min,Ne.max,!0):function(t=.5+Ne.p.pressure.curve[0]*Ne.a,e=1-Ne.p.pressure.curve[1]*Ne.b,r=Ne.cp,i=Ne.min,n=Ne.max){const o=t*fe,s=(ue.plotted<o?1.2*e:.8*e)*(fe/2);return D(1/(1+Math.pow(Math.abs((ue.plotted-o)/s),2*r)),0,1,i,n)}()}function Fe(){return["default","spray"].includes(Ne.p.type)?Ne.p.opacity:Ne.p.opacity/Math.min(p.stroke.weight,1.3)}function Ge(){const r=ke(pe,ue.x-t/2,ue.y-e/2);if(p.stroke.clipWindow){const t=ke(p.stroke.clipWindow.inverse,r.x,r.y),{bounds:e}=p.stroke.clipWindow;return t.x>=e.minX&&t.x<=e.maxX&&t.y>=e.minY&&t.y<=e.maxY}let i=.05*t;return r.x>=-t/2-i&&r.x<=t/2+i&&r.y>=-e/2-i&&r.y<=e/2+i}function $e(t,e=!0,r=Ne.alpha){const i=e?p.stroke.weight*Ne.p.scatter:0,n=e?i*T(-1,1):0,o=e?i*T(-1,1):0;ce(ue.x+n,ue.y+o,p.stroke.weight*Ne.p.weight*t,r)}function We(r,n,o=!0){b.glMask.isDrawn=!0,xe.push(),xe.noStroke(),p.stroke.color.setAlpha(n),xe.fill(p.stroke.color);const s=o?p.stroke.weight*Ne.p.scatter:0,a=o?s*T(-1,1):0,l=o?s*T(-1,1):0;xe.translate(ue.x+a-t,ue.y+l-e);const c=p.stroke.weight*r,h=function(t,e){xe.scale(t),"image"===Ne.p.type&&xe.tint(255,0,0,e/2);let r=0;return"random"===Ne.p.rotate?r=Y(0,360):"natural"===Ne.p.rotate&&(r=(me?-me.angle(ue.plotted):-ge)+ue.angle()),xe.rotate(r),r}(c,n);Ne.p.tip(xe),xe.pop(),"image"===Ne.p.type?function(t,e,r,n){const o=Ne.p.weight/2,s=n*Math.PI/180,a=Math.cos(s),l=Math.sin(s),c=ue.x+t,h=ue.y+e,u=[[-o,-o],[o,-o],[o,o],[-o,o]];let f=Infinity,m=Infinity,g=-Infinity,d=-Infinity;for(const[t,e]of u){const n=Ce(c+r*(a*t-l*e),h+r*(l*t+a*e));f=Math.min(f,n.x*i.pixelDensity()),m=Math.min(m,n.y*i.pixelDensity()),g=Math.max(g,n.x*i.pixelDensity()),d=Math.max(d,n.y*i.pixelDensity())}b.markDirtyRect(b.glMask,{minX:f-2,minY:m-2,maxX:g+2,maxY:d+2})}(a,l,c,h):b.markFull(b.glMask)}function He(){if(Ge()){let t=Oe(),e=Fe();if("marker"===Ne.p.type){for(let r=1;r<10;r++)$e(t*r/10,!1,5*e);he()}else if("custom"===Ne.p.type||"image"===Ne.p.type)for(let r=1;r<5;r++)We(t*r/5,e,!1)}}function Ue(t,e,r,i){if(!p.stroke.isActive||!p.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");st();let n=K(t,e,r,i);0!=n&&(Ye(t,e,n),Xe(q(t,e,r,i),!1))}function je(t,e,r,i){if(!p.stroke.isActive||!p.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");st(),Ye(t,e,r),Xe(j(i),!1)}C(()=>{ze.length=0});const Ze=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],Ve=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of Ve){let e={};for(let r=0;r<t[1].length;r++)e[Ze[r]]=t[1][r];be(t[0],e)}be("diamond",{type:"custom",weight:.78,scatter:.1,opacity:17,spacing:1.3,pressure:[1.2,.82],rotate:"none",tip:t=>{t.rotate(45),t.rect(-4,-4,8,8),t.rect(2,2,3,3)}}),Mt.prototype.draw=function(t=!1,e,r){let i=ye();if(t&&Ee(t,e,r),i.isActive)for(let t of this.sides)Ue(t[0].x,t[0].y,t[1].x,t[1].y);ve(i)},St.prototype.draw=function(t,e,r){ye().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,i){st(),Ye(e,r,t.length,t),Xe(i,!0)}(this,t,e,r))};const Ke={tips:new Map,add(t){this.tips.set(t,!1)},imageToWhite(t){t.loadPixels();for(let e=0;e<4*t.width*t.height;e+=4){let r=(t.pixels[e]+t.pixels[e+1]+t.pixels[e+2])/3;t.pixels[e]=t.pixels[e+1]=t.pixels[e+2]=255,t.pixels[e+3]=255-r}t.updatePixels()},async load(){const t=[...this.tips.keys()].filter(t=>!this.tips.get(t));await Promise.all(t.map(t=>new Promise((e,r)=>{const n=new window.Image;n.onload=()=>{const r=i.createImage(n.naturalWidth,n.naturalHeight);r.drawingContext.drawImage(n,0,0),Ke.imageToWhite(r),this.tips.set(t,r),e()},n.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),n.src=t})))}};function qe(){return{...p.hatch}}function Je(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let i=p.hatch;i.isActive=!0,i.dist=t,i.angle=Z(e),i.options=r}function Qe(t,e="black",r=1){p.hatch.hBrush={brush:t,color:e,weight:r}}function tr(){p.hatch.isActive=!1,p.hatch.hBrush=!1}function er(t){let e=p.hatch.dist,r=(p.hatch.angle%180+180)%180,i=p.hatch.options,n=ye();p.hatch.hBrush&&Ee(...Object.values(p.hatch.hBrush)),Array.isArray(t)||(t=[t]);const o=function(t){let e={minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity};for(let r of t){const t=rr(r);e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY)}return e}(t);let s=new Mt([[o.minX,o.minY],[o.maxX,o.minY],[o.maxX,o.maxY],[o.minX,o.maxY]]),a=r<=90&&r>=0?o.minY:o.maxY,l=i.gradient?D(i.gradient,0,1,1,1.1,!0):1,c=[],h=0,u=e,f=t=>({point1:{x:o.minX+u*t*H(90-r),y:a+u*t*U(90-r)},point2:{x:o.minX+u*t*H(90-r)+H(-r),y:a+u*t*U(90-r)+U(-r)}});for(;s.intersect(f(h)).length>0;){let e=[];for(let r of t)e.push(r.intersect(f(h)));c[h]=e.flat().sort((t,e)=>t.x===e.x?t.y-e.y:t.x-e.x),u*=l,h++}let m=c.filter(t=>void 0!==t[0]),g=i.rand||0;for(let t=0;t<m.length;t++){let r=m[t],n=t>0&&i.continuous;for(let i=0;i<r.length-1;i+=2)0!==g&&(r[i].x+=g*e*T(-1,1),r[i].y+=g*e*T(-1,1),r[i+1].x+=g*e*T(-1,1),r[i+1].y+=g*e*T(-1,1)),Ue(r[i].x,r[i].y,r[i+1].x,r[i+1].y),n&&Ue(m[t-1][1].x,m[t-1][1].y,r[i].x,r[i].y)}ve(n)}function rr(t){if(t._boundingBox)return t._boundingBox;let e=Infinity,r=Infinity,i=-Infinity,n=-Infinity;for(let o=0;o<t.a.length;o++){const[s,a]=t.a[o];s<e&&(e=s),s>i&&(i=s),a<r&&(r=a),a>n&&(n=a)}return t._boundingBox={minX:e,minY:r,maxX:i,maxY:n},t._boundingBox}function ir(t,e,r){return{x:t.a*e+t.c*r+t.e,y:t.b*e+t.d*r+t.f}}function nr(t,e){const r=t.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(e.a,e.c),Math.hypot(e.b,e.d))/2}function or(t,e,r){const i=2*Math.PI,n=b.ctx,o=n.getTransform(),s=r/2,a=ir(o,t,e),l=s*Math.hypot(o.a,o.c),c=s*Math.hypot(o.b,o.d),h=nr(n,o);b.markDirtyRect(b.mask,{minX:a.x-l-h,minY:a.y-c-h,maxX:a.x+l+h,maxY:a.y+c+h}),n.moveTo(t+s,e),n.arc(t,e,s,0,i)}p.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},Mt.prototype.hatch=function(t=!1,e,r){let i=qe();t&&Je(t,e,r),i.isActive&&er(this),function(t){p.hatch={...t}}(i)},St.prototype.hatch=function(t,e,r){qe().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},p.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const sr=()=>({...p.fill});function ar(t,e,r,n){p.fill.opacity=(arguments.length<4?e:n)||150,p.fill.color=arguments.length<3?i.color(t):i.color(t,e,r),p.fill.isActive=!0}function lr(t,e="out"){p.fill.bleed_strength=O(t,0,1),p.fill.direction=e}function cr(t=.4,e=.4){p.fill.texture_strength=O(t,0,1),p.fill.border_strength=O(e,0,1)}function hr(){p.fill.isActive=!1}let ur;const fr=[[],[]];function mr(){for(let t=0;t<512;t++)fr[0][t]=z(.5,.2),fr[1][t]=z(0,.02)}function gr(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}C(mr);class dr{constructor(t,e,r,i=[],n=!1,o,s){if(this.v=t,this.m=e,this.dir=i,this.midP=r,n){let e=0,i=0;const n=[];for(let o=0;o<t.length;o++){const s=Math.abs(r.x-t[o].x),a=Math.abs(r.y-t[o].y);e=Math.max(e,s),i=Math.max(i,a);const l=t[o],c=t[(o+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=V(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};n.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=i,this.dir=Array(t.length),n.forEach((t,e)=>{let r=0;for(const e of ur.intersect(t.ray))gr(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=T(-.6,.6)*e,s=T(-.6,.6)*i;this.midP={x:r.x+o,y:r.y+s}}else this.sizeX=o,this.sizeY=s}trim(t=1){if(t>=1||t<0||this.v.length<=8)return{v:[...this.v],m:[...this.m],dir:[...this.dir]};const e=~~((1-t)*this.v.length),r=~~(this.v.length/2-e/2),i=[...this.v],n=[...this.m],o=[...this.dir];return i.splice(r,e),n.splice(r,e),o.splice(r,e),{v:i,m:n,dir:o}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),i=[],n=e/r;for(let t=0;t<r;t++)i.push(~~(t*n+T(0,.8*n)));const o=[],s=[],a=[],l=this.midP,c=ur.sides;for(const t of i){const r=t%e;let i=this.v[r],n=0;for(const[t,e]of c){const r=t.y,o=e.y;if(r>i.y==o>i.y)continue;const s=(i.y-r)/(o-r);i.x<t.x+s*(e.x-t.x)&&n++}n%2==0&&(i={x:l.x+(i.x-l.x)*T(.3,.6),y:l.y+(i.y-l.y)*T(.3,.6)}),o.push(i),s.push(this.m[r]),a.push(!this.dir[r])}return new dr(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new dr(this.v,this.m,this.midP,this.dir.map(t=>!t),!1,this.sizeX,this.sizeY)}grow(t=1){const{v:e,m:r,dir:i}=this.trim(t),n=e.length,o=2*n,s=new Array(o),a=new Array(o),l=new Array(o),c="out"===p.fill.direction?-90:90;0===fr[0].length&&mr();const h=fr[0],u=h.length,f=fr[1],m=f.length;let g=0,d=999===t?T(.6,.8):p.fill.bleed_strength;for(let o=0;o<n;o++){const x=e[o],p=e[o+1<n?o+1:0],y=r[o],v=i[o];t<997&&(d=y);const b=(v?c:-c)+5*T(-1,1),_=H(b),w=U(b),R=p.x-x.x,M=p.y-x.y,S=_*R+w*M,E=_*M-w*R,A=h[~~(T(0,1)*u)]*T(.65,1.35)*d;s[g]=x,a[g]=y,l[g]=v,g++,s[g]={x:x.x+.5*R+S*A,y:x.y+.5*M+E*A},a[g]=y+f[~~(T(0,1)*m)],l[g]=v,g++}let x=s,y=a,v=l,b=1024/p.fill.texture_strength;if(b&&g>b){const t=Math.ceil(g/b);x=[],y=[],v=[];for(let e=0;e<g;e+=t)x.push(s[e]),y.push(a[e]),v.push(l[e])}else x.length=g,y.length=g,v.length=g;return new dr(x,y,this.midP,v,!1,this.sizeX,this.sizeY)}fill(r,i,o){const s=3*o,a=2*i*(1+o/2),l=!1!==b.isBrush;b.isBrush=!1,l&&(b.justChanged=!0),b.blend(r),b.ctx.save(),b.ctx.setTransform(n*et(),n*rt(),n*it(),n*nt(),n*(Q()+t/2),n*(tt()+e/2)),b.ctx.strokeStyle=`rgb(${r._getRed()} ${r._getGreen()} ${r._getBlue()} / ${.005*p.fill.border_strength})`,b.ctx.lineCap="round";const c=Math.max(this.sizeX,this.sizeY),h=T(.15,.7);let u=this.grow();const f=this.scatter(.1).grow().scatter(.75).flipDirs();let m;for(let t=0;t<20;t++){t%4==0&&(u=u.grow()),t%2==0&&(m=[u.grow(1-.0125*t),u.grow(.7-.0125*t),u.grow(.4-.0125*t)]);for(const e of m)e.grow(999).grow(997).layer(t,c,a,r);f.grow(999).flipDirs().grow(997).layer(t,c,1.5*a*s,r),t%2==0&&u.grow(h).grow(999).layer(t,c,2*a,r),t%5!=0&&19!==t||(0!==s&&u.erase(3*s,i),b.blend(r,!0,!1,!0))}b.ctx.restore()}layer(t,e,r,i){b.ctx.lineWidth=D(t,0,24,e/25,e/30,!0),b.ctx.fillStyle=`rgb(${i._getRed()} ${i._getGreen()} ${i._getBlue()} / ${r}%)`,function(t){const e=b.ctx,r=e.getTransform();let i=Infinity,n=Infinity,o=-Infinity,s=-Infinity;e.beginPath(),t.forEach((t,a)=>{const l=ir(r,t.x,t.y);i=Math.min(i,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),s=Math.max(s,l.y),0===a?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.closePath();const a=nr(e,r);b.markDirtyRect(b.mask,{minX:i-a,minY:n-a,maxX:o+a,maxY:s+a})}(this.v),b.ctx.fill(),b.ctx.stroke()}erase(t,e){b.ctx.save();const r=~~(T(80,110)*D(t,0,1,2,3.5)),i=this.sizeX/1.3,n=this.sizeY/1.3,o=Math.min(this.sizeX,this.sizeY)*(1.4-p.fill.bleed_strength),s=.05*o,a=.4*o,{x:l,y:c}=this.midP;b.ctx.globalCompositeOperation="destination-out";const h=(5-D(e,80,100,.3,.7,!0))*t/255;b.ctx.fillStyle=`rgb(255 0 0 / ${h})`,b.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+z(0,i),r=c+z(0,n),o=T(s,a);b.ctx.beginPath(),or(e,r,o),t%5!=0&&b.ctx.fill()}b.ctx.globalCompositeOperation="source-over",b.ctx.restore()}}Mt.prototype.fill=function(t=!1,e,r,i,n,o){let s=sr();t&&(ar(t,e),lr(r,o),cr(i,n)),s.isActive&&(st(),function(t){if(!p.fill.isActive||!p.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");ur=t;const e=[...t.vertices],r=~~(.25*e.length*X({1:5,2:10,3:60})),i=p.fill.bleed_strength,n=e.map((t,e)=>(e>r?1:.3)*T(.85,1.2)*i),o=Y(0,e.length),s=[...e.slice(o),...e.slice(0,o)],a=function(t){if(t.length<8)return t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0}).map(e=>e/t.length);const e=[...t];e[0].x===e[e.length-1].x&&e[0].y===e[e.length-1].y||e.push(e[0]);let r=0,i=0,n=0;for(let t=0;t<e.length-1;t++){const o=e[t].x*e[t+1].y-e[t+1].x*e[t].y;r+=o,i+=(e[t].x+e[t+1].x)*o,n+=(e[t].y+e[t+1].y)*o}return r*=.5,r?{x:i/(6*r),y:n/(6*r)}:{x:e[0].x,y:e[0].y}}(s);new dr(s,n,a,[],!0).fill(p.fill.color,D(p.fill.opacity,0,255,0,1,!0),p.fill.texture_strength)}(this)),(t=>{p.fill={...t}})(s)},St.prototype.fill=function(t,e,r){sr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,D(p.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const xr=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>b.blend(!1,!0),r.postdraw=()=>b.blend(!1,!0);const i=e.push,n=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){i.call(this),st(),xr.push({fill:{...p.fill},stroke:{...p.stroke},hatch:{...p.hatch},field:{...p.field}})},e.pop=function(){n.call(this),function(){const t=xr.pop();t&&(p.stroke={...t.stroke},p.field={...t.field},p.hatch={...t.hatch},p.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{k=A(t);for(const t of I)t()})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{L=E(A(t))})(t)}});export{St as Plot,Mt as Polygon,at as Position,be as add,bt as addField,kt as arc,Yt as beginShape,Dt as beginStroke,_e as box,Pt as circle,Le as clip,Xt as endShape,Bt as endStroke,yt as field,ar as fill,lr as fillBleed,cr as fillTexture,je as flowLine,Je as hatch,er as hatchArray,Qe as hatchStyle,y as instance,Ue as line,_t as listFields,m as load,Ot as move,Te as noClip,vt as noField,hr as noFill,tr as noHatch,Ae as noStroke,Re as pick,Et as polygon,At as rect,pt as refreshField,we as scaleBrushes,Ee as set,Ft as spline,Me as stroke,Se as strokeWeight,zt as vertex,X as wRand,wt as wiggle};
+let t,e,r,n,i;const o={enabled:!1,stats:new Map,timer:null},a=()=>globalThis.performance?.now?.()??Date.now(),s=(t,e)=>{if(!o.enabled)return e();const r=a();try{return e()}finally{const e=o.stats.get(t)??{total:0,count:0};e.total+=a()-r,e.count+=1,o.stats.set(t,e),o.timer&&clearTimeout(o.timer),o.timer=setTimeout(()=>{const t=[...o.stats.entries()].map(([t,e])=>({operation:t,total_ms:e.total.toFixed(2),count:e.count,avg_ms:(e.total/e.count).toFixed(4)})).sort((t,e)=>Number(e.total_ms)-Number(t.total_ms));console.log(`[p5.brush composite profile] entries=${t.length}`),console.table(t)},300)}},l=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,c=()=>x?r:window.self.p5.instance,h=()=>n&&n._renderer&&"function"==typeof n._renderer.activeFramebuffer?n._renderer.activeFramebuffer():null,u=()=>({width:Math.max(1,Math.round(t*i)),height:Math.max(1,Math.round(e*i))}),f=t=>{if(!t)return null;const{width:e,height:r}=u(),n=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),i=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),o=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),a=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return o<=n||a<=i?null:{minX:n,minY:i,maxX:o,maxY:a}},m=()=>{const{width:t,height:e}=u();return{minX:0,minY:0,maxX:t,maxY:e}},d=(t,e,r)=>{const n=(t=>{const e=f(t);if(!e)return null;const{height:r}=u();return{x:e.minX,y:r-e.maxY,width:e.maxX-e.minX,height:e.maxY-e.minY}})(e);if(!n)return!1;t.enable(t.SCISSOR_TEST),t.scissor(n.x,n.y,n.width,n.height);try{r()}finally{t.disable(t.SCISSOR_TEST)}return!0},g=(i=!1)=>{const o=((t=!1)=>{if(x&&!t)return{renderer:r,width:r.width,height:r.height};if(!t){const t=c();return{renderer:t,width:t.width,height:t.height}}if(l(t)){if(!l(e=t)||e.renderer._pInst!==c())throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch");return{renderer:c(),width:t.width,height:t.height}}var e;return{renderer:t,width:t.width,height:t.height}})(i);if(n=o.renderer,"webgl2"!==n.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");t=o.width,e=o.height,p=!0,n.loaded&&w.load()};let p=!1,x=!1;const y=()=>{p||g()},_={},b=t=>{x=!0,r=t},v=()=>{n?.loaded||(y(),w.load())},w={isBlending:!1,cachedColor:new Object,markDirtyRect(t,e){const r=f(e);var n,i;t&&r&&(t.dirtyRect=(i=r,(n=t.dirtyRect)?i?{minX:Math.min(n.minX,i.minX),minY:Math.min(n.minY,i.minY),maxX:Math.max(n.maxX,i.maxX),maxY:Math.max(n.maxY,i.maxY)}:n:i),t.isDrawn=!0)},clearMask(t){t&&(t.clear(),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:(t,e)=>t?t.dirtyRect?e&&h()?m():f(((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)):m():null,captureBlendSource(r){const o=h();if(!o)return n._renderer;const a=n.blendSourceFramebuffer;return(!a||a.width!==t||a.height!==e||"function"==typeof a.pixelDensity&&a.pixelDensity()!==i)&&(a?.remove&&a.remove(),n.blendSourceFramebuffer=n.createFramebuffer({width:t,height:e,density:i,antialias:!1,depth:!1,stencil:!1})),n.blendSourceFramebuffer.draw(()=>{d(n.drawingContext,r,()=>{n.clear(),n.push(),"function"==typeof n.imageMode&&n.imageMode(n.CENTER??n._renderer?._pInst?.CENTER),n.image(o,0,0,t,e),n.pop()})}),n.blendSourceFramebuffer},load(){o.enabled="undefined"!=typeof window&&(null!=window.__P5_BRUSH_COMPOSITE_PROFILE__?!!window.__P5_BRUSH_COMPOSITE_PROFILE__:"on"===new URLSearchParams(window.location.search).get("compositeProfile"));const r="function"==typeof n.createGraphics?n:n._pInst,a=!n.mask||!n.glMask||n.mask.width!==t||n.mask.height!==e||n.glMask.width!==t||n.glMask.height!==e;i=n.pixelDensity();const s=r.P2D??n.P2D,l=r.WEBGL??n.WEBGL;n.loaded&&!a||(n.mask?.remove&&n.mask.remove(),n.glMask?.remove&&n.glMask.remove(),n.mask=r.createGraphics(t,e,s),n.glMask=r.createGraphics(t,e,l),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.glMask=n.glMask,this.ctx=this.mask.drawingContext,this.mask.pixelDensity(i),this.mask.angleMode(n.DEGREES),this.mask.dirtyRect??=null,this.mask.noSmooth(),this.mask.isDrawn??=!1,this.glMask.pixelDensity(i),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,n=r?this.glMask:this.mask,i=r?this.mask:this.glMask,o=t?._array,a=!!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||a)&&(this.justChanged&&(this.applyShader(i,!r),this.justChanged=!1),this.isBlending&&this.applyShader(n,r),o&&(this.cachedColor=o),e&&(this.isBlending=!1))},applyShader(r,i){if(!r?.isDrawn)return;const o=i?"brush":"fill";s(`${o}.applyShader`,()=>{i&&"function"==typeof r.drawingContext?.flush&&s(`${o}.flushMask`,()=>r.drawingContext.flush());const a=s(`${o}.getCompositeRect`,()=>this.getCompositeRect(r,i));if(!a)return void s(`${o}.clearMask`,()=>this.clearMask(r));const l=n.drawingContext,c=n.shaderProgram,u=s(`${o}.captureSource`,()=>this.captureBlendSource(a)),f=!!h(),m=l.getParameter(l.DEPTH_TEST);l.disable(l.DEPTH_TEST),s(`${o}.shaderPass`,()=>{n.push(),n.translate(0,0),n.shader(c),c.setUniform("u_source",u),c.setUniform("u_isBrush",i),c.setUniform("u_flipOutputY",f),c.setUniform("u_mask",r),c.setUniform("u_color",this.cachedColor),d(l,a,()=>{n.fill(0,0,0,0),n.noStroke(),n.rect(-t/2,-e/2,t,e)}),n.pop()}),n.resetShader(),m&&l.enable(l.DEPTH_TEST),s(`${o}.clearMask`,()=>this.clearMask(r))})}},R=Math.sqrt(3),E=.5*(R-1),A=(3-R)/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 P(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 n=r+~~(t()*(256-r)),i=e[r];e[r]=e[n],e[n]=i}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]),n=new Float64Array(e).map(t=>S[t%12*2+1]);return function(t,i){let o=0,a=0,s=0;const l=(t+i)*E,c=M(t+l),h=M(i+l),u=(c+h)*A,f=t-(c-u),m=i-(h-u);let d,g;f>m?(d=1,g=0):(d=0,g=1);const p=f-d+A,x=m-g+A,y=f-1+2*A,_=m-1+2*A,b=255&c,v=255&h;let w=.5-f*f-m*m;if(w>=0){const t=b+e[v];w*=w,o=w*w*(r[t]*f+n[t]*m)}let R=.5-p*p-x*x;if(R>=0){const t=b+d+e[v+g];R*=R,a=R*R*(r[t]*p+n[t]*x)}let S=.5-y*y-_*_;if(S>=0){const t=b+1+e[v+1];S*=S,s=S*S*(r[t]*y+n[t]*_)}return 70*(o+a+s)}}function T(t,e){let r=new k(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class k{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 n=.02519603282416938*e;e=n>>>0,n-=e,n*=e,e=n>>>0,n-=e,e+=4294967296*n}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:n}=this,i=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=n,this.s2=i-(this.c=0|i)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let I=T(Math.random());const L=[],C=t=>L.push(t);let D=P(T(Math.random()));const F=(t=0,e=1)=>t+I()*(e-t),N=t=>t[~~(I()*t.length)],B=(t,e)=>~~F(t,e),Y=(t=0,e=1)=>{const r=1-I(),n=I();return Math.sqrt(-2*Math.log(r))*W(360*n)*e+t},z=t=>{let e=0;const r=[];for(const n in t)e+=t[n],r.push({key:n,cumulative:e});const n=I()*e;for(const{key:t,cumulative:e}of r)if(n<e)return isNaN(t)?t:parseInt(t)},O=(t,e,r,n,i,o=!1)=>{let a=n+(t-e)/(r-e)*(i-n);return o?n<i?X(a,n,i):X(a,i,n):a},X=(t,e,r)=>Math.max(Math.min(t,r),e),U=t=>(t%=360)<0?t+360:t,G=1440,$=2*Math.PI/G,V=new Float32Array(G).fill(NaN),H=new Float32Array(G).fill(NaN),W=t=>{const e=~~(4*U(t));let r=V[e];return isNaN(r)&&(r=Math.cos(e*$),V[e]=r),r},j=t=>{const e=~~(4*U(t));let r=H[e];return isNaN(r)&&(r=Math.sin(e*$),H[e]=r),r},K=(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,q=(t,e,r,n,i)=>{let o=W(i),a=j(i);return{x:o*(r-t)+a*(n-e)+t,y:o*(n-e)-a*(r-t)+e}},J=(t,e,r,n)=>Math.hypot(r-t,n-e),Q=(t,e,r,n)=>K(Math.atan2(-(n-e),r-t),!0),tt=(t,e,r,n,i=!1)=>{let o=t.x,a=t.y,s=e.x,l=e.y,c=r.x,h=r.y,u=n.x,f=n.y;if(o===s&&a===l||c===u&&h===f)return!1;let m=s-o,d=l-a,g=u-c,p=f-h,x=p*m-g*d;if(0===x)return!1;let y=(g*(a-h)-p*(o-c))/x,_=(m*(a-h)-d*(o-c))/x;return!(!i&&(_<0||_>1))&&{x:o+y*m,y:a+y*d}},et=()=>n._renderer.uModelMatrix.mat4[12],rt=()=>n._renderer.uModelMatrix.mat4[13],nt=()=>n._renderer.uModelMatrix.mat4[0],it=()=>n._renderer.uModelMatrix.mat4[1],ot=()=>n._renderer.uModelMatrix.mat4[4],at=()=>n._renderer.uModelMatrix.mat4[5];let st=!1;function lt(){st||(v(),ht=.01*t,ut=-.5*t,ft=-.5*e,mt=Math.round(2*t/ht),dt=Math.round(2*e/ht),wt("hand",(t,e)=>{const r=F(.2,.8),n=B(5,10);return At(e,(e,i)=>.5*n*j(r*i*e+B(15,25))*.2*W(t)+D(e,i)*n*.7)}),wt("curved",(t,e)=>{let r=B(-10,10);return B(0,100)%2==0&&(r*=-1),At(e,(e,n)=>3*O(D(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),wt("zigzag",(t,e)=>{let r=B(-30,-15)+Math.abs(44*j(t));B(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t<mt;t++){for(let r=0;r<dt;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),wt("waves",(t,e)=>{const r=B(10,15)+5*j(t),n=B(3,6)+3*W(t),i=B(20,35);return At(e,(t,e)=>j(r*t)*i*W(e*n)+B(-3,3))}),wt("seabed",(t,e)=>{const r=F(.4,.8),n=B(18,26);return At(e,(e,i)=>1.1*n*j(r*i*e+B(15,20))*W(t))}),wt("spiral",(t,e)=>{const r=B(5,10),n=2*B(0,2)-1,i=B(65,80),o=Array.from({length:r},()=>({x:F(.1,.9)*mt,y:F(.1,.9)*dt}));return At(e,(t,e)=>{let r=0,a=0;for(const s of o){const o=t-s.x,l=e-s.y,c=1/(o*o+l*l+1),h=Math.atan2(l,o)*(180/Math.PI),u=n*(h+i)*Math.PI/180;r+=c*Math.cos(u),a+=c*Math.sin(u)}return Math.atan2(a,r)*(180/Math.PI)})}),wt("columns",(t,e)=>{const r=B(3,8),n=B(25,45);return At(e,(t,e)=>j(t*r)*n)}),st=!0)}class ct{constructor(t,e){lt(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=ct.getColIndex(t),this.rowIdx=ct.getRowIndex(e)}reset(){this.plotted=0}isIn(){return _.field.isActive?ct.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const r=t,n=e,i=this.x+et(),o=this.y+rt();return i>=-.3*r&&i<=1.3*r&&o>=-.3*n&&o<=1.3*n}angle(){return this.isIn()&&_.field.isActive?gt.get(_.field.current).field[this.colIdx][this.rowIdx]*_.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,n=1){this.movePos(t,e,r,n)}movePos(t,e,r,n=!1){const i=n||1;if(this.isIn())for(let o=0;o<e/r;o++){const e=this.angle()-(n?t.angle(this.plotted):t);this.update(this.x+r*W(e),this.y+r*j(e)),this.plotted+=r/i}else this.plotted+=r/i}static getRowIndex(t,e=1){const r=t+rt()-ft;return Math.round(r/ht/e)}static getColIndex(t,e=1){const r=t+et()-ut;return Math.round(r/ht/e)}static isIn(t,e){return t>=0&&e>=0&&t<mt&&e<dt}}_.field={isActive:!1,current:null,wiggle:1};let ht,ut,ft,mt,dt,gt=new Map;const pt=new Set(["degrees","radians"]);function xt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!pt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function yt(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(mt).fill(null).map(()=>new Float32Array(dt))),t.angleMode)}function _t(t=0){if(!_.field.isActive||!_.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=gt.get(_.field.current);e.field=yt(e,t)}function bt(t){if(_.field.wiggle||(_.field.wiggle=1),lt(),!gt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(gt.keys()).join(", ")}.`);_.field.isActive=!0,_.field.current=t;const e=gt.get(t);e.field||(e.field=yt(e,0))}function vt(){lt(),_.field.isActive=!1}function wt(t,e,r={}){gt.set(t,{gen:e,field:null,angleMode:xt(r)})}function Rt(){return lt(),Array.from(gt.keys())}function Et(t=1){bt("hand"),_.field.wiggle=t}function At(t,e){for(let r=0;r<mt;r++)for(let n=0;n<dt;n++)t[r][n]=e(r,n);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,n]of this.sides){const i=tt(t.point1,t.point2,e,n);i&&r.push(i)}return this._intersectionCache[e]=r,r}show(){_.stroke&&this.draw(),_.hatch&&this.hatch(),_.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,n=!1){this.angles.length>0&&this.angles.pop(),t=n?(t%360+360)%360:K(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:K(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=K(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],n=t[this.index+1]??r;return Math.abs(n-r)>180&&(n>r?n=-(360-n):r=-(360-r)),O(e-this.suma,0,this.segments[this.index],r,n,!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,n,i=1,o){lt();const a=.5,s=[],l=Math.round(this.length/a),c=new ct(r+t/2,n+e/2);let h=0,u=0;for(let r=0;r<l;r++){c.plotTo(this,a,a);const r=this.calcIndex(c.plotted);h+=a,(h>=Math.max(this.segments[r]*o*F(.7,1.3),10)||r>=u)&&c.x&&(s.push([c.x-t/2,c.y-e/2]),h=0,r>=u&&u++)}return new Mt(s)}show(t,e,r=1){_.stroke&&this.draw(t,e,r),_.hatch&&this.hatch(t,e,r),_.fill&&this.fill(t,e,r)}}function Pt(t){new Mt(t).show()}function Tt(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),Bt(0),Yt(t,e),Yt(t+r,e),Yt(t+r,e+n),Yt(t,e+n),zt(!0)}function kt(t,e,r,n=!1){const i=new St("curve"),o=Math.PI*r,a=F(0,360),s=n?()=>1+.2*n*F():()=>1;for(let t=0;t<4;t++){const e=-90*t+a;i.addSegment(e*s(),o/2*s(),1,!0)}if(n){const t=n*B(-5,5);i.addSegment(a,Math.abs(t)*(Math.PI/180)*r,1,!0),i.endPlot(t+a,1,!0)}else i.endPlot(a,1,!0);const l=t-r*j(a),c=e-r*W(-a);i.show(l,c,1)}function It(t,e,r,n,i){const o=Z(n),a=((Z(i)-o)%360+360)%360;if(0===a)return;const s=new St("curve"),l=Math.max(1,Math.ceil(a/90)),c=a/l,h=Math.PI*r*c/180;for(let t=0;t<l;t++)s.addSegment(o+t*c+90,h,1,!0);s.endPlot(o+a+90,1,!0);const u=t+r*W(o),f=e-r*j(o);s.draw(u,f,1)}let Lt,Ct,Dt,Ft;class Nt{constructor(){this.isClosed=!1,this.curvature=Ct,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){$t(this.vert,this.curvature,this.isClosed).show()}}function Bt(t=0){Ct=X(t,0,1),Lt=new Nt}function Yt(t,e,r=1){if(!Lt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Lt.vertex(t,e,r)}function zt(t=!1){if(!Lt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(Lt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(Lt.vertex(...Lt.vert[0]),Lt.isClosed=!0),Lt.show(),Lt=!1}function Ot(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Ft=[e,r],Dt=new St(t)}function Xt(t,e,r){if(!Dt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Dt.addSegment(t,e,r)}function Ut(t,e){if(!Dt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Dt.endPlot(t,e),Dt.draw(Ft[0],Ft[1],1),Dt=!1}function Gt(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");$t(t,e).draw()}function $t(t,e=.5,r=!1){const n=new St(0===e?"segments":"curve"),i=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let o,a,s,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=J(h[0],h[1],u[0],u[1]),d=J(u[0],u[1],f[0],f[1]),g=Q(h[0],h[1],u[0],u[1]),p=Q(u[0],u[1],f[0],f[1]),x=e*Math.min(m,d,.5*Math.min(m,d)),y=Math.max(m,d),_=m-x,b=d-x;if(Math.floor(g)===Math.floor(p)){const e=r&&0===c?0:m-l,i=r?0===c?0:d-s:d;n.addSegment(g,e,h[2],!0),c===t.length-3&&n.addSegment(p,i,u[2],!0),l=0,0===c&&(o=m,s=x,a=t[1],l=0)}else{const e={x:u[0]-x*W(-g),y:u[1]-x*j(-g)},f={x:e.x+y*W(90-g),y:e.y+y*j(90-g)},m={x:u[0]+x*W(-p),y:u[1]+x*j(-p)},d={x:m.x+y*W(90-p),y:m.y+y*j(90-p)},v=tt(e,f,m,d,!0),w=J(e.x,e.y,v.x,v.y),R=J(e.x,e.y,m.x,m.y)/2,E=i*w*(2*Math.asin(R/w)*(180/Math.PI))/360,A=r&&0===c?0:_-l,M=c===t.length-3?r?o-x:b:0;n.addSegment(g,A,h[2],!0),n.addSegment(g,isNaN(E)?0:E,h[2],!0),n.addSegment(p,M,u[2],!0),l=x,0===c&&(o=_,s=x,a=[e.x,e.y])}c===t.length-3&&n.endPlot(p,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],i=J(e[0],e[1],r[0],r[1]),o=Q(e[0],e[1],r[0],r[1]);n.addSegment(o,i,r[2],!0),c===t.length-2&&n.endPlot(o,1,!0)}n.origin=r&&0!==e?a:t[0]}return n}const Vt=(t,e,r)=>{const n=t.createProgram();for(let[i,o]of[[t.VERTEX_SHADER,e],[t.FRAGMENT_SHADER,r]]){const e=t.createShader(i);t.shaderSource(e,o),t.compileShader(e),t.attachShader(n,e)}return t.linkProgram(n),n};let Ht,Wt,jt,Kt,Zt,qt,Jt=!1,Qt=0,te=0,ee=null,re=null;const ne={},ie={};let oe=1,ae=0,se=0,le=1,ce=0,he=0,ue=0,fe=0,me=1,de=1,ge=new Float32Array(8192),pe=0,xe=2048,ye=32768,_e=null,be=null,ve=null,we=null,Re=null;const Ee={},Ae={};let Me=0,Se=new Float32Array(1280),Pe=0,Te=256,ke=null;const Ie=new Map,Le=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function Ce(t){return!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer}function De(){const t=w.glMask,e=Ce(t)?t.renderer:t?._renderer;e&&(e._curShader=null,e._cachedBlendMode=null,e._isBlending=null,Ht.activeTexture(Ht.TEXTURE0),Ht.bindTexture(Ht.TEXTURE_2D,null),Ht.blendEquation(Ht.FUNC_ADD),Ht.blendFunc(Ht.ONE,Ht.ONE_MINUS_SRC_ALPHA))}function Fe(t){return t?"function"==typeof t._framebufferToBind?t._framebufferToBind():t.framebuffer??null:null}function Ne(){return Ce(w.glMask)?jt:Wt}function Be(){const t=w.glMask,e=Ht.isEnabled(Ht.DEPTH_TEST);if(Be._hadDepthTest=e,e&&Ht.disable(Ht.DEPTH_TEST),Ce(t))return re=n._renderer.activeFramebuffer?.()??null,re?._beforeEnd&&re._beforeEnd(),Ht.bindFramebuffer(Ht.FRAMEBUFFER,Fe(t)),void Ht.viewport(0,0,t.width*t.density,t.height*t.density);Ht.bindFramebuffer(Ht.FRAMEBUFFER,null),Ht.viewport(0,0,Ht.drawingBufferWidth,Ht.drawingBufferHeight)}function Ye(){Be._hadDepthTest&&Ht.enable(Ht.DEPTH_TEST),Be._hadDepthTest=!1,Ce(w.glMask)&&(re?._beforeBegin?re._beforeBegin():(Ht.bindFramebuffer(Ht.FRAMEBUFFER,null),n._renderer.viewport(n._renderer._origViewport.width,n._renderer._origViewport.height),n._renderer._applyStencilTestIfClipping?.()),re=null)}function ze(t,e,r,n,i){return t?(e<t.minX&&(t.minX=e),r<t.minY&&(t.minY=r),n>t.maxX&&(t.maxX=n),i>t.maxY&&(t.maxY=i),t):{minX:e,minY:r,maxX:n,maxY:i}}function Oe(t,e,r,n){if(pe>=xe){xe*=2;const t=new Float32Array(4*xe);t.set(ge),ge=t}const i=t-ue,o=e-fe,a=4*pe,s=oe*i+se*o+ce+ue,l=ae*i+le*o+he+fe,c=de*r*me/2;ge[a]=s,ge[a+1]=l,ge[a+2]=c,ge[a+3]=n/255;const h=s*de,u=l*de;_e=ze(_e,h-c-1,u-c-1,h+c+1,u+c+1),pe++}function Xe(t,e){if(0===Pe)return;w.glMask.isDrawn=!0,Be();let r=Ie.get(e);r||(r=Ht.createTexture(),Ht.bindTexture(Ht.TEXTURE_2D,r),Ht.texImage2D(Ht.TEXTURE_2D,0,Ht.RGBA,Ht.RGBA,Ht.UNSIGNED_BYTE,t.canvas),Ht.texParameteri(Ht.TEXTURE_2D,Ht.TEXTURE_MIN_FILTER,Ht.LINEAR),Ht.texParameteri(Ht.TEXTURE_2D,Ht.TEXTURE_MAG_FILTER,Ht.LINEAR),Ht.texParameteri(Ht.TEXTURE_2D,Ht.TEXTURE_WRAP_S,Ht.CLAMP_TO_EDGE),Ht.texParameteri(Ht.TEXTURE_2D,Ht.TEXTURE_WRAP_T,Ht.CLAMP_TO_EDGE),Ie.set(e,r)),Ht.useProgram(be),Ht.enable(Ht.BLEND),Ht.blendFunc(Ht.ONE_MINUS_DST_ALPHA,Ht.ONE),Ht.activeTexture(Ht.TEXTURE0),Ht.bindTexture(Ht.TEXTURE_2D,r),Ht.uniform1i(Ae.u_tex,0);const n=_.stroke.color._array;Ht.uniform4f(Ae.u_color,...n),Ht.uniformMatrix4fv(Ae.u_proj,!1,Ne()),Ht.bindVertexArray(ve),Ht.bindBuffer(Ht.ARRAY_BUFFER,Re);const i=5*Pe*4,o=Se.subarray(0,5*Pe);i>Me?(Ht.bufferData(Ht.ARRAY_BUFFER,Se,Ht.DYNAMIC_DRAW),Me=Se.byteLength):Ht.bufferSubData(Ht.ARRAY_BUFFER,0,o),Ht.drawArraysInstanced(Ht.TRIANGLE_STRIP,0,4,Pe),Ht.flush(),Ht.bindVertexArray(null),Ht.bindTexture(Ht.TEXTURE_2D,null),Ye(),ke&&(w.markDirtyRect(w.glMask,ke),ke=null),Pe=0,De()}_.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let Ue=new Map,Ge={a:1,b:0,c:0,d:1,tx:0,ty:0};function $e(){return n??r??window.self.p5.instance}const Ve={offset:.08,scale:.08,warp:.06,tilt:.06};function He(){return{..._.stroke}}function We(t){_.stroke={...t}}function je(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)return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t,variation:{...Ve}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...Ve,...r.variation??{}}}}return"gaussian"===t.type||"gaussian"===t.mode||Array.isArray(t.curve)&&Array.isArray(t.min_max)?{...t,type:"gaussian",curve:t.curve,min_max:t.min_max}:t}if(Array.isArray(t)){const[e,r,n]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,i=Math.min(e,r,n),o=Math.max(e,r,n),a=o-i||1,[s,l,c]=[(e-i)/a,(r-i)/a,(n-i)/a];return{type:"custom",min_max:[i,o],variation:{...Ve},curve:t=>t<.5?s+(l-s)*t*2:l+(c-l)*(t-.5)*2}}}(e.pressure),"custom"===e.type){if("function"!=typeof e.tip)throw new Error(`Brush "${t}" is type "custom" but is missing a tip function.`);const r=`custom::${t}`;!function(t){const e=Ie.get(t);e&&Ht&&Ht.deleteTexture(e),Ie.delete(t)}(r);const n=$e().createGraphics(500,500);return n.pixelDensity(1),n.background(255),n.noSmooth(),n.push(),n.translate(250,250),n.scale(5),n.noStroke(),e.tip(n),n.pop(),Ar.imageToWhite(n),Ar.tips.set(r,n),e.tipKey=r,void Ue.set(t,{param:e,colors:[],buffers:[]})}if("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 Ar.add(e.image.src),Ue.set(t,{param:e,colors:[],buffers:[]}),Ar.load()}Ue.set(t,{param:e,colors:[],buffers:[]})}function Ke(){return[...Ue.keys()]}function Ze(t){for(const{param:e}of Ue.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function qe(t){if(!Ue.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...Ue.keys()].join(", ")}.`);_.stroke.type=t}function Je(t,e,r){y(),_.stroke.color=n.color(...arguments),_.stroke.isActive=!0}function Qe(t){_.stroke.weight=t}function tr(t,e,r=1){qe(t),Je(e),Qe(r)}function er(){_.stroke.isActive=!1}function rr(){return{a:nt(),b:it(),c:ot(),d:at(),tx:et(),ty:rt()}}function nr(t){const[e,r,n,i]=t;return{minX:Math.min(e,n),minY:Math.min(r,i),maxX:Math.max(e,n),maxY:Math.max(r,i)}}function ir(t){y();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}}(rr());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");_.stroke.clipWindow={bounds:nr(t),inverse:e}}function or(){_.stroke.clipWindow=null}let ar,sr,lr,cr;const hr={};function ur(r,n,o,a=!1){oe=nt(),ae=it(),se=ot(),le=at(),ce=et(),he=rt(),ue=t/2,fe=e/2,me=Math.sqrt(oe*oe+ae*ae),de=i,Ge=rr(),ar=new ct(r+t/2,n+e/2),sr=o,lr=a,lr&&lr.calcIndex(0)}const fr=[];function mr(r,o){o||(cr=r),function(){hr.seed=999999*F();const{param:r}=Ue.get(_.stroke.type)??{};if(!r)return;hr.p=r;const{pressure:o}=r;if(hr.a="custom"!==o.type?F(-1,1):0,hr.b="custom"!==o.type?F(1,1.5):0,"custom"!==o.type)hr.cp=F(3,3.5),hr.ct=0,hr.cs=1,hr.ck=0;else{const t=o.variation??Ve;hr.cp=F(-t.offset,t.offset),hr.ct=F(-t.warp,t.warp),hr.cs=F(1-t.scale,1+t.scale),hr.ck=F(-t.tilt,t.tilt)}if([hr.min,hr.max]=o.min_max,hr.noiseoffset=.03,!lr){const t=cr*Math.PI/180;hr.cos=Math.cos(t),hr.sin=Math.sin(t)}!function(){v(),function(){const r=n?._renderer,o=i;if(ee&&ee.renderer===r&&ee.width===t&&ee.height===e&&ee.density===o)return w.glMask=ee,ee;ee?.remove&&ee.remove();const a=n.createFramebuffer({width:t,height:e,density:o,antialias:!1,depth:!1,stencil:!1});a.isDrawn=!1,a.dirtyRect=null,a.clear=()=>{const t=n._renderer,e=t.activeFramebuffer?.()??null;e?._beforeEnd&&e._beforeEnd(),Ht.bindFramebuffer(Ht.FRAMEBUFFER,Fe(a)),Ht.viewport(0,0,a.width*a.density,a.height*a.density),Ht.clearColor(0,0,0,0),Ht.clear(Ht.COLOR_BUFFER_BIT),e?._beforeBegin?e._beforeBegin():(Ht.bindFramebuffer(Ht.FRAMEBUFFER,null),t.viewport(t._origViewport.width,t._origViewport.height),t._applyStencilTestIfClipping?.())},ee=a,w.glMask=ee}();const r=n.drawingContext,o=!Jt||Ht!==r;(o||Qt!==t||te!==e)&&(Wt=new Float32Array([2/t,0,0,0,0,-2/e,0,0,0,0,1,0,-1,1,0,1]),jt=new Float32Array([2/t,0,0,0,0,2/e,0,0,0,0,1,0,-1,-1,0,1]),Qt=t,te=e),o&&(Ht=r,qt=Vt(Ht,"#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;}","#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);}"),Ht.useProgram(qt),Ht.enable(Ht.BLEND),Ht.blendFunc(Ht.ONE_MINUS_DST_ALPHA,Ht.ONE),["a_position","a_radius","a_alpha"].forEach(t=>ne[t]=Ht.getAttribLocation(qt,t)),["u_matrix","u_color"].forEach(t=>ie[t]=Ht.getUniformLocation(qt,t)),Kt=Ht.createVertexArray(),Ht.bindVertexArray(Kt),Zt=Ht.createBuffer(),Ht.bindBuffer(Ht.ARRAY_BUFFER,Zt),Ht.bufferData(Ht.ARRAY_BUFFER,ge.byteLength,Ht.DYNAMIC_DRAW),ye=ge.byteLength,Ht.enableVertexAttribArray(ne.a_position),Ht.vertexAttribPointer(ne.a_position,2,Ht.FLOAT,!1,16,0),Ht.enableVertexAttribArray(ne.a_radius),Ht.vertexAttribPointer(ne.a_radius,1,Ht.FLOAT,!1,16,8),Ht.enableVertexAttribArray(ne.a_alpha),Ht.vertexAttribPointer(ne.a_alpha,1,Ht.FLOAT,!1,16,12),Ht.bindVertexArray(null),Ie.clear(),be=Vt(Ht,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_corner;in vec2 a_pos;in float a_size;in float a_angle;in float a_alpha;uniform mat4 u_proj;out vec2 v_uv;out float v_alpha;void main(){float c=cos(a_angle);float s=sin(a_angle);vec2 rotated=vec2(c*a_corner.x-s*a_corner.y,s*a_corner.x+c*a_corner.y);gl_Position=u_proj*vec4(a_pos+rotated*a_size,0.0,1.0);v_uv=a_corner*0.5+0.5;v_alpha=a_alpha;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin vec2 v_uv;in float v_alpha;uniform sampler2D u_tex;uniform vec4 u_color;out vec4 outColor;void main(){float inkAlpha=texture(u_tex,v_uv).a;if(inkAlpha<0.01)discard;outColor=vec4(u_color.rgb,inkAlpha*v_alpha);}"),["a_corner","a_pos","a_size","a_angle","a_alpha"].forEach(t=>Ee[t]=Ht.getAttribLocation(be,t)),["u_proj","u_color","u_tex"].forEach(t=>Ae[t]=Ht.getUniformLocation(be,t)),ve=Ht.createVertexArray(),Ht.bindVertexArray(ve),we=Ht.createBuffer(),Ht.bindBuffer(Ht.ARRAY_BUFFER,we),Ht.bufferData(Ht.ARRAY_BUFFER,Le,Ht.STATIC_DRAW),Ht.enableVertexAttribArray(Ee.a_corner),Ht.vertexAttribPointer(Ee.a_corner,2,Ht.FLOAT,!1,0,0),Re=Ht.createBuffer(),Ht.bindBuffer(Ht.ARRAY_BUFFER,Re),Ht.bufferData(Ht.ARRAY_BUFFER,Se.byteLength,Ht.DYNAMIC_DRAW),Me=Se.byteLength,Ht.enableVertexAttribArray(Ee.a_pos),Ht.vertexAttribPointer(Ee.a_pos,2,Ht.FLOAT,!1,20,0),Ht.vertexAttribDivisor(Ee.a_pos,1),Ht.enableVertexAttribArray(Ee.a_size),Ht.vertexAttribPointer(Ee.a_size,1,Ht.FLOAT,!1,20,8),Ht.vertexAttribDivisor(Ee.a_size,1),Ht.enableVertexAttribArray(Ee.a_angle),Ht.vertexAttribPointer(Ee.a_angle,1,Ht.FLOAT,!1,20,12),Ht.vertexAttribDivisor(Ee.a_angle,1),Ht.enableVertexAttribArray(Ee.a_alpha),Ht.vertexAttribPointer(Ee.a_alpha,1,Ht.FLOAT,!1,20,16),Ht.vertexAttribDivisor(Ee.a_alpha,1),Ht.bindVertexArray(null),Jt=!0)}();const a=!0!==w.isBrush;w.isBrush=!0,a&&(w.justChanged=!0),w.blend(_.stroke.color),hr.alpha=["default","spray"].includes(hr.p.type)?hr.p.opacity:hr.p.opacity/Math.min(_.stroke.weight,1.3);{const r=t/2,n=e/2,i=Ge;if(_.stroke.clipWindow){const{inverse:t,bounds:e}=_.stroke.clipWindow,o=t.a*i.a+t.c*i.b,a=t.a*i.c+t.c*i.d,s=t.b*i.a+t.d*i.b,l=t.b*i.c+t.d*i.d;hr.clipA=o,hr.clipB=s,hr.clipC=a,hr.clipD=l,hr.clipTX=t.a*i.tx+t.c*i.ty+t.tx-o*r-a*n,hr.clipTY=t.b*i.tx+t.d*i.ty+t.ty-s*r-l*n,hr.clipMinX=e.minX,hr.clipMaxX=e.maxX,hr.clipMinY=e.minY,hr.clipMaxY=e.maxY}else{const e=.05*t;hr.clipA=i.a,hr.clipB=i.b,hr.clipC=i.c,hr.clipD=i.d,hr.clipTX=i.tx-i.a*r-i.c*n,hr.clipTY=i.ty-i.b*r-i.d*n,hr.clipMinX=-r-e,hr.clipMaxX=r+e,hr.clipMinY=-n-e,hr.clipMaxY=n+e}}br()}();const a=function(){const{param:t}=Ue.get(_.stroke.type)??{};return t?t.spacing:1}(),s=Math.round(sr*(o?r:1)/a);for(let t=0;t<s;t++)fr.length<2*s&&fr.push(Y()),dr(),o?ar.plotTo(lr,a,a,r,t<10):ar._moveToDegrees(r,a,a);!function(){br(),function(){if(0===pe)return;w.glMask.isDrawn=!0,Be();const t=_.stroke.color._array;Ht.useProgram(qt),Ht.enable(Ht.BLEND),Ht.blendFunc(Ht.ONE_MINUS_DST_ALPHA,Ht.ONE),Ht.bindVertexArray(Kt),Ht.bindBuffer(Ht.ARRAY_BUFFER,Zt);const e=16*pe,r=ge.subarray(0,4*pe);e>ye?(Ht.bufferData(Ht.ARRAY_BUFFER,ge,Ht.DYNAMIC_DRAW),ye=ge.byteLength):Ht.bufferSubData(Ht.ARRAY_BUFFER,0,r),Ht.uniform4f(ie.u_color,...t),Ht.uniformMatrix4fv(ie.u_matrix,!1,Ne()),Ht.drawArrays(Ht.POINTS,0,pe),Ht.flush(),Ht.bindVertexArray(null),Ye(),_e&&(w.markDirtyRect(w.glMask,_e),_e=null),pe=0,De()}();const t=hr.p?.type;"image"===t?Xe(Ar.tips.get(hr.p.image.src),hr.p.image.src):"custom"===t&&Xe(Ar.tips.get(hr.p.tipKey),hr.p.tipKey)}()}function dr(){if(!xr())return;const t=gr(),e=O(D(hr.seed+.002*ar.plotted,0),0,1,1-hr.noiseoffset,1+hr.noiseoffset);switch(hr.p.type){case"spray":!function(t){const e=_.stroke.weight*hr.p.scatter*t+_.stroke.weight*N(fr)*hr.p.scatter/3,r=hr.p.weight*F(.9,1.1),n=Math.ceil(hr.p.grain/t);for(let t=0;t<n;t++){const t=F(.9,1.1),n=t*e*F(-1,1),i=F(-1,1),o=Math.sqrt((t*e)**2-n**2);Oe(ar.x+n,ar.y+i*o,r,hr.alpha)}}(t*e);break;case"marker":yr(t*e);break;case"custom":case"image":_r(t*e);break;default:!function(t,e=1){const r=(e=O(e,0,1,.9,1.05))*_.stroke.weight*hr.p.scatter*(hr.p.sharpness+(1-hr.p.sharpness)*N(fr)/t);if(F(0,hr.p.grain*t)>.4){let e,n;if(lr)e=.7*r*F(-1,1),n=r*F(-1,1);else{const t=r*F(-1,1),i=.3*r*F(-1,1);e=t*-hr.sin+i*hr.cos,n=t*hr.cos+i*hr.sin}const i=t*t*hr.p.weight*F(.85,1.15)*_.stroke.weight,o=Math.max(.9,t)*hr.alpha*F(.75,1.1);Oe(ar.x+e,ar.y+n,i,o)}}(t*e)}}function gr(){return lr?pr()*lr.pressure(ar.plotted):pr()}function pr(){return"custom"===hr.p.pressure.type?O(hr.p.pressure.curve(Math.max(0,Math.min(1,.5+(ar.plotted/sr-.5+hr.ct)*hr.cs)))+hr.cp+hr.ck*(ar.plotted/sr-.5),0,1,hr.min,hr.max,!0):function(t=.5+hr.p.pressure.curve[0]*hr.a,e=1-hr.p.pressure.curve[1]*hr.b,r=hr.cp,n=hr.min,i=hr.max){const o=t*sr,a=(ar.plotted<o?1.2*e:.8*e)*(sr/2);return O(1/(1+Math.pow(Math.abs((ar.plotted-o)/a),2*r)),0,1,n,i)}()}function xr(){const t=hr.clipA*ar.x+hr.clipC*ar.y+hr.clipTX;if(t<hr.clipMinX||t>hr.clipMaxX)return!1;const e=hr.clipB*ar.x+hr.clipD*ar.y+hr.clipTY;return e>=hr.clipMinY&&e<=hr.clipMaxY}function yr(t,e=!0,r=hr.alpha){const n=e?_.stroke.weight*hr.p.scatter:0,i=e?n*F(-1,1):0,o=e?n*F(-1,1):0;Oe(ar.x+i,ar.y+o,_.stroke.weight*hr.p.weight*t,r*Math.max(.8,t)*F(.9,1.1))}function _r(t,e=hr.alpha){const r=_.stroke.weight*hr.p.scatter,n=r*F(-1,1),i=r*F(-1,1),o=hr.p.weight*_.stroke.weight*t;let a=0;"random"===hr.p.rotate?a=B(0,360)*(Math.PI/180):"natural"===hr.p.rotate&&(a=((lr?-lr.angle(ar.plotted):-cr)+ar.angle())*(Math.PI/180)),function(t,e,r,n,i){if(Pe>=Te){Te*=2;const t=new Float32Array(5*Te);t.set(Se),Se=t}const o=t-ue,a=e-fe,s=oe*o+se*a+ce+ue,l=ae*o+le*a+he+fe,c=de*r*me/2,h=5*Pe;Se[h]=s,Se[h+1]=l,Se[h+2]=c,Se[h+3]=n,Se[h+4]=i/255;const u=s*de,f=l*de;ke=ze(ke,u-1.42*c-1,f-1.42*c-1,u+1.42*c+1,f+1.42*c+1),Pe++}(ar.x+n,ar.y+i,o,a,e*Math.max(.8,t)*F(.9,1.1))}function br(){if(xr()){let t=gr(),e=hr.alpha;if("marker"===hr.p.type)for(let r=1;r<10;r++)yr(t*r/10,!0,8*e);else if("custom"===hr.p.type||"image"===hr.p.type)for(let r=1;r<5;r++)_r(t*r/10,2*e)}}function vr(t,e,r,n){if(!_.stroke.isActive||!_.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");lt();let i=J(t,e,r,n);0!=i&&(ur(t,e,i),mr(Q(t,e,r,n),!1))}function wr(t,e,r,n){if(!_.stroke.isActive||!_.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");lt(),ur(t,e,r),mr(K(n),!1)}C(()=>{fr.length=0});const Rr=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],Er=[["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 Er){let e={};for(let r=0;r<t[1].length;r++)e[Rr[r]]=t[1][r];je(t[0],e)}Mt.prototype.draw=function(t=!1,e,r){let n=He();if(t&&tr(t,e,r),n.isActive)for(let t of this.sides)vr(t[0].x,t[0].y,t[1].x,t[1].y);We(n)},St.prototype.draw=function(t,e,r){He().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,n){lt(),ur(e,r,t.length,t),mr(n,!0)}(this,t,e,r))};const Ar={tips:new Map,add(t){this.tips.has(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=$e().createImage(n.naturalWidth,n.naturalHeight);r.drawingContext.drawImage(n,0,0),Ar.imageToWhite(r),this.tips.set(t,r),e()},n.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),n.crossOrigin="anonymous",n.src=t})))}};function Mr(){return{..._.hatch}}function Sr(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=_.hatch;n.isActive=!0,n.dist=t,n.angle=Z(e),n.options=r}function Pr(t,e="black",r=1){_.hatch.hBrush={brush:t,color:e,weight:r}}function Tr(){_.hatch.isActive=!1,_.hatch.hBrush=!1}function kr(t,e,r,n){const i=e*Math.PI/180,o=Math.cos(i),a=Math.sin(i),s=Math.cos(-i),l=Math.sin(-i),c=t.a,h=c.length,u=new Array(h);let f=Infinity,m=-Infinity;for(let t=0;t<h;t++){const e=c[t][0],r=c[t][1],n=[e*o-r*a,e*a+r*o];u[t]=n,n[1]<f&&(f=n[1]),n[1]>m&&(m=n[1])}const d=[];for(let t=0;t<h;t++){const e=u[t],r=u[(t+1)%h];e[1]!==r[1]&&d.push(e,r)}const g=d.length,p=[];let x=f+.5*r,y=r;for(;x<m;){const t=[];for(let e=0;e<g;e+=2){const r=d[e][1],n=d[e+1][1];(r<=x&&x<n||n<=x&&x<r)&&t.push(d[e][0]+(x-r)/(n-r)*(d[e+1][0]-d[e][0]))}t.sort((t,e)=>t-e);for(let e=0;e<t.length-1;e+=2)p.push({x1:t[e]*s-x*l,y1:t[e]*l+x*s,x2:t[e+1]*s-x*l,y2:t[e+1]*l+x*s});x+=y,y*=n}return p}function Ir(t){const e=_.hatch.dist,r=(_.hatch.angle%180+180)%180,n=_.hatch.options,i=He();_.hatch.hBrush&&tr(...Object.values(_.hatch.hBrush)),Array.isArray(t)||(t=[t]);const o=n.gradient?O(n.gradient,0,1,1,1.1,!0):1,a=[];for(const n of t)for(const t of kr(n,r,e,o))a.push(t);a.sort((t,e)=>t.x1===e.x1?t.y1-e.y1:t.x1-e.x1);const s=n.rand||0;for(let t=0;t<a.length;t++){const r=a[t];let i=r.x1,o=r.y1,l=r.x2,c=r.y2;s&&(i+=s*e*F(-1,1),o+=s*e*F(-1,1),l+=s*e*F(-1,1),c+=s*e*F(-1,1)),vr(i,o,l,c),t>0&&n.continuous&&vr(a[t-1].x2,a[t-1].y2,i,o)}We(i)}function Lr(t,e,r){return{x:t.a*e+t.c*r+t.e,y:t.b*e+t.d*r+t.f}}function Cr(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 Dr(t,e,r){const n=2*Math.PI,i=w.ctx,o=i.getTransform(),a=r/2,s=Lr(o,t,e),l=a*Math.hypot(o.a,o.c),c=a*Math.hypot(o.b,o.d),h=Cr(i,o);w.markDirtyRect(w.mask,{minX:s.x-l-h,minY:s.y-c-h,maxX:s.x+l+h,maxY:s.y+c+h}),i.moveTo(t+a,e),i.arc(t,e,a,0,n)}_.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},Mt.prototype.hatch=function(t=!1,e,r){let n=Mr();t&&Sr(t,e,r),n.isActive&&Ir(this),function(t){_.hatch={...t}}(n)},St.prototype.hatch=function(t,e,r){Mr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},_.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Fr=()=>({..._.fill});function Nr(t,e,r,i){_.fill.opacity=(arguments.length<4?e:i)||150,_.fill.color=arguments.length<3?n.color(t):n.color(t,e,r),_.fill.isActive=!0}function Br(t,e="out"){_.fill.bleed_strength=X(t,0,1),_.fill.direction=e}function Yr(t=.4,e=.4){_.fill.texture_strength=X(t,0,1),_.fill.border_strength=X(e,0,1)}function zr(){_.fill.isActive=!1}let Or;const Xr=[[],[]];function Ur(){for(let t=0;t<512;t++)Xr[0][t]=Y(.5,.2),Xr[1][t]=Y(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(Ur);class $r{constructor(t,e,r,n=[],i=!1,o,a){if(this.v=t,this.m=e,this.dir=n,this.midP=r,i){let e=0,n=0;const i=[];for(let o=0;o<t.length;o++){const a=Math.abs(r.x-t[o].x),s=Math.abs(r.y-t[o].y);e=Math.max(e,a),n=Math.max(n,s);const l=t[o],c=t[(o+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=q(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};i.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=n,this.dir=Array(t.length),i.forEach((t,e)=>{let r=0;for(const e of Or.intersect(t.ray))Gr(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=F(-.6,.6)*e,a=F(-.6,.6)*n;this.midP={x:r.x+o,y:r.y+a}}else this.sizeX=o,this.sizeY=a}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),n=[...this.v],i=[...this.m],o=[...this.dir];return n.splice(r,e),i.splice(r,e),o.splice(r,e),{v:n,m:i,dir:o}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),n=[],i=e/r;for(let t=0;t<r;t++)n.push(~~(t*i+F(0,.8*i)));const o=[],a=[],s=[],l=this.midP,c=Or.sides;for(const t of n){const r=t%e;let n=this.v[r],i=0;for(const[t,e]of c){const r=t.y,o=e.y;if(r>n.y==o>n.y)continue;const a=(n.y-r)/(o-r);n.x<t.x+a*(e.x-t.x)&&i++}i%2==0&&(n={x:l.x+(n.x-l.x)*F(.3,.6),y:l.y+(n.y-l.y)*F(.3,.6)}),o.push(n),a.push(this.m[r]),s.push(!this.dir[r])}return new $r(o,a,this.midP,s,!1,this.sizeX,this.sizeY)}flipDirs(){return new $r(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:n}=this.trim(t),i=e.length,o=2*i,a=new Array(o),s=new Array(o),l=new Array(o),c="out"===_.fill.direction?-90:90;0===Xr[0].length&&Ur();const h=Xr[0],u=h.length,f=Xr[1],m=f.length;let d=0,g=999===t?F(.6,.8):_.fill.bleed_strength;for(let o=0;o<i;o++){const p=e[o],x=e[o+1<i?o+1:0],y=r[o],_=n[o];t<997&&(g=y);const b=(_?c:-c)+5*F(-1,1),v=W(b),w=j(b),R=x.x-p.x,E=x.y-p.y,A=v*R+w*E,M=v*E-w*R,S=h[~~(F(0,1)*u)]*F(.65,1.35)*g;a[d]=p,s[d]=y,l[d]=_,d++,a[d]={x:p.x+.5*R+A*S,y:p.y+.5*E+M*S},s[d]=y+f[~~(F(0,1)*m)],l[d]=_,d++}let p=a,x=s,y=l;const b=1024/_.fill.texture_strength;if(b&&d>b){const t=Math.ceil(d/b);p=[],x=[],y=[];for(let e=0;e<d;e+=t)p.push(a[e]),x.push(s[e]),y.push(l[e])}else p.length=d,x.length=d,y.length=d;return new $r(p,x,this.midP,y,!1,this.sizeX,this.sizeY)}fill(r,n,o){const a=3*o,s=2*n*(1+o/2),l=!1!==w.isBrush;w.isBrush=!1,l&&(w.justChanged=!0),w.blend(r),w.ctx.save(),w.ctx.setTransform(i*nt(),i*it(),i*ot(),i*at(),i*(et()+t/2),i*(rt()+e/2)),w.ctx.strokeStyle=`rgb(${r._getRed()} ${r._getGreen()} ${r._getBlue()} / ${.005*_.fill.border_strength})`,w.ctx.lineCap="round";const c=Math.max(this.sizeX,this.sizeY),h=F(.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,s,r);f.grow(999).flipDirs().grow(997).layer(t,c,s*a,r),t%2==0&&u.grow(h).grow(999).layer(t,c,2*s,r),t%8!=0&&19!==t||(0!==a&&u.erase(3*a,n),w.blend(r,!0,!1,!0))}w.ctx.restore()}layer(t,e,r,n){w.ctx.lineWidth=O(t,0,24,e/25,e/30,!0),w.ctx.fillStyle=`rgb(${n._getRed()} ${n._getGreen()} ${n._getBlue()} / ${r}%)`,function(t){const e=w.ctx,r=e.getTransform();let n=Infinity,i=Infinity,o=-Infinity,a=-Infinity;e.beginPath(),t.forEach((t,s)=>{const l=Lr(r,t.x,t.y);n=Math.min(n,l.x),i=Math.min(i,l.y),o=Math.max(o,l.x),a=Math.max(a,l.y),0===s?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.closePath();const s=Cr(e,r);w.markDirtyRect(w.mask,{minX:n-s,minY:i-s,maxX:o+s,maxY:a+s})}(this.v),w.ctx.fill(),w.ctx.stroke()}erase(t,e){w.ctx.save();const r=~~(F(80,110)*O(t,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,o=Math.min(this.sizeX,this.sizeY)*(1.4-_.fill.bleed_strength),a=.05*o,s=.4*o,{x:l,y:c}=this.midP;w.ctx.globalCompositeOperation="destination-out";const h=(5-O(e,80,100,.3,.7,!0))*t/255;w.ctx.fillStyle=`rgb(255 0 0 / ${h})`,w.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+Y(0,n),r=c+Y(0,i),o=F(a,s);w.ctx.beginPath(),Dr(e,r,o),t%5!=0&&w.ctx.fill()}w.ctx.globalCompositeOperation="source-over",w.ctx.restore()}}Mt.prototype.fill=function(t=!1,e,r,n,i,o){let a=Fr();t&&(Nr(t,e),Br(r,o),Yr(n,i)),a.isActive&&(lt(),function(t){if(!_.fill.isActive||!_.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Or=t;const e=[...t.vertices],r=~~(.25*e.length*z({1:5,2:10,3:60})),n=_.fill.bleed_strength,i=e.map((t,e)=>(e>r?1:.3)*F(.85,1.4)*n),o=B(0,e.length),a=[...e.slice(o),...e.slice(0,o)],s=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,n=0,i=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,n+=(e[t].x+e[t+1].x)*o,i+=(e[t].y+e[t+1].y)*o}return r*=.5,r?{x:n/(6*r),y:i/(6*r)}:{x:e[0].x,y:e[0].y}}(a);new $r(a,i,s,[],!0).fill(_.fill.color,O(_.fill.opacity,0,255,0,1,!0),_.fill.texture_strength)}(this)),(t=>{_.fill={...t}})(a)},St.prototype.fill=function(t,e,r){Fr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,O(_.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const Vr=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>w.blend(!1,!0),r.postdraw=()=>w.blend(!1,!0);const n=e.push,i=e.pop,o=e.randomSeed,a=e.noiseSeed;e.push=function(){n.call(this),lt(),Vr.push({fill:{..._.fill},stroke:{..._.stroke},hatch:{..._.hatch},field:{..._.field}})},e.pop=function(){i.call(this),function(){const t=Vr.pop();t&&(_.stroke={...t.stroke},_.field={...t.field},_.hatch={...t.hatch},_.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{I=T(t);for(const t of L)t()})(t)},e.noiseSeed=function(t){a.call(this,t),(t=>{D=P(T(t))})(t)}});export{St as Plot,Mt as Polygon,ct as Position,je as add,wt as addField,It as arc,Bt as beginShape,Ot as beginStroke,Ke as box,kt as circle,ir as clip,zt as endShape,Ut as endStroke,bt as field,Nr as fill,Br as fillBleed,Yr as fillTexture,wr as flowLine,Sr as hatch,Ir as hatchArray,Pr as hatchStyle,b as instance,vr as line,Rt as listFields,g as load,Xt as move,or as noClip,vt as noField,zr as noFill,Tr as noHatch,er as noStroke,qe as pick,Pt as polygon,Tt as rect,_t as refreshField,Ze as scaleBrushes,tr as set,Gt as spline,Je as stroke,Qe as strokeWeight,Yt as vertex,z as wRand,Et as wiggle};
//# sourceMappingURL=p5.brush.esm.js.map
diff --git a/dist/p5.brush.esm.js.map b/dist/p5.brush.esm.js.map
index 6b50aec..5880d9c 100644
--- a/dist/p5.brush.esm.js.map
+++ b/dist/p5.brush.esm.js.map
@@ -1 +1 @@
-{"version":3,"file":"p5.brush.esm.js","sources":["../src/core/color.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/flowfield.js","../src/core/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/core/gl/utils.js","../src/hatch/hatch.js","../src/core/mask.js","../src/fill/fill.js","../src/core/save.js","../src/index.js"],"sourcesContent":["import vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Section: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties\n\nconst isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\nconst getSketchRenderer = () =>\n _isInstanced ? Instance : window.self.p5.instance;\n\nconst isSupportedFramebufferTarget = (target) =>\n isFramebufferTarget(target) && target.renderer._pInst === getSketchRenderer();\n\nconst resolveTarget = (buffer = false) => {\n if (_isInstanced && !buffer) {\n return {\n renderer: Instance,\n width: Instance.width,\n height: Instance.height,\n };\n }\n\n if (!buffer) {\n const renderer = getSketchRenderer();\n return {\n renderer,\n width: renderer.width,\n height: renderer.height,\n };\n }\n\n if (isFramebufferTarget(buffer)) {\n if (!isSupportedFramebufferTarget(buffer)) {\n throw new Error(\n \"p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.\",\n );\n }\n\n return {\n renderer: getSketchRenderer(),\n width: buffer.width,\n height: buffer.height,\n };\n }\n\n return {\n renderer: buffer,\n width: buffer.width,\n height: buffer.height,\n };\n};\n\nconst removeTargetBuffer = (buffer) => {\n if (buffer && typeof buffer.remove === \"function\") {\n buffer.remove();\n }\n};\n\nconst getGraphicsFactory = () =>\n typeof Renderer.createGraphics === \"function\" ? Renderer : Renderer._pInst;\n\nconst getActiveFramebuffer = () =>\n Renderer &&\n Renderer._renderer &&\n typeof Renderer._renderer.activeFramebuffer === \"function\"\n ? Renderer._renderer.activeFramebuffer()\n : null;\n\nconst needsBlendSourceFramebuffer = (framebuffer) =>\n !framebuffer ||\n framebuffer.width !== Cwidth ||\n framebuffer.height !== Cheight ||\n (typeof framebuffer.pixelDensity === \"function\" &&\n framebuffer.pixelDensity() !== Density);\n\nconst needsMixBuffers = () =>\n !Renderer.mask ||\n !Renderer.glMask ||\n Renderer.mask.width !== Cwidth ||\n Renderer.mask.height !== Cheight ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight;\n\nconst DIRTY_BRUSH_PADDING = 2;\nconst DIRTY_FILL_PADDING = 4;\n\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n\n const { width, height } = getTargetPixelSize();\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\nconst unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return { minX: 0, minY: 0, maxX: width, maxY: height };\n};\n\nconst toScissorBox = (rect) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: height - normalized.maxY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\nconst withScissor = (gl, rect, draw) => {\n const box = toScissorBox(rect);\n if (!box) return false;\n\n const wasEnabled = gl.isEnabled(gl.SCISSOR_TEST);\n const prevBox = gl.getParameter(gl.SCISSOR_BOX);\n\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n if (wasEnabled) {\n gl.scissor(prevBox[0], prevBox[1], prevBox[2], prevBox[3]);\n } else {\n gl.disable(gl.SCISSOR_TEST);\n }\n }\n\n return true;\n};\n\n/**\n * Loads and initializes a canvas for the drawing system.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.\n * Pass a framebuffer only while drawing inside its begin()/end() or draw() scope.\n * Framebuffers created from p5.Graphics are not supported.\n */\nexport const load = (buffer = false) => {\n const target = resolveTarget(buffer);\n Renderer = target.renderer;\n\n // Check if Rendrer is webgl and throw error if it's not\n\n if (Renderer.webglVersion !== \"webgl2\") {\n throw new Error(\"p5.brush requires a WEBGL canvas\");\n }\n\n Cwidth = target.width;\n Cheight = target.height;\n\n _isReady = true;\n if (Renderer.loaded) Mix.load();\n};\n\nlet _isReady = false;\nlet _isInstanced = false;\n\n/**\n * Ensures the drawing system is ready before any operation.\n */\nexport const isCanvasReady = () => {\n if (!_isReady) load();\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n\nexport const instance = (inst) => {\n _isInstanced = true;\n Instance = inst;\n};\n\n\n// =============================================================================\n// Section: Color Blending\n// =============================================================================\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer?.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\nconst disable = false;\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: new Object(),\n\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n markFull(target) {\n if (!target) return;\n\n target.dirtyRect = getFullDirtyRect();\n target.isDrawn = true;\n },\n\n clearMask(target) {\n if (!target) return;\n\n target.clear();\n target.isDrawn = false;\n target.dirtyRect = null;\n },\n\n getCompositeRect(target, isBrushMask) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n\n return normalizeDirtyRect(\n expandDirtyRect(\n target.dirtyRect,\n isBrushMask ? DIRTY_BRUSH_PADDING : DIRTY_FILL_PADDING,\n ),\n );\n },\n\n captureBlendSource(dirtyRect) {\n const activeFramebuffer = getActiveFramebuffer();\n\n if (!activeFramebuffer) return Renderer._renderer;\n\n if (needsBlendSourceFramebuffer(Renderer.blendSourceFramebuffer)) {\n removeTargetBuffer(Renderer.blendSourceFramebuffer);\n Renderer.blendSourceFramebuffer = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n const source = Renderer.blendSourceFramebuffer;\n\n source.draw(() => {\n withScissor(Renderer.drawingContext, dirtyRect, () => {\n Renderer.clear();\n Renderer.push();\n if (typeof Renderer.imageMode === \"function\") {\n Renderer.imageMode(\n Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER,\n );\n }\n Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n });\n });\n\n return source;\n },\n\n /**\n * Loads necessary resources and prepares the mask buffer and shader for colour blending.\n */\n load() {\n Density = Renderer.pixelDensity();\n const graphicsFactory = getGraphicsFactory();\n const p2dMode = graphicsFactory.P2D ?? Renderer.P2D;\n const webglMode = graphicsFactory.WEBGL ?? Renderer.WEBGL;\n\n if (!Renderer.loaded || needsMixBuffers()) {\n removeTargetBuffer(Renderer.mask);\n removeTargetBuffer(Renderer.glMask);\n\n Renderer.mask = graphicsFactory.createGraphics(Cwidth, Cheight, p2dMode);\n Renderer.glMask = graphicsFactory.createGraphics(\n Cwidth,\n Cheight,\n webglMode,\n );\n Renderer.loaded = true;\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n\n this.mask = Renderer.mask;\n this.mask.pixelDensity(Density);\n this.mask.clear();\n this.mask.angleMode(Renderer.DEGREES);\n this.mask.dirtyRect = null;\n this.mask.isDrawn = false;\n\n this.ctx = this.mask.drawingContext;\n\n this.glMask = Renderer.glMask;\n this.glMask.pixelDensity(Density);\n this.glMask.clear();\n this.glMask.angleMode(this.glMask.DEGREES);\n this.glMask.drawingContext.lineWidth = 0;\n this.glMask.dirtyRect = null;\n this.glMask.isDrawn = false;\n } else {\n this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\n this.mask.dirtyRect ??= null;\n this.mask.isDrawn ??= false;\n this.glMask.dirtyRect ??= null;\n this.glMask.isDrawn ??= false;\n }\n\n // Link Matrix of GL mask to main Renderer\n this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;\n },\n\n /**\n * Applies blending effects using the current color and mask.\n * @param {Color} _color - Color to blend.\n * @param {boolean} _isLast - If this is the final blend operation.\n * @param {boolean} _isImg - If blending an image.\n * @param {boolean} _isFillLayer - If this is a special case.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n\n const activeIsBrush = this.isBrush === true;\n const mask = activeIsBrush ? this.glMask : this.mask;\n const no_mask = activeIsBrush ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor[0] !== nextColor[0] ||\n this.cachedColor[1] !== nextColor[1] ||\n this.cachedColor[2] !== nextColor[2] ||\n this.cachedColor[3] !== nextColor[3]);\n\n // Perf gains are minimal but let's keep it for now\n if (disable) {\n if (_isLast && mask.isDrawn) {\n Renderer.push();\n Renderer.translate(0, 0);\n Renderer.image(mask, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n mask.isDrawn = false;\n }\n return;\n }\n\n // Initialize blending if not already active\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Force p5 to bind its internal render target for glMask,\n // so the first glDraw() writes to the correct framebuffer.\n this.glMask.clear();\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(no_mask, !activeIsBrush);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, activeIsBrush);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) this.isBlending = false;\n }\n },\n\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n let shader = Renderer.shaderProgram;\n const gl = Renderer.drawingContext;\n const targetIsFramebuffer = !!getActiveFramebuffer();\n const source = this.captureBlendSource(dirtyRect);\n\n // Disable depth test for this compositing draw so the fullscreen rect\n // does not write Z=0 into the depth buffer — which would cause any\n // subsequent p5 geometry drawn at the same depth to fail depth testing\n // and become invisible.\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n gl.disable(gl.DEPTH_TEST);\n\n Renderer.push();\n Renderer.translate(0, 0);\n\n // Use the blend shader for rendering\n Renderer.shader(shader);\n\n // Set shader uniforms\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n shader.setUniform(\"u_flipOutputY\", targetIsFramebuffer);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", this.cachedColor);\n\n // Draw a rectangle covering the whole canvas to apply the shader\n withScissor(gl, dirtyRect, () => {\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n });\n\n // Finish and clear mask\n Renderer.pop();\n Renderer.resetShader();\n\n // Restore depth test state\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n this.clearMask(mask);\n },\n};\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { Renderer } from \"./color.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n const usesRadians =\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS);\n // Only if Renderer.angleMode() is set to radians\n if (usesRadians) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS)\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","import { isMixReady, Cwidth, Cheight, State, Renderer } from \"./color.js\";\nimport { randInt, noise, rr, sin, cos, map, toDegreesSigned } from \"./utils.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n/**\n * The `Matrix` object exposes the current 2D affine transform from p5's model matrix.\n * mat4 layout (column-major 4x4):\n * [0]=a [1]=b [4]=c [5]=d [12]=tx [13]=ty\n * where the 2D transform of a point (x,y) is: (a*x + c*y + tx, b*x + d*y + ty)\n */\nexport const Matrix = {\n x: () => Renderer._renderer.uModelMatrix.mat4[12],\n y: () => Renderer._renderer.uModelMatrix.mat4[13],\n a: () => Renderer._renderer.uModelMatrix.mat4[0],\n b: () => Renderer._renderer.uModelMatrix.mat4[1],\n c: () => Renderer._renderer.uModelMatrix.mat4[4],\n d: () => Renderer._renderer.uModelMatrix.mat4[5],\n};\n\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n this.colIdx = Position.getColIndex(x);\n this.rowIdx = Position.getRowIndex(y);\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + Matrix.x();\n const y = this.y + Matrix.y();\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle() {\n return this.isIn() && State.field.isActive\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current p5 angle mode.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1) {\n this.movePos(_plot, _length, _step_length, _scale);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n for (let i = 0; i < _length / _step; i++) {\n const angle =\n this.angle() - (_scale ? _dirPlot.angle(this.plotted) : _dirPlot);\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + Matrix.y() - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + Matrix.x() - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr(0.2, 0.8),\n ba = randInt(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt(15, 25));\n return 0.2 * angle * cos(t) + noise(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt(-10, 10);\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt(-30, -15) + Math.abs(44 * sin(t));\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt(10, 15) + 5 * sin(t),\n cr = randInt(3, 6) + 3 * cos(t),\n ba = randInt(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr(0.4, 0.8),\n ba = randInt(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt(5, 10);\n const dir = randInt(0, 2) * 2 - 1;\n const offset = randInt(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr(0.1, 0.9) * num_columns,\n y: rr(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt(3, 8),\n amp = randInt(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.stroke) this.draw();\n if (State.hatch) this.hatch();\n if (State.fill) this.fill();\n }\n}\n","import { State, Cwidth, Cheight } from \"./color.js\";\nimport { toDegrees, map, rr } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = 0.5;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n const maxSize = Math.max(this.segments[idx] * _side * rr(0.7, 1.3), 10);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.stroke) this.draw(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n }\n}\n","import {\n rr,\n randInt,\n sin,\n cos,\n toDegrees,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current p5 angle mode.\n * @param {number} end - End angle in the current p5 angle mode.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module provides functions for rendering shapes (circles and squares)\n * using WebGL2. It initializes the WebGL context and shader programs, prepares buffers,\n * and implements drawing routines based on queued drawing primitives. The module uses\n * an orthographic projection to map canvas coordinates to clip space and supports adjustable\n * blending for translucent effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\n State,\n} from \"../core/color.js\";\nimport { Matrix } from \"../core/flowfield.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n projMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0;\n\n/**\n * Snapshots the current p5 model matrix. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n _ma = Matrix.a();\n _mb = Matrix.b();\n _mc = Matrix.c();\n _md = Matrix.d();\n _mx = Matrix.x();\n _my = Matrix.y();\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n\n const nextGl = Mix.glMask.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n projMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n -2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * p5's current model matrix so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - Cwidth / 2;\n const py = y - Cheight / 2;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + Cwidth / 2;\n const screenY = _mb * px + _md * py + _my + Cheight / 2;\n const radius =\n (Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n Mix.markDirtyRect(Mix.glMask, {\n minX: screenX * Density - radius - 1,\n minY: screenY * Density - radius - 1,\n maxX: screenX * Density + radius + 1,\n maxY: screenY * Density + radius + 1,\n });\n\n circleCount++;\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader (p5 drawing may have switched programs)\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, projMatrix);\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing p5's _curShader tracking.\n // Reset it to null so p5 is forced to re-activate its own shader next time\n // it draws — otherwise p5 skips gl.useProgram() and sets uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n Mix.glMask._renderer._curShader = null;\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n State,\n Renderer,\n isCanvasReady,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed,\n} from \"../core/utils.js\";\nimport { Position, Matrix, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { isReady, glDraw, circle, snapshotMatrix } from \"./gl_draw.js\";\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n clipWindow: null,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nlet Mask = null;\nlet _strokeTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n tx: 0,\n ty: 0,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { type, min_max, curve } — old internal format, passed through unchanged\n */\nfunction normalizePressure(p) {\n if (!p || (typeof p === \"object\" && !Array.isArray(p))) return p;\n if (typeof p === \"function\")\n return { type: \"custom\", min_max: [0, 1], curve: p };\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n params.tip = () => {\n Mask.image(\n T.tips.get(current.p.image.src),\n -current.p.weight / 2,\n -current.p.weight / 2,\n current.p.weight,\n current.p.weight,\n );\n };\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = Renderer.color(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\nfunction snapshotTransform() {\n return {\n a: Matrix.a(),\n b: Matrix.b(),\n c: Matrix.c(),\n d: Matrix.d(),\n tx: Matrix.x(),\n ty: Matrix.y(),\n };\n}\n\nfunction invertTransform(transform) {\n const det = transform.a * transform.d - transform.b * transform.c;\n if (Math.abs(det) < 1e-12) return null;\n\n return {\n a: transform.d / det,\n b: -transform.b / det,\n c: -transform.c / det,\n d: transform.a / det,\n tx: (transform.c * transform.ty - transform.d * transform.tx) / det,\n ty: (transform.b * transform.tx - transform.a * transform.ty) / det,\n };\n}\n\nfunction transformPoint(transform, x, y) {\n return {\n x: transform.a * x + transform.c * y + transform.tx,\n y: transform.b * x + transform.d * y + transform.ty,\n };\n}\n\nfunction normalizeRegion(region) {\n const [x1, y1, x2, y2] = region;\n return {\n minX: Math.min(x1, x2),\n minY: Math.min(y1, y2),\n maxX: Math.max(x1, x2),\n maxY: Math.max(y1, y2),\n };\n}\n\nfunction currentPointInUserSpace() {\n return transformPoint(\n _strokeTransform,\n _position.x - Cwidth / 2,\n _position.y - Cheight / 2,\n );\n}\n\nfunction screenPointFromPosition(x, y) {\n const point = transformPoint(_strokeTransform, x - Cwidth / 2, y - Cheight / 2);\n return {\n x: point.x + Cwidth / 2,\n y: point.y + Cheight / 2,\n };\n}\n\nfunction markImageTipDirty(rx, ry, scale, angle) {\n const halfWeight = current.p.weight / 2;\n const radians = (angle * Math.PI) / 180;\n const cosAngle = Math.cos(radians);\n const sinAngle = Math.sin(radians);\n const userCenterX = _position.x + rx;\n const userCenterY = _position.y + ry;\n const corners = [\n [-halfWeight, -halfWeight],\n [halfWeight, -halfWeight],\n [halfWeight, halfWeight],\n [-halfWeight, halfWeight],\n ];\n\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n for (const [x, y] of corners) {\n const lx = scale * (cosAngle * x - sinAngle * y);\n const ly = scale * (sinAngle * x + cosAngle * y);\n const point = screenPointFromPosition(userCenterX + lx, userCenterY + ly);\n\n minX = Math.min(minX, point.x * Renderer.pixelDensity());\n minY = Math.min(minY, point.y * Renderer.pixelDensity());\n maxX = Math.max(maxX, point.x * Renderer.pixelDensity());\n maxY = Math.max(maxY, point.y * Renderer.pixelDensity());\n }\n\n Mix.markDirtyRect(Mix.glMask, {\n minX: minX - 2,\n minY: minY - 2,\n maxX: maxX + 2,\n maxY: maxY + 2,\n });\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current p5 transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n const inverse = invertTransform(snapshotTransform());\n if (!inverse) {\n throw new Error(\n \"brush.clip() cannot be used with a non-invertible transform.\",\n );\n }\n State.stroke.clipWindow = {\n bounds: normalizeRegion(region),\n inverse,\n };\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n State.stroke.clipWindow = null;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {boolean} flow - Flag for vector-field following.\n * @param {Object|boolean} plot - Plot object or false.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _strokeTransform = snapshotTransform();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n isPlot\n ? _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n )\n : _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n Mask = Mix.glMask;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.a = pressure.type !== \"custom\" ? rr(-1, 1) : 0;\n current.b = pressure.type !== \"custom\" ? rr(1, 1.5) : 0;\n current.cp = pressure.type !== \"custom\" ? rr(3, 3.5) : rr(-0.2, 0.2);\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.03;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n const dirRad = (_dir * Math.PI) / 180;\n current.cos = Math.cos(dirRad);\n current.sin = Math.sin(dirRad);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n if (isInsideClippingArea()) Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n glDraw();\n markerTip();\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n * @param {number} [customPressure=false] - Optional custom pressure.\n */\nfunction tip(customPressure = false) {\n if (!isInsideClippingArea()) return;\n let pressure = customPressure || calculatePressure();\n\n let lineNoise = map(\n noise(current.seed + _position.plotted * 0.002, 0),\n 0,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n\n switch (current.p.type) {\n case \"spray\":\n drawSpray(pressure * lineNoise);\n break;\n case \"marker\":\n drawMarker(pressure * lineNoise);\n break;\n case \"custom\":\n case \"image\":\n drawTip(pressure * lineNoise, current.alpha);\n break;\n default:\n drawDefault(pressure * lineNoise);\n break;\n }\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n return _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n return current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(_position.plotted / _length) + current.cp,\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Checks if the current drawing position is within the clipping region.\n * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n const point = currentPointInUserSpace();\n\n if (State.stroke.clipWindow) {\n const local = transformPoint(\n State.stroke.clipWindow.inverse,\n point.x,\n point.y,\n );\n const { bounds } = State.stroke.clipWindow;\n return (\n local.x >= bounds.minX &&\n local.x <= bounds.maxX &&\n local.y >= bounds.minY &&\n local.y <= bounds.maxY\n );\n }\n\n let o = Cwidth * 0.05;\n return (\n point.x >= -Cwidth / 2 - o &&\n point.x <= Cwidth / 2 + o &&\n point.y >= -Cheight / 2 - o &&\n point.y <= Cheight / 2 + o\n );\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return 1;\n return param.spacing;\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha,\n );\n}\n\n/**\n * Draws a custom or image-based brush tip.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Alpha (opacity) for drawing.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawTip(pressure, alpha, vibrate = true) {\n Mix.glMask.isDrawn = true;\n Mask.push();\n Mask.noStroke();\n let color = State.stroke.color;\n color.setAlpha(alpha);\n Mask.fill(State.stroke.color);\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n Mask.translate(_position.x + rx - Cwidth, _position.y + ry - Cheight);\n const scale = State.stroke.weight * pressure;\n const angle = adjustSizeAndRotation(scale, alpha);\n current.p.tip(Mask);\n Mask.pop();\n\n if (current.p.type === \"image\") {\n markImageTipDirty(rx, ry, scale, angle);\n } else {\n Mix.markFull(Mix.glMask);\n }\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n if (rr(0, current.p.grain * pressure) > 0.4) {\n let dx, dy;\n if (_plot) {\n dx = 0.7 * vibration * rr(-1, 1);\n dy = vibration * rr(-1, 1);\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * -current.sin + along * current.cos;\n dy = perp * current.cos + along * current.sin;\n }\n circle(\n _position.x + dx,\n _position.y + dy,\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight,\n Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1),\n );\n }\n}\n\n/**\n * Adjusts the size and rotation of the brush tip before rendering.\n * @param {number} pressure - Pressure-based scaling factor.\n * @param {number} alpha - Opacity value.\n */\nfunction adjustSizeAndRotation(pressure, alpha) {\n Mask.scale(pressure);\n if (current.p.type === \"image\") {\n Mask.tint(255, 0, 0, alpha / 2);\n }\n let angle = 0;\n if (current.p.rotate === \"random\") angle = randInt(0, 360);\n else if (current.p.rotate === \"natural\") {\n angle =\n (_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle();\n }\n Mask.rotate(angle);\n return angle;\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (isInsideClippingArea()) {\n let pressure = calculatePressure();\n let alpha = calculateAlpha(pressure);\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, false, alpha * 5);\n }\n glDraw();\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawTip((pressure * s) / 5, alpha, false);\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current p5 angle mode.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, vibration, definition, quality, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\nadd(\"diamond\", {\n type: \"custom\",\n weight: 0.78,\n scatter: 0.1,\n opacity: 17,\n spacing: 1.3,\n pressure: [1.2, 0.82],\n rotate: \"none\",\n tip: (_m) => {\n _m.rotate(45);\n _m.rect(-4, -4, 8, 8);\n _m.rect(2, 2, 3, 3);\n },\n});\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the p5.js graphics library.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The p5.Image to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const p5img = Renderer.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n T.imageToWhite(p5img);\n this.tips.set(src, p5img);\n resolve();\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.src = src;\n }),\n ),\n );\n },\n};\n\n/**\n * Loads all registered image tips. Must be awaited before setup/draw.\n * @returns {Promise}\n *\n * @example\n * // In your sketch:\n * await brush.preload();\n */\nexport async function preload() {\n await T.load();\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};","// =============================================================================\n// Module: Hatch\n// =============================================================================\n/**\n * The Hatch module contains functions and classes dedicated to applying\n * hatch patterns over shapes and polygons. It enables the simulation of\n * cross-hatching and shading effects by drawing parallel lines or strokes\n * across a geometry. The module supports adjustable spacing, angle, and\n * optional style parameters (such as randomness, continuity, and gradient),\n * giving an artistic representation similar to hand-drawn hatching techniques.\n *\n * The implementation allows for hatching to be applied either to a Polygon\n * directly or via a Plot, extending the drawing capabilities with layered,\n * stylized textures.\n */\n\nimport { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, cos, sin, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// ---------------------------------------------------------------------------\n// Hatch State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global hatch state settings.\n */\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow copy of the current hatch state.\n * @returns {object} The current hatch state.\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Updates the global hatch state.\n * @param {object} state - The new hatch state.\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Activates hatching for subsequent geometries.\n *\n * @param {number} dist - The distance between hatching lines.\n * @param {number} angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} options - Optional parameters to affect the hatching style:\n * - rand: Number value to introduce randomness.\n * - continuous: Boolean to connect adjacent lines.\n * - gradient: Number to gradually change spacing.\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Sets the hatch brush style for subsequent hatching.\n *\n * @param {string} brush - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} weight - The brush weight (size).\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Disables hatching.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a hatching pattern over the given polygon(s).\n *\n * @param {Polygon|Polygon[]} polygons - A polygon or an array of polygons.\n */\nexport function createHatch(polygons) {\n let dist = State.hatch.dist;\n let angle = ((State.hatch.angle % 180) + 180) % 180;\n let options = State.hatch.options;\n\n // Save current stroke state\n let save = BrushState();\n // If a hatch brush is set, override with those parameters.\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n\n // Compute overall bounding box for all polygons.\n if (!Array.isArray(polygons)) polygons = [polygons];\n const overallBB = computeOverallBoundingBox(polygons);\n\n // Build a bounding polygon based on the overall bounding box.\n let ventana = new Polygon([\n [overallBB.minX, overallBB.minY],\n [overallBB.maxX, overallBB.minY],\n [overallBB.maxX, overallBB.maxY],\n [overallBB.minX, overallBB.maxY],\n ]);\n\n // Determine starting y coordinate based on angle.\n let startY = angle <= 90 && angle >= 0 ? overallBB.minY : overallBB.maxY;\n let gradient = options.gradient\n ? map(options.gradient, 0, 1, 1, 1.1, true)\n : 1;\n let dots = [];\n let i = 0;\n let dist1 = dist;\n\n // Function to generate a line for index i.\n let linea = (i) => {\n return {\n point1: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90),\n y: startY + dist1 * i * sin(-angle + 90),\n },\n point2: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90) + cos(-angle),\n y: startY + dist1 * i * sin(-angle + 90) + sin(-angle),\n },\n };\n };\n\n // Generate lines and calculate intersections with polygons\n // Loop through the lines based on the distance and angle to calculate intersections with the polygons\n // The loop continues until a line does not intersect with the bounding window polygon\n // Each iteration accounts for the gradient effect by adjusting the distance between lines\n while (ventana.intersect(linea(i)).length > 0) {\n let tempArray = [];\n for (let p of polygons) {\n tempArray.push(p.intersect(linea(i)));\n }\n dots[i] = tempArray\n .flat()\n .sort((a, b) => (a.x === b.x ? a.y - b.y : a.x - b.x));\n dist1 *= gradient;\n i++;\n }\n\n // Filter out empty intersection sets.\n let gdots = dots.filter((dd) => typeof dd[0] !== \"undefined\");\n\n // Draw the hatching lines using the calculated intersections\n // If the 'rand' option is enabled, add randomness to the start and end points of the lines\n // If the 'continuous' option is set, connect the end of one line to the start of the next\n let r = options.rand || 0;\n for (let j = 0; j < gdots.length; j++) {\n let dd = gdots[j];\n let continuousLine = j > 0 && options.continuous;\n for (let i = 0; i < dd.length - 1; i += 2) {\n if (r !== 0) {\n dd[i].x += r * dist * rr(-1, 1);\n dd[i].y += r * dist * rr(-1, 1);\n dd[i + 1].x += r * dist * rr(-1, 1);\n dd[i + 1].y += r * dist * rr(-1, 1);\n }\n line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);\n if (continuousLine) {\n line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);\n }\n }\n }\n\n // Restore previous brush state.\n BrushSetState(save);\n}\n\n/**\n * Computes the bounding box for a single polygon.\n * @param {Polygon} polygon - The polygon to evaluate.\n * @returns {object} The bounding box as {minX, minY, maxX, maxY}.\n */\nfunction computeBoundingBoxForPolygon(polygon) {\n if (polygon._boundingBox) return polygon._boundingBox;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n for (let i = 0; i < polygon.a.length; i++) {\n const [x, y] = polygon.a[i];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n polygon._boundingBox = { minX, minY, maxX, maxY };\n return polygon._boundingBox;\n}\n\n/**\n * Computes an overall bounding box for an array of polygons.\n * @param {Array} polygons - Array of Polygon objects.\n * @returns {object} The overall bounding box {minX, minY, maxX, maxY}.\n */\nfunction computeOverallBoundingBox(polygons) {\n let overall = {\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity,\n };\n for (let poly of polygons) {\n const bb = computeBoundingBoxForPolygon(poly);\n overall.minX = Math.min(overall.minX, bb.minX);\n overall.minY = Math.min(overall.minY, bb.minY);\n overall.maxX = Math.max(overall.maxX, bb.maxX);\n overall.maxY = Math.max(overall.maxY, bb.maxY);\n }\n return overall;\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Adds a hatch effect to the polygon.\n *\n * If a distance is provided, activates hatching with the given parameters.\n * Then, if hatch is active, applies the hatching pattern.\n *\n * @param {number} [_dist] - The distance between hatch lines.\n * @param {number} _angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} _options - Optional hatch options.\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) {\n createHatch(this);\n }\n HatchSetState(state);\n};\n\n/**\n * Applies hatching to a plot.\n *\n * If hatching is active, generates a polygon from the plot and applies hatch.\n *\n * @param {number} x - The x-coordinate to draw at.\n * @param {number} y - The y-coordinate to draw at.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.25);\n this.pol.hatch();\n }\n};\n","import { Mix } from \"./color.js\";\n\nfunction transformPoint(matrix, x, y) {\n return {\n x: matrix.a * x + matrix.c * y + matrix.e,\n y: matrix.b * x + matrix.d * y + matrix.f,\n };\n}\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices) {\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n vertices.forEach((v, i) => {\n const point = transformPoint(matrix, v.x, v.y);\n minX = Math.min(minX, point.x);\n minY = Math.min(minY, point.y);\n maxX = Math.max(maxX, point.x);\n maxY = Math.max(maxY, point.y);\n\n if (i === 0) ctx.moveTo(v.x, v.y);\n else ctx.lineTo(v.x, v.y);\n });\n ctx.closePath();\n\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n const radius = d / 2;\n const center = transformPoint(matrix, x, y);\n const rx = radius * Math.hypot(matrix.a, matrix.c);\n const ry = radius * Math.hypot(matrix.b, matrix.d);\n const padding = strokePadding(ctx, matrix);\n\n Mix.markDirtyRect(Mix.mask, {\n minX: center.x - rx - padding,\n minY: center.y - ry - padding,\n maxX: center.x + rx + padding,\n maxY: center.y + ry + padding,\n });\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\nimport { Renderer, Mix, State, Cwidth, Cheight, Density } from \"../core/color.js\";\nimport { drawPolygon, circle } from \"../core/mask.js\";\nimport {\n constrain,\n weightedRand,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady, Matrix } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 1024;\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color =\n arguments.length < 3 ? Renderer.color(a) : Renderer.color(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length < 8) {\n // Simple average for small polygons\n return pts\n .reduce((c, p) => ({ x: c.x + p.x, y: c.y + p.y }), { x: 0, y: 0 })\n .map((v) => v / pts.length);\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n const v = [...polygon.vertices];\n\n // Map vertices\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n\n // Create bleed modifiers\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.2) * strength,\n );\n\n // Randomize starting point\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n\n // Calculate center and create FillPolygon\n const center = _center(shifted);\n new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions\n this.dir = Array(v.length);\n rayCalc.forEach((rc, i) => {\n let count = 0;\n for (const isect of _polygon.intersect(rc.ray)) {\n if (_isLeft(rc.v1, rc.v2, isect)) count++;\n }\n this.dir[i] = count % 2 === 0;\n });\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: [...this.v], m: [...this.m], dir: [...this.dir] };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Clone and splice\n const v = [...this.v],\n m = [...this.m],\n dir = [...this.dir];\n v.splice(s, n);\n m.splice(s, n);\n dir.splice(s, n);\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n\n // Build sorted random indices\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [], sm = [], sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n\n // Ray-cast: count intersections from p to far right\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y, by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n // If outside (even crossings), pull toward center\n if (crossings % 2 === 0) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]); // flip direction → grow inward\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n // Get trimmed vertices\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n \n // Pre-allocate output arrays\n const outLen = len * 2;\n const newVerts = new Array(outLen);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\n \n // Determine bleed direction\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n \n // Ensure gaussian pool is filled\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0], gPoolLen = gPool.length;\n const g2Pool = _gaussians[1], g2PoolLen = g2Pool.length;\n \n let idx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n \n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n \n if (f < 997) mod = mi;\n \n // Inline rotate: rotDeg = ±bleedDirDeg + small jitter\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n \n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n \n // Outward distance: inline rArray + rr\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n \n // First vertex: original\n newVerts[idx] = cv;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n \n // Second vertex: midpoint + outward push\n newVerts[idx] = {\n x: cv.x + sideX * 0.5 + dirX * d,\n y: cv.y + sideY * 0.5 + dirY * d,\n };\n newMods[idx] = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n newDirs[idx] = di;\n idx++;\n }\n \n // Cap vertex count to prevent exponential blowup.\n let fv = newVerts, fm = newMods, fd = newDirs;\n let growe = GROW_MAX_VERTS / (State.fill.texture_strength);\n if (growe && idx > growe) {\n const step = Math.ceil(idx / growe);\n fv = []; fm = []; fd = [];\n for (let j = 0; j < idx; j += step) {\n fv.push(newVerts[j]);\n fm.push(newMods[j]);\n fd.push(newDirs[j]);\n }\n } else {\n // Trim pre-allocated arrays to actual size\n fv.length = idx;\n fm.length = idx;\n fd.length = idx;\n }\n \n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n // Precalculate stuff\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n // Perform initial setup only once\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(), Density * Matrix.b(),\n Density * Matrix.c(), Density * Matrix.d(),\n Density * (Matrix.x() + Cwidth / 2),\n Density * (Matrix.y() + Cheight / 2),\n );\n\n Mix.ctx.strokeStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${\n 0.005 * State.fill.border_strength\n })`;\n Mix.ctx.lineCap = \"round\";\n\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n\n // Create initial polygon\n let pol = this.grow();\n // Create sparse inner polygon from original (pre-grow) vertices\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n // Grow polygon every 4 layers\n if (i % 4 === 0) pol = pol.grow();\n\n // Create variant polygons\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n // Draw layers\n for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);\n sparse.grow(999).flipDirs().grow(997).layer(i, size, int * 1.5 * texture, color);\n if (i % 2 === 0)\n pol\n .grow(darker)\n .grow(999)\n .layer(i, size, int * 2, color);\n\n // Apply texture and blend periodically\n if (i % 5 === 0 || i === numLayers - 1) {\n if (texture !== 0) pol.erase(texture * 3, intensity);\n Mix.blend(color, true, false, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, color) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\n drawPolygon(this.v);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n // Optimize by pre-calculating values\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.4 - State.fill.bleed_strength);\n const minSizeFactor = 0.05 * minSize;\n const maxSizeFactor = 0.4 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n // Set up erase mode\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n // Calculate transparency\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n // Draw erase circles\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const size = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, size);\n if (i % 5 !== 0) Mix.ctx.fill();\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n map(State.fill.bleed_strength, 0, 0.6, 0.3, 0.45, true),\n );\n this.pol.fill();\n }\n};\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n}\n","/**\n * @fileoverview p5.brush - A comprehensive toolset for brush management in p5.js.\n * @version 2.0.0-alpha\n * @license MIT\n * @author Alejandro Campos Uribe\n *\n * @description\n * p5.brush is a p5.js library dedicated to the creation and management of custom brushes.\n * It extends the drawing capabilities of p5.js by allowing users to simulate a wide range\n * of brush strokes, vector fields, hatching patterns, and fill textures. These features\n * are essential for emulating the nuanced effects found in traditional sketching and painting.\n * Whether for digital art applications or procedural generation of graphics, p5.brush provides\n * a robust framework for artists and developers to create rich, dynamic, and textured visuals.\n *\n * @example\n * // Basic usage:\n * brush.pick('marker'); // Select brush type\n * brush.stroke(255, 0, 0); // Set brush color\n * brush.strokeWeight(10); // Set brush size\n * brush.line(25, 25, 75, 75); // Draw a line\n *\n * // Add a new brush type:\n * brush.add('customBrush', { /* parameters for the brush *\\/ });\n * brush.pick('customBrush');\n *\n * // Use the custom brush for a vector-field line:\n * brush.field('field_name') // Pick a flowfield\n * brush.flowLine(50, 50, 100, PI / 4); // Draw a line within the vector-field; angle follows p5 angleMode()\n *\n * // Fill textures:\n * brush.noStroke();\n * brush.fill('#FF0000', 90); // Set fill color to red and opacity to 90\n * brush.bleed(0.3); // Set bleed effect for a watercolor-like appearance\n * brush.rect(100, 100, 50, 50); // Fill a rectangle with the bleed effect\n *\n * @license\n * MIT License\n *\n * Copyright (c) 2023-2024 Alejandro Campos Uribe\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n// Randomness and other auxiliary functions\nexport { weightedRand as wRand } from \"./core/utils.js\";\n\n// Color Blending\nexport { load, instance } from \"./core/color.js\";\n\n// Matrix transformations, FlowField and Position Class\nexport {\n field,\n noField,\n addField,\n refreshField,\n listFields,\n Position,\n wiggle,\n} from \"./core/flowfield.js\";\n\n// Polygon and Plot classes\nexport { Polygon } from \"./core/polygon.js\";\nexport { Plot } from \"./core/plot.js\";\n\n// Primitives\nexport {\n rect,\n circle,\n arc,\n beginShape,\n vertex,\n endShape,\n beginStroke,\n move,\n endStroke,\n spline,\n polygon,\n} from \"./core/primitives.js\";\n\n// Brushes\nexport {\n add,\n box,\n scaleBrushes,\n pick,\n stroke,\n strokeWeight,\n set,\n noStroke,\n clip,\n noClip,\n line,\n flowLine,\n} from \"./stroke/stroke.js\";\n\n// Section: Hatching\nexport {\n hatch,\n hatchStyle,\n noHatch,\n createHatch as hatchArray,\n} from \"./hatch/hatch.js\";\n\n// Fill\nexport { fill, noFill, fillTexture, fillBleed } from \"./fill/fill.js\";\n\n// p5 addon registration\nimport { Mix } from \"./core/color.js\";\nimport { push as brushPush, pop as brushPop } from \"./core/save.js\";\nimport { seed as brushSeed, noiseSeed as brushNoiseSeed } from \"./core/utils.js\";\n\nfunction registerAddon(_p5, fn, lifecycles) {\n lifecycles.postsetup = () => Mix.blend(false, true);\n lifecycles.postdraw = () => Mix.blend(false, true);\n\n const _push = fn.push;\n const _pop = fn.pop;\n const _randomSeed = fn.randomSeed;\n const _noiseSeed = fn.noiseSeed;\n\n fn.push = function () {\n _push.call(this);\n brushPush();\n };\n\n fn.pop = function () {\n _pop.call(this);\n brushPop();\n };\n\n fn.randomSeed = function (s) {\n _randomSeed.call(this, s);\n brushSeed(s);\n };\n\n fn.noiseSeed = function (s) {\n _noiseSeed.call(this, s);\n brushNoiseSeed(s);\n };\n}\n\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerAddon);\n"],"names":["Cwidth","Cheight","Instance","Renderer","Density","isFramebufferTarget","target","begin","end","renderer","_pInst","getSketchRenderer","_isInstanced","window","self","p5","instance","removeTargetBuffer","buffer","remove","getActiveFramebuffer","_renderer","activeFramebuffer","getTargetPixelSize","width","Math","max","round","height","normalizeDirtyRect","rect","minX","floor","min","maxX","minY","maxY","ceil","getFullDirtyRect","withScissor","gl","draw","box","normalized","x","y","toScissorBox","wasEnabled","isEnabled","SCISSOR_TEST","prevBox","getParameter","SCISSOR_BOX","enable","scissor","disable","load","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","inst","isMixReady","isBlending","cachedColor","Object","markDirtyRect","a","b","dirtyRect","isDrawn","markFull","clearMask","clear","getCompositeRect","isBrushMask","padding","expandDirtyRect","captureBlendSource","framebuffer","blendSourceFramebuffer","pixelDensity","createFramebuffer","density","antialias","depth","stencil","source","drawingContext","push","imageMode","CENTER","image","pop","graphicsFactory","createGraphics","p2dMode","P2D","webglMode","WEBGL","mask","glMask","this","ctx","shaderProgram","createShader","angleMode","DEGREES","lineWidth","uModelMatrix","blend","_color","_isLast","activeIsBrush","isBrush","no_mask","nextColor","_array","colorChanged","justChanged","applyShader","shader","targetIsFramebuffer","hadDepthTest","DEPTH_TEST","translate","setUniform","fill","noStroke","resetShader","SQRT3","sqrt","F2","G2","fastFloor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","c","s0","s1","s2","copy","f","rng","_seedCallbacks","_onSeed","cb","noise","rr","e","rArray","array","randInt","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","d","withinBounds","constrain","low","high","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","NaN","sLookup","idx","sin","toDegrees","rad","isRad","RADIANS","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","Matrix","mat4","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","update","plotted","colIdx","getColIndex","rowIdx","getRowIndex","reset","isIn","isActive","isInCanvas","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","y_offset","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","has","generateField","entry","normalizeFieldAngles","gen","refreshField","currentField","keys","join","noField","name","funct","set","listFields","fn","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","intersection","show","stroke","hatch","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","polygon","mode","beginShape","vertex","endShape","circle","radius","arcLength","angleOffset","randomFactor","randomAngle","offsetX","offsetY","arc","startDeg","sweepDeg","segmentCount","segmentSweep","startX","startY","_current","_curvature","_strokeArray","_strokeOrigin","SubPath","isClosed","curvature","vert","_createSpline","close","beginStroke","move","endStroke","spline","_array_points","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","halfDist","asin","origin","projMatrix","vao","buf","program","loadedWidth","loadedHeight","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","diameter","alpha","newData","px","py","screenX","screenY","glDraw","color","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","uniform4f","u_color","uniformMatrix4fv","u_matrix","drawArrays","POINTS","_curShader","weight","clipWindow","opacity","_position","Mask","_strokeTransform","tx","ty","BrushState","BrushSetState","state","add","params","includes","undefined","vibration","scatter","definition","sharpness","quality","grain","isArray","min_max","curve","m","range","ns","nm","ne","normalizePressure","src","T","tip","tips","param","colors","buffers","scaleBrushes","values","spacing","pick","brushName","g","arguments","strokeWeight","snapshotTransform","transformPoint","transform","normalizeRegion","region","screenPointFromPosition","point","clip","inverse","det","invertTransform","bounds","noClip","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","noiseoffset","dirRad","nextGl","needsContextRefresh","createProgram","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","isReady","switchingToBrush","isInsideClippingArea","calculateAlpha","markerTip","saveState","stepSize","totalSteps","customPressure","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","local","o","vibrate","rx","ry","setAlpha","tint","adjustSizeAndRotation","halfWeight","radians","cosAngle","sinAngle","userCenterX","userCenterY","corners","Infinity","markImageTipDirty","flowLine","_vals","_standard_brushes","obj","_m","prototype","_brush","_weight","imageToWhite","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","p5img","createImage","naturalWidth","naturalHeight","drawImage","onerror","HatchState","rand","continuous","gradient","hatchStyle","brush","hBrush","noHatch","createHatch","polygons","save","overallBB","overall","poly","bb","computeBoundingBoxForPolygon","computeOverallBoundingBox","ventana","dots","dist1","linea","tempArray","flat","sort","gdots","dd","continuousLine","_boundingBox","matrix","strokePadding","getTransform","center","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","noFill","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","sx","sy","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","splice","ratio","L","keep","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","newVerts","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","fv","fm","fd","growe","intensity","tex","texture","int","switchingToFill","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","size","darker","sparse","pols","layer","numLayers","erase","restore","fillStyle","beginPath","lineTo","closePath","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","_opacity","_bleed","fluid","strength","modifiers","_","shift","shifted","slice","pts","area","cross","_center","createFill","FillSetState","_stateStack","registerAddon","_p5","lifecycles","postsetup","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","callback","brushSe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sd,EAAMtd,QAC1BxT,EAAM6N,MAAQ,IAAKijB,EAAMjjB,OACzB7N,EAAMyT,MAAQ,IAAKqd,EAAMrd,OACzBzT,EAAMmE,KAAO,IAAK2sB,EAAM3sB,MAC1B,CCyGI4sB,EACF,EAEAxe,EAAGme,WAAa,SAAU5qB,GACxB2qB,EAAYI,KAAKnuB,KAAMoD,GZpHP,CAACA,IACnB4C,EAAMzB,EAAUnB,GAChB,IAAK,MAAMkrB,KAAYroB,EACrBqoB,KYkHAC,CAAUnrB,EACZ,EAEAyM,EAAGqe,UAAY,SAAU9qB,GACvB6qB,EAAWE,KAAKnuB,KAAMoD,GZvGD,CAACA,IACxBgD,EAAQjE,EAAcoC,EAAUnB,KYuG9BorB,CAAeprB,EACjB,CACF","x_google_ignoreList":[1,2]}
\ No newline at end of file
+{"version":3,"file":"p5.brush.esm.js","sources":["../src/core/color.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/flowfield.js","../src/core/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/core/gl/utils.js","../src/stroke/gl_draw.js","../src/stroke/stroke.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// Module: 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\n// =============================================================================\n// Section: Composite Profiling\n// =============================================================================\nconst CompositeProfile = {\n enabled: false,\n stats: new Map(),\n timer: null,\n};\n\nconst getCompositeProfileFlag = () => {\n if (typeof window === \"undefined\") return false;\n if (window.__P5_BRUSH_COMPOSITE_PROFILE__ != null) {\n return !!window.__P5_BRUSH_COMPOSITE_PROFILE__;\n }\n return new URLSearchParams(window.location.search).get(\"compositeProfile\") === \"on\";\n};\n\nconst now = () => globalThis.performance?.now?.() ?? Date.now();\n\nconst profileComposite = (name, fn) => {\n if (!CompositeProfile.enabled) return fn();\n const start = now();\n try {\n return fn();\n } finally {\n const stat = CompositeProfile.stats.get(name) ?? { total: 0, count: 0 };\n stat.total += now() - start;\n stat.count += 1;\n CompositeProfile.stats.set(name, stat);\n if (CompositeProfile.timer) clearTimeout(CompositeProfile.timer);\n CompositeProfile.timer = setTimeout(() => {\n const rows = [...CompositeProfile.stats.entries()]\n .map(([operation, stat]) => ({\n operation,\n total_ms: stat.total.toFixed(2),\n count: stat.count,\n avg_ms: (stat.total / stat.count).toFixed(4),\n }))\n .sort((a, b) => Number(b.total_ms) - Number(a.total_ms));\n console.log(\n `[p5.brush composite profile] entries=${rows.length}`,\n );\n console.table(rows);\n }, 300);\n }\n};\n\n// =============================================================================\n// Section: Target Resolution\n// =============================================================================\n\n/**\n * Checks whether the given draw target is a p5.Framebuffer-like object.\n * @param {*} target - Candidate draw target.\n * @returns {boolean} True when the target behaves like a p5.Framebuffer.\n */\nconst isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\n/**\n * Resolves the sketch renderer that owns the current drawing session.\n * @returns {p5|Window[\"p5\"][\"instance\"]} The active sketch renderer.\n */\nconst getSketchRenderer = () =>\n _isInstanced ? Instance : window.self.p5.instance;\n\n/**\n * Verifies that a framebuffer belongs to the currently active sketch.\n * @param {p5.Framebuffer} target - Framebuffer candidate.\n * @returns {boolean} True when the framebuffer belongs to the active sketch.\n */\nconst isSupportedFramebufferTarget = (target) =>\n isFramebufferTarget(target) && target.renderer._pInst === getSketchRenderer();\n\n/**\n * Resolves the renderer and pixel size used by `brush.load()`.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional draw target.\n * @returns {{renderer: object, width: number, height: number}} Active renderer info.\n */\nconst resolveTarget = (buffer = false) => {\n // brush.load() can target the main sketch renderer, a p5.Graphics surface,\n // or an active framebuffer owned by the current sketch.\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\",\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\n/**\n * Returns the currently bound sketch framebuffer when drawing into one.\n * @returns {p5.Framebuffer|null} Active framebuffer or null.\n */\nconst getActiveFramebuffer = () =>\n Renderer &&\n Renderer._renderer &&\n typeof Renderer._renderer.activeFramebuffer === \"function\"\n ? Renderer._renderer.activeFramebuffer()\n : null;\n\n// =============================================================================\n// Section: Dirty Rect Utilities\n// =============================================================================\nconst DIRTY_BRUSH_PADDING = 2;\nconst DIRTY_FILL_PADDING = 4;\n\n/**\n * Returns the current render target size in physical pixels.\n * @returns {{width: number, height: number}} Pixel size of the active target.\n */\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to expand.\n * @param {number} [padding=0] - Padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Expanded rect.\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\n/**\n * Clamps a dirty rectangle to the current target bounds.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\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\n/**\n * Returns the union of two dirty rectangles.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} a - First rect.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} b - Second rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Union rect.\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\n/**\n * Returns a dirty rectangle covering the full active target.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return { minX: 0, minY: 0, maxX: width, maxY: height };\n};\n\n// =============================================================================\n// Section: Scissor Helpers\n// =============================================================================\n/**\n * Converts a top-left-based dirty rectangle into a WebGL scissor box.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @returns {{x:number,y:number,width:number,height:number}|null} Scissor box or null.\n */\nconst toScissorBox = (rect) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n // WebGL scissor coordinates are bottom-left based, unlike p5's top-left\n // oriented screen-space bookkeeping.\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\n/**\n * Runs a draw callback with a temporary scissor region.\n * @param {WebGL2RenderingContext} gl - Active WebGL context.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @param {Function} draw - Draw callback executed under the scissor box.\n * @returns {boolean} True when a valid scissor box was applied.\n */\nconst withScissor = (gl, rect, draw) => {\n const box = toScissorBox(rect);\n if (!box) return false;\n\n // Scissor is never nested in this module, so we can set/clear it directly\n // without saving previous GL state.\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 gl.disable(gl.SCISSOR_TEST);\n }\n\n return true;\n};\n\n// =============================================================================\n// Section: Load and State\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 * 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// Section: Color Blending / Rendering\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\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 /**\n * Merges a new dirty rectangle into the target's accumulated draw bounds.\n * @param {object} target - Mask buffer receiving draw output.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to merge.\n */\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n /**\n * Clears a mask buffer and resets its dirty-rect tracking.\n * @param {object} target - Mask buffer to reset.\n */\n clearMask(target) {\n if (!target) return;\n\n target.clear();\n target.isDrawn = false;\n target.dirtyRect = null;\n },\n\n /**\n * Resolves the region that should be composited back into the destination.\n * @param {object} target - Mask buffer being sampled.\n * @param {boolean} isBrushMask - True when compositing the WEBGL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n\n // Brush masks are generated in a separate WEBGL surface and sampled back\n // into the active renderer. Framebuffer output can disagree about Y\n // orientation there, so brush-mask compositing falls back to full-frame.\n if (isBrushMask && getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(\n target.dirtyRect,\n isBrushMask ? DIRTY_BRUSH_PADDING : DIRTY_FILL_PADDING,\n ),\n );\n },\n\n /**\n * Captures the current framebuffer contents into a reusable source texture.\n * For main-canvas draws this simply returns the sketch renderer directly.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}} dirtyRect - Region to copy.\n * @returns {object} Renderer or framebuffer source to sample in the blend shader.\n */\n captureBlendSource(dirtyRect) {\n const activeFramebuffer = getActiveFramebuffer();\n if (!activeFramebuffer) return Renderer._renderer;\n\n // Framebuffer compositing cannot safely sample from the active framebuffer\n // while drawing back into it, so we copy the relevant area first.\n const source = Renderer.blendSourceFramebuffer;\n const needsSource =\n !source ||\n source.width !== Cwidth ||\n source.height !== Cheight ||\n (typeof source.pixelDensity === \"function\" &&\n source.pixelDensity() !== Density);\n\n if (needsSource) {\n if (source?.remove) source.remove();\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 Renderer.blendSourceFramebuffer.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 return Renderer.blendSourceFramebuffer;\n },\n\n // =============================================================================\n // Section: Setup and load shaders\n // =============================================================================\n /**\n * Ensures the mask buffers and blend shader exist for the current renderer.\n */\n load() {\n CompositeProfile.enabled = getCompositeProfileFlag();\n const graphicsFactory =\n typeof Renderer.createGraphics === \"function\" ? Renderer : Renderer._pInst;\n const needsBuffers =\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 Density = Renderer.pixelDensity();\n const p2dMode = graphicsFactory.P2D ?? Renderer.P2D;\n const webglMode = graphicsFactory.WEBGL ?? Renderer.WEBGL;\n\n if (!Renderer.loaded || needsBuffers) {\n if (Renderer.mask?.remove) Renderer.mask.remove();\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n // Keep one 2D mask for fill/hatch work and one WEBGL mask for brush\n // stamps so each path can draw in the renderer that suits it best.\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\n this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\n\n this.mask.pixelDensity(Density);\n this.mask.angleMode(Renderer.DEGREES);\n this.mask.dirtyRect ??= null;\n this.mask.noSmooth();\n this.mask.isDrawn ??= false;\n\n this.glMask.pixelDensity(Density);\n this.glMask.angleMode(this.glMask.DEGREES);\n this.glMask.drawingContext.lineWidth = 0;\n this.glMask.dirtyRect ??= null;\n this.glMask.isDrawn ??= false;\n\n // Link Matrix of GL mask to main Renderer\n this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;\n },\n\n // =============================================================================\n // Section: Compositing\n // =============================================================================\n /**\n * Flushes pending mask work when the blend color changes or a frame ends.\n * @param {Color|false} [_color=false] - New blend color.\n * @param {boolean} [_isLast=false] - True when this is the final blend flush.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n\n // Only one mask is \"active\" for the current drawing mode; the other one\n // may still need flushing if the mode just changed mid-frame.\n const isBrushMask = this.isBrush === true;\n const mask = isBrushMask ? this.glMask : this.mask;\n const otherMask = isBrushMask ? 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 if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Force p5 to bind its internal render target for glMask before the\n // first raw GL brush draw of the blend cycle.\n this.glMask.clear();\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(otherMask, !isBrushMask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, isBrushMask);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) this.isBlending = false;\n }\n },\n\n /**\n * Runs the blend shader over a mask and composites the result into the active renderer.\n * @param {object} mask - Mask buffer to composite.\n * @param {boolean} isBrushMask - True when compositing the WEBGL brush mask.\n */\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n const profilePrefix = isBrushMask ? \"brush\" : \"fill\";\n profileComposite(`${profilePrefix}.applyShader`, () => {\n // Brush masks are drawn via raw GL into a separate WEBGL graphics surface,\n // so flush that context before sampling it as a texture.\n if (isBrushMask && typeof mask.drawingContext?.flush === \"function\") {\n profileComposite(`${profilePrefix}.flushMask`, () =>\n mask.drawingContext.flush(),\n );\n }\n\n const dirtyRect = profileComposite(\n `${profilePrefix}.getCompositeRect`,\n () => this.getCompositeRect(mask, isBrushMask),\n );\n if (!dirtyRect) {\n profileComposite(`${profilePrefix}.clearMask`, () => this.clearMask(mask));\n return;\n }\n\n const gl = Renderer.drawingContext;\n const shader = Renderer.shaderProgram;\n const source = profileComposite(\n `${profilePrefix}.captureSource`,\n () => this.captureBlendSource(dirtyRect),\n );\n const flipOutputY = !!getActiveFramebuffer();\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n\n // This pass is a fullscreen compositing rect, not scene geometry, so it\n // should not participate in the sketch's depth buffer.\n gl.disable(gl.DEPTH_TEST);\n\n const drawShaderPass = () => {\n Renderer.push();\n Renderer.translate(0, 0);\n Renderer.shader(shader);\n\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n shader.setUniform(\"u_flipOutputY\", flipOutputY);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", this.cachedColor);\n\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 Renderer.pop();\n };\n\n profileComposite(`${profilePrefix}.shaderPass`, drawShaderPass);\n\n Renderer.resetShader();\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n profileComposite(`${profilePrefix}.clearMask`, () => this.clearMask(mask));\n });\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 * 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","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module batches brush primitives for WebGL2 rendering. It initializes\n * the shader programs and buffers used by circle-based brushes and image-tip brushes,\n * then flushes those queues into the shared framebuffer-backed brush mask.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\n State,\n Renderer,\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\";\nimport imgVertSrc from \"./image.vert\";\nimport imgFragSrc from \"./image.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n projMatrix,\n framebufferProjMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nlet brushMaskTarget = null;\nlet prevMaskTarget = null;\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 _halfW = 0,\n _halfH = 0,\n _scale = 1,\n _density = 1;\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 _halfW = Cwidth / 2;\n _halfH = Cheight / 2;\n _scale = Math.sqrt(_ma * _ma + _mb * _mb);\n _density = Density;\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\nlet circleDirtyRect = null;\n\n// ---------------------------------------------------------------------------\n// Image instancing state\n// ---------------------------------------------------------------------------\nlet imgProgram = null;\nlet imgVao = null;\nlet imgCornerBuf = null;\nlet imgInstanceBuf = null;\nconst imgAttr = {};\nconst imgFrag = {};\nlet imgGpuSize = 0;\n\nconst IMG_FLOATS = 5; // screenX, screenY, halfSize, angle, alpha — per stamp\nconst IMG_INIT_CAP = 256;\nlet imgData = new Float32Array(IMG_INIT_CAP * IMG_FLOATS);\nlet imgCount = 0;\nlet imgCapacity = IMG_INIT_CAP;\nlet imgDirtyRect = null;\n\n// Texture cache: src string → WebGLTexture (cleared whenever the GL context changes)\nconst texCache = new Map();\n\n// Static unit-quad corners for gl.TRIANGLE_STRIP in quad-local space.\nconst QUAD_CORNERS = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);\n\nfunction isFramebufferMask(target) {\n return (\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer\n );\n}\n\nfunction resetMaskShaderTracking() {\n const target = Mix.glMask;\n const renderer = isFramebufferMask(target) ? target.renderer : target?._renderer;\n if (!renderer) return;\n renderer._curShader = null;\n renderer._cachedBlendMode = null;\n renderer._isBlending = null;\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n}\n\nfunction getFramebufferHandle(target) {\n if (!target) return null;\n if (typeof target._framebufferToBind === \"function\") return target._framebufferToBind();\n return target.framebuffer ?? null;\n}\n\nfunction ensureBrushMaskTarget() {\n const targetRenderer = Renderer?._renderer;\n const targetDensity = Density;\n const needsTarget =\n !brushMaskTarget ||\n brushMaskTarget.renderer !== targetRenderer ||\n brushMaskTarget.width !== Cwidth ||\n brushMaskTarget.height !== Cheight ||\n brushMaskTarget.density !== targetDensity;\n\n if (!needsTarget) {\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n }\n\n if (brushMaskTarget?.remove) brushMaskTarget.remove();\n\n const target = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: targetDensity,\n antialias: false,\n depth: false,\n stencil: false,\n });\n target.isDrawn = false;\n target.dirtyRect = null;\n target.clear = () => {\n const renderer = Renderer._renderer;\n const previous = renderer.activeFramebuffer?.() ?? null;\n if (previous?._beforeEnd) previous._beforeEnd();\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(target));\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n if (previous?._beforeBegin) {\n previous._beforeBegin();\n } else {\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n renderer.viewport(renderer._origViewport.width, renderer._origViewport.height);\n renderer._applyStencilTestIfClipping?.();\n }\n };\n\n brushMaskTarget = target;\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n}\n\nfunction getProjectionMatrix() {\n return isFramebufferMask(Mix.glMask) ? framebufferProjMatrix : projMatrix;\n}\n\nfunction beginMaskTarget() {\n const target = Mix.glMask;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = hadDepthTest;\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n if (isFramebufferMask(target)) {\n prevMaskTarget = Renderer._renderer.activeFramebuffer?.() ?? null;\n if (prevMaskTarget?._beforeEnd) prevMaskTarget._beforeEnd();\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(target));\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n return;\n }\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n}\n\nfunction endMaskTarget() {\n if (beginMaskTarget._hadDepthTest) gl.enable(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = false;\n if (!isFramebufferMask(Mix.glMask)) return;\n if (prevMaskTarget?._beforeBegin) {\n prevMaskTarget._beforeBegin();\n } else {\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n Renderer._renderer.viewport(\n Renderer._renderer._origViewport.width,\n Renderer._renderer._origViewport.height,\n );\n Renderer._renderer._applyStencilTestIfClipping?.();\n }\n prevMaskTarget = null;\n}\n\nfunction accumulateDirtyRect(currentRect, minX, minY, maxX, maxY) {\n if (!currentRect) return { minX, minY, maxX, maxY };\n if (minX < currentRect.minX) currentRect.minX = minX;\n if (minY < currentRect.minY) currentRect.minY = minY;\n if (maxX > currentRect.maxX) currentRect.maxX = maxX;\n if (maxY > currentRect.maxY) currentRect.maxY = maxY;\n return currentRect;\n}\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n ensureBrushMaskTarget();\n\n const nextGl = Renderer.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 framebufferProjMatrix = 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 // ------------------------------------------------------------------\n // Image-tip instancing program\n // ------------------------------------------------------------------\n texCache.clear();\n\n imgProgram = createProgram(gl, imgVertSrc, imgFragSrc);\n [\"a_corner\", \"a_pos\", \"a_size\", \"a_angle\", \"a_alpha\"].forEach(\n (n) => (imgAttr[n] = gl.getAttribLocation(imgProgram, n)),\n );\n [\"u_proj\", \"u_color\", \"u_tex\"].forEach(\n (n) => (imgFrag[n] = gl.getUniformLocation(imgProgram, n)),\n );\n\n imgVao = gl.createVertexArray();\n gl.bindVertexArray(imgVao);\n\n // Static corner VBO (per-vertex, no divisor)\n imgCornerBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgCornerBuf);\n gl.bufferData(gl.ARRAY_BUFFER, QUAD_CORNERS, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(imgAttr.a_corner);\n gl.vertexAttribPointer(imgAttr.a_corner, 2, gl.FLOAT, false, 0, 0);\n\n // Instance data VBO (per-instance)\n imgInstanceBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n gl.bufferData(gl.ARRAY_BUFFER, imgData.byteLength, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n\n const istride = IMG_FLOATS * 4; // 20 bytes\n gl.enableVertexAttribArray(imgAttr.a_pos);\n gl.vertexAttribPointer(imgAttr.a_pos, 2, gl.FLOAT, false, istride, 0);\n gl.vertexAttribDivisor(imgAttr.a_pos, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_size);\n gl.vertexAttribPointer(imgAttr.a_size, 1, gl.FLOAT, false, istride, 8);\n gl.vertexAttribDivisor(imgAttr.a_size, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_angle);\n gl.vertexAttribPointer(imgAttr.a_angle, 1, gl.FLOAT, false, istride, 12);\n gl.vertexAttribDivisor(imgAttr.a_angle, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_alpha);\n gl.vertexAttribPointer(imgAttr.a_alpha, 1, gl.FLOAT, false, istride, 16);\n gl.vertexAttribDivisor(imgAttr.a_alpha, 1);\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 - _halfW;\n const py = y - _halfH;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const radius = (_density * diameter * _scale) / 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 const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n circleDirtyRect = accumulateDirtyRect(\n circleDirtyRect,\n dScreenX - radius - 1,\n dScreenY - radius - 1,\n dScreenX + radius + 1,\n dScreenY + radius + 1,\n );\n\n circleCount++;\n}\n\n/**\n * Queue an image stamp to be drawn with instanced rendering.\n * Accepts the same coordinate conventions as circle(): x/y in position space\n * (user coords + Cwidth/2, Cheight/2), size in user-coord units, alpha in [0..255].\n * @param {number} x - X in position space.\n * @param {number} y - Y in position space.\n * @param {number} size - Full stamp diameter in user-coord units.\n * @param {number} angle - Rotation in radians.\n * @param {number} alpha - Opacity [0..255].\n */\nexport function stampImage(x, y, size, angle, alpha) {\n if (imgCount >= imgCapacity) {\n imgCapacity *= 2;\n const next = new Float32Array(imgCapacity * IMG_FLOATS);\n next.set(imgData);\n imgData = next;\n }\n\n const px = x - _halfW;\n const py = y - _halfH;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const halfSize = (_density * size * _scale) / 2;\n\n const base = imgCount * IMG_FLOATS;\n imgData[base] = screenX;\n imgData[base + 1] = screenY;\n imgData[base + 2] = halfSize;\n imgData[base + 3] = angle;\n imgData[base + 4] = alpha / 255;\n\n // Bounding box: rotated square worst-case = circle of radius halfSize * √2\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - halfSize * 1.42 - 1,\n dScreenY - halfSize * 1.42 - 1,\n dScreenX + halfSize * 1.42 + 1,\n dScreenY + halfSize * 1.42 + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {p5.Image} p5img - The preprocessed brush-tip image (from T.tips).\n * @param {string} src - The image src string, used as the texture cache key.\n */\nexport function glDrawImages(p5img, src) {\n if (imgCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n beginMaskTarget();\n\n // Lazy-create the WebGL texture from the p5.Image canvas on first use\n let tex = texCache.get(src);\n if (!tex) {\n tex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, p5img.canvas);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n texCache.set(src, tex);\n }\n\n gl.useProgram(imgProgram);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.uniform1i(imgFrag.u_tex, 0);\n\n const color = State.stroke.color._array;\n gl.uniform4f(imgFrag.u_color, ...color);\n gl.uniformMatrix4fv(imgFrag.u_proj, false, getProjectionMatrix());\n\n gl.bindVertexArray(imgVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n\n const byteCount = imgCount * IMG_FLOATS * 4;\n const dataView = imgData.subarray(0, imgCount * IMG_FLOATS);\n if (byteCount > imgGpuSize) {\n gl.bufferData(gl.ARRAY_BUFFER, imgData, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, imgCount);\n gl.flush();\n\n gl.bindVertexArray(null);\n gl.bindTexture(gl.TEXTURE_2D, null);\n endMaskTarget();\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let p5 know we changed the active program\n resetMaskShaderTracking();\n}\n\n/**\n * Removes a cached GL texture by key, forcing re-upload on next draw.\n * Call this when a custom tip function changes after brush.add().\n */\nexport function invalidateTexEntry(key) {\n const tex = texCache.get(key);\n if (tex && gl) gl.deleteTexture(tex);\n texCache.delete(key);\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 beginMaskTarget();\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, getProjectionMatrix());\n gl.drawArrays(gl.POINTS, 0, circleCount);\n gl.flush();\n\n gl.bindVertexArray(null);\n endMaskTarget();\n\n if (circleDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, circleDirtyRect);\n circleDirtyRect = null;\n }\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 resetMaskShaderTracking();\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 Instance,\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 {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} 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();\nlet _strokeTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n tx: 0,\n ty: 0,\n};\n\nfunction getBrushFactory() {\n return Renderer ?? Instance ?? window.self.p5.instance;\n}\n\nconst DEFAULT_CUSTOM_PRESSURE_VARIATION = {\n offset: 0.08,\n scale: 0.08,\n warp: 0.06,\n tilt: 0.06,\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 * { mode: \"gaussian\", curve, min_max } — advanced built-in pressure profile\n * { curve, min_max } — legacy gaussian format, preserved for compatibility\n */\nexport function normalizePressure(p) {\n if (!p) return p;\n if (typeof p === \"function\")\n return {\n type: \"custom\",\n min_max: [0, 1],\n curve: p,\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n };\n if (typeof p === \"object\" && !Array.isArray(p)) {\n if (p.type === \"custom\" || p.mode === \"custom\") {\n const { mode, ...rest } = p;\n return {\n ...rest,\n type: \"custom\",\n variation: {\n ...DEFAULT_CUSTOM_PRESSURE_VARIATION,\n ...(rest.variation ?? {}),\n },\n };\n }\n if (\n p.type === \"gaussian\" ||\n p.mode === \"gaussian\" ||\n (Array.isArray(p.curve) && Array.isArray(p.min_max))\n ) {\n return {\n ...p,\n type: \"gaussian\",\n curve: p.curve,\n min_max: p.min_max,\n };\n }\n return p;\n }\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 variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\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 === \"custom\") {\n if (typeof params.tip !== \"function\") {\n throw new Error(`Brush \"${name}\" is type \"custom\" but is missing a tip function.`);\n }\n // Rasterise the tip once into a 500×500 P2D buffer.\n // Users draw in a 100×100 coordinate space (origin at centre);\n // dark fills/strokes → high opacity, light/white → transparent.\n const key = `custom::${name}`;\n invalidateTexEntry(key); // discard stale GPU texture if tip changed\n const factory = getBrushFactory();\n const g = factory.createGraphics(500, 500);\n g.pixelDensity(1);\n g.background(255);\n g.noSmooth();\n g.push();\n g.translate(250, 250); // centre origin\n g.scale(5); // 100 user units → 500 px\n g.noStroke();\n params.tip(g);\n g.pop();\n T.imageToWhite(g); // dark → high alpha, RGB → white for tint\n T.tips.set(key, g);\n params.tipKey = key;\n list.set(name, { param: params, colors: [], buffers: [] });\n return;\n }\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 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 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\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 {Plot|false} [plot=false] - Plot object for path-following strokes.\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 // 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 if (pressure.type !== \"custom\") {\n current.cp = rr(3, 3.5);\n current.ct = 0;\n current.cs = 1;\n current.ck = 0;\n } else {\n const variation = pressure.variation ?? DEFAULT_CUSTOM_PRESSURE_VARIATION;\n current.cp = rr(-variation.offset, variation.offset);\n current.ct = rr(-variation.warp, variation.warp);\n current.cs = rr(1 - variation.scale, 1 + variation.scale);\n current.ck = rr(-variation.tilt, variation.tilt);\n }\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 Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n\n // Pre-compute clip-check coefficients so isInsideClippingArea() needs no\n // temporary objects and only one matrix×vector multiply per step instead of two.\n {\n const cw2 = Cwidth / 2, ch2 = Cheight / 2;\n const T = _strokeTransform;\n if (State.stroke.clipWindow) {\n const { inverse: I, bounds: B } = State.stroke.clipWindow;\n // Compose (I ∘ T) and fold the -cw2/-ch2 position offset into the translation\n const ca = I.a * T.a + I.c * T.b, cc = I.a * T.c + I.c * T.d;\n const cb = I.b * T.a + I.d * T.b, cd = I.b * T.c + I.d * T.d;\n current.clipA = ca; current.clipB = cb;\n current.clipC = cc; current.clipD = cd;\n current.clipTX = I.a * T.tx + I.c * T.ty + I.tx - ca * cw2 - cc * ch2;\n current.clipTY = I.b * T.tx + I.d * T.ty + I.ty - cb * cw2 - cd * ch2;\n current.clipMinX = B.minX; current.clipMaxX = B.maxX;\n current.clipMinY = B.minY; current.clipMaxY = B.maxY;\n } else {\n const o = Cwidth * 0.05;\n current.clipA = T.a; current.clipB = T.b;\n current.clipC = T.c; current.clipD = T.d;\n current.clipTX = T.tx - T.a * cw2 - T.c * ch2;\n current.clipTY = T.ty - T.b * cw2 - T.d * ch2;\n current.clipMinX = -cw2 - o; current.clipMaxX = cw2 + o;\n current.clipMinY = -ch2 - o; current.clipMaxY = ch2 + o;\n }\n }\n\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n markerTip();\n glDraw();\n const type = current.p?.type;\n if (type === \"image\") glDrawImages(T.tips.get(current.p.image.src), current.p.image.src);\n else if (type === \"custom\") glDrawImages(T.tips.get(current.p.tipKey), current.p.tipKey);\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n */\nfunction tip() {\n const insideClip = isInsideClippingArea();\n if (!insideClip) return;\n const pressure = calculatePressure();\n const 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 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 drawImageTip(pressure * lineNoise);\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 const value = current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(\n Math.max(\n 0,\n Math.min(\n 1,\n 0.5 + ((_position.plotted / _length) - 0.5 + current.ct) * current.cs,\n ),\n ),\n ) +\n current.cp +\n current.ck * ((_position.plotted / _length) - 0.5),\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\n return value;\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 * Uses coefficients pre-computed in saveState() — no object allocations,\n * one fused matrix×vector multiply (both transforms composed at setup time).\n * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n const lx = current.clipA * _position.x + current.clipC * _position.y + current.clipTX;\n if (lx < current.clipMinX || lx > current.clipMaxX) return false;\n const ly = current.clipB * _position.x + current.clipD * _position.y + current.clipTY;\n return ly >= current.clipMinY && ly <= current.clipMaxY;\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 * Math.max(0.8, pressure) * rr(0.9,1.1),\n );\n}\n\n/**\n * Queues a stamp for instanced GL rendering.\n * Handles both \"image\" and \"custom\" tip types.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Opacity [0..255].\n */\nfunction drawImageTip(pressure, alpha = current.alpha) {\n const vibration = State.stroke.weight * current.p.scatter;\n const rx = vibration * rr(-1, 1);\n const ry = vibration * rr(-1, 1);\n const size = current.p.weight * State.stroke.weight * pressure;\n let angle = 0;\n if (current.p.rotate === \"random\") {\n angle = randInt(0, 360) * (Math.PI / 180);\n } else if (current.p.rotate === \"natural\") {\n angle = ((_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle()) * (Math.PI / 180);\n }\n stampImage(_position.x + rx, _position.y + ry, size, angle, alpha * Math.max(0.8, pressure) * rr(0.9,1.1));\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 const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\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 const diameter =\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight;\n const alpha = Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1);\n circle(\n _position.x + dx,\n _position.y + dy,\n diameter,\n alpha,\n );\n }\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 = current.alpha;\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, true, alpha * 8);\n }\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawImageTip((pressure * s) / 10, alpha * 2);\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, scatter, sharpness, grain, 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\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 if (!this.tips.has(src)) 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 factory = getBrushFactory();\n const p5img = factory.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.crossOrigin = \"anonymous\";\n nativeImg.src = src;\n }),\n ),\n );\n },\n};\n","// =============================================================================\n// Module: Classic Hatch\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, 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\n// ---------------------------------------------------------------------------\n\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\nexport function HatchState() {\n return { ...State.hatch };\n}\n\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\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\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Hatching\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for a polygon via scanline intersection.\n * Rotates vertices so hatch lines become horizontal, scans for edge\n * crossings, then rotates intersections back to original space.\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad), sinA = Math.sin(rad);\n const cosB = Math.cos(-rad), sinB = Math.sin(-rad);\n\n const verts = polygon.a, n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity, maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0], y = verts[i][1];\n const r = [x * cosA - y * sinA, x * sinA + y * cosA];\n rotated[i] = r;\n if (r[1] < minY) minY = r[1];\n if (r[1] > maxY) maxY = r[1];\n }\n\n // Build edge list (skip horizontal edges)\n const edges = [];\n for (let i = 0; i < n; i++) {\n const a = rotated[i], b = rotated[(i + 1) % n];\n if (a[1] !== b[1]) edges.push(a, b);\n }\n const eLen = edges.length;\n\n // Scan, find crossings, rotate back\n const segments = [];\n let Y = minY + dist * 0.5, step = dist;\n while (Y < maxY) {\n const cx = [];\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1], y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0]));\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n x1: cx[i] * cosB - Y * sinB, y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB, y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n// ---------------------------------------------------------------------------\n// Create Hatch\n// ---------------------------------------------------------------------------\n\nexport function createHatch(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n if (!Array.isArray(polygons)) polygons = [polygons];\n\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n\n const segs = [];\n for (const poly of polygons)\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n segs.sort((a, b) => a.x1 === b.x1 ? a.y1 - b.y1 : a.x1 - b.x1);\n\n const r = options.rand || 0;\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n let x1 = s.x1, y1 = s.y1, x2 = s.x2, y2 = s.y2;\n if (r) {\n x1 += r * dist * rr(-1, 1);\n y1 += r * dist * rr(-1, 1);\n x2 += r * dist * rr(-1, 1);\n y2 += r * dist * rr(-1, 1);\n }\n line(x1, y1, x2, y2);\n if (j > 0 && options.continuous) line(segs[j - 1].x2, segs[j - 1].y2, x1, y1);\n }\n\n BrushSetState(save);\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) createHatch(this);\n HatchSetState(state);\n};\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 {\n Renderer,\n Mix,\n State,\n Cwidth,\n Cheight,\n Density,\n} 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 const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.4) * strength,\n );\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n const center = _center(shifted);\n return 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 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 = [],\n sm = [],\n 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 let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y,\n 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 (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 sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]);\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 const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n\n const outLen = len * 2;\n const newVerts = new Array(outLen);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0],\n gPoolLen = gPool.length;\n const g2Pool = _gaussians[1],\n 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 const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\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 const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n\n newVerts[idx] = cv;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n\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 let fv = newVerts,\n fm = newMods,\n fd = newDirs;\n const growCap = GROW_MAX_VERTS / State.fill.texture_strength;\n if (growCap && idx > growCap) {\n const step = Math.ceil(idx / growCap);\n fv = [];\n fm = [];\n 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 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 const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\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(),\n Density * Matrix.b(),\n Density * Matrix.c(),\n 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 let pol = this.grow();\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 if (i % 4 === 0) pol = pol.grow();\n\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 for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);\n sparse\n .grow(999)\n .flipDirs()\n .grow(997)\n .layer(i, size, int * texture, color);\n if (i % 2 === 0) {\n pol.grow(darker).grow(999).layer(i, size, int * 2, color);\n }\n\n if (i % 8 === 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 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 Mix.ctx.globalCompositeOperation = \"destination-out\";\n\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 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 {\n fill,\n noFill,\n fillTexture,\n fillBleed,\n} 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","CompositeProfile","enabled","stats","Map","timer","now","globalThis","performance","Date","profileComposite","name","fn","start","stat","get","total","count","set","clearTimeout","setTimeout","rows","entries","map","operation","total_ms","toFixed","avg_ms","sort","a","b","Number","console","log","length","table","isFramebufferTarget","target","begin","end","renderer","_pInst","getSketchRenderer","_isInstanced","window","self","p5","instance","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","enable","SCISSOR_TEST","scissor","disable","load","buffer","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","inst","isMixReady","isBlending","cachedColor","Object","markDirtyRect","dirtyRect","isDrawn","clearMask","clear","getCompositeRect","isBrushMask","padding","expandDirtyRect","captureBlendSource","source","blendSourceFramebuffer","pixelDensity","remove","createFramebuffer","density","antialias","depth","stencil","drawingContext","push","imageMode","CENTER","image","pop","__P5_BRUSH_COMPOSITE_PROFILE__","URLSearchParams","location","search","graphicsFactory","createGraphics","needsBuffers","mask","glMask","p2dMode","P2D","webglMode","WEBGL","shaderProgram","createShader","this","ctx","angleMode","DEGREES","noSmooth","lineWidth","uModelMatrix","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","profilePrefix","flush","shader","flipOutputY","hadDepthTest","getParameter","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","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","n","mash","data","String","charCodeAt","h","c","s0","s1","s2","copy","f","rng","_seedCallbacks","_onSeed","cb","noise","rr","e","rArray","array","randInt","gaussian","mean","stdev","u","cos","weightedRand","weights","totalWeight","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","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","y_offset","x_offset","col","row","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","has","generateField","entry","normalizeFieldAngles","gen","refreshField","currentField","keys","join","noField","funct","listFields","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","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","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","projMatrix","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","prevMaskTarget","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","_halfW","_halfH","_density","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circleDirtyRect","imgProgram","imgVao","imgCornerBuf","imgInstanceBuf","imgAttr","imgFrag","imgGpuSize","imgData","IMG_INIT_CAP","imgCount","imgCapacity","imgDirtyRect","texCache","QUAD_CORNERS","isFramebufferMask","resetMaskShaderTracking","_curShader","_cachedBlendMode","_isBlending","activeTexture","TEXTURE0","bindTexture","TEXTURE_2D","blendEquation","FUNC_ADD","blendFunc","ONE","ONE_MINUS_SRC_ALPHA","getFramebufferHandle","_framebufferToBind","framebuffer","getProjectionMatrix","beginMaskTarget","isEnabled","_hadDepthTest","_beforeEnd","bindFramebuffer","FRAMEBUFFER","viewport","drawingBufferWidth","drawingBufferHeight","endMaskTarget","_beforeBegin","_origViewport","_applyStencilTestIfClipping","accumulateDirtyRect","currentRect","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","tex","createTexture","texImage2D","RGBA","UNSIGNED_BYTE","canvas","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","ONE_MINUS_DST_ALPHA","uniform1i","u_tex","color","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","weight","clipWindow","opacity","_strokeTransform","tx","ty","getBrushFactory","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","state","add","params","includes","undefined","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","rest","m","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","g","background","T","imageToWhite","tips","tipKey","param","colors","buffers","scaleBrushes","values","spacing","pick","brushName","arguments","strokeWeight","snapshotTransform","normalizeRegion","region","clip","inverse","transform","det","invertTransform","bounds","noClip","_position","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","ct","cs","ck","noiseoffset","dirRad","targetRenderer","targetDensity","previous","clearColor","COLOR_BUFFER_BIT","ensureBrushMaskTarget","nextGl","needsContextRefresh","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","STATIC_DRAW","a_corner","a_pos","IMG_FLOATS","vertexAttribDivisor","a_size","a_angle","isReady","switchingToBrush","cw2","ch2","I","B","ca","cc","cd","clipA","clipB","clipC","clipD","clipTX","clipTY","clipMinX","clipMaxX","clipMinY","clipMaxY","o","markerTip","saveState","stepSize","totalSteps","u_matrix","drawArrays","POINTS","glDraw","restoreState","isInsideClippingArea","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawImageTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","lx","ly","vibrate","rx","ry","size","halfSize","base","stampImage","flowLine","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","createImage","naturalWidth","naturalHeight","drawImage","onerror","crossOrigin","HatchState","rand","continuous","gradient","hatchStyle","brush","hBrush","noHatch","scanlineHatch","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","createHatch","polygons","save","segs","poly","transformPoint","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","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","growCap","intensity","texture","int","switchingToFill","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","darker","sparse","pols","layer","numLayers","erase","restore","fillStyle","beginPath","point","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,EAKhD,MAAMC,EAAmB,CACvBC,SAAS,EACTC,MAAO,IAAIC,IACXC,MAAO,MAWHC,EAAM,IAAMC,WAAWC,aAAaF,SAAWG,KAAKH,MAEpDI,EAAmB,CAACC,EAAMC,KAC9B,IAAKX,EAAiBC,QAAS,OAAOU,IACtC,MAAMC,EAAQP,IACd,IACE,OAAOM,GACT,CAAC,QACC,MAAME,EAAOb,EAAiBE,MAAMY,IAAIJ,IAAS,CAAEK,MAAO,EAAGC,MAAO,GACpEH,EAAKE,OAASV,IAAQO,EACtBC,EAAKG,OAAS,EACdhB,EAAiBE,MAAMe,IAAIP,EAAMG,GAC7Bb,EAAiBI,OAAOc,aAAalB,EAAiBI,OAC1DJ,EAAiBI,MAAQe,WAAW,KAClC,MAAMC,EAAO,IAAIpB,EAAiBE,MAAMmB,WACrCC,IAAI,EAAEC,EAAWV,MAAK,CACrBU,YACAC,SAAUX,EAAKE,MAAMU,QAAQ,GAC7BT,MAAOH,EAAKG,MACZU,QAASb,EAAKE,MAAQF,EAAKG,OAAOS,QAAQ,MAE3CE,KAAK,CAACC,EAAGC,IAAMC,OAAOD,EAAEL,UAAYM,OAAOF,EAAEJ,WAChDO,QAAQC,IACN,wCAAwCZ,EAAKa,UAE/CF,QAAQG,MAAMd,IACb,IACL,G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CAACA,IACnB0C,EAAMvB,EAAUnB,GAChB,IAAK,MAAM4wB,KAAYjuB,EACrBiuB,KYuHAC,CAAU7wB,EACZ,EAEA9K,EAAGs7B,UAAY,SAAUxwB,GACvBuwB,EAAWE,KAAK7zB,KAAMoD,GZ5GD,CAACA,IACxB8C,EAAQ9D,EAAcmC,EAAUnB,KY4G9B8wB,CAAe9wB,EACjB,CACF","x_google_ignoreList":[1,2]}
\ No newline at end of file
diff --git a/dist/p5.brush.js b/dist/p5.brush.js
index 3143cb9..d16c7e1 100644
--- a/dist/p5.brush.js
+++ b/dist/p5.brush.js
@@ -1,2 +1,2 @@
-var t,e;t=this,e=function(t){let e,r,i,n,o;const s=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,a=()=>x?i:window.self.p5.instance,l=t=>{t&&"function"==typeof t.remove&&t.remove()},c=()=>n&&n._renderer&&"function"==typeof n._renderer.activeFramebuffer?n._renderer.activeFramebuffer():null,h=()=>({width:Math.max(1,Math.round(e*o)),height:Math.max(1,Math.round(r*o))}),u=t=>{if(!t)return null;const{width:e,height:r}=h(),i=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),n=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),o=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),s=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return o<=i||s<=n?null:{minX:i,minY:n,maxX:o,maxY:s}},f=()=>{const{width:t,height:e}=h();return{minX:0,minY:0,maxX:t,maxY:e}},m=(t,e,r)=>{const i=(t=>{const e=u(t);if(!e)return null;const{height:r}=h();return{x:e.minX,y:r-e.maxY,width:e.maxX-e.minX,height:e.maxY-e.minY}})(e);if(!i)return!1;const n=t.isEnabled(t.SCISSOR_TEST),o=t.getParameter(t.SCISSOR_BOX);t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{r()}finally{n?t.scissor(o[0],o[1],o[2],o[3]):t.disable(t.SCISSOR_TEST)}return!0},g=(t=!1)=>{const o=((t=!1)=>{if(x&&!t)return{renderer:i,width:i.width,height:i.height};if(!t){const t=a();return{renderer:t,width:t.width,height:t.height}}if(s(t)){if(!s(e=t)||e.renderer._pInst!==a())throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.");return{renderer:a(),width:t.width,height:t.height}}var e;return{renderer:t,width:t.width,height:t.height}})(t);if(n=o.renderer,"webgl2"!==n.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");e=o.width,r=o.height,d=!0,n.loaded&&b.load()};let d=!1,x=!1;const p=()=>{d||g()},y={},v=()=>{n?.loaded||(p(),b.load())},b={isBlending:!1,cachedColor:new Object,markDirtyRect(t,e){const r=u(e);var i,n;t&&r&&(t.dirtyRect=(n=r,(i=t.dirtyRect)?n?{minX:Math.min(i.minX,n.minX),minY:Math.min(i.minY,n.minY),maxX:Math.max(i.maxX,n.maxX),maxY:Math.max(i.maxY,n.maxY)}:i:n),t.isDrawn=!0)},markFull(t){t&&(t.dirtyRect=f(),t.isDrawn=!0)},clearMask(t){t&&(t.clear(),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:(t,e)=>t?t.dirtyRect?u(((t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null)(t.dirtyRect,e?2:4)):f():null,captureBlendSource(t){const i=c();if(!i)return n._renderer;var s;(!(s=n.blendSourceFramebuffer)||s.width!==e||s.height!==r||"function"==typeof s.pixelDensity&&s.pixelDensity()!==o)&&(l(n.blendSourceFramebuffer),n.blendSourceFramebuffer=n.createFramebuffer({width:e,height:r,density:o,antialias:!1,depth:!1,stencil:!1}));const a=n.blendSourceFramebuffer;return a.draw(()=>{m(n.drawingContext,t,()=>{n.clear(),n.push(),"function"==typeof n.imageMode&&n.imageMode(n.CENTER??n._renderer?._pInst?.CENTER),n.image(i,0,0,e,r),n.pop()})}),a},load(){o=n.pixelDensity();const t="function"==typeof n.createGraphics?n:n._pInst,i=t.P2D??n.P2D,s=t.WEBGL??n.WEBGL;n.loaded&&n.mask&&n.glMask&&n.mask.width===e&&n.mask.height===r&&n.glMask.width===e&&n.glMask.height===r?(this.mask=n.mask,this.glMask=n.glMask,this.ctx=this.mask.drawingContext,this.mask.dirtyRect??=null,this.mask.isDrawn??=!1,this.glMask.dirtyRect??=null,this.glMask.isDrawn??=!1):(l(n.mask),l(n.glMask),n.mask=t.createGraphics(e,r,i),n.glMask=t.createGraphics(e,r,s),n.loaded=!0,n.shaderProgram??=n.createShader("#version 300 es\n#define GLSLIFY 1\nuniform bool u_flipOutputY;out vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,u_flipOutputY ?-v.y : v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0000000000000001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;i<SPECTRAL_SIZE;i++){float concentration1=pow(factor1,2.)*pow(tintingStrength1,2.)*luminance1;float concentration2=pow(factor2,2.)*pow(tintingStrength2,2.)*luminance2;float totalConcentration=concentration1+concentration2;float ksMix=0.;ksMix+=KS(R1[i])*concentration1;ksMix+=KS(R2[i])*concentration2;R[i]=KM(ksMix/totalConcentration);}return spectral_xyz_to_srgb(spectral_reflectance_to_xyz(R));}vec3 spectral_mix(vec3 color1,vec3 color2,float factor){return spectral_mix(color1,1.,1.-factor,color2,1.,factor);}vec3 spectral_mix(vec3 color1,float factor1,vec3 color2,float factor2){return spectral_mix(color1,1.,factor1,color2,1.,factor2);}const float GAMMA=2.4,EPSILON=0.0001;const float DARKEN_THRESHOLD=0.7;const float EDGE_MIN=0.05,EDGE_MAX=0.35;void main(void){vec2 uv=0.5*p+0.5;vec2 uv1=vec2(uv.x,1.0-uv.y);vec4 source=texture(u_source,uv1);vec4 maskColor=texture(u_mask,uv1);if(maskColor.a==0.0){outColor=source;return;}vec4 pigment=vec4(u_color.xyz,1.0);if(maskColor.a>DARKEN_THRESHOLD){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=uv1+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.0);}"),this.mask=n.mask,this.mask.pixelDensity(o),this.mask.clear(),this.mask.angleMode(n.DEGREES),this.mask.dirtyRect=null,this.mask.isDrawn=!1,this.ctx=this.mask.drawingContext,this.glMask=n.glMask,this.glMask.pixelDensity(o),this.glMask.clear(),this.glMask.angleMode(this.glMask.DEGREES),this.glMask.drawingContext.lineWidth=0,this.glMask.dirtyRect=null,this.glMask.isDrawn=!1),this.glMask._renderer.uModelMatrix=n._renderer.uModelMatrix},blend(t=!1,e=!1){v();const r=!0===this.isBrush,i=r?this.glMask:this.mask,n=r?this.mask:this.glMask,o=t?._array,s=!!o&&(this.cachedColor[0]!==o[0]||this.cachedColor[1]!==o[1]||this.cachedColor[2]!==o[2]||this.cachedColor[3]!==o[3]);!this.isBlending&&o&&(this.isBlending=!0,this.cachedColor=o,this.glMask.clear()),(e||s)&&(this.justChanged&&(this.applyShader(n,!r),this.justChanged=!1),this.isBlending&&this.applyShader(i,r),o&&(this.cachedColor=o),e&&(this.isBlending=!1))},applyShader(t,i){if(!t?.isDrawn)return;const o=this.getCompositeRect(t,i);if(!o)return void this.clearMask(t);let s=n.shaderProgram;const a=n.drawingContext,l=!!c(),h=this.captureBlendSource(o),u=a.getParameter(a.DEPTH_TEST);a.disable(a.DEPTH_TEST),n.push(),n.translate(0,0),n.shader(s),s.setUniform("u_source",h),s.setUniform("u_isBrush",i),s.setUniform("u_flipOutputY",l),s.setUniform("u_mask",t),s.setUniform("u_color",this.cachedColor),m(a,o,()=>{n.fill(0,0,0,0),n.noStroke(),n.rect(-e/2,-r/2,e,r)}),n.pop(),n.resetShader(),u&&a.enable(a.DEPTH_TEST),this.clearMask(t)}},_=Math.sqrt(3),w=.5*(_-1),R=(3-_)/6,S=t=>0|Math.floor(t),M=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);function E(t=Math.random){const e=function(t){const e=new Uint8Array(512);for(let t=0;t<256;t++)e[t]=t;for(let r=0;r<255;r++){const i=r+~~(t()*(256-r)),n=e[r];e[r]=e[i],e[i]=n}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>M[t%12*2]),i=new Float64Array(e).map(t=>M[t%12*2+1]);return function(t,n){let o=0,s=0,a=0;const l=(t+n)*w,c=S(t+l),h=S(n+l),u=(c+h)*R,f=t-(c-u),m=n-(h-u);let g,d;f>m?(g=1,d=0):(g=0,d=1);const x=f-g+R,p=m-d+R,y=f-1+2*R,v=m-1+2*R,b=255&c,_=255&h;let M=.5-f*f-m*m;if(M>=0){const t=b+e[_];M*=M,o=M*M*(r[t]*f+i[t]*m)}let E=.5-x*x-p*p;if(E>=0){const t=b+g+e[_+d];E*=E,s=E*E*(r[t]*x+i[t]*p)}let A=.5-y*y-v*v;if(A>=0){const t=b+1+e[_+1];A*=A,a=A*A*(r[t]*y+i[t]*v)}return 70*(o+s+a)}}function A(t,e){let r=new P(t),i=()=>r.next();return i.double=()=>i()+11102230246251565e-32*(2097152*i()|0),i.int32=()=>4294967296*r.next()|0,i.quick=i,i}class P{constructor(t){null==t&&(t=+new Date);let e=4022871197;function r(t){t=String(t);for(let r=0;r<t.length;r++){e+=t.charCodeAt(r);let i=.02519603282416938*e;e=i>>>0,i-=e,i*=e,e=i>>>0,i-=e,e+=4294967296*i}return 2.3283064365386963e-10*(e>>>0)}this.c=1,this.s0=r(" "),this.s1=r(" "),this.s2=r(" "),this.s0-=r(t),this.s0<0&&(this.s0+=1),this.s1-=r(t),this.s1<0&&(this.s1+=1),this.s2-=r(t),this.s2<0&&(this.s2+=1)}next(){let{c:t,s0:e,s1:r,s2:i}=this,n=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=i,this.s2=n-(this.c=0|n)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let k=A(Math.random());const I=[],C=t=>I.push(t);let L=E(A(Math.random()));const T=(t=0,e=1)=>t+k()*(e-t),N=t=>t[~~(k()*t.length)],Y=(t,e)=>~~T(t,e),z=(t=0,e=1)=>{const r=1-k(),i=k();return Math.sqrt(-2*Math.log(r))*H(360*i)*e+t},X=t=>{let e=0;const r=[];for(const i in t)e+=t[i],r.push({key:i,cumulative:e});const i=k()*e;for(const{key:t,cumulative:e}of r)if(i<e)return isNaN(t)?t:parseInt(t)},D=(t,e,r,i,n,o=!1)=>{let s=i+(t-e)/(r-e)*(n-i);return o?i<n?O(s,i,n):O(s,n,i):s},O=(t,e,r)=>Math.max(Math.min(t,r),e),B=t=>(t%=360)<0?t+360:t,F=1440,G=2*Math.PI/F,$=new Float32Array(F).fill(NaN),W=new Float32Array(F).fill(NaN),H=t=>{const e=~~(4*B(t));let r=$[e];return isNaN(r)&&(r=Math.cos(e*G),$[e]=r),r},U=t=>{const e=~~(4*B(t));let r=W[e];return isNaN(r)&&(r=Math.sin(e*G),W[e]=r),r},j=(t,e=!1)=>{if(e||n&&"function"==typeof n.angleMode&&n.angleMode()===n.RADIANS){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},Z=(t,e=!1)=>e||n&&"function"==typeof n.angleMode&&n.angleMode()===n.RADIANS?180*t/Math.PI:t,V=(t,e,r,i,n)=>{let o=H(n),s=U(n);return{x:o*(r-t)+s*(i-e)+t,y:o*(i-e)-s*(r-t)+e}},K=(t,e,r,i)=>Math.hypot(r-t,i-e),q=(t,e,r,i)=>j(Math.atan2(-(i-e),r-t),!0),J=(t,e,r,i,n=!1)=>{let o=t.x,s=t.y,a=e.x,l=e.y,c=r.x,h=r.y,u=i.x,f=i.y;if(o===a&&s===l||c===u&&h===f)return!1;let m=a-o,g=l-s,d=u-c,x=f-h,p=x*m-d*g;if(0===p)return!1;let y=(d*(s-h)-x*(o-c))/p,v=(m*(s-h)-g*(o-c))/p;return!(!n&&(v<0||v>1))&&{x:o+y*m,y:s+y*g}},Q=()=>n._renderer.uModelMatrix.mat4[12],tt=()=>n._renderer.uModelMatrix.mat4[13],et=()=>n._renderer.uModelMatrix.mat4[0],rt=()=>n._renderer.uModelMatrix.mat4[1],it=()=>n._renderer.uModelMatrix.mat4[4],nt=()=>n._renderer.uModelMatrix.mat4[5];let ot=!1;function st(){ot||(v(),lt=.01*e,ct=-.5*e,ht=-.5*r,ut=Math.round(2*e/lt),ft=Math.round(2*r/lt),yt("hand",(t,e)=>{const r=T(.2,.8),i=Y(5,10);return vt(e,(e,n)=>.5*i*U(r*n*e+Y(15,25))*.2*H(t)+L(e,n)*i*.7)}),yt("curved",(t,e)=>{let r=Y(-10,10);return Y(0,100)%2==0&&(r*=-1),vt(e,(e,i)=>3*D(L(.02*e+.03*t,.02*i+.03*t),0,1,-r,r))}),yt("zigzag",(t,e)=>{let r=Y(-30,-15)+Math.abs(44*U(t));Y(0,100)%2==0&&(r*=-1);let i=r,n=0;for(let t=0;t<ut;t++){for(let r=0;r<ft;r++)e[t][r]=n,n+=i,i*=-1;n+=i,i*=-1}return e}),yt("waves",(t,e)=>{const r=Y(10,15)+5*U(t),i=Y(3,6)+3*H(t),n=Y(20,35);return vt(e,(t,e)=>U(r*t)*n*H(e*i)+Y(-3,3))}),yt("seabed",(t,e)=>{const r=T(.4,.8),i=Y(18,26);return vt(e,(e,n)=>1.1*i*U(r*n*e+Y(15,20))*H(t))}),yt("spiral",(t,e)=>{const r=Y(5,10),i=2*Y(0,2)-1,n=Y(65,80),o=Array.from({length:r},()=>({x:T(.1,.9)*ut,y:T(.1,.9)*ft}));return vt(e,(t,e)=>{let r=0,s=0;for(const a of o){const o=t-a.x,l=e-a.y,c=1/(o*o+l*l+1),h=Math.atan2(l,o)*(180/Math.PI),u=i*(h+n)*Math.PI/180;r+=c*Math.cos(u),s+=c*Math.sin(u)}return Math.atan2(s,r)*(180/Math.PI)})}),yt("columns",(t,e)=>{const r=Y(3,8),i=Y(25,45);return vt(e,(t,e)=>U(t*r)*i)}),ot=!0)}class at{constructor(t,e){st(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=at.getColIndex(t),this.rowIdx=at.getRowIndex(e)}reset(){this.plotted=0}isIn(){return y.field.isActive?at.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,i=r,n=this.x+Q(),o=this.y+tt();return n>=-.3*t&&n<=1.3*t&&o>=-.3*i&&o<=1.3*i}angle(){return this.isIn()&&y.field.isActive?mt.get(y.field.current).field[this.colIdx][this.rowIdx]*y.field.wiggle:0}moveTo(t,e,r=1){this.movePos(Z(t),e,r)}_moveToDegrees(t,e,r=1){this.movePos(t,e,r)}plotTo(t,e,r,i=1){this.movePos(t,e,r,i)}movePos(t,e,r,i=!1){const n=i||1;if(this.isIn())for(let o=0;o<e/r;o++){const e=this.angle()-(i?t.angle(this.plotted):t);this.update(this.x+r*H(e),this.y+r*U(e)),this.plotted+=r/n}else this.plotted+=r/n}static getRowIndex(t,e=1){const r=t+tt()-ht;return Math.round(r/lt/e)}static getColIndex(t,e=1){const r=t+Q()-ct;return Math.round(r/lt/e)}static isIn(t,e){return t>=0&&e>=0&&t<ut&&e<ft}}y.field={isActive:!1,current:null,wiggle:1};let lt,ct,ht,ut,ft,mt=new Map;const gt=new Set(["degrees","radians"]);function dt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!gt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function xt(t,e){return function(t,e){if("radians"!==e)return t;for(let e=0;e<t.length;e++)for(let r=0;r<t[e].length;r++)t[e][r]=Z(t[e][r],!0);return t}(t.gen(e,new Array(ut).fill(null).map(()=>new Float32Array(ft))),t.angleMode)}function pt(t){if(y.field.wiggle||(y.field.wiggle=1),st(),!mt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(mt.keys()).join(", ")}.`);y.field.isActive=!0,y.field.current=t;const e=mt.get(t);e.field||(e.field=xt(e,0))}function yt(t,e,r={}){mt.set(t,{gen:e,field:null,angleMode:dt(r)})}function vt(t,e){for(let r=0;r<ut;r++)for(let i=0;i<ft;i++)t[r][i]=e(r,i);return t}class bt{constructor(t,e=!1){this.a=t,this.vertices=e?t:t.map(([t,e])=>({x:t,y:e})),this.sides=this.vertices.map((t,e,r)=>[t,r[(e+1)%r.length]]),this._intersectionCache={}}intersect(t){const e=`${t.point1.x},${t.point1.y}-${t.point2.x},${t.point2.y}`;if(this._intersectionCache[e])return this._intersectionCache[e];const r=[];for(const[e,i]of this.sides){const n=J(t.point1,t.point2,e,i);n&&r.push(n)}return this._intersectionCache[e]=r,r}show(){y.stroke&&this.draw(),y.hatch&&this.hatch(),y.fill&&this.fill()}}class _t{constructor(t){this.segments=[],this.angles=[],this.pres=[],this.type=t,this.dir=0,this.calcIndex(0),this.pol=!1}addSegment(t=0,e=0,r=1,i=!1){this.angles.length>0&&this.angles.pop(),t=i?(t%360+360)%360:j(t),this.angles.push(t,t),this.pres.push(r),this.segments.push(e),this.length=this.segments.reduce((t,e)=>t+e,0)}endPlot(t=0,e=1,r=!1){t=r?(t%360+360)%360:j(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=j(t)}pressure(t){return t>this.length?this.pres[this.pres.length-1]:this.curving(this.pres,t)}angle(t){return t>this.length?this.angles[this.angles.length-1]:(this.calcIndex(t),"curve"===this.type?this.curving(this.angles,t)+this.dir:this.angles[this.index]+this.dir)}curving(t,e){let r=t[this.index],i=t[this.index+1]??r;return Math.abs(i-r)>180&&(i>r?i=-(360-i):r=-(360-r)),D(e-this.suma,0,this.segments[this.index],r,i,!0)}calcIndex(t){this.index=-1,this.suma=0;let e=0;for(;e<=t;)this.suma=e,e+=this.segments[this.index+1],this.index++;return this.index}genPol(t,i,n=1,o){st();const s=.5,a=[],l=Math.round(this.length/s),c=new at(t+e/2,i+r/2);let h=0,u=0;for(let t=0;t<l;t++){c.plotTo(this,s,s);const t=this.calcIndex(c.plotted);h+=s,(h>=Math.max(this.segments[t]*o*T(.7,1.3),10)||t>=u)&&c.x&&(a.push([c.x-e/2,c.y-r/2]),h=0,t>=u&&u++)}return new bt(a)}show(t,e,r=1){y.stroke&&this.draw(t,e,r),y.hatch&&this.hatch(t,e,r),y.fill&&this.fill(t,e,r)}}let wt,Rt,St,Mt;class Et{constructor(){this.isClosed=!1,this.curvature=Rt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){It(this.vert,this.curvature,this.isClosed).show()}}function At(t=0){Rt=O(t,0,1),wt=new Et}function Pt(t,e,r=1){if(!wt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");wt.vertex(t,e,r)}function kt(t=!1){if(!wt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(wt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(wt.vertex(...wt.vert[0]),wt.isClosed=!0),wt.show(),wt=!1}function It(t,e=.5,r=!1){const i=new _t(0===e?"segments":"curve"),n=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let o,s,a,l=0;for(let c=0;c<t.length-1;c++)if(e>0&&c<t.length-2){const h=t[c],u=t[c+1],f=t[c+2],m=K(h[0],h[1],u[0],u[1]),g=K(u[0],u[1],f[0],f[1]),d=q(h[0],h[1],u[0],u[1]),x=q(u[0],u[1],f[0],f[1]),p=e*Math.min(m,g,.5*Math.min(m,g)),y=Math.max(m,g),v=m-p,b=g-p;if(Math.floor(d)===Math.floor(x)){const e=r&&0===c?0:m-l,n=r?0===c?0:g-a:g;i.addSegment(d,e,h[2],!0),c===t.length-3&&i.addSegment(x,n,u[2],!0),l=0,0===c&&(o=m,a=p,s=t[1],l=0)}else{const e={x:u[0]-p*H(-d),y:u[1]-p*U(-d)},f={x:e.x+y*H(90-d),y:e.y+y*U(90-d)},m={x:u[0]+p*H(-x),y:u[1]+p*U(-x)},g={x:m.x+y*H(90-x),y:m.y+y*U(90-x)},_=J(e,f,m,g,!0),w=K(e.x,e.y,_.x,_.y),R=K(e.x,e.y,m.x,m.y)/2,S=n*w*(2*Math.asin(R/w)*(180/Math.PI))/360,M=r&&0===c?0:v-l,E=c===t.length-3?r?o-p:b:0;i.addSegment(d,M,h[2],!0),i.addSegment(d,isNaN(S)?0:S,h[2],!0),i.addSegment(x,E,u[2],!0),l=p,0===c&&(o=v,a=p,s=[e.x,e.y])}c===t.length-3&&i.endPlot(x,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],n=K(e[0],e[1],r[0],r[1]),o=q(e[0],e[1],r[0],r[1]);i.addSegment(o,n,r[2],!0),c===t.length-2&&i.endPlot(o,1,!0)}i.origin=r&&0!==e?s:t[0]}return i}let Ct,Lt,Tt,Nt,Yt,zt=!1,Xt=0,Dt=0;const Ot={},Bt={};let Ft=1,Gt=0,$t=0,Wt=1,Ht=0,Ut=0,jt=new Float32Array(8192),Zt=0,Vt=2048,Kt=32768;function qt(t,i,n,s){if(Zt>=Vt){Vt*=2;const t=new Float32Array(4*Vt);t.set(jt),jt=t}const a=t-e/2,l=i-r/2,c=4*Zt,h=Ft*a+$t*l+Ht+e/2,u=Gt*a+Wt*l+Ut+r/2,f=o*n*Math.sqrt(Ft*Ft+Gt*Gt)/2;jt[c]=h,jt[c+1]=u,jt[c+2]=f,jt[c+3]=s/255,b.markDirtyRect(b.glMask,{minX:h*o-f-1,minY:u*o-f-1,maxX:h*o+f+1,maxY:u*o+f+1}),Zt++}function Jt(){if(0===Zt)return;b.glMask.isDrawn=!0;const t=y.stroke.color._array;Ct.useProgram(Yt),Ct.enable(Ct.BLEND),Ct.blendFunc(Ct.ONE_MINUS_DST_ALPHA,Ct.ONE),Ct.bindVertexArray(Tt),Ct.bindBuffer(Ct.ARRAY_BUFFER,Nt);const e=16*Zt,r=jt.subarray(0,4*Zt);e>Kt?(Ct.bufferData(Ct.ARRAY_BUFFER,jt,Ct.DYNAMIC_DRAW),Kt=jt.byteLength):Ct.bufferSubData(Ct.ARRAY_BUFFER,0,r),Ct.uniform4f(Bt.u_color,...t),Ct.uniformMatrix4fv(Bt.u_matrix,!1,Lt),Ct.drawArrays(Ct.POINTS,0,Zt),Ct.bindVertexArray(null),Zt=0,b.glMask._renderer._curShader=null}y.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let Qt,te,ee,re,ie=new Map,ne=null,oe={a:1,b:0,c:0,d:1,tx:0,ty:0};function se(){return{...y.stroke}}function ae(t){y.stroke={...t}}function le(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0!==e.vibration&&void 0===e.scatter&&(e.scatter=e.vibration),void 0!==e.definition&&void 0===e.sharpness&&(e.sharpness=e.definition),void 0!==e.quality&&void 0===e.grain&&(e.grain=e.quality),e.pressure=function(t){if(!t||"object"==typeof t&&!Array.isArray(t))return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t};if(Array.isArray(t)){const[e,r,i]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,n=Math.min(e,r,i),o=Math.max(e,r,i),s=o-n||1,[a,l,c]=[(e-n)/s,(r-n)/s,(i-n)/s];return{type:"custom",min_max:[n,o],curve:t=>t<.5?a+(l-a)*t*2:l+(c-l)*(t-.5)*2}}}(e.pressure),"image"===e.type){if(!e.image||!e.image.src)throw new Error(`Brush "${t}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return Le.add(e.image.src),e.tip=()=>{ne.image(Le.tips.get(pe.p.image.src),-pe.p.weight/2,-pe.p.weight/2,pe.p.weight,pe.p.weight)},ie.set(t,{param:e,colors:[],buffers:[]}),Le.load()}ie.set(t,{param:e,colors:[],buffers:[]})}function ce(t){if(!ie.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...ie.keys()].join(", ")}.`);y.stroke.type=t}function he(t,e,r){p(),y.stroke.color=n.color(...arguments),y.stroke.isActive=!0}function ue(t){y.stroke.weight=t}function fe(t,e,r=1){ce(t),he(e),ue(r)}function me(){return{a:et(),b:rt(),c:it(),d:nt(),tx:Q(),ty:tt()}}function ge(t,e,r){return{x:t.a*e+t.c*r+t.tx,y:t.b*e+t.d*r+t.ty}}function de(t){const[e,r,i,n]=t;return{minX:Math.min(e,i),minY:Math.min(r,n),maxX:Math.max(e,i),maxY:Math.max(r,n)}}function xe(t,i){const n=ge(oe,t-e/2,i-r/2);return{x:n.x+e/2,y:n.y+r/2}}const pe={};function ye(t,i,n,o=!1){Ft=et(),Gt=rt(),$t=it(),Wt=nt(),Ht=Q(),Ut=tt(),oe=me(),Qt=new at(t+e/2,i+r/2),te=n,ee=o,ee&&ee.calcIndex(0)}const ve=[];function be(t,i){i||(re=t),function(){pe.seed=999999*T();const{param:t}=ie.get(y.stroke.type)??{};if(!t)return;pe.p=t,ne=b.glMask;const{pressure:i}=t;if(pe.a="custom"!==i.type?T(-1,1):0,pe.b="custom"!==i.type?T(1,1.5):0,pe.cp="custom"!==i.type?T(3,3.5):T(-.2,.2),[pe.min,pe.max]=i.min_max,pe.noiseoffset=.03,!ee){const t=re*Math.PI/180;pe.cos=Math.cos(t),pe.sin=Math.sin(t)}!function(){v();const t=b.glMask.drawingContext,i=!zt||Ct!==t;(i||Xt!==e||Dt!==r)&&(Lt=new Float32Array([2/e,0,0,0,0,-2/r,0,0,0,0,1,0,-1,1,0,1]),Xt=e,Dt=r),i&&(Ct=t,Yt=(t=>{const e=t.createProgram();for(let[r,i]of[[t.VERTEX_SHADER,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}"],[t.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"]]){const n=t.createShader(r);t.shaderSource(n,i),t.compileShader(n),t.attachShader(e,n)}return t.linkProgram(e),e})(Ct),Ct.useProgram(Yt),Ct.enable(Ct.BLEND),Ct.blendFunc(Ct.ONE_MINUS_DST_ALPHA,Ct.ONE),["a_position","a_radius","a_alpha"].forEach(t=>Ot[t]=Ct.getAttribLocation(Yt,t)),["u_matrix","u_color"].forEach(t=>Bt[t]=Ct.getUniformLocation(Yt,t)),Tt=Ct.createVertexArray(),Ct.bindVertexArray(Tt),Nt=Ct.createBuffer(),Ct.bindBuffer(Ct.ARRAY_BUFFER,Nt),Ct.bufferData(Ct.ARRAY_BUFFER,jt.byteLength,Ct.DYNAMIC_DRAW),Kt=jt.byteLength,Ct.enableVertexAttribArray(Ot.a_position),Ct.vertexAttribPointer(Ot.a_position,2,Ct.FLOAT,!1,16,0),Ct.enableVertexAttribArray(Ot.a_radius),Ct.vertexAttribPointer(Ot.a_radius,1,Ct.FLOAT,!1,16,8),Ct.enableVertexAttribArray(Ot.a_alpha),Ct.vertexAttribPointer(Ot.a_alpha,1,Ct.FLOAT,!1,16,12),Ct.bindVertexArray(null),zt=!0)}();const n=!0!==b.isBrush;b.isBrush=!0,n&&(b.justChanged=!0),Me()&&b.blend(y.stroke.color),pe.alpha=Se(),Pe()}();const n=function(){const{param:t}=ie.get(y.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(te*(i?t:1)/n);for(let e=0;e<o;e++)ve.length<2*o&&ve.push(z()),_e(),i?Qt.plotTo(ee,n,n,t,e<10):Qt._moveToDegrees(t,n,n);Jt(),Pe()}function _e(t=!1){if(!Me())return;let e=t||we(),r=D(L(pe.seed+.002*Qt.plotted,0),0,1,1-pe.noiseoffset,1+pe.noiseoffset);switch(pe.p.type){case"spray":!function(t){const e=y.stroke.weight*pe.p.scatter*t+y.stroke.weight*N(ve)*pe.p.scatter/3,r=pe.p.weight*T(.9,1.1),i=Math.ceil(pe.p.grain/t);for(let t=0;t<i;t++){const t=T(.9,1.1),i=t*e*T(-1,1),n=T(-1,1),o=Math.sqrt((t*e)**2-i**2);qt(Qt.x+i,Qt.y+n*o,r,pe.alpha)}}(e*r);break;case"marker":Ee(e*r);break;case"custom":case"image":Ae(e*r,pe.alpha);break;default:!function(t,e=1){const r=(e=D(e,0,1,.9,1.05))*y.stroke.weight*pe.p.scatter*(pe.p.sharpness+(1-pe.p.sharpness)*N(ve)/t);if(T(0,pe.p.grain*t)>.4){let e,i;if(ee)e=.7*r*T(-1,1),i=r*T(-1,1);else{const t=r*T(-1,1),n=.3*r*T(-1,1);e=t*-pe.sin+n*pe.cos,i=t*pe.cos+n*pe.sin}qt(Qt.x+e,Qt.y+i,t*t*pe.p.weight*T(.85,1.15)*y.stroke.weight,Math.max(.9,t)*pe.alpha*T(.75,1.1))}}(e*r)}}function we(){return ee?Re()*ee.pressure(Qt.plotted):Re()}function Re(){return"custom"===pe.p.pressure.type?D(pe.p.pressure.curve(Qt.plotted/te)+pe.cp,0,1,pe.min,pe.max,!0):function(t=.5+pe.p.pressure.curve[0]*pe.a,e=1-pe.p.pressure.curve[1]*pe.b,r=pe.cp,i=pe.min,n=pe.max){const o=t*te,s=(Qt.plotted<o?1.2*e:.8*e)*(te/2);return D(1/(1+Math.pow(Math.abs((Qt.plotted-o)/s),2*r)),0,1,i,n)}()}function Se(){return["default","spray"].includes(pe.p.type)?pe.p.opacity:pe.p.opacity/Math.min(y.stroke.weight,1.3)}function Me(){const t=ge(oe,Qt.x-e/2,Qt.y-r/2);if(y.stroke.clipWindow){const e=ge(y.stroke.clipWindow.inverse,t.x,t.y),{bounds:r}=y.stroke.clipWindow;return e.x>=r.minX&&e.x<=r.maxX&&e.y>=r.minY&&e.y<=r.maxY}let i=.05*e;return t.x>=-e/2-i&&t.x<=e/2+i&&t.y>=-r/2-i&&t.y<=r/2+i}function Ee(t,e=!0,r=pe.alpha){const i=e?y.stroke.weight*pe.p.scatter:0,n=e?i*T(-1,1):0,o=e?i*T(-1,1):0;qt(Qt.x+n,Qt.y+o,y.stroke.weight*pe.p.weight*t,r)}function Ae(t,i,o=!0){b.glMask.isDrawn=!0,ne.push(),ne.noStroke(),y.stroke.color.setAlpha(i),ne.fill(y.stroke.color);const s=o?y.stroke.weight*pe.p.scatter:0,a=o?s*T(-1,1):0,l=o?s*T(-1,1):0;ne.translate(Qt.x+a-e,Qt.y+l-r);const c=y.stroke.weight*t,h=function(t,e){ne.scale(t),"image"===pe.p.type&&ne.tint(255,0,0,e/2);let r=0;return"random"===pe.p.rotate?r=Y(0,360):"natural"===pe.p.rotate&&(r=(ee?-ee.angle(Qt.plotted):-re)+Qt.angle()),ne.rotate(r),r}(c,i);pe.p.tip(ne),ne.pop(),"image"===pe.p.type?function(t,e,r,i){const o=pe.p.weight/2,s=i*Math.PI/180,a=Math.cos(s),l=Math.sin(s),c=Qt.x+t,h=Qt.y+e,u=[[-o,-o],[o,-o],[o,o],[-o,o]];let f=Infinity,m=Infinity,g=-Infinity,d=-Infinity;for(const[t,e]of u){const i=xe(c+r*(a*t-l*e),h+r*(l*t+a*e));f=Math.min(f,i.x*n.pixelDensity()),m=Math.min(m,i.y*n.pixelDensity()),g=Math.max(g,i.x*n.pixelDensity()),d=Math.max(d,i.y*n.pixelDensity())}b.markDirtyRect(b.glMask,{minX:f-2,minY:m-2,maxX:g+2,maxY:d+2})}(a,l,c,h):b.markFull(b.glMask)}function Pe(){if(Me()){let t=we(),e=Se();if("marker"===pe.p.type){for(let r=1;r<10;r++)Ee(t*r/10,!1,5*e);Jt()}else if("custom"===pe.p.type||"image"===pe.p.type)for(let r=1;r<5;r++)Ae(t*r/5,e,!1)}}function ke(t,e,r,i){if(!y.stroke.isActive||!y.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");st();let n=K(t,e,r,i);0!=n&&(ye(t,e,n),be(q(t,e,r,i),!1))}C(()=>{ve.length=0});const Ie=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],Ce=[["pen",[.3,.15,.9,2,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,15,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,15,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,10,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,4,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.3,.55,.8,7,75,.1,{curve:[.15,.2],min_max:[.95,1.2]}]],["charcoal",[.35,1.5,.68,500,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of Ce){let e={};for(let r=0;r<t[1].length;r++)e[Ie[r]]=t[1][r];le(t[0],e)}le("diamond",{type:"custom",weight:.78,scatter:.1,opacity:17,spacing:1.3,pressure:[1.2,.82],rotate:"none",tip:t=>{t.rotate(45),t.rect(-4,-4,8,8),t.rect(2,2,3,3)}}),bt.prototype.draw=function(t=!1,e,r){let i=se();if(t&&fe(t,e,r),i.isActive)for(let t of this.sides)ke(t[0].x,t[0].y,t[1].x,t[1].y);ae(i)},_t.prototype.draw=function(t,e,r){se().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,i){st(),ye(e,r,t.length,t),be(i,!0)}(this,t,e,r))};const Le={tips:new Map,add(t){this.tips.set(t,!1)},imageToWhite(t){t.loadPixels();for(let e=0;e<4*t.width*t.height;e+=4){let r=(t.pixels[e]+t.pixels[e+1]+t.pixels[e+2])/3;t.pixels[e]=t.pixels[e+1]=t.pixels[e+2]=255,t.pixels[e+3]=255-r}t.updatePixels()},async load(){const t=[...this.tips.keys()].filter(t=>!this.tips.get(t));await Promise.all(t.map(t=>new Promise((e,r)=>{const i=new window.Image;i.onload=()=>{const r=n.createImage(i.naturalWidth,i.naturalHeight);r.drawingContext.drawImage(i,0,0),Le.imageToWhite(r),this.tips.set(t,r),e()},i.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),i.src=t})))}};function Te(){return{...y.hatch}}function Ne(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let i=y.hatch;i.isActive=!0,i.dist=t,i.angle=Z(e),i.options=r}function Ye(t){let e=y.hatch.dist,r=(y.hatch.angle%180+180)%180,i=y.hatch.options,n=se();y.hatch.hBrush&&fe(...Object.values(y.hatch.hBrush)),Array.isArray(t)||(t=[t]);const o=function(t){let e={minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity};for(let r of t){const t=ze(r);e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY)}return e}(t);let s=new bt([[o.minX,o.minY],[o.maxX,o.minY],[o.maxX,o.maxY],[o.minX,o.maxY]]),a=r<=90&&r>=0?o.minY:o.maxY,l=i.gradient?D(i.gradient,0,1,1,1.1,!0):1,c=[],h=0,u=e,f=t=>({point1:{x:o.minX+u*t*H(90-r),y:a+u*t*U(90-r)},point2:{x:o.minX+u*t*H(90-r)+H(-r),y:a+u*t*U(90-r)+U(-r)}});for(;s.intersect(f(h)).length>0;){let e=[];for(let r of t)e.push(r.intersect(f(h)));c[h]=e.flat().sort((t,e)=>t.x===e.x?t.y-e.y:t.x-e.x),u*=l,h++}let m=c.filter(t=>void 0!==t[0]),g=i.rand||0;for(let t=0;t<m.length;t++){let r=m[t],n=t>0&&i.continuous;for(let i=0;i<r.length-1;i+=2)0!==g&&(r[i].x+=g*e*T(-1,1),r[i].y+=g*e*T(-1,1),r[i+1].x+=g*e*T(-1,1),r[i+1].y+=g*e*T(-1,1)),ke(r[i].x,r[i].y,r[i+1].x,r[i+1].y),n&&ke(m[t-1][1].x,m[t-1][1].y,r[i].x,r[i].y)}ae(n)}function ze(t){if(t._boundingBox)return t._boundingBox;let e=Infinity,r=Infinity,i=-Infinity,n=-Infinity;for(let o=0;o<t.a.length;o++){const[s,a]=t.a[o];s<e&&(e=s),s>i&&(i=s),a<r&&(r=a),a>n&&(n=a)}return t._boundingBox={minX:e,minY:r,maxX:i,maxY:n},t._boundingBox}function Xe(t,e,r){return{x:t.a*e+t.c*r+t.e,y:t.b*e+t.d*r+t.f}}function De(t,e){const r=t.lineWidth||0;return r<=0?1:1+r*Math.max(Math.hypot(e.a,e.c),Math.hypot(e.b,e.d))/2}function Oe(t,e,r){const i=2*Math.PI,n=b.ctx,o=n.getTransform(),s=r/2,a=Xe(o,t,e),l=s*Math.hypot(o.a,o.c),c=s*Math.hypot(o.b,o.d),h=De(n,o);b.markDirtyRect(b.mask,{minX:a.x-l-h,minY:a.y-c-h,maxX:a.x+l+h,maxY:a.y+c+h}),n.moveTo(t+s,e),n.arc(t,e,s,0,i)}y.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},bt.prototype.hatch=function(t=!1,e,r){let i=Te();t&&Ne(t,e,r),i.isActive&&Ye(this),function(t){y.hatch={...t}}(i)},_t.prototype.hatch=function(t,e,r){Te().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},y.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Be=()=>({...y.fill});function Fe(t,e,r,i){y.fill.opacity=(arguments.length<4?e:i)||150,y.fill.color=arguments.length<3?n.color(t):n.color(t,e,r),y.fill.isActive=!0}function Ge(t,e="out"){y.fill.bleed_strength=O(t,0,1),y.fill.direction=e}function $e(t=.4,e=.4){y.fill.texture_strength=O(t,0,1),y.fill.border_strength=O(e,0,1)}let We;const He=[[],[]];function Ue(){for(let t=0;t<512;t++)He[0][t]=z(.5,.2),He[1][t]=z(0,.02)}function je(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}C(Ue);class Ze{constructor(t,e,r,i=[],n=!1,o,s){if(this.v=t,this.m=e,this.dir=i,this.midP=r,n){let e=0,i=0;const n=[];for(let o=0;o<t.length;o++){const s=Math.abs(r.x-t[o].x),a=Math.abs(r.y-t[o].y);e=Math.max(e,s),i=Math.max(i,a);const l=t[o],c=t[(o+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=V(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};n.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=i,this.dir=Array(t.length),n.forEach((t,e)=>{let r=0;for(const e of We.intersect(t.ray))je(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=T(-.6,.6)*e,s=T(-.6,.6)*i;this.midP={x:r.x+o,y:r.y+s}}else this.sizeX=o,this.sizeY=s}trim(t=1){if(t>=1||t<0||this.v.length<=8)return{v:[...this.v],m:[...this.m],dir:[...this.dir]};const e=~~((1-t)*this.v.length),r=~~(this.v.length/2-e/2),i=[...this.v],n=[...this.m],o=[...this.dir];return i.splice(r,e),n.splice(r,e),o.splice(r,e),{v:i,m:n,dir:o}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),i=[],n=e/r;for(let t=0;t<r;t++)i.push(~~(t*n+T(0,.8*n)));const o=[],s=[],a=[],l=this.midP,c=We.sides;for(const t of i){const r=t%e;let i=this.v[r],n=0;for(const[t,e]of c){const r=t.y,o=e.y;if(r>i.y==o>i.y)continue;const s=(i.y-r)/(o-r);i.x<t.x+s*(e.x-t.x)&&n++}n%2==0&&(i={x:l.x+(i.x-l.x)*T(.3,.6),y:l.y+(i.y-l.y)*T(.3,.6)}),o.push(i),s.push(this.m[r]),a.push(!this.dir[r])}return new Ze(o,s,this.midP,a,!1,this.sizeX,this.sizeY)}flipDirs(){return new Ze(this.v,this.m,this.midP,this.dir.map(t=>!t),!1,this.sizeX,this.sizeY)}grow(t=1){const{v:e,m:r,dir:i}=this.trim(t),n=e.length,o=2*n,s=new Array(o),a=new Array(o),l=new Array(o),c="out"===y.fill.direction?-90:90;0===He[0].length&&Ue();const h=He[0],u=h.length,f=He[1],m=f.length;let g=0,d=999===t?T(.6,.8):y.fill.bleed_strength;for(let o=0;o<n;o++){const x=e[o],p=e[o+1<n?o+1:0],y=r[o],v=i[o];t<997&&(d=y);const b=(v?c:-c)+5*T(-1,1),_=H(b),w=U(b),R=p.x-x.x,S=p.y-x.y,M=_*R+w*S,E=_*S-w*R,A=h[~~(T(0,1)*u)]*T(.65,1.35)*d;s[g]=x,a[g]=y,l[g]=v,g++,s[g]={x:x.x+.5*R+M*A,y:x.y+.5*S+E*A},a[g]=y+f[~~(T(0,1)*m)],l[g]=v,g++}let x=s,p=a,v=l,b=1024/y.fill.texture_strength;if(b&&g>b){const t=Math.ceil(g/b);x=[],p=[],v=[];for(let e=0;e<g;e+=t)x.push(s[e]),p.push(a[e]),v.push(l[e])}else x.length=g,p.length=g,v.length=g;return new Ze(x,p,this.midP,v,!1,this.sizeX,this.sizeY)}fill(t,i,n){const s=3*n,a=2*i*(1+n/2),l=!1!==b.isBrush;b.isBrush=!1,l&&(b.justChanged=!0),b.blend(t),b.ctx.save(),b.ctx.setTransform(o*et(),o*rt(),o*it(),o*nt(),o*(Q()+e/2),o*(tt()+r/2)),b.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*y.fill.border_strength})`,b.ctx.lineCap="round";const c=Math.max(this.sizeX,this.sizeY),h=T(.15,.7);let u=this.grow();const f=this.scatter(.1).grow().scatter(.75).flipDirs();let m;for(let e=0;e<20;e++){e%4==0&&(u=u.grow()),e%2==0&&(m=[u.grow(1-.0125*e),u.grow(.7-.0125*e),u.grow(.4-.0125*e)]);for(const r of m)r.grow(999).grow(997).layer(e,c,a,t);f.grow(999).flipDirs().grow(997).layer(e,c,1.5*a*s,t),e%2==0&&u.grow(h).grow(999).layer(e,c,2*a,t),e%5!=0&&19!==e||(0!==s&&u.erase(3*s,i),b.blend(t,!0,!1,!0))}b.ctx.restore()}layer(t,e,r,i){b.ctx.lineWidth=D(t,0,24,e/25,e/30,!0),b.ctx.fillStyle=`rgb(${i._getRed()} ${i._getGreen()} ${i._getBlue()} / ${r}%)`,function(t){const e=b.ctx,r=e.getTransform();let i=Infinity,n=Infinity,o=-Infinity,s=-Infinity;e.beginPath(),t.forEach((t,a)=>{const l=Xe(r,t.x,t.y);i=Math.min(i,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),s=Math.max(s,l.y),0===a?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.closePath();const a=De(e,r);b.markDirtyRect(b.mask,{minX:i-a,minY:n-a,maxX:o+a,maxY:s+a})}(this.v),b.ctx.fill(),b.ctx.stroke()}erase(t,e){b.ctx.save();const r=~~(T(80,110)*D(t,0,1,2,3.5)),i=this.sizeX/1.3,n=this.sizeY/1.3,o=Math.min(this.sizeX,this.sizeY)*(1.4-y.fill.bleed_strength),s=.05*o,a=.4*o,{x:l,y:c}=this.midP;b.ctx.globalCompositeOperation="destination-out";const h=(5-D(e,80,100,.3,.7,!0))*t/255;b.ctx.fillStyle=`rgb(255 0 0 / ${h})`,b.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+z(0,i),r=c+z(0,n),o=T(s,a);b.ctx.beginPath(),Oe(e,r,o),t%5!=0&&b.ctx.fill()}b.ctx.globalCompositeOperation="source-over",b.ctx.restore()}}bt.prototype.fill=function(t=!1,e,r,i,n,o){let s=Be();t&&(Fe(t,e),Ge(r,o),$e(i,n)),s.isActive&&(st(),function(t){if(!y.fill.isActive||!y.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");We=t;const e=[...t.vertices],r=~~(.25*e.length*X({1:5,2:10,3:60})),i=y.fill.bleed_strength,n=e.map((t,e)=>(e>r?1:.3)*T(.85,1.2)*i),o=Y(0,e.length),s=[...e.slice(o),...e.slice(0,o)],a=function(t){if(t.length<8)return t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0}).map(e=>e/t.length);const e=[...t];e[0].x===e[e.length-1].x&&e[0].y===e[e.length-1].y||e.push(e[0]);let r=0,i=0,n=0;for(let t=0;t<e.length-1;t++){const o=e[t].x*e[t+1].y-e[t+1].x*e[t].y;r+=o,i+=(e[t].x+e[t+1].x)*o,n+=(e[t].y+e[t+1].y)*o}return r*=.5,r?{x:i/(6*r),y:n/(6*r)}:{x:e[0].x,y:e[0].y}}(s);new Ze(s,n,a,[],!0).fill(y.fill.color,D(y.fill.opacity,0,255,0,1,!0),y.fill.texture_strength)}(this)),(t=>{y.fill={...t}})(s)},_t.prototype.fill=function(t,e,r){Be().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,D(y.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const Ve=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>b.blend(!1,!0),r.postdraw=()=>b.blend(!1,!0);const i=e.push,n=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){i.call(this),st(),Ve.push({fill:{...y.fill},stroke:{...y.stroke},hatch:{...y.hatch},field:{...y.field}})},e.pop=function(){n.call(this),function(){const t=Ve.pop();t&&(y.stroke={...t.stroke},y.field={...t.field},y.hatch={...t.hatch},y.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{k=A(t);for(const t of I)t()})(t)},e.noiseSeed=function(t){s.call(this,t),(t=>{L=E(A(t))})(t)}}),t.Plot=_t,t.Polygon=bt,t.Position=at,t.add=le,t.addField=yt,t.arc=function(t,e,r,i,n){const o=Z(i),s=((Z(n)-o)%360+360)%360;if(0===s)return;const a=new _t("curve"),l=Math.max(1,Math.ceil(s/90)),c=s/l,h=Math.PI*r*c/180;for(let t=0;t<l;t++)a.addSegment(o+t*c+90,h,1,!0);a.endPlot(o+s+90,1,!0);const u=t+r*H(o),f=e-r*U(o);a.draw(u,f,1)},t.beginShape=At,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Mt=[e,r],St=new _t(t)},t.box=function(){return[...ie.keys()]},t.circle=function(t,e,r,i=!1){const n=new _t("curve"),o=Math.PI*r,s=T(0,360),a=i?()=>1+.2*i*T():()=>1;for(let t=0;t<4;t++){const e=-90*t+s;n.addSegment(e*a(),o/2*a(),1,!0)}if(i){const t=i*Y(-5,5);n.addSegment(s,Math.abs(t)*(Math.PI/180)*r,1,!0),n.endPlot(t+s,1,!0)}else n.endPlot(s,1,!0);const l=t-r*U(s),c=e-r*H(-s);n.show(l,c,1)},t.clip=function(t){p();const e=function(t){const e=t.a*t.d-t.b*t.c;return Math.abs(e)<1e-12?null:{a:t.d/e,b:-t.b/e,c:-t.c/e,d:t.a/e,tx:(t.c*t.ty-t.d*t.tx)/e,ty:(t.b*t.tx-t.a*t.ty)/e}}(me());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");y.stroke.clipWindow={bounds:de(t),inverse:e}},t.endShape=kt,t.endStroke=function(t,e){if(!St)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");St.endPlot(t,e),St.draw(Mt[0],Mt[1],1),St=!1},t.field=pt,t.fill=Fe,t.fillBleed=Ge,t.fillTexture=$e,t.flowLine=function(t,e,r,i){if(!y.stroke.isActive||!y.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");st(),ye(t,e,r),be(j(i),!1)},t.hatch=Ne,t.hatchArray=Ye,t.hatchStyle=function(t,e="black",r=1){y.hatch.hBrush={brush:t,color:e,weight:r}},t.instance=t=>{x=!0,i=t},t.line=ke,t.listFields=function(){return st(),Array.from(mt.keys())},t.load=g,t.move=function(t,e,r){if(!St)throw new Error("move() called without beginStroke(). Call beginStroke() first.");St.addSegment(t,e,r)},t.noClip=function(){y.stroke.clipWindow=null},t.noField=function(){st(),y.field.isActive=!1},t.noFill=function(){y.fill.isActive=!1},t.noHatch=function(){y.hatch.isActive=!1,y.hatch.hBrush=!1},t.noStroke=function(){y.stroke.isActive=!1},t.pick=ce,t.polygon=function(t){new bt(t).show()},t.rect=function(t,e,r,i,n="corner"){"center"===n&&(t-=r/2,e-=i/2),At(0),Pt(t,e),Pt(t+r,e),Pt(t+r,e+i),Pt(t,e+i),kt(!0)},t.refreshField=function(t=0){if(!y.field.isActive||!y.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=mt.get(y.field.current);e.field=xt(e,t)},t.scaleBrushes=function(t){for(const{param:e}of ie.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.set=fe,t.spline=function(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");It(t,e).draw()},t.stroke=he,t.strokeWeight=ue,t.vertex=Pt,t.wRand=X,t.wiggle=function(t=1){pt("hand"),y.field.wiggle=t}},"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).brush={});
+var t,e;t=this,e=function(t){let e,r,n,i,o;const a={enabled:!1,stats:new Map,timer:null},s=()=>globalThis.performance?.now?.()??Date.now(),l=(t,e)=>{if(!a.enabled)return e();const r=s();try{return e()}finally{const e=a.stats.get(t)??{total:0,count:0};e.total+=s()-r,e.count+=1,a.stats.set(t,e),a.timer&&clearTimeout(a.timer),a.timer=setTimeout(()=>{const t=[...a.stats.entries()].map(([t,e])=>({operation:t,total_ms:e.total.toFixed(2),count:e.count,avg_ms:(e.total/e.count).toFixed(4)})).sort((t,e)=>Number(e.total_ms)-Number(t.total_ms));console.log(`[p5.brush composite profile] entries=${t.length}`),console.table(t)},300)}},c=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,h=()=>y?n:window.self.p5.instance,u=()=>i&&i._renderer&&"function"==typeof i._renderer.activeFramebuffer?i._renderer.activeFramebuffer():null,f=()=>({width:Math.max(1,Math.round(e*o)),height:Math.max(1,Math.round(r*o))}),d=t=>{if(!t)return null;const{width:e,height:r}=f(),n=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),i=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),o=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),a=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return o<=n||a<=i?null:{minX:n,minY:i,maxX:o,maxY:a}},m=()=>{const{width:t,height:e}=f();return{minX:0,minY:0,maxX:t,maxY:e}},g=(t,e,r)=>{const n=(t=>{const e=d(t);if(!e)return null;const{height:r}=f();return{x:e.minX,y:r-e.maxY,width:e.maxX-e.minX,height:e.maxY-e.minY}})(e);if(!n)return!1;t.enable(t.SCISSOR_TEST),t.scissor(n.x,n.y,n.width,n.height);try{r()}finally{t.disable(t.SCISSOR_TEST)}return!0},p=(t=!1)=>{const o=((t=!1)=>{if(y&&!t)return{renderer:n,width:n.width,height:n.height};if(!t){const t=h();return{renderer:t,width:t.width,height:t.height}}if(c(t)){if(!c(e=t)||e.renderer._pInst!==h())throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch");return{renderer:h(),width:t.width,height:t.height}}var e;return{renderer:t,width:t.width,height:t.height}})(t);if(i=o.renderer,"webgl2"!==i.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");e=o.width,r=o.height,x=!0,i.loaded&&w.load()};let x=!1,y=!1;const _=()=>{x||p()},b={},v=()=>{i?.loaded||(_(),w.load())},w={isBlending:!1,cachedColor:new Object,markDirtyRect(t,e){const r=d(e);var n,i;t&&r&&(t.dirtyRect=(i=r,(n=t.dirtyRect)?i?{minX:Math.min(n.minX,i.minX),minY:Math.min(n.minY,i.minY),maxX:Math.max(n.maxX,i.maxX),maxY:Math.max(n.maxY,i.maxY)}:n:i),t.isDrawn=!0)},clearMask(t){t&&(t.clear(),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:(t,e)=>t?t.dirtyRect?e&&u()?m():d(((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)):m():null,captureBlendSource(t){const n=u();if(!n)return i._renderer;const a=i.blendSourceFramebuffer;return(!a||a.width!==e||a.height!==r||"function"==typeof a.pixelDensity&&a.pixelDensity()!==o)&&(a?.remove&&a.remove(),i.blendSourceFramebuffer=i.createFramebuffer({width:e,height:r,density:o,antialias:!1,depth:!1,stencil:!1})),i.blendSourceFramebuffer.draw(()=>{g(i.drawingContext,t,()=>{i.clear(),i.push(),"function"==typeof i.imageMode&&i.imageMode(i.CENTER??i._renderer?._pInst?.CENTER),i.image(n,0,0,e,r),i.pop()})}),i.blendSourceFramebuffer},load(){a.enabled="undefined"!=typeof window&&(null!=window.__P5_BRUSH_COMPOSITE_PROFILE__?!!window.__P5_BRUSH_COMPOSITE_PROFILE__:"on"===new URLSearchParams(window.location.search).get("compositeProfile"));const t="function"==typeof i.createGraphics?i:i._pInst,n=!i.mask||!i.glMask||i.mask.width!==e||i.mask.height!==r||i.glMask.width!==e||i.glMask.height!==r;o=i.pixelDensity();const s=t.P2D??i.P2D,l=t.WEBGL??i.WEBGL;i.loaded&&!n||(i.mask?.remove&&i.mask.remove(),i.glMask?.remove&&i.glMask.remove(),i.mask=t.createGraphics(e,r,s),i.glMask=t.createGraphics(e,r,l),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.glMask=i.glMask,this.ctx=this.mask.drawingContext,this.mask.pixelDensity(o),this.mask.angleMode(i.DEGREES),this.mask.dirtyRect??=null,this.mask.noSmooth(),this.mask.isDrawn??=!1,this.glMask.pixelDensity(o),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,n=r?this.glMask:this.mask,i=r?this.mask:this.glMask,o=t?._array,a=!!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||a)&&(this.justChanged&&(this.applyShader(i,!r),this.justChanged=!1),this.isBlending&&this.applyShader(n,r),o&&(this.cachedColor=o),e&&(this.isBlending=!1))},applyShader(t,n){if(!t?.isDrawn)return;const o=n?"brush":"fill";l(`${o}.applyShader`,()=>{n&&"function"==typeof t.drawingContext?.flush&&l(`${o}.flushMask`,()=>t.drawingContext.flush());const a=l(`${o}.getCompositeRect`,()=>this.getCompositeRect(t,n));if(!a)return void l(`${o}.clearMask`,()=>this.clearMask(t));const s=i.drawingContext,c=i.shaderProgram,h=l(`${o}.captureSource`,()=>this.captureBlendSource(a)),f=!!u(),d=s.getParameter(s.DEPTH_TEST);s.disable(s.DEPTH_TEST),l(`${o}.shaderPass`,()=>{i.push(),i.translate(0,0),i.shader(c),c.setUniform("u_source",h),c.setUniform("u_isBrush",n),c.setUniform("u_flipOutputY",f),c.setUniform("u_mask",t),c.setUniform("u_color",this.cachedColor),g(s,a,()=>{i.fill(0,0,0,0),i.noStroke(),i.rect(-e/2,-r/2,e,r)}),i.pop()}),i.resetShader(),d&&s.enable(s.DEPTH_TEST),l(`${o}.clearMask`,()=>this.clearMask(t))})}},R=Math.sqrt(3),E=.5*(R-1),A=(3-R)/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 P(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 n=r+~~(t()*(256-r)),i=e[r];e[r]=e[n],e[n]=i}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]),n=new Float64Array(e).map(t=>S[t%12*2+1]);return function(t,i){let o=0,a=0,s=0;const l=(t+i)*E,c=M(t+l),h=M(i+l),u=(c+h)*A,f=t-(c-u),d=i-(h-u);let m,g;f>d?(m=1,g=0):(m=0,g=1);const p=f-m+A,x=d-g+A,y=f-1+2*A,_=d-1+2*A,b=255&c,v=255&h;let w=.5-f*f-d*d;if(w>=0){const t=b+e[v];w*=w,o=w*w*(r[t]*f+n[t]*d)}let R=.5-p*p-x*x;if(R>=0){const t=b+m+e[v+g];R*=R,a=R*R*(r[t]*p+n[t]*x)}let S=.5-y*y-_*_;if(S>=0){const t=b+1+e[v+1];S*=S,s=S*S*(r[t]*y+n[t]*_)}return 70*(o+a+s)}}function T(t,e){let r=new k(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class k{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 n=.02519603282416938*e;e=n>>>0,n-=e,n*=e,e=n>>>0,n-=e,e+=4294967296*n}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:n}=this,i=2091639*e+2.3283064365386963e-10*t;return this.s0=r,this.s1=n,this.s2=i-(this.c=0|i)}copy(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}}let L=T(Math.random());const I=[],C=t=>I.push(t);let F=P(T(Math.random()));const D=(t=0,e=1)=>t+L()*(e-t),N=t=>t[~~(L()*t.length)],B=(t,e)=>~~D(t,e),Y=(t=0,e=1)=>{const r=1-L(),n=L();return Math.sqrt(-2*Math.log(r))*W(360*n)*e+t},z=t=>{let e=0;const r=[];for(const n in t)e+=t[n],r.push({key:n,cumulative:e});const n=L()*e;for(const{key:t,cumulative:e}of r)if(n<e)return isNaN(t)?t:parseInt(t)},O=(t,e,r,n,i,o=!1)=>{let a=n+(t-e)/(r-e)*(i-n);return o?n<i?X(a,n,i):X(a,i,n):a},X=(t,e,r)=>Math.max(Math.min(t,r),e),U=t=>(t%=360)<0?t+360:t,G=1440,$=2*Math.PI/G,V=new Float32Array(G).fill(NaN),H=new Float32Array(G).fill(NaN),W=t=>{const e=~~(4*U(t));let r=V[e];return isNaN(r)&&(r=Math.cos(e*$),V[e]=r),r},j=t=>{const e=~~(4*U(t));let r=H[e];return isNaN(r)&&(r=Math.sin(e*$),H[e]=r),r},K=(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,q=(t,e,r,n,i)=>{let o=W(i),a=j(i);return{x:o*(r-t)+a*(n-e)+t,y:o*(n-e)-a*(r-t)+e}},J=(t,e,r,n)=>Math.hypot(r-t,n-e),Q=(t,e,r,n)=>K(Math.atan2(-(n-e),r-t),!0),tt=(t,e,r,n,i=!1)=>{let o=t.x,a=t.y,s=e.x,l=e.y,c=r.x,h=r.y,u=n.x,f=n.y;if(o===s&&a===l||c===u&&h===f)return!1;let d=s-o,m=l-a,g=u-c,p=f-h,x=p*d-g*m;if(0===x)return!1;let y=(g*(a-h)-p*(o-c))/x,_=(d*(a-h)-m*(o-c))/x;return!(!i&&(_<0||_>1))&&{x:o+y*d,y:a+y*m}},et=()=>i._renderer.uModelMatrix.mat4[12],rt=()=>i._renderer.uModelMatrix.mat4[13],nt=()=>i._renderer.uModelMatrix.mat4[0],it=()=>i._renderer.uModelMatrix.mat4[1],ot=()=>i._renderer.uModelMatrix.mat4[4],at=()=>i._renderer.uModelMatrix.mat4[5];let st=!1;function lt(){st||(v(),ht=.01*e,ut=-.5*e,ft=-.5*r,dt=Math.round(2*e/ht),mt=Math.round(2*r/ht),bt("hand",(t,e)=>{const r=D(.2,.8),n=B(5,10);return vt(e,(e,i)=>.5*n*j(r*i*e+B(15,25))*.2*W(t)+F(e,i)*n*.7)}),bt("curved",(t,e)=>{let r=B(-10,10);return B(0,100)%2==0&&(r*=-1),vt(e,(e,n)=>3*O(F(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),bt("zigzag",(t,e)=>{let r=B(-30,-15)+Math.abs(44*j(t));B(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t<dt;t++){for(let r=0;r<mt;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),bt("waves",(t,e)=>{const r=B(10,15)+5*j(t),n=B(3,6)+3*W(t),i=B(20,35);return vt(e,(t,e)=>j(r*t)*i*W(e*n)+B(-3,3))}),bt("seabed",(t,e)=>{const r=D(.4,.8),n=B(18,26);return vt(e,(e,i)=>1.1*n*j(r*i*e+B(15,20))*W(t))}),bt("spiral",(t,e)=>{const r=B(5,10),n=2*B(0,2)-1,i=B(65,80),o=Array.from({length:r},()=>({x:D(.1,.9)*dt,y:D(.1,.9)*mt}));return vt(e,(t,e)=>{let r=0,a=0;for(const s of o){const o=t-s.x,l=e-s.y,c=1/(o*o+l*l+1),h=Math.atan2(l,o)*(180/Math.PI),u=n*(h+i)*Math.PI/180;r+=c*Math.cos(u),a+=c*Math.sin(u)}return Math.atan2(a,r)*(180/Math.PI)})}),bt("columns",(t,e)=>{const r=B(3,8),n=B(25,45);return vt(e,(t,e)=>j(t*r)*n)}),st=!0)}class ct{constructor(t,e){lt(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=ct.getColIndex(t),this.rowIdx=ct.getRowIndex(e)}reset(){this.plotted=0}isIn(){return b.field.isActive?ct.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,n=r,i=this.x+et(),o=this.y+rt();return i>=-.3*t&&i<=1.3*t&&o>=-.3*n&&o<=1.3*n}angle(){return this.isIn()&&b.field.isActive?gt.get(b.field.current).field[this.colIdx][this.rowIdx]*b.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,n=1){this.movePos(t,e,r,n)}movePos(t,e,r,n=!1){const i=n||1;if(this.isIn())for(let o=0;o<e/r;o++){const e=this.angle()-(n?t.angle(this.plotted):t);this.update(this.x+r*W(e),this.y+r*j(e)),this.plotted+=r/i}else this.plotted+=r/i}static getRowIndex(t,e=1){const r=t+rt()-ft;return Math.round(r/ht/e)}static getColIndex(t,e=1){const r=t+et()-ut;return Math.round(r/ht/e)}static isIn(t,e){return t>=0&&e>=0&&t<dt&&e<mt}}b.field={isActive:!1,current:null,wiggle:1};let ht,ut,ft,dt,mt,gt=new Map;const pt=new Set(["degrees","radians"]);function xt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!pt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function yt(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(dt).fill(null).map(()=>new Float32Array(mt))),t.angleMode)}function _t(t){if(b.field.wiggle||(b.field.wiggle=1),lt(),!gt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(gt.keys()).join(", ")}.`);b.field.isActive=!0,b.field.current=t;const e=gt.get(t);e.field||(e.field=yt(e,0))}function bt(t,e,r={}){gt.set(t,{gen:e,field:null,angleMode:xt(r)})}function vt(t,e){for(let r=0;r<dt;r++)for(let n=0;n<mt;n++)t[r][n]=e(r,n);return t}class wt{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,n]of this.sides){const i=tt(t.point1,t.point2,e,n);i&&r.push(i)}return this._intersectionCache[e]=r,r}show(){b.stroke&&this.draw(),b.hatch&&this.hatch(),b.fill&&this.fill()}}class Rt{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,n=!1){this.angles.length>0&&this.angles.pop(),t=n?(t%360+360)%360:K(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:K(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=K(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],n=t[this.index+1]??r;return Math.abs(n-r)>180&&(n>r?n=-(360-n):r=-(360-r)),O(e-this.suma,0,this.segments[this.index],r,n,!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,n,i=1,o){lt();const a=.5,s=[],l=Math.round(this.length/a),c=new ct(t+e/2,n+r/2);let h=0,u=0;for(let t=0;t<l;t++){c.plotTo(this,a,a);const t=this.calcIndex(c.plotted);h+=a,(h>=Math.max(this.segments[t]*o*D(.7,1.3),10)||t>=u)&&c.x&&(s.push([c.x-e/2,c.y-r/2]),h=0,t>=u&&u++)}return new wt(s)}show(t,e,r=1){b.stroke&&this.draw(t,e,r),b.hatch&&this.hatch(t,e,r),b.fill&&this.fill(t,e,r)}}let Et,At,Mt,St;class Pt{constructor(){this.isClosed=!1,this.curvature=At,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){It(this.vert,this.curvature,this.isClosed).show()}}function Tt(t=0){At=X(t,0,1),Et=new Pt}function kt(t,e,r=1){if(!Et)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Et.vertex(t,e,r)}function Lt(t=!1){if(!Et)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(Et.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(Et.vertex(...Et.vert[0]),Et.isClosed=!0),Et.show(),Et=!1}function It(t,e=.5,r=!1){const n=new Rt(0===e?"segments":"curve"),i=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let o,a,s,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],d=J(h[0],h[1],u[0],u[1]),m=J(u[0],u[1],f[0],f[1]),g=Q(h[0],h[1],u[0],u[1]),p=Q(u[0],u[1],f[0],f[1]),x=e*Math.min(d,m,.5*Math.min(d,m)),y=Math.max(d,m),_=d-x,b=m-x;if(Math.floor(g)===Math.floor(p)){const e=r&&0===c?0:d-l,i=r?0===c?0:m-s:m;n.addSegment(g,e,h[2],!0),c===t.length-3&&n.addSegment(p,i,u[2],!0),l=0,0===c&&(o=d,s=x,a=t[1],l=0)}else{const e={x:u[0]-x*W(-g),y:u[1]-x*j(-g)},f={x:e.x+y*W(90-g),y:e.y+y*j(90-g)},d={x:u[0]+x*W(-p),y:u[1]+x*j(-p)},m={x:d.x+y*W(90-p),y:d.y+y*j(90-p)},v=tt(e,f,d,m,!0),w=J(e.x,e.y,v.x,v.y),R=J(e.x,e.y,d.x,d.y)/2,E=i*w*(2*Math.asin(R/w)*(180/Math.PI))/360,A=r&&0===c?0:_-l,M=c===t.length-3?r?o-x:b:0;n.addSegment(g,A,h[2],!0),n.addSegment(g,isNaN(E)?0:E,h[2],!0),n.addSegment(p,M,u[2],!0),l=x,0===c&&(o=_,s=x,a=[e.x,e.y])}c===t.length-3&&n.endPlot(p,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],i=J(e[0],e[1],r[0],r[1]),o=Q(e[0],e[1],r[0],r[1]);n.addSegment(o,i,r[2],!0),c===t.length-2&&n.endPlot(o,1,!0)}n.origin=r&&0!==e?a:t[0]}return n}const Ct=(t,e,r)=>{const n=t.createProgram();for(let[i,o]of[[t.VERTEX_SHADER,e],[t.FRAGMENT_SHADER,r]]){const e=t.createShader(i);t.shaderSource(e,o),t.compileShader(e),t.attachShader(n,e)}return t.linkProgram(n),n};let Ft,Dt,Nt,Bt,Yt,zt,Ot=!1,Xt=0,Ut=0,Gt=null,$t=null;const Vt={},Ht={};let Wt=1,jt=0,Kt=0,Zt=1,qt=0,Jt=0,Qt=0,te=0,ee=1,re=1,ne=new Float32Array(8192),ie=0,oe=2048,ae=32768,se=null,le=null,ce=null,he=null,ue=null;const fe={},de={};let me=0,ge=new Float32Array(1280),pe=0,xe=256,ye=null;const _e=new Map,be=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function ve(t){return!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer}function we(){const t=w.glMask,e=ve(t)?t.renderer:t?._renderer;e&&(e._curShader=null,e._cachedBlendMode=null,e._isBlending=null,Ft.activeTexture(Ft.TEXTURE0),Ft.bindTexture(Ft.TEXTURE_2D,null),Ft.blendEquation(Ft.FUNC_ADD),Ft.blendFunc(Ft.ONE,Ft.ONE_MINUS_SRC_ALPHA))}function Re(t){return t?"function"==typeof t._framebufferToBind?t._framebufferToBind():t.framebuffer??null:null}function Ee(){return ve(w.glMask)?Nt:Dt}function Ae(){const t=w.glMask,e=Ft.isEnabled(Ft.DEPTH_TEST);if(Ae._hadDepthTest=e,e&&Ft.disable(Ft.DEPTH_TEST),ve(t))return $t=i._renderer.activeFramebuffer?.()??null,$t?._beforeEnd&&$t._beforeEnd(),Ft.bindFramebuffer(Ft.FRAMEBUFFER,Re(t)),void Ft.viewport(0,0,t.width*t.density,t.height*t.density);Ft.bindFramebuffer(Ft.FRAMEBUFFER,null),Ft.viewport(0,0,Ft.drawingBufferWidth,Ft.drawingBufferHeight)}function Me(){Ae._hadDepthTest&&Ft.enable(Ft.DEPTH_TEST),Ae._hadDepthTest=!1,ve(w.glMask)&&($t?._beforeBegin?$t._beforeBegin():(Ft.bindFramebuffer(Ft.FRAMEBUFFER,null),i._renderer.viewport(i._renderer._origViewport.width,i._renderer._origViewport.height),i._renderer._applyStencilTestIfClipping?.()),$t=null)}function Se(t,e,r,n,i){return t?(e<t.minX&&(t.minX=e),r<t.minY&&(t.minY=r),n>t.maxX&&(t.maxX=n),i>t.maxY&&(t.maxY=i),t):{minX:e,minY:r,maxX:n,maxY:i}}function Pe(t,e,r,n){if(ie>=oe){oe*=2;const t=new Float32Array(4*oe);t.set(ne),ne=t}const i=t-Qt,o=e-te,a=4*ie,s=Wt*i+Kt*o+qt+Qt,l=jt*i+Zt*o+Jt+te,c=re*r*ee/2;ne[a]=s,ne[a+1]=l,ne[a+2]=c,ne[a+3]=n/255;const h=s*re,u=l*re;se=Se(se,h-c-1,u-c-1,h+c+1,u+c+1),ie++}function Te(t,e){if(0===pe)return;w.glMask.isDrawn=!0,Ae();let r=_e.get(e);r||(r=Ft.createTexture(),Ft.bindTexture(Ft.TEXTURE_2D,r),Ft.texImage2D(Ft.TEXTURE_2D,0,Ft.RGBA,Ft.RGBA,Ft.UNSIGNED_BYTE,t.canvas),Ft.texParameteri(Ft.TEXTURE_2D,Ft.TEXTURE_MIN_FILTER,Ft.LINEAR),Ft.texParameteri(Ft.TEXTURE_2D,Ft.TEXTURE_MAG_FILTER,Ft.LINEAR),Ft.texParameteri(Ft.TEXTURE_2D,Ft.TEXTURE_WRAP_S,Ft.CLAMP_TO_EDGE),Ft.texParameteri(Ft.TEXTURE_2D,Ft.TEXTURE_WRAP_T,Ft.CLAMP_TO_EDGE),_e.set(e,r)),Ft.useProgram(le),Ft.enable(Ft.BLEND),Ft.blendFunc(Ft.ONE_MINUS_DST_ALPHA,Ft.ONE),Ft.activeTexture(Ft.TEXTURE0),Ft.bindTexture(Ft.TEXTURE_2D,r),Ft.uniform1i(de.u_tex,0);const n=b.stroke.color._array;Ft.uniform4f(de.u_color,...n),Ft.uniformMatrix4fv(de.u_proj,!1,Ee()),Ft.bindVertexArray(ce),Ft.bindBuffer(Ft.ARRAY_BUFFER,ue);const i=5*pe*4,o=ge.subarray(0,5*pe);i>me?(Ft.bufferData(Ft.ARRAY_BUFFER,ge,Ft.DYNAMIC_DRAW),me=ge.byteLength):Ft.bufferSubData(Ft.ARRAY_BUFFER,0,o),Ft.drawArraysInstanced(Ft.TRIANGLE_STRIP,0,4,pe),Ft.flush(),Ft.bindVertexArray(null),Ft.bindTexture(Ft.TEXTURE_2D,null),Me(),ye&&(w.markDirtyRect(w.glMask,ye),ye=null),pe=0,we()}b.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let ke=new Map,Le={a:1,b:0,c:0,d:1,tx:0,ty:0};function Ie(){return i??n??window.self.p5.instance}const Ce={offset:.08,scale:.08,warp:.06,tilt:.06};function Fe(){return{...b.stroke}}function De(t){b.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)return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t,variation:{...Ce}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...Ce,...r.variation??{}}}}return"gaussian"===t.type||"gaussian"===t.mode||Array.isArray(t.curve)&&Array.isArray(t.min_max)?{...t,type:"gaussian",curve:t.curve,min_max:t.min_max}:t}if(Array.isArray(t)){const[e,r,n]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,i=Math.min(e,r,n),o=Math.max(e,r,n),a=o-i||1,[s,l,c]=[(e-i)/a,(r-i)/a,(n-i)/a];return{type:"custom",min_max:[i,o],variation:{...Ce},curve:t=>t<.5?s+(l-s)*t*2:l+(c-l)*(t-.5)*2}}}(e.pressure),"custom"===e.type){if("function"!=typeof e.tip)throw new Error(`Brush "${t}" is type "custom" but is missing a tip function.`);const r=`custom::${t}`;!function(t){const e=_e.get(t);e&&Ft&&Ft.deleteTexture(e),_e.delete(t)}(r);const n=Ie().createGraphics(500,500);return n.pixelDensity(1),n.background(255),n.noSmooth(),n.push(),n.translate(250,250),n.scale(5),n.noStroke(),e.tip(n),n.pop(),sr.imageToWhite(n),sr.tips.set(r,n),e.tipKey=r,void ke.set(t,{param:e,colors:[],buffers:[]})}if("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 sr.add(e.image.src),ke.set(t,{param:e,colors:[],buffers:[]}),sr.load()}ke.set(t,{param:e,colors:[],buffers:[]})}function Be(t){if(!ke.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...ke.keys()].join(", ")}.`);b.stroke.type=t}function Ye(t,e,r){_(),b.stroke.color=i.color(...arguments),b.stroke.isActive=!0}function ze(t){b.stroke.weight=t}function Oe(t,e,r=1){Be(t),Ye(e),ze(r)}function Xe(){return{a:nt(),b:it(),c:ot(),d:at(),tx:et(),ty:rt()}}function Ue(t){const[e,r,n,i]=t;return{minX:Math.min(e,n),minY:Math.min(r,i),maxX:Math.max(e,n),maxY:Math.max(r,i)}}let Ge,$e,Ve,He;const We={};function je(t,n,i,a=!1){Wt=nt(),jt=it(),Kt=ot(),Zt=at(),qt=et(),Jt=rt(),Qt=e/2,te=r/2,ee=Math.sqrt(Wt*Wt+jt*jt),re=o,Le=Xe(),Ge=new ct(t+e/2,n+r/2),$e=i,Ve=a,Ve&&Ve.calcIndex(0)}const Ke=[];function Ze(t,n){n||(He=t),function(){We.seed=999999*D();const{param:t}=ke.get(b.stroke.type)??{};if(!t)return;We.p=t;const{pressure:n}=t;if(We.a="custom"!==n.type?D(-1,1):0,We.b="custom"!==n.type?D(1,1.5):0,"custom"!==n.type)We.cp=D(3,3.5),We.ct=0,We.cs=1,We.ck=0;else{const t=n.variation??Ce;We.cp=D(-t.offset,t.offset),We.ct=D(-t.warp,t.warp),We.cs=D(1-t.scale,1+t.scale),We.ck=D(-t.tilt,t.tilt)}if([We.min,We.max]=n.min_max,We.noiseoffset=.03,!Ve){const t=He*Math.PI/180;We.cos=Math.cos(t),We.sin=Math.sin(t)}!function(){v(),function(){const t=i?._renderer,n=o;if(Gt&&Gt.renderer===t&&Gt.width===e&&Gt.height===r&&Gt.density===n)return w.glMask=Gt,Gt;Gt?.remove&&Gt.remove();const a=i.createFramebuffer({width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1});a.isDrawn=!1,a.dirtyRect=null,a.clear=()=>{const t=i._renderer,e=t.activeFramebuffer?.()??null;e?._beforeEnd&&e._beforeEnd(),Ft.bindFramebuffer(Ft.FRAMEBUFFER,Re(a)),Ft.viewport(0,0,a.width*a.density,a.height*a.density),Ft.clearColor(0,0,0,0),Ft.clear(Ft.COLOR_BUFFER_BIT),e?._beforeBegin?e._beforeBegin():(Ft.bindFramebuffer(Ft.FRAMEBUFFER,null),t.viewport(t._origViewport.width,t._origViewport.height),t._applyStencilTestIfClipping?.())},Gt=a,w.glMask=Gt}();const t=i.drawingContext,n=!Ot||Ft!==t;(n||Xt!==e||Ut!==r)&&(Dt=new Float32Array([2/e,0,0,0,0,-2/r,0,0,0,0,1,0,-1,1,0,1]),Nt=new Float32Array([2/e,0,0,0,0,2/r,0,0,0,0,1,0,-1,-1,0,1]),Xt=e,Ut=r),n&&(Ft=t,zt=Ct(Ft,"#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;}","#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);}"),Ft.useProgram(zt),Ft.enable(Ft.BLEND),Ft.blendFunc(Ft.ONE_MINUS_DST_ALPHA,Ft.ONE),["a_position","a_radius","a_alpha"].forEach(t=>Vt[t]=Ft.getAttribLocation(zt,t)),["u_matrix","u_color"].forEach(t=>Ht[t]=Ft.getUniformLocation(zt,t)),Bt=Ft.createVertexArray(),Ft.bindVertexArray(Bt),Yt=Ft.createBuffer(),Ft.bindBuffer(Ft.ARRAY_BUFFER,Yt),Ft.bufferData(Ft.ARRAY_BUFFER,ne.byteLength,Ft.DYNAMIC_DRAW),ae=ne.byteLength,Ft.enableVertexAttribArray(Vt.a_position),Ft.vertexAttribPointer(Vt.a_position,2,Ft.FLOAT,!1,16,0),Ft.enableVertexAttribArray(Vt.a_radius),Ft.vertexAttribPointer(Vt.a_radius,1,Ft.FLOAT,!1,16,8),Ft.enableVertexAttribArray(Vt.a_alpha),Ft.vertexAttribPointer(Vt.a_alpha,1,Ft.FLOAT,!1,16,12),Ft.bindVertexArray(null),_e.clear(),le=Ct(Ft,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_corner;in vec2 a_pos;in float a_size;in float a_angle;in float a_alpha;uniform mat4 u_proj;out vec2 v_uv;out float v_alpha;void main(){float c=cos(a_angle);float s=sin(a_angle);vec2 rotated=vec2(c*a_corner.x-s*a_corner.y,s*a_corner.x+c*a_corner.y);gl_Position=u_proj*vec4(a_pos+rotated*a_size,0.0,1.0);v_uv=a_corner*0.5+0.5;v_alpha=a_alpha;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin vec2 v_uv;in float v_alpha;uniform sampler2D u_tex;uniform vec4 u_color;out vec4 outColor;void main(){float inkAlpha=texture(u_tex,v_uv).a;if(inkAlpha<0.01)discard;outColor=vec4(u_color.rgb,inkAlpha*v_alpha);}"),["a_corner","a_pos","a_size","a_angle","a_alpha"].forEach(t=>fe[t]=Ft.getAttribLocation(le,t)),["u_proj","u_color","u_tex"].forEach(t=>de[t]=Ft.getUniformLocation(le,t)),ce=Ft.createVertexArray(),Ft.bindVertexArray(ce),he=Ft.createBuffer(),Ft.bindBuffer(Ft.ARRAY_BUFFER,he),Ft.bufferData(Ft.ARRAY_BUFFER,be,Ft.STATIC_DRAW),Ft.enableVertexAttribArray(fe.a_corner),Ft.vertexAttribPointer(fe.a_corner,2,Ft.FLOAT,!1,0,0),ue=Ft.createBuffer(),Ft.bindBuffer(Ft.ARRAY_BUFFER,ue),Ft.bufferData(Ft.ARRAY_BUFFER,ge.byteLength,Ft.DYNAMIC_DRAW),me=ge.byteLength,Ft.enableVertexAttribArray(fe.a_pos),Ft.vertexAttribPointer(fe.a_pos,2,Ft.FLOAT,!1,20,0),Ft.vertexAttribDivisor(fe.a_pos,1),Ft.enableVertexAttribArray(fe.a_size),Ft.vertexAttribPointer(fe.a_size,1,Ft.FLOAT,!1,20,8),Ft.vertexAttribDivisor(fe.a_size,1),Ft.enableVertexAttribArray(fe.a_angle),Ft.vertexAttribPointer(fe.a_angle,1,Ft.FLOAT,!1,20,12),Ft.vertexAttribDivisor(fe.a_angle,1),Ft.enableVertexAttribArray(fe.a_alpha),Ft.vertexAttribPointer(fe.a_alpha,1,Ft.FLOAT,!1,20,16),Ft.vertexAttribDivisor(fe.a_alpha,1),Ft.bindVertexArray(null),Ot=!0)}();const a=!0!==w.isBrush;w.isBrush=!0,a&&(w.justChanged=!0),w.blend(b.stroke.color),We.alpha=["default","spray"].includes(We.p.type)?We.p.opacity:We.p.opacity/Math.min(b.stroke.weight,1.3);{const t=e/2,n=r/2,i=Le;if(b.stroke.clipWindow){const{inverse:e,bounds:r}=b.stroke.clipWindow,o=e.a*i.a+e.c*i.b,a=e.a*i.c+e.c*i.d,s=e.b*i.a+e.d*i.b,l=e.b*i.c+e.d*i.d;We.clipA=o,We.clipB=s,We.clipC=a,We.clipD=l,We.clipTX=e.a*i.tx+e.c*i.ty+e.tx-o*t-a*n,We.clipTY=e.b*i.tx+e.d*i.ty+e.ty-s*t-l*n,We.clipMinX=r.minX,We.clipMaxX=r.maxX,We.clipMinY=r.minY,We.clipMaxY=r.maxY}else{const r=.05*e;We.clipA=i.a,We.clipB=i.b,We.clipC=i.c,We.clipD=i.d,We.clipTX=i.tx-i.a*t-i.c*n,We.clipTY=i.ty-i.b*t-i.d*n,We.clipMinX=-t-r,We.clipMaxX=t+r,We.clipMinY=-n-r,We.clipMaxY=n+r}}nr()}();const a=function(){const{param:t}=ke.get(b.stroke.type)??{};return t?t.spacing:1}(),s=Math.round($e*(n?t:1)/a);for(let e=0;e<s;e++)Ke.length<2*s&&Ke.push(Y()),qe(),n?Ge.plotTo(Ve,a,a,t,e<10):Ge._moveToDegrees(t,a,a);!function(){nr(),function(){if(0===ie)return;w.glMask.isDrawn=!0,Ae();const t=b.stroke.color._array;Ft.useProgram(zt),Ft.enable(Ft.BLEND),Ft.blendFunc(Ft.ONE_MINUS_DST_ALPHA,Ft.ONE),Ft.bindVertexArray(Bt),Ft.bindBuffer(Ft.ARRAY_BUFFER,Yt);const e=16*ie,r=ne.subarray(0,4*ie);e>ae?(Ft.bufferData(Ft.ARRAY_BUFFER,ne,Ft.DYNAMIC_DRAW),ae=ne.byteLength):Ft.bufferSubData(Ft.ARRAY_BUFFER,0,r),Ft.uniform4f(Ht.u_color,...t),Ft.uniformMatrix4fv(Ht.u_matrix,!1,Ee()),Ft.drawArrays(Ft.POINTS,0,ie),Ft.flush(),Ft.bindVertexArray(null),Me(),se&&(w.markDirtyRect(w.glMask,se),se=null),ie=0,we()}();const t=We.p?.type;"image"===t?Te(sr.tips.get(We.p.image.src),We.p.image.src):"custom"===t&&Te(sr.tips.get(We.p.tipKey),We.p.tipKey)}()}function qe(){if(!tr())return;const t=Je(),e=O(F(We.seed+.002*Ge.plotted,0),0,1,1-We.noiseoffset,1+We.noiseoffset);switch(We.p.type){case"spray":!function(t){const e=b.stroke.weight*We.p.scatter*t+b.stroke.weight*N(Ke)*We.p.scatter/3,r=We.p.weight*D(.9,1.1),n=Math.ceil(We.p.grain/t);for(let t=0;t<n;t++){const t=D(.9,1.1),n=t*e*D(-1,1),i=D(-1,1),o=Math.sqrt((t*e)**2-n**2);Pe(Ge.x+n,Ge.y+i*o,r,We.alpha)}}(t*e);break;case"marker":er(t*e);break;case"custom":case"image":rr(t*e);break;default:!function(t,e=1){const r=(e=O(e,0,1,.9,1.05))*b.stroke.weight*We.p.scatter*(We.p.sharpness+(1-We.p.sharpness)*N(Ke)/t);if(D(0,We.p.grain*t)>.4){let e,n;if(Ve)e=.7*r*D(-1,1),n=r*D(-1,1);else{const t=r*D(-1,1),i=.3*r*D(-1,1);e=t*-We.sin+i*We.cos,n=t*We.cos+i*We.sin}const i=t*t*We.p.weight*D(.85,1.15)*b.stroke.weight,o=Math.max(.9,t)*We.alpha*D(.75,1.1);Pe(Ge.x+e,Ge.y+n,i,o)}}(t*e)}}function Je(){return Ve?Qe()*Ve.pressure(Ge.plotted):Qe()}function Qe(){return"custom"===We.p.pressure.type?O(We.p.pressure.curve(Math.max(0,Math.min(1,.5+(Ge.plotted/$e-.5+We.ct)*We.cs)))+We.cp+We.ck*(Ge.plotted/$e-.5),0,1,We.min,We.max,!0):function(t=.5+We.p.pressure.curve[0]*We.a,e=1-We.p.pressure.curve[1]*We.b,r=We.cp,n=We.min,i=We.max){const o=t*$e,a=(Ge.plotted<o?1.2*e:.8*e)*($e/2);return O(1/(1+Math.pow(Math.abs((Ge.plotted-o)/a),2*r)),0,1,n,i)}()}function tr(){const t=We.clipA*Ge.x+We.clipC*Ge.y+We.clipTX;if(t<We.clipMinX||t>We.clipMaxX)return!1;const e=We.clipB*Ge.x+We.clipD*Ge.y+We.clipTY;return e>=We.clipMinY&&e<=We.clipMaxY}function er(t,e=!0,r=We.alpha){const n=e?b.stroke.weight*We.p.scatter:0,i=e?n*D(-1,1):0,o=e?n*D(-1,1):0;Pe(Ge.x+i,Ge.y+o,b.stroke.weight*We.p.weight*t,r*Math.max(.8,t)*D(.9,1.1))}function rr(t,e=We.alpha){const r=b.stroke.weight*We.p.scatter,n=r*D(-1,1),i=r*D(-1,1),o=We.p.weight*b.stroke.weight*t;let a=0;"random"===We.p.rotate?a=B(0,360)*(Math.PI/180):"natural"===We.p.rotate&&(a=((Ve?-Ve.angle(Ge.plotted):-He)+Ge.angle())*(Math.PI/180)),function(t,e,r,n,i){if(pe>=xe){xe*=2;const t=new Float32Array(5*xe);t.set(ge),ge=t}const o=t-Qt,a=e-te,s=Wt*o+Kt*a+qt+Qt,l=jt*o+Zt*a+Jt+te,c=re*r*ee/2,h=5*pe;ge[h]=s,ge[h+1]=l,ge[h+2]=c,ge[h+3]=n,ge[h+4]=i/255;const u=s*re,f=l*re;ye=Se(ye,u-1.42*c-1,f-1.42*c-1,u+1.42*c+1,f+1.42*c+1),pe++}(Ge.x+n,Ge.y+i,o,a,e*Math.max(.8,t)*D(.9,1.1))}function nr(){if(tr()){let t=Je(),e=We.alpha;if("marker"===We.p.type)for(let r=1;r<10;r++)er(t*r/10,!0,8*e);else if("custom"===We.p.type||"image"===We.p.type)for(let r=1;r<5;r++)rr(t*r/10,2*e)}}function ir(t,e,r,n){if(!b.stroke.isActive||!b.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");lt();let i=J(t,e,r,n);0!=i&&(je(t,e,i),Ze(Q(t,e,r,n),!1))}C(()=>{Ke.length=0});const or=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],ar=[["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 ar){let e={};for(let r=0;r<t[1].length;r++)e[or[r]]=t[1][r];Ne(t[0],e)}wt.prototype.draw=function(t=!1,e,r){let n=Fe();if(t&&Oe(t,e,r),n.isActive)for(let t of this.sides)ir(t[0].x,t[0].y,t[1].x,t[1].y);De(n)},Rt.prototype.draw=function(t,e,r){Fe().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,n){lt(),je(e,r,t.length,t),Ze(n,!0)}(this,t,e,r))};const sr={tips:new Map,add(t){this.tips.has(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=Ie().createImage(n.naturalWidth,n.naturalHeight);r.drawingContext.drawImage(n,0,0),sr.imageToWhite(r),this.tips.set(t,r),e()},n.onerror=()=>r(new Error(`Failed to load image tip: ${t}`)),n.crossOrigin="anonymous",n.src=t})))}};function lr(){return{...b.hatch}}function cr(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=b.hatch;n.isActive=!0,n.dist=t,n.angle=Z(e),n.options=r}function hr(t,e,r,n){const i=e*Math.PI/180,o=Math.cos(i),a=Math.sin(i),s=Math.cos(-i),l=Math.sin(-i),c=t.a,h=c.length,u=new Array(h);let f=Infinity,d=-Infinity;for(let t=0;t<h;t++){const e=c[t][0],r=c[t][1],n=[e*o-r*a,e*a+r*o];u[t]=n,n[1]<f&&(f=n[1]),n[1]>d&&(d=n[1])}const m=[];for(let t=0;t<h;t++){const e=u[t],r=u[(t+1)%h];e[1]!==r[1]&&m.push(e,r)}const g=m.length,p=[];let x=f+.5*r,y=r;for(;x<d;){const t=[];for(let e=0;e<g;e+=2){const r=m[e][1],n=m[e+1][1];(r<=x&&x<n||n<=x&&x<r)&&t.push(m[e][0]+(x-r)/(n-r)*(m[e+1][0]-m[e][0]))}t.sort((t,e)=>t-e);for(let e=0;e<t.length-1;e+=2)p.push({x1:t[e]*s-x*l,y1:t[e]*l+x*s,x2:t[e+1]*s-x*l,y2:t[e+1]*l+x*s});x+=y,y*=n}return p}function ur(t){const e=b.hatch.dist,r=(b.hatch.angle%180+180)%180,n=b.hatch.options,i=Fe();b.hatch.hBrush&&Oe(...Object.values(b.hatch.hBrush)),Array.isArray(t)||(t=[t]);const o=n.gradient?O(n.gradient,0,1,1,1.1,!0):1,a=[];for(const n of t)for(const t of hr(n,r,e,o))a.push(t);a.sort((t,e)=>t.x1===e.x1?t.y1-e.y1:t.x1-e.x1);const s=n.rand||0;for(let t=0;t<a.length;t++){const r=a[t];let i=r.x1,o=r.y1,l=r.x2,c=r.y2;s&&(i+=s*e*D(-1,1),o+=s*e*D(-1,1),l+=s*e*D(-1,1),c+=s*e*D(-1,1)),ir(i,o,l,c),t>0&&n.continuous&&ir(a[t-1].x2,a[t-1].y2,i,o)}De(i)}function fr(t,e,r){return{x:t.a*e+t.c*r+t.e,y:t.b*e+t.d*r+t.f}}function dr(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 mr(t,e,r){const n=2*Math.PI,i=w.ctx,o=i.getTransform(),a=r/2,s=fr(o,t,e),l=a*Math.hypot(o.a,o.c),c=a*Math.hypot(o.b,o.d),h=dr(i,o);w.markDirtyRect(w.mask,{minX:s.x-l-h,minY:s.y-c-h,maxX:s.x+l+h,maxY:s.y+c+h}),i.moveTo(t+a,e),i.arc(t,e,a,0,n)}b.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},wt.prototype.hatch=function(t=!1,e,r){let n=lr();t&&cr(t,e,r),n.isActive&&ur(this),function(t){b.hatch={...t}}(n)},Rt.prototype.hatch=function(t,e,r){lr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.25),this.pol.hatch())},b.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const gr=()=>({...b.fill});function pr(t,e,r,n){b.fill.opacity=(arguments.length<4?e:n)||150,b.fill.color=arguments.length<3?i.color(t):i.color(t,e,r),b.fill.isActive=!0}function xr(t,e="out"){b.fill.bleed_strength=X(t,0,1),b.fill.direction=e}function yr(t=.4,e=.4){b.fill.texture_strength=X(t,0,1),b.fill.border_strength=X(e,0,1)}let _r;const br=[[],[]];function vr(){for(let t=0;t<512;t++)br[0][t]=Y(.5,.2),br[1][t]=Y(0,.02)}function wr(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}C(vr);class Rr{constructor(t,e,r,n=[],i=!1,o,a){if(this.v=t,this.m=e,this.dir=n,this.midP=r,i){let e=0,n=0;const i=[];for(let o=0;o<t.length;o++){const a=Math.abs(r.x-t[o].x),s=Math.abs(r.y-t[o].y);e=Math.max(e,a),n=Math.max(n,s);const l=t[o],c=t[(o+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=q(0,0,h.x,h.y,90),f={x:l.x+h.x/2,y:l.y+h.y/2};i.push({v1:l,v2:c,ray:{point1:f,point2:{x:f.x+u.x,y:f.y+u.y}}})}this.sizeX=e,this.sizeY=n,this.dir=Array(t.length),i.forEach((t,e)=>{let r=0;for(const e of _r.intersect(t.ray))wr(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=D(-.6,.6)*e,a=D(-.6,.6)*n;this.midP={x:r.x+o,y:r.y+a}}else this.sizeX=o,this.sizeY=a}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),n=[...this.v],i=[...this.m],o=[...this.dir];return n.splice(r,e),i.splice(r,e),o.splice(r,e),{v:n,m:i,dir:o}}scatter(t=.3){const e=this.v.length,r=Math.max(3,~~(e*t)),n=[],i=e/r;for(let t=0;t<r;t++)n.push(~~(t*i+D(0,.8*i)));const o=[],a=[],s=[],l=this.midP,c=_r.sides;for(const t of n){const r=t%e;let n=this.v[r],i=0;for(const[t,e]of c){const r=t.y,o=e.y;if(r>n.y==o>n.y)continue;const a=(n.y-r)/(o-r);n.x<t.x+a*(e.x-t.x)&&i++}i%2==0&&(n={x:l.x+(n.x-l.x)*D(.3,.6),y:l.y+(n.y-l.y)*D(.3,.6)}),o.push(n),a.push(this.m[r]),s.push(!this.dir[r])}return new Rr(o,a,this.midP,s,!1,this.sizeX,this.sizeY)}flipDirs(){return new Rr(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:n}=this.trim(t),i=e.length,o=2*i,a=new Array(o),s=new Array(o),l=new Array(o),c="out"===b.fill.direction?-90:90;0===br[0].length&&vr();const h=br[0],u=h.length,f=br[1],d=f.length;let m=0,g=999===t?D(.6,.8):b.fill.bleed_strength;for(let o=0;o<i;o++){const p=e[o],x=e[o+1<i?o+1:0],y=r[o],_=n[o];t<997&&(g=y);const b=(_?c:-c)+5*D(-1,1),v=W(b),w=j(b),R=x.x-p.x,E=x.y-p.y,A=v*R+w*E,M=v*E-w*R,S=h[~~(D(0,1)*u)]*D(.65,1.35)*g;a[m]=p,s[m]=y,l[m]=_,m++,a[m]={x:p.x+.5*R+A*S,y:p.y+.5*E+M*S},s[m]=y+f[~~(D(0,1)*d)],l[m]=_,m++}let p=a,x=s,y=l;const _=1024/b.fill.texture_strength;if(_&&m>_){const t=Math.ceil(m/_);p=[],x=[],y=[];for(let e=0;e<m;e+=t)p.push(a[e]),x.push(s[e]),y.push(l[e])}else p.length=m,x.length=m,y.length=m;return new Rr(p,x,this.midP,y,!1,this.sizeX,this.sizeY)}fill(t,n,i){const a=3*i,s=2*n*(1+i/2),l=!1!==w.isBrush;w.isBrush=!1,l&&(w.justChanged=!0),w.blend(t),w.ctx.save(),w.ctx.setTransform(o*nt(),o*it(),o*ot(),o*at(),o*(et()+e/2),o*(rt()+r/2)),w.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*b.fill.border_strength})`,w.ctx.lineCap="round";const c=Math.max(this.sizeX,this.sizeY),h=D(.15,.7);let u=this.grow();const f=this.scatter(.1).grow().scatter(.75).flipDirs();let d;for(let e=0;e<20;e++){e%4==0&&(u=u.grow()),e%2==0&&(d=[u.grow(1-.0125*e),u.grow(.7-.0125*e),u.grow(.4-.0125*e)]);for(const r of d)r.grow(999).grow(997).layer(e,c,s,t);f.grow(999).flipDirs().grow(997).layer(e,c,s*a,t),e%2==0&&u.grow(h).grow(999).layer(e,c,2*s,t),e%8!=0&&19!==e||(0!==a&&u.erase(3*a,n),w.blend(t,!0,!1,!0))}w.ctx.restore()}layer(t,e,r,n){w.ctx.lineWidth=O(t,0,24,e/25,e/30,!0),w.ctx.fillStyle=`rgb(${n._getRed()} ${n._getGreen()} ${n._getBlue()} / ${r}%)`,function(t){const e=w.ctx,r=e.getTransform();let n=Infinity,i=Infinity,o=-Infinity,a=-Infinity;e.beginPath(),t.forEach((t,s)=>{const l=fr(r,t.x,t.y);n=Math.min(n,l.x),i=Math.min(i,l.y),o=Math.max(o,l.x),a=Math.max(a,l.y),0===s?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.closePath();const s=dr(e,r);w.markDirtyRect(w.mask,{minX:n-s,minY:i-s,maxX:o+s,maxY:a+s})}(this.v),w.ctx.fill(),w.ctx.stroke()}erase(t,e){w.ctx.save();const r=~~(D(80,110)*O(t,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,o=Math.min(this.sizeX,this.sizeY)*(1.4-b.fill.bleed_strength),a=.05*o,s=.4*o,{x:l,y:c}=this.midP;w.ctx.globalCompositeOperation="destination-out";const h=(5-O(e,80,100,.3,.7,!0))*t/255;w.ctx.fillStyle=`rgb(255 0 0 / ${h})`,w.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=l+Y(0,n),r=c+Y(0,i),o=D(a,s);w.ctx.beginPath(),mr(e,r,o),t%5!=0&&w.ctx.fill()}w.ctx.globalCompositeOperation="source-over",w.ctx.restore()}}wt.prototype.fill=function(t=!1,e,r,n,i,o){let a=gr();t&&(pr(t,e),xr(r,o),yr(n,i)),a.isActive&&(lt(),function(t){if(!b.fill.isActive||!b.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");_r=t;const e=[...t.vertices],r=~~(.25*e.length*z({1:5,2:10,3:60})),n=b.fill.bleed_strength,i=e.map((t,e)=>(e>r?1:.3)*D(.85,1.4)*n),o=B(0,e.length),a=[...e.slice(o),...e.slice(0,o)],s=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,n=0,i=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,n+=(e[t].x+e[t+1].x)*o,i+=(e[t].y+e[t+1].y)*o}return r*=.5,r?{x:n/(6*r),y:i/(6*r)}:{x:e[0].x,y:e[0].y}}(a);new Rr(a,i,s,[],!0).fill(b.fill.color,O(b.fill.opacity,0,255,0,1,!0),b.fill.texture_strength)}(this)),(t=>{b.fill={...t}})(a)},Rt.prototype.fill=function(t,e,r){gr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,O(b.fill.bleed_strength,0,.6,.3,.45,!0)),this.pol.fill())};const Er=[];"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.postsetup=()=>w.blend(!1,!0),r.postdraw=()=>w.blend(!1,!0);const n=e.push,i=e.pop,o=e.randomSeed,a=e.noiseSeed;e.push=function(){n.call(this),lt(),Er.push({fill:{...b.fill},stroke:{...b.stroke},hatch:{...b.hatch},field:{...b.field}})},e.pop=function(){i.call(this),function(){const t=Er.pop();t&&(b.stroke={...t.stroke},b.field={...t.field},b.hatch={...t.hatch},b.fill={...t.fill})}()},e.randomSeed=function(t){o.call(this,t),(t=>{L=T(t);for(const t of I)t()})(t)},e.noiseSeed=function(t){a.call(this,t),(t=>{F=P(T(t))})(t)}}),t.Plot=Rt,t.Polygon=wt,t.Position=ct,t.add=Ne,t.addField=bt,t.arc=function(t,e,r,n,i){const o=Z(n),a=((Z(i)-o)%360+360)%360;if(0===a)return;const s=new Rt("curve"),l=Math.max(1,Math.ceil(a/90)),c=a/l,h=Math.PI*r*c/180;for(let t=0;t<l;t++)s.addSegment(o+t*c+90,h,1,!0);s.endPlot(o+a+90,1,!0);const u=t+r*W(o),f=e-r*j(o);s.draw(u,f,1)},t.beginShape=Tt,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);St=[e,r],Mt=new Rt(t)},t.box=function(){return[...ke.keys()]},t.circle=function(t,e,r,n=!1){const i=new Rt("curve"),o=Math.PI*r,a=D(0,360),s=n?()=>1+.2*n*D():()=>1;for(let t=0;t<4;t++){const e=-90*t+a;i.addSegment(e*s(),o/2*s(),1,!0)}if(n){const t=n*B(-5,5);i.addSegment(a,Math.abs(t)*(Math.PI/180)*r,1,!0),i.endPlot(t+a,1,!0)}else i.endPlot(a,1,!0);const l=t-r*j(a),c=e-r*W(-a);i.show(l,c,1)},t.clip=function(t){_();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}}(Xe());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");b.stroke.clipWindow={bounds:Ue(t),inverse:e}},t.endShape=Lt,t.endStroke=function(t,e){if(!Mt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Mt.endPlot(t,e),Mt.draw(St[0],St[1],1),Mt=!1},t.field=_t,t.fill=pr,t.fillBleed=xr,t.fillTexture=yr,t.flowLine=function(t,e,r,n){if(!b.stroke.isActive||!b.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");lt(),je(t,e,r),Ze(K(n),!1)},t.hatch=cr,t.hatchArray=ur,t.hatchStyle=function(t,e="black",r=1){b.hatch.hBrush={brush:t,color:e,weight:r}},t.instance=t=>{y=!0,n=t},t.line=ir,t.listFields=function(){return lt(),Array.from(gt.keys())},t.load=p,t.move=function(t,e,r){if(!Mt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Mt.addSegment(t,e,r)},t.noClip=function(){b.stroke.clipWindow=null},t.noField=function(){lt(),b.field.isActive=!1},t.noFill=function(){b.fill.isActive=!1},t.noHatch=function(){b.hatch.isActive=!1,b.hatch.hBrush=!1},t.noStroke=function(){b.stroke.isActive=!1},t.pick=Be,t.polygon=function(t){new wt(t).show()},t.rect=function(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),Tt(0),kt(t,e),kt(t+r,e),kt(t+r,e+n),kt(t,e+n),Lt(!0)},t.refreshField=function(t=0){if(!b.field.isActive||!b.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=gt.get(b.field.current);e.field=yt(e,t)},t.scaleBrushes=function(t){for(const{param:e}of ke.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.set=Oe,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=Ye,t.strokeWeight=ze,t.vertex=kt,t.wRand=z,t.wiggle=function(t=1){_t("hand"),b.field.wiggle=t}},"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).brush={});
//# sourceMappingURL=p5.brush.js.map
diff --git a/dist/p5.brush.js.map b/dist/p5.brush.js.map
index 6b5db67..73dad96 100644
--- a/dist/p5.brush.js.map
+++ b/dist/p5.brush.js.map
@@ -1 +1 @@
-{"version":3,"file":"p5.brush.js","sources":["../src/core/color.js","../node_modules/simplex-noise/dist/esm/simplex-noise.js","../node_modules/esm-seedrandom/esm/index.mjs","../src/core/utils.js","../src/core/flowfield.js","../src/core/polygon.js","../src/core/plot.js","../src/core/primitives.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/core/gl/utils.js","../src/hatch/hatch.js","../src/core/mask.js","../src/fill/fill.js","../src/core/save.js","../src/index.js"],"sourcesContent":["import vertSrc from \"./gl/shader.vert\";\nimport fragSrc from \"./gl/shader.frag\";\n\n// =============================================================================\n// Section: Configure and Initiate\n// =============================================================================\n/**\n * This module handles the configuration and initialization of the drawing system.\n * It manages canvas properties, ensures the system is ready for rendering, and\n * provides utilities for saving and restoring states.\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties\n\nconst isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\nconst getSketchRenderer = () =>\n _isInstanced ? Instance : window.self.p5.instance;\n\nconst isSupportedFramebufferTarget = (target) =>\n isFramebufferTarget(target) && target.renderer._pInst === getSketchRenderer();\n\nconst resolveTarget = (buffer = false) => {\n if (_isInstanced && !buffer) {\n return {\n renderer: Instance,\n width: Instance.width,\n height: Instance.height,\n };\n }\n\n if (!buffer) {\n const renderer = getSketchRenderer();\n return {\n renderer,\n width: renderer.width,\n height: renderer.height,\n };\n }\n\n if (isFramebufferTarget(buffer)) {\n if (!isSupportedFramebufferTarget(buffer)) {\n throw new Error(\n \"p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.\",\n );\n }\n\n return {\n renderer: getSketchRenderer(),\n width: buffer.width,\n height: buffer.height,\n };\n }\n\n return {\n renderer: buffer,\n width: buffer.width,\n height: buffer.height,\n };\n};\n\nconst removeTargetBuffer = (buffer) => {\n if (buffer && typeof buffer.remove === \"function\") {\n buffer.remove();\n }\n};\n\nconst getGraphicsFactory = () =>\n typeof Renderer.createGraphics === \"function\" ? Renderer : Renderer._pInst;\n\nconst getActiveFramebuffer = () =>\n Renderer &&\n Renderer._renderer &&\n typeof Renderer._renderer.activeFramebuffer === \"function\"\n ? Renderer._renderer.activeFramebuffer()\n : null;\n\nconst needsBlendSourceFramebuffer = (framebuffer) =>\n !framebuffer ||\n framebuffer.width !== Cwidth ||\n framebuffer.height !== Cheight ||\n (typeof framebuffer.pixelDensity === \"function\" &&\n framebuffer.pixelDensity() !== Density);\n\nconst needsMixBuffers = () =>\n !Renderer.mask ||\n !Renderer.glMask ||\n Renderer.mask.width !== Cwidth ||\n Renderer.mask.height !== Cheight ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight;\n\nconst DIRTY_BRUSH_PADDING = 2;\nconst DIRTY_FILL_PADDING = 4;\n\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\nconst expandDirtyRect = (rect, padding = 0) =>\n rect\n ? {\n minX: rect.minX - padding,\n minY: rect.minY - padding,\n maxX: rect.maxX + padding,\n maxY: rect.maxY + padding,\n }\n : null;\n\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n\n const { width, height } = getTargetPixelSize();\n const minX = Math.max(0, Math.floor(Math.min(rect.minX, rect.maxX)));\n const minY = Math.max(0, Math.floor(Math.min(rect.minY, rect.maxY)));\n const maxX = Math.min(width, Math.ceil(Math.max(rect.minX, rect.maxX)));\n const maxY = Math.min(height, Math.ceil(Math.max(rect.minY, rect.maxY)));\n\n if (maxX <= minX || maxY <= minY) return null;\n\n return { minX, minY, maxX, maxY };\n};\n\nconst unionDirtyRect = (a, b) => {\n if (!a) return b;\n if (!b) return a;\n\n return {\n minX: Math.min(a.minX, b.minX),\n minY: Math.min(a.minY, b.minY),\n maxX: Math.max(a.maxX, b.maxX),\n maxY: Math.max(a.maxY, b.maxY),\n };\n};\n\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return { minX: 0, minY: 0, maxX: width, maxY: height };\n};\n\nconst toScissorBox = (rect) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: height - normalized.maxY,\n width: normalized.maxX - normalized.minX,\n height: normalized.maxY - normalized.minY,\n };\n};\n\nconst withScissor = (gl, rect, draw) => {\n const box = toScissorBox(rect);\n if (!box) return false;\n\n const wasEnabled = gl.isEnabled(gl.SCISSOR_TEST);\n const prevBox = gl.getParameter(gl.SCISSOR_BOX);\n\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(box.x, box.y, box.width, box.height);\n\n try {\n draw();\n } finally {\n if (wasEnabled) {\n gl.scissor(prevBox[0], prevBox[1], prevBox[2], prevBox[3]);\n } else {\n gl.disable(gl.SCISSOR_TEST);\n }\n }\n\n return true;\n};\n\n/**\n * Loads and initializes a canvas for the drawing system.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.\n * Pass a framebuffer only while drawing inside its begin()/end() or draw() scope.\n * Framebuffers created from p5.Graphics are not supported.\n */\nexport const load = (buffer = false) => {\n const target = resolveTarget(buffer);\n Renderer = target.renderer;\n\n // Check if Rendrer is webgl and throw error if it's not\n\n if (Renderer.webglVersion !== \"webgl2\") {\n throw new Error(\"p5.brush requires a WEBGL canvas\");\n }\n\n Cwidth = target.width;\n Cheight = target.height;\n\n _isReady = true;\n if (Renderer.loaded) Mix.load();\n};\n\nlet _isReady = false;\nlet _isInstanced = false;\n\n/**\n * Ensures the drawing system is ready before any operation.\n */\nexport const isCanvasReady = () => {\n if (!_isReady) load();\n};\n\n/**\n * Stores the current state of the drawing system.\n * Can be used to save and restore configurations or canvas states.\n */\nexport const State = {};\n\nexport const instance = (inst) => {\n _isInstanced = true;\n Instance = inst;\n};\n\n\n// =============================================================================\n// Section: Color Blending\n// =============================================================================\n/**\n * Handles color blending using WebGL shaders. Implements advanced blending\n * effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.\n */\n\n/**\n * Ensures the Mix object is initialized and ready for blending.\n */\nexport const isMixReady = () => {\n if (!Renderer?.loaded) {\n isCanvasReady();\n Mix.load();\n }\n};\n\nconst disable = false;\n\n/**\n * Manages blending operations with WebGL shaders.\n * @property {boolean} loaded - Indicates if shaders are loaded.\n * @property {boolean} isBlending - Indicates if blending is active.\n * @property {object} currentColor - Current color in WebGL format.\n * @property {function} load - Initializes blending resources.\n * @property {function} blend - Applies blending effects.\n */\nexport const Mix = {\n isBlending: false,\n cachedColor: new Object(),\n\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n markFull(target) {\n if (!target) return;\n\n target.dirtyRect = getFullDirtyRect();\n target.isDrawn = true;\n },\n\n clearMask(target) {\n if (!target) return;\n\n target.clear();\n target.isDrawn = false;\n target.dirtyRect = null;\n },\n\n getCompositeRect(target, isBrushMask) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n\n return normalizeDirtyRect(\n expandDirtyRect(\n target.dirtyRect,\n isBrushMask ? DIRTY_BRUSH_PADDING : DIRTY_FILL_PADDING,\n ),\n );\n },\n\n captureBlendSource(dirtyRect) {\n const activeFramebuffer = getActiveFramebuffer();\n\n if (!activeFramebuffer) return Renderer._renderer;\n\n if (needsBlendSourceFramebuffer(Renderer.blendSourceFramebuffer)) {\n removeTargetBuffer(Renderer.blendSourceFramebuffer);\n Renderer.blendSourceFramebuffer = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n const source = Renderer.blendSourceFramebuffer;\n\n source.draw(() => {\n withScissor(Renderer.drawingContext, dirtyRect, () => {\n Renderer.clear();\n Renderer.push();\n if (typeof Renderer.imageMode === \"function\") {\n Renderer.imageMode(\n Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER,\n );\n }\n Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n });\n });\n\n return source;\n },\n\n /**\n * Loads necessary resources and prepares the mask buffer and shader for colour blending.\n */\n load() {\n Density = Renderer.pixelDensity();\n const graphicsFactory = getGraphicsFactory();\n const p2dMode = graphicsFactory.P2D ?? Renderer.P2D;\n const webglMode = graphicsFactory.WEBGL ?? Renderer.WEBGL;\n\n if (!Renderer.loaded || needsMixBuffers()) {\n removeTargetBuffer(Renderer.mask);\n removeTargetBuffer(Renderer.glMask);\n\n Renderer.mask = graphicsFactory.createGraphics(Cwidth, Cheight, p2dMode);\n Renderer.glMask = graphicsFactory.createGraphics(\n Cwidth,\n Cheight,\n webglMode,\n );\n Renderer.loaded = true;\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n\n this.mask = Renderer.mask;\n this.mask.pixelDensity(Density);\n this.mask.clear();\n this.mask.angleMode(Renderer.DEGREES);\n this.mask.dirtyRect = null;\n this.mask.isDrawn = false;\n\n this.ctx = this.mask.drawingContext;\n\n this.glMask = Renderer.glMask;\n this.glMask.pixelDensity(Density);\n this.glMask.clear();\n this.glMask.angleMode(this.glMask.DEGREES);\n this.glMask.drawingContext.lineWidth = 0;\n this.glMask.dirtyRect = null;\n this.glMask.isDrawn = false;\n } else {\n this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\n this.mask.dirtyRect ??= null;\n this.mask.isDrawn ??= false;\n this.glMask.dirtyRect ??= null;\n this.glMask.isDrawn ??= false;\n }\n\n // Link Matrix of GL mask to main Renderer\n this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;\n },\n\n /**\n * Applies blending effects using the current color and mask.\n * @param {Color} _color - Color to blend.\n * @param {boolean} _isLast - If this is the final blend operation.\n * @param {boolean} _isImg - If blending an image.\n * @param {boolean} _isFillLayer - If this is a special case.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n\n const activeIsBrush = this.isBrush === true;\n const mask = activeIsBrush ? this.glMask : this.mask;\n const no_mask = activeIsBrush ? this.mask : this.glMask;\n const nextColor = _color?._array;\n const colorChanged =\n !!nextColor &&\n (this.cachedColor[0] !== nextColor[0] ||\n this.cachedColor[1] !== nextColor[1] ||\n this.cachedColor[2] !== nextColor[2] ||\n this.cachedColor[3] !== nextColor[3]);\n\n // Perf gains are minimal but let's keep it for now\n if (disable) {\n if (_isLast && mask.isDrawn) {\n Renderer.push();\n Renderer.translate(0, 0);\n Renderer.image(mask, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n mask.isDrawn = false;\n }\n return;\n }\n\n // Initialize blending if not already active\n if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Force p5 to bind its internal render target for glMask,\n // so the first glDraw() writes to the correct framebuffer.\n this.glMask.clear();\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(no_mask, !activeIsBrush);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, activeIsBrush);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) this.isBlending = false;\n }\n },\n\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n let shader = Renderer.shaderProgram;\n const gl = Renderer.drawingContext;\n const targetIsFramebuffer = !!getActiveFramebuffer();\n const source = this.captureBlendSource(dirtyRect);\n\n // Disable depth test for this compositing draw so the fullscreen rect\n // does not write Z=0 into the depth buffer — which would cause any\n // subsequent p5 geometry drawn at the same depth to fail depth testing\n // and become invisible.\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n gl.disable(gl.DEPTH_TEST);\n\n Renderer.push();\n Renderer.translate(0, 0);\n\n // Use the blend shader for rendering\n Renderer.shader(shader);\n\n // Set shader uniforms\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n shader.setUniform(\"u_flipOutputY\", targetIsFramebuffer);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", this.cachedColor);\n\n // Draw a rectangle covering the whole canvas to apply the shader\n withScissor(gl, dirtyRect, () => {\n Renderer.fill(0, 0, 0, 0);\n Renderer.noStroke();\n Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);\n });\n\n // Finish and clear mask\n Renderer.pop();\n Renderer.resetShader();\n\n // Restore depth test state\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n\n this.clearMask(mask);\n },\n};\n","/*\n * A fast javascript implementation of simplex noise by Jonas Wagner\n\nBased on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.\nWhich is based on example code by Stefan Gustavson ([email protected]).\nWith Optimisations by Peter Eastman ([email protected]).\nBetter rank ordering method by Stefan Gustavson in 2012.\n\n Copyright (c) 2024 Jonas Wagner\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n// these __PURE__ comments help uglifyjs with dead code removal\n//\nconst SQRT3 = /*#__PURE__*/ Math.sqrt(3.0);\nconst SQRT5 = /*#__PURE__*/ Math.sqrt(5.0);\nconst F2 = 0.5 * (SQRT3 - 1.0);\nconst G2 = (3.0 - SQRT3) / 6.0;\nconst F3 = 1.0 / 3.0;\nconst G3 = 1.0 / 6.0;\nconst F4 = (SQRT5 - 1.0) / 4.0;\nconst G4 = (5.0 - SQRT5) / 20.0;\n// I'm really not sure why this | 0 (basically a coercion to int)\n// is making this faster but I get ~5 million ops/sec more on the\n// benchmarks across the board or a ~10% speedup.\nconst fastFloor = (x) => Math.floor(x) | 0;\nconst grad2 = /*#__PURE__*/ new Float64Array([1, 1,\n -1, 1,\n 1, -1,\n -1, -1,\n 1, 0,\n -1, 0,\n 1, 0,\n -1, 0,\n 0, 1,\n 0, -1,\n 0, 1,\n 0, -1]);\n// double seems to be faster than single or int's\n// probably because most operations are in double precision\nconst grad3 = /*#__PURE__*/ new Float64Array([1, 1, 0,\n -1, 1, 0,\n 1, -1, 0,\n -1, -1, 0,\n 1, 0, 1,\n -1, 0, 1,\n 1, 0, -1,\n -1, 0, -1,\n 0, 1, 1,\n 0, -1, 1,\n 0, 1, -1,\n 0, -1, -1]);\n// double is a bit quicker here as well\nconst grad4 = /*#__PURE__*/ new Float64Array([0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1,\n 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1,\n 1, 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1,\n -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1,\n 1, 1, 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1,\n -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1,\n 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0,\n -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0]);\n/**\n * Creates a 2D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction2D}\n */\nexport function createNoise2D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating this yields a little ~3% performance improvement.\n const permGrad2x = new Float64Array(perm).map(v => grad2[(v % 12) * 2]);\n const permGrad2y = new Float64Array(perm).map(v => grad2[(v % 12) * 2 + 1]);\n return function noise2D(x, y) {\n // if(!isFinite(x) || !isFinite(y)) return 0;\n let n0 = 0; // Noise contributions from the three corners\n let n1 = 0;\n let n2 = 0;\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y) * F2; // Hairy factor for 2D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const t = (i + j) * G2;\n const X0 = i - t; // Unskew the cell origin back to (x,y) space\n const Y0 = j - t;\n const x0 = x - X0; // The x,y distances from the cell origin\n const y0 = y - Y0;\n // For the 2D case, the simplex shape is an equilateral triangle.\n // Determine which simplex we are in.\n let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n if (x0 > y0) {\n i1 = 1;\n j1 = 0;\n } // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n else {\n i1 = 0;\n j1 = 1;\n } // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n // c = (3-sqrt(3))/6\n const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n const y1 = y0 - j1 + G2;\n const x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords\n const y2 = y0 - 1.0 + 2.0 * G2;\n // Work out the hashed gradient indices of the three simplex corners\n const ii = i & 255;\n const jj = j & 255;\n // Calculate the contribution from the three corners\n let t0 = 0.5 - x0 * x0 - y0 * y0;\n if (t0 >= 0) {\n const gi0 = ii + perm[jj];\n const g0x = permGrad2x[gi0];\n const g0y = permGrad2y[gi0];\n t0 *= t0;\n // n0 = t0 * t0 * (grad2[gi0] * x0 + grad2[gi0 + 1] * y0); // (x,y) of grad3 used for 2D gradient\n n0 = t0 * t0 * (g0x * x0 + g0y * y0);\n }\n let t1 = 0.5 - x1 * x1 - y1 * y1;\n if (t1 >= 0) {\n const gi1 = ii + i1 + perm[jj + j1];\n const g1x = permGrad2x[gi1];\n const g1y = permGrad2y[gi1];\n t1 *= t1;\n // n1 = t1 * t1 * (grad2[gi1] * x1 + grad2[gi1 + 1] * y1);\n n1 = t1 * t1 * (g1x * x1 + g1y * y1);\n }\n let t2 = 0.5 - x2 * x2 - y2 * y2;\n if (t2 >= 0) {\n const gi2 = ii + 1 + perm[jj + 1];\n const g2x = permGrad2x[gi2];\n const g2y = permGrad2y[gi2];\n t2 *= t2;\n // n2 = t2 * t2 * (grad2[gi2] * x2 + grad2[gi2 + 1] * y2);\n n2 = t2 * t2 * (g2x * x2 + g2y * y2);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to return values in the interval [-1,1].\n return 70.0 * (n0 + n1 + n2);\n };\n}\n/**\n * Creates a 3D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction3D}\n */\nexport function createNoise3D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these seems to yield a speedup of over 15%\n const permGrad3x = new Float64Array(perm).map(v => grad3[(v % 12) * 3]);\n const permGrad3y = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 1]);\n const permGrad3z = new Float64Array(perm).map(v => grad3[(v % 12) * 3 + 2]);\n return function noise3D(x, y, z) {\n let n0, n1, n2, n3; // Noise contributions from the four corners\n // Skew the input space to determine which simplex cell we're in\n const s = (x + y + z) * F3; // Very nice and simple skew factor for 3D\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const t = (i + j + k) * G3;\n const X0 = i - t; // Unskew the cell origin back to (x,y,z) space\n const Y0 = j - t;\n const Z0 = k - t;\n const x0 = x - X0; // The x,y,z distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n // Determine which simplex we are in.\n let i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n let i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n if (x0 >= y0) {\n if (y0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // X Y Z order\n else if (x0 >= z0) {\n i1 = 1;\n j1 = 0;\n k1 = 0;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // X Z Y order\n else {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 1;\n j2 = 0;\n k2 = 1;\n } // Z X Y order\n }\n else { // x0<y0\n if (y0 < z0) {\n i1 = 0;\n j1 = 0;\n k1 = 1;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Z Y X order\n else if (x0 < z0) {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 0;\n j2 = 1;\n k2 = 1;\n } // Y Z X order\n else {\n i1 = 0;\n j1 = 1;\n k1 = 0;\n i2 = 1;\n j2 = 1;\n k2 = 0;\n } // Y X Z order\n }\n // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n // c = 1/6.\n const x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords\n const y1 = y0 - j1 + G3;\n const z1 = z0 - k1 + G3;\n const x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords\n const y2 = y0 - j2 + 2.0 * G3;\n const z2 = z0 - k2 + 2.0 * G3;\n const x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords\n const y3 = y0 - 1.0 + 3.0 * G3;\n const z3 = z0 - 1.0 + 3.0 * G3;\n // Work out the hashed gradient indices of the four simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n // Calculate the contribution from the four corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);\n }\n // Add contributions from each corner to get the final noise value.\n // The result is scaled to stay just inside [-1,1]\n return 32.0 * (n0 + n1 + n2 + n3);\n };\n}\n/**\n * Creates a 4D noise function\n * @param random the random function that will be used to build the permutation table\n * @returns {NoiseFunction4D}\n */\nexport function createNoise4D(random = Math.random) {\n const perm = buildPermutationTable(random);\n // precalculating these leads to a ~10% speedup\n const permGrad4x = new Float64Array(perm).map(v => grad4[(v % 32) * 4]);\n const permGrad4y = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 1]);\n const permGrad4z = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 2]);\n const permGrad4w = new Float64Array(perm).map(v => grad4[(v % 32) * 4 + 3]);\n return function noise4D(x, y, z, w) {\n let n0, n1, n2, n3, n4; // Noise contributions from the five corners\n // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in\n const s = (x + y + z + w) * F4; // Factor for 4D skewing\n const i = fastFloor(x + s);\n const j = fastFloor(y + s);\n const k = fastFloor(z + s);\n const l = fastFloor(w + s);\n const t = (i + j + k + l) * G4; // Factor for 4D unskewing\n const X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space\n const Y0 = j - t;\n const Z0 = k - t;\n const W0 = l - t;\n const x0 = x - X0; // The x,y,z,w distances from the cell origin\n const y0 = y - Y0;\n const z0 = z - Z0;\n const w0 = w - W0;\n // For the 4D case, the simplex is a 4D shape I won't even try to describe.\n // To find out which of the 24 possible simplices we're in, we need to\n // determine the magnitude ordering of x0, y0, z0 and w0.\n // Six pair-wise comparisons are performed between each possible pair\n // of the four coordinates, and the results are used to rank the numbers.\n let rankx = 0;\n let ranky = 0;\n let rankz = 0;\n let rankw = 0;\n if (x0 > y0)\n rankx++;\n else\n ranky++;\n if (x0 > z0)\n rankx++;\n else\n rankz++;\n if (x0 > w0)\n rankx++;\n else\n rankw++;\n if (y0 > z0)\n ranky++;\n else\n rankz++;\n if (y0 > w0)\n ranky++;\n else\n rankw++;\n if (z0 > w0)\n rankz++;\n else\n rankw++;\n // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.\n // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w\n // impossible. Only the 24 indices which have non-zero entries make any sense.\n // We use a thresholding to set the coordinates in turn from the largest magnitude.\n // Rank 3 denotes the largest coordinate.\n // Rank 2 denotes the second largest coordinate.\n // Rank 1 denotes the second smallest coordinate.\n // The integer offsets for the second simplex corner\n const i1 = rankx >= 3 ? 1 : 0;\n const j1 = ranky >= 3 ? 1 : 0;\n const k1 = rankz >= 3 ? 1 : 0;\n const l1 = rankw >= 3 ? 1 : 0;\n // The integer offsets for the third simplex corner\n const i2 = rankx >= 2 ? 1 : 0;\n const j2 = ranky >= 2 ? 1 : 0;\n const k2 = rankz >= 2 ? 1 : 0;\n const l2 = rankw >= 2 ? 1 : 0;\n // The integer offsets for the fourth simplex corner\n const i3 = rankx >= 1 ? 1 : 0;\n const j3 = ranky >= 1 ? 1 : 0;\n const k3 = rankz >= 1 ? 1 : 0;\n const l3 = rankw >= 1 ? 1 : 0;\n // The fifth corner has all coordinate offsets = 1, so no need to compute that.\n const x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords\n const y1 = y0 - j1 + G4;\n const z1 = z0 - k1 + G4;\n const w1 = w0 - l1 + G4;\n const x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords\n const y2 = y0 - j2 + 2.0 * G4;\n const z2 = z0 - k2 + 2.0 * G4;\n const w2 = w0 - l2 + 2.0 * G4;\n const x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords\n const y3 = y0 - j3 + 3.0 * G4;\n const z3 = z0 - k3 + 3.0 * G4;\n const w3 = w0 - l3 + 3.0 * G4;\n const x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords\n const y4 = y0 - 1.0 + 4.0 * G4;\n const z4 = z0 - 1.0 + 4.0 * G4;\n const w4 = w0 - 1.0 + 4.0 * G4;\n // Work out the hashed gradient indices of the five simplex corners\n const ii = i & 255;\n const jj = j & 255;\n const kk = k & 255;\n const ll = l & 255;\n // Calculate the contribution from the five corners\n let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;\n if (t0 < 0)\n n0 = 0.0;\n else {\n const gi0 = ii + perm[jj + perm[kk + perm[ll]]];\n t0 *= t0;\n n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);\n }\n let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;\n if (t1 < 0)\n n1 = 0.0;\n else {\n const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];\n t1 *= t1;\n n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);\n }\n let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;\n if (t2 < 0)\n n2 = 0.0;\n else {\n const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];\n t2 *= t2;\n n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);\n }\n let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;\n if (t3 < 0)\n n3 = 0.0;\n else {\n const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];\n t3 *= t3;\n n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);\n }\n let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;\n if (t4 < 0)\n n4 = 0.0;\n else {\n const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];\n t4 *= t4;\n n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);\n }\n // Sum up and scale the result to cover the range [-1,1]\n return 27.0 * (n0 + n1 + n2 + n3 + n4);\n };\n}\n/**\n * Builds a random permutation table.\n * This is exported only for (internal) testing purposes.\n * Do not rely on this export.\n * @private\n */\nexport function buildPermutationTable(random) {\n const tableSize = 512;\n const p = new Uint8Array(tableSize);\n for (let i = 0; i < tableSize / 2; i++) {\n p[i] = i;\n }\n for (let i = 0; i < tableSize / 2 - 1; i++) {\n const r = i + ~~(random() * (256 - i));\n const aux = p[i];\n p[i] = p[r];\n p[r] = aux;\n }\n for (let i = 256; i < tableSize; i++) {\n p[i] = p[i - 256];\n }\n return p;\n}\n//# sourceMappingURL=simplex-noise.js.map","function _prng_restore(prng, xg, opts) {\n let state = opts && opts.state;\n if (state) {\n if (typeof(state) == 'object') xg.copy(state, xg);\n prng.state = () => xg.copy(xg, {});\n }\n}\n\nfunction _prng_xor_core(xg, opts) {\n let prng = () => (xg.next() >>> 0) / 0x100000000;\n\n prng.double = () => {\n let top, bot, result;\n do {\n top = xg.next() >>> 11;\n bot = (xg.next() >>> 0) / 0x100000000;\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n\n prng.int32 = () => xg.next() | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng;\n}\n\n// A port of an algorithm by Johannes Baagøe <[email protected]>, 2010\nfunction prng_alea(seed, opts) {\n let xg = new AleaGen(seed);\n\n let prng = () => xg.next();\n\n prng.double = () =>\n prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n\n prng.int32 = () => (xg.next() * 0x100000000) | 0;\n\n prng.quick = prng;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\nclass AleaGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let n = 0xefc8249d;\n\n // Apply the seeding algorithm from Baagoe.\n this.c = 1;\n this.s0 = mash(' ');\n this.s1 = mash(' ');\n this.s2 = mash(' ');\n this.s0 -= mash(seed);\n if (this.s0 < 0) { this.s0 += 1; }\n this.s1 -= mash(seed);\n if (this.s1 < 0) { this.s1 += 1; }\n this.s2 -= mash(seed);\n if (this.s2 < 0) { this.s2 += 1; }\n\n function mash(data) {\n data = String(data);\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n }\n }\n\n next() {\n let {c,s0,s1,s2} = this;\n let t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32\n this.s0 = s1;\n this.s1 = s2;\n return this.s2 = t - (this.c = t | 0);\n }\n\n copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xor128\" prng algorithm by\nfunction prng_xor128(seed, opts) {\n let xg = new Xor128Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass Xor128Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w} = this;\n let t = x ^ (x << 11);\n this.x = y;\n this.y = z;\n this.z = w;\n return this.w = w ^ ((w >>> 19) ^ t ^ (t >>> 8));\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorwow\" prng algorithm by\nfunction prng_xorwow(seed, opts) {\n let xg = new XorWowGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass XorWowGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.x = 0;\n this.y = 0;\n this.z = 0;\n this.w = 0;\n this.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n this.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 64; k++) {\n this.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n this.d = this.x << 10 ^ this.x >>> 4;\n }\n this.next();\n }\n }\n\n next() {\n let {x,y,z,w,v,d} = this;\n let t = (x ^ (x >>> 2));\n this.x = y;\n this.y = z;\n this.z = w;\n this.w = v;\n return (this.d = (d + 362437 | 0)) +\n (this.v = (v ^ (v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n }\n}\n\n// A Javascript implementaion of the \"xorshift7\" algorithm by\nfunction prng_xorshift7(seed, opts) {\n let xg = new XorShift7Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass XorShift7Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n var j, w, x = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = x[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n x[j & 7] = (x[j & 7] << 15) ^\n (seed.charCodeAt(j) + x[(j + 1) & 7] << 13);\n }\n }\n\n // Enforce an array length of 8, not all zeroes.\n while (x.length < 8) x.push(0);\n for (j = 0; j < 8 && x[j] === 0; ++j);\n if (j == 8) w = x[7] = -1; else w = x[j];\n\n this.x = x;\n this.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n this.next();\n }\n }\n\n next() {\n // Update xor generator.\n let t, v, {x,i} = this;\n t = x[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = x[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = x[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = x[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = x[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n x[i] = v;\n this.i = (i + 1) & 7;\n return v;\n };\n\n copy(f, t) {\n t.x = [... f.x];\n t.i = f.i;\n return t;\n }\n}\n\n// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\nfunction prng_xor4096(seed, opts) {\n let xg = new Xor4096Gen(seed);\n return _prng_xor_core(xg, opts);\n}\n\n\nclass Xor4096Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n this.w = w;\n this.X = X;\n this.i = i;\n }\n\n next() {\n let t, v, {w, X, i} = this;\n // Update Weyl generator.\n this.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n this.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = [... f.X];\n return t;\n }\n}\n\n// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\nfunction prng_tychei(seed, opts) {\n let xg = new TycheiGen(seed);\n return _prng_xor_core(xg, opts);\n}\n\nclass TycheiGen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let strseed = '';\n\n this.a = 0;\n this.b = 0;\n this.c = 2654435769 | 0;\n this.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n this.a = (seed / 0x100000000) | 0;\n this.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (let k = 0; k < strseed.length + 20; k++) {\n this.b ^= strseed.charCodeAt(k) | 0;\n this.next();\n }\n }\n\n next() {\n let {a,b,c,d} = this;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n this.b = b = (b << 20) ^ (b >>> 12) ^ c;\n this.c = c = (c - d) | 0;\n this.d = (d << 16) ^ (c >>> 16) ^ a;\n return this.a = (a - b) | 0;\n };\n\n copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n }\n}\n\n\n/* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n *\n\nclass TycheiGenAlt extends TycheiGen {\n next() {\n let {a,b,c,d} = this\n a = (a + b | 0) >>> 0;\n d = d ^ a; d = d << 16 ^ d >>> 16;\n c = c + d | 0;\n b = b ^ c; b = b << 12 ^ d >>> 20;\n this.a = a = a + b | 0;\n d = d ^ a; this.d = d = d << 8 ^ d >>> 24;\n this.c = c = c + d | 0;\n b = b ^ c;\n return this.b = (b << 7 ^ b >>> 25);\n }\n}\n*/\n\n/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\nfunction prng_arc4(seed, opts) {\n let xg = new ARC4Gen(seed);\n let prng = () => xg.next();\n\n prng.double = prng;\n\n prng.int32 = () => xg.g(4) | 0;\n\n prng.quick = () => xg.g(4) / 0x100000000;\n\n _prng_restore(prng, xg, opts);\n return prng\n}\n\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\n\n//\n// The following constants are related to IEEE 754 limits.\n//\n\n// const width = 256 // each RC4 output is 0 <= x < 256\n// const chunks = 6 // at least six RC4 outputs for each double\nconst _arc4_startdenom = 281474976710656; // 256 ** 6 == width ** chunks\nconst _arc4_significance = 4503599627370496; // 2 ** 52 significant digits in a double\nconst _arc4_overflow = 9007199254740992; // 2 ** 53 == significance * 2\n\n\nclass ARC4Gen {\n constructor(seed) {\n if (seed == null) seed = +(new Date);\n\n let key = this.mixkey(seed, []);\n let i,j,t, S=[], keylen = key.length;\n this.i = this.j = i = j = 0;\n this.S = S;\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i <= 0xff) {\n S[i] = i++;\n }\n for (i = 0; i <= 0xff; i++) {\n S[i] = S[j = 0xff & (j + key[i % keylen] + (t = S[i]))];\n S[j] = t;\n }\n\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n this.g(256);\n }\n\n next() {\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n\n let n = this.g(6); // Start with a numerator n < 2 ^ 48\n let d = _arc4_startdenom; // and denominator d = 2 ^ 48.\n let x = 0; // and no 'extra last byte'.\n\n while (n < _arc4_significance) { // Fill up all significant digits (2 ** 52)\n n = (n + x) * 256; // by shifting numerator and\n d *= 256; // denominator and generating a\n x = this.g(1); // new least-significant-byte.\n }\n while (n >= _arc4_overflow) { // To avoid rounding past overflow, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n }\n\n g(count) {\n // The \"g\" method returns the next (count) outputs as one number.\n let t, r = 0, {i,j,S} = this;\n while (count--) {\n t = S[i = 0xff & (i + 1)];\n r = r * 256 + S[0xff & ((S[i] = S[j = 0xff & (j + t)]) + (S[j] = t))];\n }\n this.i = i;\n this.j = j;\n return r;\n }\n\n copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = [... f.S];\n return t;\n }\n\n mixkey(seed, key) {\n seed = seed + '';\n let smear=0, j=0;\n while (j < seed.length) {\n key[0xff & j] =\n 0xff & ((smear ^= key[0xff & j] * 19) + seed.charCodeAt(j++));\n }\n return key\n }\n}\n\nexport { prng_alea, prng_arc4, prng_tychei, prng_xor128, prng_xor4096, prng_xorshift7, prng_xorwow };\n//# sourceMappingURL=index.mjs.map\n","import { Renderer } from \"./color.js\";\n\n// =============================================================================\n// Section: Randomness & Noise\n// =============================================================================\n\nimport { createNoise2D } from \"simplex-noise\";\nimport { prng_alea } from \"esm-seedrandom\";\n\n/**\n * A uniform PRNG function. Returns a float in [0,1).\n * @callback RNG\n * @returns {number}\n */\n/** @type {RNG} */\nlet rng = prng_alea(Math.random());\n\nconst _seedCallbacks = [];\n\n/**\n * Register a callback to be called whenever seed() is invoked.\n * Used internally by modules that maintain gaussian pools.\n * @param {Function} cb\n */\nexport const _onSeed = (cb) => _seedCallbacks.push(cb);\n\n/**\n * Seed the random number generator.\n * @param {number|string} s – The seed value.\n * @returns {void}\n */\nexport const seed = (s) => {\n rng = prng_alea(s);\n for (const callback of _seedCallbacks) {\n callback();\n }\n};\n\n/**\n * Simplex‐noise 2D function.\n * @type {function(number, number): number}\n */\nexport let noise = createNoise2D(prng_alea(Math.random()));\n\n/**\n * Seed the noise generator.\n * @param {number|string} s - The seed value.\n * @returns {void}\n */\nexport const noiseSeed = (s) => {\n noise = createNoise2D(prng_alea(s));\n};\n\n/**\n * Returns a random float in [min, max).\n * @param {number} [min=0]\n * @param {number} [max=1]\n * @returns {number}\n */\nexport const rr = (e = 0, r = 1) => e + rng() * (r - e);\n\n/**\n * Selects a random element from an array.\n * @param {T[]} array - Input array.\n * @returns {T}\n */\nexport const rArray = (array) => array[~~(rng() * array.length)];\n\n/**\n * Returns a random integer in [min, max).\n * @param {number} min\n * @param {number} max\n * @returns {number}\n */\nexport const randInt = (e, r) => ~~rr(e, r);\n\n/**\n * Gaussian (normal) random sample N(mean, stdev²).\n * @param {number} [mean=0]\n * @param {number} [stdev=1]\n * @returns {number}\n */\nexport const gaussian = (mean = 0, stdev = 1) => {\n const u = 1 - rng();\n const v = rng();\n const z = Math.sqrt(-2.0 * Math.log(u)) * cos(360 * v);\n return z * stdev + mean;\n};\n\n/**\n * Picks a key from an object according to weighted probabilities.\n * @param {Object<string|number, number>} weights\n * @returns {string|number}\n */\nexport const weightedRand = (weights) => {\n let totalWeight = 0;\n const entries = [];\n\n // Build cumulative weights array\n for (const key in weights) {\n totalWeight += weights[key];\n entries.push({ key, cumulative: totalWeight });\n }\n\n // Get a random number between 0 and totalWeight\n const rnd = rng() * totalWeight;\n\n // Pick the first entry where rnd is less than the cumulative weight\n for (const { key, cumulative } of entries) {\n if (rnd < cumulative) {\n return isNaN(key) ? key : parseInt(key);\n }\n }\n};\n\n// =============================================================================\n// Section: Numeric Mapping & Constraints\n// =============================================================================\n\n/**\n * Maps a value from range [a,b] to [c,d], optionally clamped.\n * @param {number} value\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @param {number} d\n * @param {boolean} [withinBounds=false]\n * @returns {number}\n */\nexport const map = (value, a, b, c, d, withinBounds = false) => {\n let r = c + ((value - a) / (b - a)) * (d - c);\n if (!withinBounds) return r;\n if (c < d) return constrain(r, c, d);\n else return constrain(r, d, c);\n};\n\n/**\n * Constrains a number within the provided bounds.\n * @param {number} n - The number.\n * @param {number} low - Lower bound.\n * @param {number} high - Upper bound.\n * @returns {number} The constrained number.\n */\nexport const constrain = (n, low, high) => Math.max(Math.min(n, high), low);\n\n// =============================================================================\n// Section: Trigonometry\n// =============================================================================\n\n/**\n * Normalize an angle in degrees to [0,360).\n * @param {number} angle\n * @returns {number}\n */\nconst nAngle = (angle) => {\n angle = angle % 360;\n return angle < 0 ? angle + 360 : angle;\n};\n\n// number of discrete steps (360° × 4 samples per degree)\nconst totalDegrees = 1440;\nconst radiansPerIndex = (2 * Math.PI) / totalDegrees;\n\n// lazy‐initialized lookup tables\nconst cLookup = new Float32Array(totalDegrees).fill(NaN);\nconst sLookup = new Float32Array(totalDegrees).fill(NaN);\n\n/**\n * Cosine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const cos = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = cLookup[idx];\n if (isNaN(v)) {\n v = Math.cos(idx * radiansPerIndex);\n cLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Sine of an angle (degrees), via a lazy lookup table.\n * @param {number} angle\n * @returns {number}\n */\nexport const sin = (angle) => {\n const idx = ~~(4 * nAngle(angle));\n let v = sLookup[idx];\n if (isNaN(v)) {\n v = Math.sin(idx * radiansPerIndex);\n sLookup[idx] = v;\n }\n return v;\n};\n\n/**\n * Converts radians to degrees, normalized to [0,360).\n * @param {number} rad\n * @returns {number}\n */\nexport const toDegrees = (rad, isRad = false) => {\n const usesRadians =\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS);\n // Only if Renderer.angleMode() is set to radians\n if (usesRadians) {\n let angle = ((rad * 180) / Math.PI) % 360;\n return angle < 0 ? angle + 360 : angle;\n } else {\n return rad;\n }\n};\n\n/**\n * Converts radians to degrees without wrapping the result.\n * Preserves signed angles so downstream scaling keeps its direction.\n * @param {number} angle\n * @param {boolean} [isRad=false]\n * @returns {number}\n */\nexport const toDegreesSigned = (angle, isRad = false) =>\n isRad ||\n (Renderer &&\n typeof Renderer.angleMode === \"function\" &&\n Renderer.angleMode() === Renderer.RADIANS)\n ? (angle * 180) / Math.PI\n : angle;\n\n// =============================================================================\n// Section: Geometry & Transforms\n// =============================================================================\n\n/**\n * Rotates point (x,y) around center (cx,cy) by angle degrees.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x\n * @param {number} y\n * @param {number} angle - Degrees\n * @returns {{x:number,y:number}}\n */\nexport const rotate = (cx, cy, x, y, angle) => {\n let coseno = cos(angle),\n seno = sin(angle),\n nx = coseno * (x - cx) + seno * (y - cy) + cx,\n ny = coseno * (y - cy) - seno * (x - cx) + cy;\n return { x: nx, y: ny };\n};\n\n/**\n * Euclidean distance between two points.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);\n\n/**\n * Angle in degrees between two points, measured clockwise from +X.\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {number}\n */\nexport const calcAngle = (x1, y1, x2, y2) =>\n toDegrees(Math.atan2(-(y2 - y1), x2 - x1), true);\n\n/**\n * Intersection of two line segments, or false if none.\n * @param {{x:number,y:number}} s1a\n * @param {{x:number,y:number}} s1b\n * @param {{x:number,y:number}} s2a\n * @param {{x:number,y:number}} s2b\n * @param {boolean} [includeSegmentExtension=false]\n * @returns {{x:number,y:number}|false}\n */\nexport const intersectLines = (\n s1a,\n s1b,\n s2a,\n s2b,\n includeSegmentExtension = false\n) => {\n // Extract coordinates from points\n let x1 = s1a.x,\n y1 = s1a.y;\n let x2 = s1b.x,\n y2 = s1b.y;\n let x3 = s2a.x,\n y3 = s2a.y;\n let x4 = s2b.x,\n y4 = s2b.y;\n // Early return if line segments are points or if the lines are parallel\n if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {\n return false; // Segments are points\n }\n let deltaX1 = x2 - x1,\n deltaY1 = y2 - y1;\n let deltaX2 = x4 - x3,\n deltaY2 = y4 - y3;\n let denominator = deltaY2 * deltaX1 - deltaX2 * deltaY1;\n if (denominator === 0) {\n return false; // Lines are parallel\n }\n // Calculate the intersection point\n let ua = (deltaX2 * (y1 - y3) - deltaY2 * (x1 - x3)) / denominator;\n let ub = (deltaX1 * (y1 - y3) - deltaY1 * (x1 - x3)) / denominator;\n // Check if the intersection is within the bounds of the line segments\n if (!includeSegmentExtension && (ub < 0 || ub > 1)) {\n return false;\n }\n // Calculate the intersection coordinates\n let x = x1 + ua * deltaX1;\n let y = y1 + ua * deltaY1;\n return { x: x, y: y };\n};\n","import { isMixReady, Cwidth, Cheight, State, Renderer } from \"./color.js\";\nimport { randInt, noise, rr, sin, cos, map, toDegreesSigned } from \"./utils.js\";\n\n// =============================================================================\n// Section: Matrix transformations\n// =============================================================================\n\n/**\n * The `Matrix` object exposes the current 2D affine transform from p5's model matrix.\n * mat4 layout (column-major 4x4):\n * [0]=a [1]=b [4]=c [5]=d [12]=tx [13]=ty\n * where the 2D transform of a point (x,y) is: (a*x + c*y + tx, b*x + d*y + ty)\n */\nexport const Matrix = {\n x: () => Renderer._renderer.uModelMatrix.mat4[12],\n y: () => Renderer._renderer.uModelMatrix.mat4[13],\n a: () => Renderer._renderer.uModelMatrix.mat4[0],\n b: () => Renderer._renderer.uModelMatrix.mat4[1],\n c: () => Renderer._renderer.uModelMatrix.mat4[4],\n d: () => Renderer._renderer.uModelMatrix.mat4[5],\n};\n\n\n// =============================================================================\n// Section: Field Initialization\n// =============================================================================\n\nlet isLoaded = false;\n\n/**\n * Ensures the field system is initialized and ready for use.\n * If the field is not loaded, it initializes the mixing system and creates the field.\n */\nexport function isFieldReady() {\n if (!isLoaded) {\n isMixReady(); // Ensure the mixing system is ready\n createField(); // Initialize the field\n isLoaded = true;\n }\n}\n\n// =============================================================================\n// Section: Position Class\n// =============================================================================\n\n/**\n * The Position class represents a point within a two-dimensional space, which can interact with a vector field.\n * It provides methods to update the position based on the field's flow and to check whether the position is\n * within certain bounds (e.g., within the field or canvas).\n */\nexport class Position {\n /**\n * Constructs a new Position instance.\n * @param {number} x - The initial x-coordinate.\n * @param {number} y - The initial y-coordinate.\n */\n constructor(x, y) {\n isFieldReady();\n this.update(x, y);\n this.plotted = 0; // Tracks the total distance plotted\n }\n\n /**\n * Updates the position's coordinates and calculates its offsets and indices within the flow field.\n * @param {number} x - The new x-coordinate.\n * @param {number} y - The new y-coordinate.\n */\n update(x, y) {\n this.x = x;\n this.y = y;\n this.colIdx = Position.getColIndex(x);\n this.rowIdx = Position.getRowIndex(y);\n }\n\n /**\n * Resets the 'plotted' property to 0.\n */\n reset() {\n this.plotted = 0;\n }\n\n /**\n * Checks if the position is within the active flow field's bounds.\n * @returns {boolean} - True if the position is within the flow field, false otherwise.\n */\n isIn() {\n return State.field.isActive\n ? Position.isIn(this.colIdx, this.rowIdx)\n : this.isInCanvas(this.x, this.y);\n }\n\n /**\n * Checks if the position is within the canvas bounds (with a margin).\n * @returns {boolean} - True if the position is within bounds, false otherwise.\n */\n isInCanvas() {\n const margin = 0.3;\n const w = Cwidth;\n const h = Cheight;\n const x = this.x + Matrix.x();\n const y = this.y + Matrix.y();\n return (\n x >= -margin * w &&\n x <= (1 + margin) * w &&\n y >= -margin * h &&\n y <= (1 + margin) * h\n );\n }\n\n /**\n * Calculates the angle of the flow field at the position's current coordinates.\n * @returns {number} - The internal flow angle in degrees, or 0 if the position is not in the field or if no field is active.\n */\n angle() {\n return this.isIn() && State.field.isActive\n ? flow_field()[this.colIdx][this.rowIdx] * State.field.wiggle\n : 0;\n }\n\n /**\n * Moves the position along the flow field by a certain length.\n * @param {number} _dir - The direction of movement, interpreted using the current p5 angle mode.\n * @param {number} _length - The length to move along the field.\n * @param {number} _step_length - The length of each step.\n */\n moveTo(_dir, _length, _step_length = 1) {\n this.movePos(toDegreesSigned(_dir), _length, _step_length);\n }\n\n /**\n * Internal variant of moveTo() that expects a degree value already normalized to the library's internal representation.\n */\n _moveToDegrees(_dir, _length, _step_length = 1) {\n this.movePos(_dir, _length, _step_length);\n }\n\n /**\n * Plots a point to another position within the flow field, following a Plot object\n * @param {Position} _plot - The Plot path object.\n * @param {number} _length - The length to move towards the target position.\n * @param {number} _step_length - The length of each step.\n * @param {number} _scale - The scaling factor for the plotting path.\n */\n plotTo(_plot, _length, _step_length, _scale = 1) {\n this.movePos(_plot, _length, _step_length, _scale);\n }\n\n movePos(_dirPlot, _length, _step, _scale = false) {\n const scaleFactor = _scale || 1;\n if (!this.isIn()) {\n this.plotted += _step / scaleFactor;\n return;\n }\n for (let i = 0; i < _length / _step; i++) {\n const angle =\n this.angle() - (_scale ? _dirPlot.angle(this.plotted) : _dirPlot);\n // Calculate new position\n this.update(this.x + _step * cos(angle), this.y + _step * sin(angle));\n this.plotted += _step / scaleFactor;\n }\n }\n\n // Static Methods\n\n /**\n * Gets the row index for a given y-coordinate.\n * @param {number} y - The y-coordinate.\n * @returns {number} - The row index.\n */\n static getRowIndex(y, d = 1) {\n const y_offset = y + Matrix.y() - top_y;\n return Math.round(y_offset / resolution / d);\n }\n\n /**\n * Gets the column index for a given x-coordinate.\n * @param {number} x - The x-coordinate.\n * @returns {number} - The column index.\n */\n static getColIndex(x, d = 1) {\n const x_offset = x + Matrix.x() - left_x;\n return Math.round(x_offset / resolution / d);\n }\n\n /**\n * Checks if a column and row index are within the flow field bounds.\n * @param {number} col - The column index.\n * @param {number} row - The row index.\n * @returns {boolean} - True if the indices are within bounds, false otherwise.\n */\n static isIn(col, row) {\n return col >= 0 && row >= 0 && col < num_columns && row < num_rows;\n }\n}\n\n// =============================================================================\n// Section: VectorField\n// =============================================================================\n\n/**\n * Represents the state of the vector field.\n * @property {boolean} isActive - Indicates if the vector field is active.\n * @property {string|null} current - The name of the currently active vector field.\n */\nState.field = {\n isActive: false,\n current: null,\n wiggle: 1,\n};\n\n// Internal variables for field configuration\nlet list = new Map();\nlet resolution, left_x, top_y, num_columns, num_rows;\nconst FIELD_ANGLE_MODES = new Set([\"degrees\", \"radians\"]);\n\n/**\n * Initializes the field grid and sets up the vector field's structure based on the renderer's dimensions.\n */\nfunction createField() {\n resolution = Cwidth * 0.01; // Determine the resolution of the field grid\n left_x = -0.5 * Cwidth; // Left boundary of the field\n top_y = -0.5 * Cheight; // Top boundary of the field\n num_columns = Math.round((2 * Cwidth) / resolution); // Number of columns in the grid\n num_rows = Math.round((2 * Cheight) / resolution); // Number of columns in the grid\n addStandard(); // Add default vector field\n}\n\n/**\n * Retrieves the field values for the current vector field.\n * @returns {Float32Array[]} The current vector field grid.\n */\nfunction flow_field() {\n return list.get(State.field.current).field;\n}\n\nfunction normalizeFieldAngleMode(options = {}) {\n const config =\n typeof options === \"string\" ? { angleMode: options } : options || {};\n const angleMode = config.angleMode ?? \"degrees\";\n\n if (!FIELD_ANGLE_MODES.has(angleMode)) {\n throw new Error(\n `Invalid field angle mode \"${angleMode}\". Use \"degrees\" or \"radians\".`,\n );\n }\n\n return angleMode;\n}\n\nfunction normalizeFieldAngles(field, angleMode) {\n if (angleMode !== \"radians\") return field;\n\n for (let c = 0; c < field.length; c++) {\n for (let r = 0; r < field[c].length; r++) {\n field[c][r] = toDegreesSigned(field[c][r], true);\n }\n }\n\n return field;\n}\n\nfunction generateField(entry, t) {\n return normalizeFieldAngles(entry.gen(t, genField()), entry.angleMode);\n}\n\n/**\n * Regenerates the current vector field using its associated generator function.\n * @param {number} [t=0] - An optional time parameter that can affect field generation.\n */\nexport function refreshField(t = 0) {\n if (!State.field.isActive || !State.field.current) {\n throw new Error(\n \"No field is currently active. Call brush.field('name') to activate one before refreshing.\",\n );\n }\n const currentField = list.get(State.field.current);\n currentField.field = generateField(currentField, t);\n}\n\n/**\n * Generates an empty field array.\n * Reuses existing arrays to reduce memory allocation overhead.\n * @returns {Float32Array[]} Empty vector field grid.\n */\nfunction genField() {\n return new Array(num_columns)\n .fill(null)\n .map(() => new Float32Array(num_rows));\n}\n\n/**\n * Activates a specific vector field by name, ensuring it's ready for use.\n * @param {string} a - The name of the vector field to activate.\n */\nexport function field(a) {\n if (!State.field.wiggle) {\n State.field.wiggle = 1;\n } // Set default wiggle value\n isFieldReady();\n if (!list.has(a)) {\n throw new Error(\n `Field \"${a}\" does not exist. Available fields: ${Array.from(list.keys()).join(\", \")}.`,\n );\n }\n State.field.isActive = true;\n State.field.current = a;\n const entry = list.get(a);\n if (!entry.field) entry.field = generateField(entry, 0);\n}\n\n/**\n * Deactivates the current vector field.\n */\nexport function noField() {\n isFieldReady();\n State.field.isActive = false;\n}\n\n/**\n * Adds a new vector field to the field list with a unique name and a generator function.\n * @param {string} name - The unique name for the new vector field.\n * @param {Function} funct - The function that generates the field values.\n * @param {object} [options] - Optional field configuration.\n * @param {\"degrees\"|\"radians\"} [options.angleMode=\"degrees\"] - How the generator's output angles should be interpreted.\n */\nexport function addField(name, funct, options = {}) {\n list.set(name, {\n gen: funct,\n field: null,\n angleMode: normalizeFieldAngleMode(options),\n });\n}\n\n/**\n * Retrieves a list of all available vector field names.\n * @returns {string[]} An array of all the field names.\n */\nexport function listFields() {\n isFieldReady();\n return Array.from(list.keys());\n}\n\nexport function wiggle(a = 1) {\n field(\"hand\");\n State.field.wiggle = a;\n}\n\n/**\n * Fills every cell of a field grid using a callback (c, r) => angle.\n */\nfunction fillField(field, fn) {\n for (let c = 0; c < num_columns; c++)\n for (let r = 0; r < num_rows; r++) field[c][r] = fn(c, r);\n return field;\n}\n\n/**\n * Adds standard predefined vector fields to the list with unique behaviors.\n */\nfunction addStandard() {\n // Organic noise — basis for brush.wiggle()\n addField(\"hand\", (t, field) => {\n const bs = rr(0.2, 0.8),\n ba = randInt(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt(15, 25));\n return 0.2 * angle * cos(t) + noise(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt(-10, 10);\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise(c * 0.02 + t * 0.03, r * 0.02 + t * 0.03), 0, 1, -ar, ar),\n );\n });\n // Sharp alternating angles per cell — herringbone / wicker look\n addField(\"zigzag\", (t, field) => {\n let ar = randInt(-30, -15) + Math.abs(44 * sin(t));\n if (randInt(0, 100) % 2 == 0) ar *= -1;\n let dif = ar,\n angle = 0;\n for (let c = 0; c < num_columns; c++) {\n for (let r = 0; r < num_rows; r++) {\n field[c][r] = angle;\n angle += dif;\n dif *= -1;\n }\n angle += dif;\n dif *= -1;\n }\n return field;\n });\n // Sinusoidal wave bands\n addField(\"waves\", (t, field) => {\n const sr = randInt(10, 15) + 5 * sin(t),\n cr = randInt(3, 6) + 3 * cos(t),\n ba = randInt(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr(0.4, 0.8),\n ba = randInt(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt(5, 10);\n const dir = randInt(0, 2) * 2 - 1;\n const offset = randInt(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr(0.1, 0.9) * num_columns,\n y: rr(0.1, 0.9) * num_rows,\n }));\n return fillField(field, (c, r) => {\n let wx = 0,\n wy = 0;\n for (const att of attractors) {\n const dx = c - att.x,\n dy = r - att.y;\n const w = 1 / (dx * dx + dy * dy + 1);\n const a = Math.atan2(dy, dx) * (180 / Math.PI);\n const angle = (dir * (a + offset) * Math.PI) / 180;\n wx += w * Math.cos(angle);\n wy += w * Math.sin(angle);\n }\n return Math.atan2(wy, wx) * (180 / Math.PI);\n });\n });\n // Column-banded stripes — parallel rake marks\n addField(\"columns\", (_t, field) => {\n const freq = randInt(3, 8),\n amp = randInt(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\n });\n}\n","import { State } from \"./color.js\";\nimport { intersectLines } from \"./utils.js\";\n\n// =============================================================================\n// Section: Polygon Class\n// =============================================================================\n\n/**\n * Represents a polygon with a set of vertices and provides methods for\n * intersection, drawing, filling, and hatching.\n */\nexport class Polygon {\n /**\n * Constructs the Polygon object from an array of points.\n * @param {Array} pointsArray - An array of points, where each point is an array of two numbers [x, y].\n * @param {boolean} [useRawVertices=false] - If true, uses the raw array as vertices.\n */\n constructor(pointsArray, useRawVertices = false) {\n this.a = pointsArray;\n this.vertices = useRawVertices\n ? pointsArray\n : pointsArray.map(([x, y]) => ({ x, y }));\n this.sides = this.vertices.map((v, i, arr) => [\n v,\n arr[(i + 1) % arr.length],\n ]);\n this._intersectionCache = {}; // Cache for intersection results\n }\n\n /**\n * Intersects a given line with the polygon, returning all intersection points.\n * @param {Object} line - The line to intersect with the polygon, having two properties 'point1' and 'point2'.\n * @returns {Array} An array of intersection points (each with 'x' and 'y' properties) or an empty array if no intersections.\n */\n intersect(line) {\n // Check if the result has been cached\n const cacheKey = `${line.point1.x},${line.point1.y}-${line.point2.x},${line.point2.y}`;\n if (this._intersectionCache[cacheKey]) {\n return this._intersectionCache[cacheKey];\n }\n const points = [];\n for (const [start, end] of this.sides) {\n const intersection = intersectLines(line.point1, line.point2, start, end);\n if (intersection) points.push(intersection);\n }\n this._intersectionCache[cacheKey] = points; // Cache the result\n return points;\n }\n\n /**\n * Displays the polygon with optional stroke, hatch, and fill effects.\n */\n show() {\n if (State.stroke) this.draw();\n if (State.hatch) this.hatch();\n if (State.fill) this.fill();\n }\n}\n","import { State, Cwidth, Cheight } from \"./color.js\";\nimport { toDegrees, map, rr } from \"./utils.js\";\nimport { Position, isFieldReady } from \"./flowfield.js\";\nimport { Polygon } from \"./polygon.js\";\n\n// =============================================================================\n// Section: Plot Class\n// =============================================================================\n\n/**\n * The Plot class represents a collection of segments that define shapes or paths.\n * It supports operations like adding segments, calculating angles and pressures,\n * and generating polygons based on the plot's structure.\n */\nexport class Plot {\n /**\n * Creates a new Plot.\n * @param {string} _type - The type of plot, \"curve\" or \"segments\".\n */\n constructor(_type) {\n this.segments = [];\n this.angles = [];\n this.pres = [];\n this.type = _type;\n this.dir = 0;\n this.calcIndex(0);\n this.pol = false;\n }\n\n /**\n * Adds a segment to the plot with specified angle, length, and pressure.\n * @param {number} _a - The angle of the segment.\n * @param {number} _length - The length of the segment.\n * @param {number} _pres - The pressure of the segment.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n addSegment(_a = 0, _length = 0, _pres = 1, _degrees = false) {\n if (this.angles.length > 0) this.angles.pop(); // Remove the last angle\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a); // Normalize angle\n this.angles.push(_a, _a); // Push angle twice for continuity\n this.pres.push(_pres);\n this.segments.push(_length);\n this.length = this.segments.reduce((sum, len) => sum + len, 0); // Update total length\n }\n\n /**\n * Finalizes the plot by setting the last angle and pressure.\n * @param {number} _a - The final angle.\n * @param {number} _pres - The final pressure.\n * @param {boolean} _degrees - Whether the angle is in degrees.\n */\n endPlot(_a = 0, _pres = 1, _degrees = false) {\n _a = _degrees ? ((_a % 360) + 360) % 360 : toDegrees(_a);\n this.angles[this.angles.length - 1] = _a; // Update the last angle\n this.pres.push(_pres);\n }\n\n /**\n * Rotates the entire plot by a given angle.\n * @param {number} _a - The angle to rotate the plot.\n */\n rotate(_a) {\n this.dir = toDegrees(_a);\n }\n\n /**\n * Calculates the pressure at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated pressure.\n */\n pressure(_d) {\n // If the distance exceeds the plot length, return the last pressure\n if (_d > this.length) return this.pres[this.pres.length - 1];\n // Otherwise, calculate the pressure using the curving function\n return this.curving(this.pres, _d);\n }\n\n /**\n * Calculates the angle at a given distance along the plot.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The calculated angle.\n */\n angle(_d) {\n // If the distance exceeds the plot length, return the last angle\n if (_d > this.length) return this.angles[this.angles.length - 1];\n // Calculate the index for the given distance\n this.calcIndex(_d);\n // Return the angle, adjusted for the plot type and direction\n return this.type === \"curve\"\n ? this.curving(this.angles, _d) + this.dir\n : this.angles[this.index] + this.dir;\n }\n\n /**\n * Interpolates values between segments for smooth transitions.\n * @param {Array<number>} array - The array to interpolate within.\n * @param {number} _d - The distance along the plot.\n * @returns {number} - The interpolated value.\n */\n curving(array, _d) {\n let map0 = array[this.index];\n let map1 = array[this.index + 1] ?? map0;\n if (Math.abs(map1 - map0) > 180) {\n if (map1 > map0) map1 = -(360 - map1);\n else map0 = -(360 - map0);\n }\n return map(_d - this.suma, 0, this.segments[this.index], map0, map1, true);\n }\n\n /**\n * Calculates the current index of the plot based on the distance.\n * @param {number} _d - The distance along the plot.\n */\n calcIndex(_d) {\n this.index = -1;\n this.suma = 0;\n let d = 0;\n while (d <= _d) {\n this.suma = d;\n d += this.segments[this.index + 1];\n this.index++;\n }\n return this.index;\n }\n\n /**\n * Generates a polygon based on the plot.\n * @param {number} _x - The x-coordinate for the starting point.\n * @param {number} _y - The y-coordinate for the starting point.\n * @param {number} _scale - The scale factor for the polygon.\n * @param {number} _side - The side factor for the polygon.\n * @returns {Polygon} - The generated polygon.\n */\n genPol(_x, _y, _scale = 1, _side) {\n isFieldReady(); // Ensure that the drawing environment is prepared\n const step = 0.5;\n const vertices = [];\n const numSteps = Math.round(this.length / step);\n const pos = new Position(_x + Cwidth / 2, _y + Cheight / 2);\n let pside = 0;\n let prevIdx = 0;\n\n for (let i = 0; i < numSteps; i++) {\n pos.plotTo(this, step, step);\n const idx = this.calcIndex(pos.plotted);\n pside += step;\n const maxSize = Math.max(this.segments[idx] * _side * rr(0.7, 1.3), 10);\n if ((pside >= maxSize || idx >= prevIdx) && pos.x) {\n vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);\n pside = 0;\n if (idx >= prevIdx) prevIdx++;\n }\n }\n return new Polygon(vertices);\n }\n\n /**\n * Displays the plot with optional stroke, hatch, and fill effects.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\n show(x, y, scale = 1) {\n if (State.stroke) this.draw(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n }\n}\n","import {\n rr,\n randInt,\n sin,\n cos,\n toDegrees,\n toDegreesSigned,\n constrain,\n dist,\n calcAngle,\n intersectLines,\n} from \"./utils.js\";\nimport { Polygon } from \"./polygon.js\";\nimport { Plot } from \"./plot.js\";\n\n// =============================================================================\n// Section: Primitives and Geommetry\n// =============================================================================\n\n/**\n * Creates a Polygon from an array of points and calls its show() method.\n * @param {Array<Array<number>>} pointsArray - Array of points [x, y, pressure]\n */\nexport function polygon(pointsArray) {\n // Create a new Polygon instance\n const polygon = new Polygon(pointsArray);\n polygon.show();\n}\n\n/**\n * Draws a rectangle on the canvas using path functions.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} w - Width.\n * @param {number} h - Height.\n * @param {boolean} [mode=\"corner\"] - \"corner\" (default) or \"center\".\n */\nexport function rect(x, y, w, h, mode = \"corner\") {\n if (mode === \"center\") {\n x -= w / 2;\n y -= h / 2;\n }\n beginShape(0);\n vertex(x, y);\n vertex(x + w, y);\n vertex(x + w, y + h);\n vertex(x, y + h);\n endShape(true);\n}\n\n/**\n * Draws a circle on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Circle radius.\n * @param {boolean} [r=false] - Randomizes segment lengths if true.\n */\nexport function circle(x, y, radius, r = false) {\n const p = new Plot(\"curve\");\n const arcLength = Math.PI * radius;\n const angleOffset = rr(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr() : () => 1;\n\n // Divide circle into 4 segments\n for (let i = 0; i < 4; i++) {\n const angle = -90 * i + angleOffset;\n p.addSegment(\n angle * randomFactor(),\n (arcLength / 2) * randomFactor(),\n 1,\n true,\n );\n }\n\n // Optionally add a random final angle for the last segment\n if (r) {\n const randomAngle = r * randInt(-5, 5);\n p.addSegment(\n angleOffset,\n Math.abs(randomAngle) * (Math.PI / 180) * radius,\n 1,\n true,\n );\n p.endPlot(randomAngle + angleOffset, 1, true);\n } else {\n p.endPlot(angleOffset, 1, true);\n }\n\n // Draw the circle\n const offsetX = x - radius * sin(angleOffset);\n const offsetY = y - radius * cos(-angleOffset);\n p.show(offsetX, offsetY, 1);\n}\n\n/**\n * Draws an arc on the canvas.\n * @param {number} x - Center x.\n * @param {number} y - Center y.\n * @param {number} radius - Radius.\n * @param {number} start - Start angle in the current p5 angle mode.\n * @param {number} end - End angle in the current p5 angle mode.\n */\nexport function arc(x, y, radius, start, end) {\n const startDeg = toDegreesSigned(start);\n const endDeg = toDegreesSigned(end);\n const sweepDeg = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweepDeg === 0) return;\n\n const p = new Plot(\"curve\");\n const segmentCount = Math.max(1, Math.ceil(sweepDeg / 90));\n const segmentSweep = sweepDeg / segmentCount;\n const arcLength = (Math.PI * radius * segmentSweep) / 180;\n\n for (let i = 0; i < segmentCount; i++) {\n p.addSegment(startDeg + i * segmentSweep + 90, arcLength, 1, true);\n }\n p.endPlot(startDeg + sweepDeg + 90, 1, true);\n\n const startX = x + radius * cos(startDeg);\n const startY = y - radius * sin(startDeg);\n p.draw(startX, startY, 1);\n}\n\n// Variables for managing paths and strokes\nlet _current;\nlet _curvature;\n\nclass SubPath {\n constructor() {\n this.isClosed = false;\n this.curvature = _curvature;\n this.vert = [];\n }\n /**\n * Adds a vertex to this subpath.\n * @param {number} x\n * @param {number} y\n * @param {number} pressure\n */\n vertex(x, y, pressure) {\n this.vert.push([x, y, pressure]);\n }\n /**\n * Renders the subpath by creating a spline from its vertices.\n */\n show() {\n let plot = _createSpline(this.vert, this.curvature, this.isClosed);\n plot.show();\n }\n}\n\n/**\n * Begins a new path with a specified curvature.\n * @param {number} [curvature=0] - Curvature from 0 to 1.\n */\nexport function beginShape(curvature = 0) {\n _curvature = constrain(curvature, 0, 1);\n _current = new SubPath();\n}\n\n/**\n * Adds a line segment from the current point to the given coordinates.\n * @param {number} x - X-coordinate.\n * @param {number} y - Y-coordinate.\n * @param {number} [pressure=1] - Pressure value.\n */\nexport function vertex(x, y, pressure = 1) {\n if (!_current) {\n throw new Error(\n \"vertex() called outside of beginShape()/endShape(). Call beginShape() first.\",\n );\n }\n _current.vertex(x, y, pressure);\n}\n\n/**\n * Ends the current path and renders all subpaths.\n */\nexport function endShape(close = false) {\n if (!_current) {\n throw new Error(\n \"endShape() called without beginShape(). Call beginShape() first.\",\n );\n }\n if (_current.vert.length < 2) {\n throw new Error(\n \"endShape() requires at least 2 vertices. Add more with vertex().\",\n );\n }\n if (close) {\n _current.vertex(..._current.vert[0]);\n _current.isClosed = true;\n }\n _current.show();\n _current = false;\n}\n\nlet _strokeArray, _strokeOrigin;\n\n/**\n * Begins a new stroke with a given type and starting position.\n * @param {string} type - Stroke type.\n * @param {number} x - Starting x.\n * @param {number} y - Starting y.\n */\nexport function beginStroke(type, x, y) {\n if (type !== \"curve\" && type !== \"segments\") {\n throw new Error(\n `beginStroke() type must be \"curve\" or \"segments\", got \"${type}\".`,\n );\n }\n _strokeOrigin = [x, y];\n _strokeArray = new Plot(type);\n}\n\n/**\n * Adds a segment to the stroke.\n * @param {number} angle - Segment angle.\n * @param {number} length - Segment length.\n * @param {number} pressure - Segment pressure.\n */\nexport function move(angle, length, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"move() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.addSegment(angle, length, pressure);\n}\n\n/**\n * Completes and renders the stroke.\n * @param {number} angle - End angle.\n * @param {number} pressure - End pressure.\n */\nexport function endStroke(angle, pressure) {\n if (!_strokeArray) {\n throw new Error(\n \"endStroke() called without beginStroke(). Call beginStroke() first.\",\n );\n }\n _strokeArray.endPlot(angle, pressure);\n _strokeArray.draw(_strokeOrigin[0], _strokeOrigin[1], 1);\n _strokeArray = false;\n}\n\n/**\n * Creates and draws a spline curve from an array of points.\n * @param {Array<Array<number>>} array_points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature from 0 to 1.\n */\nexport function spline(_array_points, _curvature = 0.5) {\n if (!_array_points || _array_points.length < 2) {\n throw new Error(\n \"spline() requires at least 2 points. Each point should be [x, y, pressure].\",\n );\n }\n let p = _createSpline(_array_points, _curvature);\n p.draw();\n}\n\n/**\n * Creates a new Plot object representing a spline curve.\n *\n * For curved segments (curvature > 0) with at least 3 points available,\n * the function either treats segments as straight (if their angles match)\n * or calculates control points to compute a circular arc.\n *\n * If no curvature is specified, a simple straight segment is used.\n *\n * @param {Array<Array<number>>} points - Array of points [x, y, pressure].\n * @param {number} [curvature=0.5] - Curvature value between 0 and 1.\n * @param {boolean} [close=false] - Whether to close the spline.\n * @returns {Plot} - The generated Plot object.\n */\nfunction _createSpline(points, curvature = 0.5, close = false) {\n const plotType = curvature === 0 ? \"segments\" : \"curve\";\n const p = new Plot(plotType);\n const PI2 = Math.PI * 2;\n\n // If closing the spline, add the second point to the end\n if (close && curvature !== 0) {\n points.push(points[1]);\n }\n\n if (points && points.length > 0) {\n let done = 0; // Tracks excess length from previous segment\n let pep, tep, pep2; // Variables used for initial calibration\n\n for (let i = 0; i < points.length - 1; i++) {\n // For curved segments (if curvature > 0 and there is at least 3 points ahead)\n if (curvature > 0 && i < points.length - 2) {\n const p1 = points[i];\n const p2 = points[i + 1];\n const p3 = points[i + 2];\n\n const d1 = dist(p1[0], p1[1], p2[0], p2[1]);\n const d2 = dist(p2[0], p2[1], p3[0], p3[1]);\n const a1 = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n const a2 = calcAngle(p2[0], p2[1], p3[0], p3[1]);\n\n // Compute the adjustment length based on curvature\n const curvAdjust = curvature * Math.min(d1, d2, 0.5 * Math.min(d1, d2));\n const dmax = Math.max(d1, d2);\n const s1 = d1 - curvAdjust;\n const s2 = d2 - curvAdjust;\n\n if (Math.floor(a1) === Math.floor(a2)) {\n // If angles are nearly the same, treat as a straight segment\n const temp = close ? (i === 0 ? 0 : d1 - done) : d1 - done;\n const temp2 = close ? (i === 0 ? 0 : d2 - pep2) : d2;\n\n p.addSegment(a1, temp, p1[2], true);\n if (i === points.length - 3) {\n p.addSegment(a2, temp2, p2[2], true);\n }\n\n done = 0;\n if (i === 0) {\n pep = d1;\n pep2 = curvAdjust;\n tep = points[1];\n done = 0;\n }\n } else {\n // For a curved segment, compute control points and arc segment details\n const point1 = {\n x: p2[0] - curvAdjust * cos(-a1),\n y: p2[1] - curvAdjust * sin(-a1),\n };\n const point2 = {\n x: point1.x + dmax * cos(-a1 + 90),\n y: point1.y + dmax * sin(-a1 + 90),\n };\n const point3 = {\n x: p2[0] + curvAdjust * cos(-a2),\n y: p2[1] + curvAdjust * sin(-a2),\n };\n const point4 = {\n x: point3.x + dmax * cos(-a2 + 90),\n y: point3.y + dmax * sin(-a2 + 90),\n };\n\n const intPt = intersectLines(point1, point2, point3, point4, true);\n const radius = dist(point1.x, point1.y, intPt.x, intPt.y);\n const halfDist = dist(point1.x, point1.y, point3.x, point3.y) / 2;\n const arcAngle = 2 * Math.asin(halfDist / radius) * (180 / Math.PI);\n const arcLength = (PI2 * radius * arcAngle) / 360;\n\n const temp = close ? (i === 0 ? 0 : s1 - done) : s1 - done;\n const temp2 =\n i === points.length - 3 ? (close ? pep - curvAdjust : s2) : 0;\n\n p.addSegment(a1, temp, p1[2], true);\n p.addSegment(a1, isNaN(arcLength) ? 0 : arcLength, p1[2], true);\n p.addSegment(a2, temp2, p2[2], true);\n\n done = curvAdjust;\n if (i === 0) {\n pep = s1;\n pep2 = curvAdjust;\n tep = [point1.x, point1.y];\n }\n }\n\n if (i === points.length - 3) {\n p.endPlot(a2, p2[2], true);\n }\n } else if (curvature === 0) {\n // If no curvature, add a simple straight segment\n const p1 = points[i];\n const p2 = points[i + 1];\n const d = dist(p1[0], p1[1], p2[0], p2[1]);\n const a = calcAngle(p1[0], p1[1], p2[0], p2[1]);\n\n p.addSegment(a, d, p2[2], true);\n if (i === points.length - 2) {\n p.endPlot(a, 1, true);\n }\n }\n }\n\n p.origin = close && curvature !== 0 ? tep : points[0];\n }\n\n return p;\n}\n","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module provides functions for rendering shapes (circles and squares)\n * using WebGL2. It initializes the WebGL context and shader programs, prepares buffers,\n * and implements drawing routines based on queued drawing primitives. The module uses\n * an orthographic projection to map canvas coordinates to clip space and supports adjustable\n * blending for translucent effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\n State,\n} from \"../core/color.js\";\nimport { Matrix } from \"../core/flowfield.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport vertSrc from \"./shader.vert\";\nimport fragSrc from \"./shader.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n projMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nconst Attr = {},\n Frag = {};\n\n// Cached matrix values — snapshotted once per stroke in snapshotMatrix()\nlet _ma = 1,\n _mb = 0,\n _mc = 0,\n _md = 1,\n _mx = 0,\n _my = 0;\n\n/**\n * Snapshots the current p5 model matrix. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n _ma = Matrix.a();\n _mb = Matrix.b();\n _mc = Matrix.c();\n _md = Matrix.d();\n _mx = Matrix.x();\n _my = Matrix.y();\n}\n\n// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)\nconst INITIAL_CAPACITY = 2048;\nlet circleData = new Float32Array(INITIAL_CAPACITY * 4);\nlet circleCount = 0;\nlet bufferCapacity = INITIAL_CAPACITY;\nlet gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n\n const nextGl = Mix.glMask.drawingContext;\n const needsContextRefresh = !isLoaded || gl !== nextGl;\n const needsProjectionRefresh =\n needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (needsProjectionRefresh) {\n projMatrix = new Float32Array([\n 2 / Cwidth,\n 0,\n 0,\n 0,\n 0,\n -2 / Cheight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n }\n\n if (!needsContextRefresh) return;\n\n gl = nextGl;\n\n // Create shader program and initialize\n program = createProgram(gl, vertSrc, fragSrc);\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n // Cache attribute and uniform locations\n [\"a_position\", \"a_radius\", \"a_alpha\"].forEach(\n (n) => (Attr[n] = gl.getAttribLocation(program, n)),\n );\n [\"u_matrix\", \"u_color\"].forEach(\n (n) => (Frag[n] = gl.getUniformLocation(program, n)),\n );\n\n // Create persistent VAO and VBO\n vao = gl.createVertexArray();\n gl.bindVertexArray(vao);\n\n buf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n gl.bufferData(gl.ARRAY_BUFFER, circleData.byteLength, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n\n // Set up vertex attributes (only needs to happen once with persistent VAO)\n const stride = 16; // 4 floats × 4 bytes\n gl.enableVertexAttribArray(Attr.a_position);\n gl.vertexAttribPointer(Attr.a_position, 2, gl.FLOAT, false, stride, 0);\n gl.enableVertexAttribArray(Attr.a_radius);\n gl.vertexAttribPointer(Attr.a_radius, 1, gl.FLOAT, false, stride, 8);\n gl.enableVertexAttribArray(Attr.a_alpha);\n gl.vertexAttribPointer(Attr.a_alpha, 1, gl.FLOAT, false, stride, 12);\n\n gl.bindVertexArray(null);\n\n isLoaded = true;\n}\n\n// =============================================================================\n// Section: Drawing Primitives\n// =============================================================================\n\n/**\n * Queue a circle to be drawn with the specified parameters.\n * Data is written directly into a flat Float32Array to avoid object allocation.\n * Applies the full 2D affine transform (rotation + scale + translation) from\n * p5's current model matrix so that brush.rotate() and brush.scale() work correctly.\n */\nexport function circle(x, y, diameter, alpha) {\n // Grow buffer if needed\n if (circleCount >= bufferCapacity) {\n bufferCapacity *= 2;\n const newData = new Float32Array(bufferCapacity * 4);\n newData.set(circleData);\n circleData = newData;\n }\n\n // x/y arrive in \"position space\": user coords + (Cwidth/2, Cheight/2).\n // Subtract the offset to recover user coords, apply the full matrix, then re-add\n // the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].\n const px = x - Cwidth / 2;\n const py = y - Cheight / 2;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + Cwidth / 2;\n const screenY = _mb * px + _md * py + _my + Cheight / 2;\n const radius =\n (Density * diameter * Math.sqrt(_ma * _ma + _mb * _mb)) / 2;\n\n circleData[offset] = screenX;\n circleData[offset + 1] = screenY;\n // Scale the diameter by the matrix's scale factor (length of the transformed x-axis)\n circleData[offset + 2] = radius;\n circleData[offset + 3] = alpha / 255;\n\n Mix.markDirtyRect(Mix.glMask, {\n minX: screenX * Density - radius - 1,\n minY: screenY * Density - radius - 1,\n maxX: screenX * Density + radius + 1,\n maxY: screenY * Density + radius + 1,\n });\n\n circleCount++;\n}\n\n/**\n * Draw all queued circles using WebGL\n */\nexport function glDraw() {\n if (circleCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader (p5 drawing may have switched programs)\n gl.useProgram(program);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.bindVertexArray(vao);\n gl.bindBuffer(gl.ARRAY_BUFFER, buf);\n\n // Upload vertex data — reallocate GPU buffer only if needed\n const byteCount = circleCount * 16; // 4 floats × 4 bytes\n const dataView = circleData.subarray(0, circleCount * 4);\n if (byteCount > gpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, circleData, gl.DYNAMIC_DRAW);\n gpuBufferSize = circleData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n // Set uniforms and draw\n gl.uniform4f(Frag.u_color, ...color);\n gl.uniformMatrix4fv(Frag.u_matrix, false, projMatrix);\n gl.drawArrays(gl.POINTS, 0, circleCount);\n\n gl.bindVertexArray(null);\n\n // Reset queue (no deallocation)\n circleCount = 0;\n\n // We called gl.useProgram() directly, bypassing p5's _curShader tracking.\n // Reset it to null so p5 is forced to re-activate its own shader next time\n // it draws — otherwise p5 skips gl.useProgram() and sets uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n Mix.glMask._renderer._curShader = null;\n}\n","// =============================================================================\n// Module: Brush\n// =============================================================================\n/**\n * The Brush module provides a comprehensive set of functions and classes for\n * simulating various drawing tools ranging from pens, markers, pencils, to\n * custom image-based brushes. This module controls brush properties such as\n * weight, color, vibration, and spacing, and manages the drawing process through\n * stateful methods that enable features like pressure sensitivity, clipping, and\n * blending. By supporting multiple brush types and dynamic parameter adjustments,\n * the Brush module facilitates the creation of realistic and expressive stroke effects.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n State,\n Renderer,\n isCanvasReady,\n} from \"../core/color.js\";\nimport {\n rr,\n map,\n dist,\n randInt,\n calcAngle,\n toDegrees,\n gaussian,\n rArray,\n noise,\n _onSeed,\n} from \"../core/utils.js\";\nimport { Position, Matrix, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { isReady, glDraw, circle, snapshotMatrix } from \"./gl_draw.js\";\n\n// ---------------------------------------------------------------------------\n// Brush State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global stroke state settings.\n */\nState.stroke = {\n color: null,\n weight: 1,\n clipWindow: null,\n type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\n\nlet Mask = null;\nlet _strokeTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n tx: 0,\n ty: 0,\n};\n\n/**\n * Retrieves a shallow copy of the current stroke state.\n * @returns {object} The stroke state.\n */\nexport function BrushState() {\n return { ...State.stroke };\n}\n\n/**\n * Updates the stroke state.\n * @param {object} state - The new stroke state.\n */\nexport function BrushSetState(state) {\n State.stroke = { ...state };\n}\n\n// =============================================================================\n// Section: Brush Manager\n// =============================================================================\n\n/**\n * Adds a new brush with the specified parameters to the brush list.\n * @param {string} name - The unique name for the new brush.\n * @param {object} params - The parameters defining the brush behavior and appearance.\n */\n/**\n * Normalizes the pressure parameter to the internal { type, min_max, curve } format.\n * Accepts:\n * [start, end] — linear ramp between two pressure values\n * [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)\n * (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]\n * { type, min_max, curve } — old internal format, passed through unchanged\n */\nfunction normalizePressure(p) {\n if (!p || (typeof p === \"object\" && !Array.isArray(p))) return p;\n if (typeof p === \"function\")\n return { type: \"custom\", min_max: [0, 1], curve: p };\n if (Array.isArray(p)) {\n const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;\n const min = Math.min(s, m, e),\n max = Math.max(s, m, e);\n const range = max - min || 1;\n const [ns, nm, ne] = [\n (s - min) / range,\n (m - min) / range,\n (e - min) / range,\n ];\n return {\n type: \"custom\",\n min_max: [min, max],\n curve: (t) =>\n t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,\n };\n }\n}\n\nexport function add(name, params) {\n const validTypes = [\"marker\", \"custom\", \"image\", \"spray\"];\n params.type = validTypes.includes(params.type) ? params.type : \"default\";\n // Accept legacy param names for backward compatibility\n if (params.vibration !== undefined && params.scatter === undefined)\n params.scatter = params.vibration;\n if (params.definition !== undefined && params.sharpness === undefined)\n params.sharpness = params.definition;\n if (params.quality !== undefined && params.grain === undefined)\n params.grain = params.quality;\n params.pressure = normalizePressure(params.pressure);\n if (params.type === \"image\") {\n if (!params.image || !params.image.src) {\n throw new Error(\n `Brush \"${name}\" is type \"image\" but is missing params.image.src. Example: image: { src: \"./tip.jpg\" }`,\n );\n }\n T.add(params.image.src);\n params.tip = () => {\n Mask.image(\n T.tips.get(current.p.image.src),\n -current.p.weight / 2,\n -current.p.weight / 2,\n current.p.weight,\n current.p.weight,\n );\n };\n list.set(name, { param: params, colors: [], buffers: [] });\n return T.load(); // returns a Promise; only loads images not yet loaded\n }\n list.set(name, { param: params, colors: [], buffers: [] });\n}\n\n/**\n * Retrieves the list of available brush names.\n * @returns {Array<string>} Array of brush names.\n */\nexport function box() {\n return [...list.keys()];\n}\n\n/**\n * Scales standard brush parameters by the provided factor.\n * @param {number} scaleFactor - The scaling factor to apply.\n */\nexport function scaleBrushes(scaleFactor) {\n for (const { param } of list.values()) {\n if (param) {\n param.weight *= scaleFactor;\n param.scatter *= scaleFactor;\n param.spacing *= scaleFactor;\n }\n }\n}\n\n/**\n * Sets the current brush type by name.\n * @param {string} brushName - The name of the brush.\n */\nexport function pick(brushName) {\n if (!list.has(brushName)) {\n throw new Error(\n `Brush \"${brushName}\" not found. Available brushes: ${[...list.keys()].join(\", \")}.`,\n );\n }\n State.stroke.type = brushName;\n}\n\n/**\n * Sets the stroke style (color) for the current brush.\n * @param {number|string|Color} r - Red component, CSS color string, or Color object.\n * @param {number} [g] - Green component.\n * @param {number} [b] - Blue component.\n */\nexport function stroke(r, g, b) {\n isCanvasReady();\n State.stroke.color = Renderer.color(...arguments);\n State.stroke.isActive = true;\n}\n\n/**\n * Sets the brush weight (thickness).\n * @param {number} weight - The weight value.\n */\nexport function strokeWeight(weight) {\n State.stroke.weight = weight;\n}\n\n/**\n * Sets the current brush with name, color, and weight.\n * @param {string} brushName - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} [weight=1] - The brush weight.\n */\nexport function set(brushName, color, weight = 1) {\n pick(brushName);\n stroke(color);\n strokeWeight(weight);\n}\n\n/**\n * Disables the stroke effect.\n */\nexport function noStroke() {\n State.stroke.isActive = false;\n}\n\nfunction snapshotTransform() {\n return {\n a: Matrix.a(),\n b: Matrix.b(),\n c: Matrix.c(),\n d: Matrix.d(),\n tx: Matrix.x(),\n ty: Matrix.y(),\n };\n}\n\nfunction invertTransform(transform) {\n const det = transform.a * transform.d - transform.b * transform.c;\n if (Math.abs(det) < 1e-12) return null;\n\n return {\n a: transform.d / det,\n b: -transform.b / det,\n c: -transform.c / det,\n d: transform.a / det,\n tx: (transform.c * transform.ty - transform.d * transform.tx) / det,\n ty: (transform.b * transform.tx - transform.a * transform.ty) / det,\n };\n}\n\nfunction transformPoint(transform, x, y) {\n return {\n x: transform.a * x + transform.c * y + transform.tx,\n y: transform.b * x + transform.d * y + transform.ty,\n };\n}\n\nfunction normalizeRegion(region) {\n const [x1, y1, x2, y2] = region;\n return {\n minX: Math.min(x1, x2),\n minY: Math.min(y1, y2),\n maxX: Math.max(x1, x2),\n maxY: Math.max(y1, y2),\n };\n}\n\nfunction currentPointInUserSpace() {\n return transformPoint(\n _strokeTransform,\n _position.x - Cwidth / 2,\n _position.y - Cheight / 2,\n );\n}\n\nfunction screenPointFromPosition(x, y) {\n const point = transformPoint(_strokeTransform, x - Cwidth / 2, y - Cheight / 2);\n return {\n x: point.x + Cwidth / 2,\n y: point.y + Cheight / 2,\n };\n}\n\nfunction markImageTipDirty(rx, ry, scale, angle) {\n const halfWeight = current.p.weight / 2;\n const radians = (angle * Math.PI) / 180;\n const cosAngle = Math.cos(radians);\n const sinAngle = Math.sin(radians);\n const userCenterX = _position.x + rx;\n const userCenterY = _position.y + ry;\n const corners = [\n [-halfWeight, -halfWeight],\n [halfWeight, -halfWeight],\n [halfWeight, halfWeight],\n [-halfWeight, halfWeight],\n ];\n\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n for (const [x, y] of corners) {\n const lx = scale * (cosAngle * x - sinAngle * y);\n const ly = scale * (sinAngle * x + cosAngle * y);\n const point = screenPointFromPosition(userCenterX + lx, userCenterY + ly);\n\n minX = Math.min(minX, point.x * Renderer.pixelDensity());\n minY = Math.min(minY, point.y * Renderer.pixelDensity());\n maxX = Math.max(maxX, point.x * Renderer.pixelDensity());\n maxY = Math.max(maxY, point.y * Renderer.pixelDensity());\n }\n\n Mix.markDirtyRect(Mix.glMask, {\n minX: minX - 2,\n minY: minY - 2,\n maxX: maxX + 2,\n maxY: maxY + 2,\n });\n}\n\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current p5 transform captured at call time.\n * @param {number[]} region - Array as [x1, y1, x2, y2] defining the clipping region.\n */\nexport function clip(region) {\n isCanvasReady();\n const inverse = invertTransform(snapshotTransform());\n if (!inverse) {\n throw new Error(\n \"brush.clip() cannot be used with a non-invertible transform.\",\n );\n }\n State.stroke.clipWindow = {\n bounds: normalizeRegion(region),\n inverse,\n };\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n State.stroke.clipWindow = null;\n}\n\n// ---------------------------------------------------------------------------\n// Drawing Variables and Functions\n// ---------------------------------------------------------------------------\nlet _position, _length, _plot, _dir;\nconst current = {};\n\n/**\n * Initializes the drawing state.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of stroke.\n * @param {boolean} flow - Flag for vector-field following.\n * @param {Object|boolean} plot - Plot object or false.\n */\nfunction initializeDrawingState(x, y, length, plot = false) {\n snapshotMatrix();\n _strokeTransform = snapshotTransform();\n _position = new Position(x + Cwidth / 2, y + Cheight / 2);\n _length = length;\n _plot = plot;\n if (_plot) _plot.calcIndex(0);\n}\n\nconst gaussians = [];\n\n_onSeed(() => {\n gaussians.length = 0;\n});\n\n/**\n * Executes the drawing operation.\n * @param {number} angleScale - Angle (in degrees) or scaling factor.\n * @param {boolean} isPlot - True if plotting a shape.\n */\nfunction draw(angleScale, isPlot) {\n if (!isPlot) _dir = angleScale;\n saveState();\n\n const stepSize = spacing();\n const totalSteps = Math.round(\n (_length * (isPlot ? angleScale : 1)) / stepSize,\n );\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n isPlot\n ? _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n )\n : _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\n restoreState();\n}\n\n/**\n * Prepares the environment for a brush stroke.\n */\nfunction saveState() {\n current.seed = rr() * 999999;\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return;\n current.p = param;\n\n Mask = Mix.glMask;\n\n // Set pressure values for the stroke\n const { pressure } = param;\n current.a = pressure.type !== \"custom\" ? rr(-1, 1) : 0;\n current.b = pressure.type !== \"custom\" ? rr(1, 1.5) : 0;\n current.cp = pressure.type !== \"custom\" ? rr(3, 3.5) : rr(-0.2, 0.2);\n [current.min, current.max] = pressure.min_max;\n\n current.noiseoffset = 0.03;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n const dirRad = (_dir * Math.PI) / 180;\n current.cos = Math.cos(dirRad);\n current.sin = Math.sin(dirRad);\n }\n\n // Ensure GL is ready and blend state\n isReady();\n const switchingToBrush = Mix.isBrush !== true;\n Mix.isBrush = true;\n if (switchingToBrush) Mix.justChanged = true;\n if (isInsideClippingArea()) Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n glDraw();\n markerTip();\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n * @param {number} [customPressure=false] - Optional custom pressure.\n */\nfunction tip(customPressure = false) {\n if (!isInsideClippingArea()) return;\n let pressure = customPressure || calculatePressure();\n\n let lineNoise = map(\n noise(current.seed + _position.plotted * 0.002, 0),\n 0,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n\n switch (current.p.type) {\n case \"spray\":\n drawSpray(pressure * lineNoise);\n break;\n case \"marker\":\n drawMarker(pressure * lineNoise);\n break;\n case \"custom\":\n case \"image\":\n drawTip(pressure * lineNoise, current.alpha);\n break;\n default:\n drawDefault(pressure * lineNoise);\n break;\n }\n}\n\n/**\n * Calculates the effective brush pressure.\n * @returns {number} The calculated pressure.\n */\nfunction calculatePressure() {\n return _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n}\n\n/**\n * Simulates brush pressure based on stroke parameters.\n * @returns {number} Simulated pressure value.\n */\nfunction simPressure() {\n return current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(_position.plotted / _length) + current.cp,\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\n}\n\n/**\n * Generates a Gaussian-based pressure value.\n * @param {number} [a] - Center parameter.\n * @param {number} [b] - Width parameter.\n * @param {number} [c] - Shape parameter.\n * @param {number} [min] - Minimum pressure.\n * @param {number} [max] - Maximum pressure.\n * @returns {number} Gaussian pressure value.\n */\nfunction gauss(\n a = 0.5 + current.p.pressure.curve[0] * current.a,\n b = 1 - current.p.pressure.curve[1] * current.b,\n c = current.cp,\n min = current.min,\n max = current.max,\n) {\n const peakPos = a * _length;\n const halfWidth =\n (_position.plotted < peakPos ? b * 1.2 : b * 0.8) * (_length / 2);\n return map(\n 1 /\n (1 +\n Math.pow(Math.abs((_position.plotted - peakPos) / halfWidth), 2 * c)),\n 0,\n 1,\n min,\n max,\n );\n}\n\n/**\n * Calculates the alpha (opacity) level for a brush stroke.\n * @returns {number} The calculated opacity.\n */\nfunction calculateAlpha() {\n return [\"default\", \"spray\"].includes(current.p.type)\n ? current.p.opacity\n : current.p.opacity / Math.min(State.stroke.weight, 1.3);\n}\n\n/**\n * Checks if the current drawing position is within the clipping region.\n * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n const point = currentPointInUserSpace();\n\n if (State.stroke.clipWindow) {\n const local = transformPoint(\n State.stroke.clipWindow.inverse,\n point.x,\n point.y,\n );\n const { bounds } = State.stroke.clipWindow;\n return (\n local.x >= bounds.minX &&\n local.x <= bounds.maxX &&\n local.y >= bounds.minY &&\n local.y <= bounds.maxY\n );\n }\n\n let o = Cwidth * 0.05;\n return (\n point.x >= -Cwidth / 2 - o &&\n point.x <= Cwidth / 2 + o &&\n point.y >= -Cheight / 2 - o &&\n point.y <= Cheight / 2 + o\n );\n}\n\n/**\n * Calculates the step spacing based on the current brush parameters.\n * @returns {number} The spacing value.\n */\nfunction spacing() {\n const { param } = list.get(State.stroke.type) ?? {};\n if (!param) return 1;\n return param.spacing;\n}\n\n// ---------------------------------------------------------------------------\n// Brush Tip Rendering Methods\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the spray tip effect.\n * @param {number} pressure - Current pressure.\n */\nfunction drawSpray(pressure) {\n const vibration =\n State.stroke.weight * current.p.scatter * pressure +\n (State.stroke.weight * rArray(gaussians) * current.p.scatter) / 3;\n const sw = current.p.weight * rr(0.9, 1.1);\n const iterations = Math.ceil(current.p.grain / pressure);\n for (let j = 0; j < iterations; j++) {\n const r = rr(0.9, 1.1);\n const rX = r * vibration * rr(-1, 1);\n const yRandomFactor = rr(-1, 1);\n const sqrtPart = Math.sqrt((r * vibration) ** 2 - rX ** 2);\n circle(\n _position.x + rX,\n _position.y + yRandomFactor * sqrtPart,\n sw,\n current.alpha,\n );\n }\n}\n\n/**\n * Draws the marker tip effect.\n * @param {number} pressure - Current pressure.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawMarker(pressure, vibrate = true, alpha = current.alpha) {\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n circle(\n _position.x + rx,\n _position.y + ry,\n State.stroke.weight * current.p.weight * pressure,\n alpha,\n );\n}\n\n/**\n * Draws a custom or image-based brush tip.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Alpha (opacity) for drawing.\n * @param {boolean} [vibrate=true] - Whether to apply vibration.\n */\nfunction drawTip(pressure, alpha, vibrate = true) {\n Mix.glMask.isDrawn = true;\n Mask.push();\n Mask.noStroke();\n let color = State.stroke.color;\n color.setAlpha(alpha);\n Mask.fill(State.stroke.color);\n const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;\n const rx = vibrate ? vibration * rr(-1, 1) : 0;\n const ry = vibrate ? vibration * rr(-1, 1) : 0;\n Mask.translate(_position.x + rx - Cwidth, _position.y + ry - Cheight);\n const scale = State.stroke.weight * pressure;\n const angle = adjustSizeAndRotation(scale, alpha);\n current.p.tip(Mask);\n Mask.pop();\n\n if (current.p.type === \"image\") {\n markImageTipDirty(rx, ry, scale, angle);\n } else {\n Mix.markFull(Mix.glMask);\n }\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n if (rr(0, current.p.grain * pressure) > 0.4) {\n let dx, dy;\n if (_plot) {\n dx = 0.7 * vibration * rr(-1, 1);\n dy = vibration * rr(-1, 1);\n } else {\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * -current.sin + along * current.cos;\n dy = perp * current.cos + along * current.sin;\n }\n circle(\n _position.x + dx,\n _position.y + dy,\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight,\n Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1),\n );\n }\n}\n\n/**\n * Adjusts the size and rotation of the brush tip before rendering.\n * @param {number} pressure - Pressure-based scaling factor.\n * @param {number} alpha - Opacity value.\n */\nfunction adjustSizeAndRotation(pressure, alpha) {\n Mask.scale(pressure);\n if (current.p.type === \"image\") {\n Mask.tint(255, 0, 0, alpha / 2);\n }\n let angle = 0;\n if (current.p.rotate === \"random\") angle = randInt(0, 360);\n else if (current.p.rotate === \"natural\") {\n angle =\n (_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle();\n }\n Mask.rotate(angle);\n return angle;\n}\n\n/**\n * Draws the marker tip with a blend effect.\n */\nfunction markerTip() {\n if (isInsideClippingArea()) {\n let pressure = calculatePressure();\n let alpha = calculateAlpha(pressure);\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, false, alpha * 5);\n }\n glDraw();\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawTip((pressure * s) / 5, alpha, false);\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Basic Drawing Operations\n// ---------------------------------------------------------------------------\n\n/**\n * Draws a line using the current brush.\n * @param {number} x1 - Start x-coordinate.\n * @param {number} y1 - Start y-coordinate.\n * @param {number} x2 - End x-coordinate.\n * @param {number} y2 - End y-coordinate.\n */\nexport function line(x1, y1, x2, y2) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n let d = dist(x1, y1, x2, y2);\n if (d == 0) return;\n initializeDrawingState(x1, y1, d);\n let angle = calcAngle(x1, y1, x2, y2);\n draw(angle, false);\n}\n\n/**\n * Draws a stroke from a starting point in a given direction.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} length - Length of the stroke.\n * @param {number} dir - Direction, interpreted using the current p5 angle mode.\n */\nexport function flowLine(x, y, length, dir) {\n if (!State.stroke.isActive || !State.stroke.color) {\n throw new Error(\n \"No brush or color set. Call brush.set('brushName', color) before drawing.\",\n );\n }\n isFieldReady();\n initializeDrawingState(x, y, length);\n draw(toDegrees(dir), false);\n}\n\n/**\n * Draws a predefined plot.\n * @param {object} p - Shape object representing the plot.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nfunction plot(p, x, y, scale) {\n isFieldReady();\n initializeDrawingState(x, y, p.length, p);\n draw(scale, true);\n}\n\n// ---------------------------------------------------------------------------\n// Standard Brushes Definition and Initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Defines a set of standard brushes with specific characteristics. Each brush is defined\n * with properties such as weight, vibration, definition, quality, opacity, spacing, and\n * pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.\n */\nconst _vals = [\n \"weight\",\n \"scatter\",\n \"sharpness\",\n \"grain\",\n \"opacity\",\n \"spacing\",\n \"pressure\",\n \"type\",\n \"tip\",\n \"rotate\",\n];\nconst _standard_brushes = [\n [\n \"pen\",\n [0.3, 0.15, 0.9, 2, 150, 0.1, { curve: [0.15, 0.2], min_max: [1.2, 1] }],\n ],\n [\n \"rotring\",\n [0.15, 0.05, 0.7, 15, 210, 0.1, { curve: [0.35, 0.2], min_max: [1.3, 1] }],\n ],\n [\n \"2B\",\n [0.3, 0.75, 0.45, 15, 180, 0.1, { curve: [0.1, 0.3], min_max: [1.1, 0.9] }],\n ],\n [\n \"HB\",\n [0.3, 0.6, 0.3, 10, 170, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"2H\",\n [0.2, 0.6, 0.3, 4, 120, 0.1, { curve: [0.15, 0.2], min_max: [1.1, 0.9] }],\n ],\n [\n \"cpencil\",\n [0.3, 0.55, 0.8, 7, 75, 0.1, { curve: [0.15, 0.2], min_max: [0.95, 1.2] }],\n ],\n [\n \"charcoal\",\n [\n 0.35,\n 1.5,\n 0.68,\n 500,\n 120,\n 0.03,\n { curve: [0.15, 0.4], min_max: [1.1, 0.95] },\n ],\n ],\n [\n \"spray\",\n [\n 0.2,\n 6,\n 15,\n 40,\n 90,\n 0.5,\n { curve: [0.2, 0.35], min_max: [0.7, 1] },\n \"spray\",\n ],\n ],\n [\n \"marker\",\n [\n 2,\n 0.2,\n null,\n null,\n 1,\n 0.03,\n { curve: [0.35, 0.25], min_max: [1.2, 0.85] },\n \"marker\",\n ],\n ],\n];\n\nfor (let s of _standard_brushes) {\n let obj = {};\n for (let i = 0; i < s[1].length; i++) obj[_vals[i]] = s[1][i];\n add(s[0], obj);\n}\n\nadd(\"diamond\", {\n type: \"custom\",\n weight: 0.78,\n scatter: 0.1,\n opacity: 17,\n spacing: 1.3,\n pressure: [1.2, 0.82],\n rotate: \"none\",\n tip: (_m) => {\n _m.rotate(45);\n _m.rect(-4, -4, 8, 8);\n _m.rect(2, 2, 3, 3);\n },\n});\n\n// ---------------------------------------------------------------------------\n// Extensions to Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Draws the polygon using the current brush.\n * @param {boolean} [_brush=false] - Optional brush name override.\n * @param {string|Color} [_color] - Optional color override.\n * @param {number} [_weight] - Optional weight override.\n */\nPolygon.prototype.draw = function (_brush = false, _color, _weight) {\n let state = BrushState();\n if (_brush) set(_brush, _color, _weight);\n if (state.isActive) {\n for (let s of this.sides) {\n line(s[0].x, s[0].y, s[1].x, s[1].y);\n }\n }\n BrushSetState(state);\n};\n\n/**\n * Draws the plot using the current brush.\n * @param {number} x - Starting x-coordinate.\n * @param {number} y - Starting y-coordinate.\n * @param {number} scale - Scale factor.\n */\nPlot.prototype.draw = function (x, y, scale) {\n if (BrushState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n plot(this, x, y, scale);\n }\n};\n\n// =============================================================================\n// Section: Loading Custom Image Tips\n// =============================================================================\n/**\n * This section defines the functionality for managing the loading and processing of image tips.\n * Images are loaded from specified source URLs, converted to a white tint for visual effects,\n * and then stored for future use. It includes methods to add new images, convert their color\n * scheme, and integrate them into the p5.js graphics library.\n */\n\n/**\n * Manages loading and processing of image tips.\n * Images are converted to white with inverted alpha for tinting via shaders.\n */\nconst T = {\n tips: new Map(),\n\n /**\n * Registers an image source for later loading.\n * @param {string} src - The source URL of the image.\n */\n add(src) {\n this.tips.set(src, false);\n },\n\n /**\n * Converts image to white with inverted alpha for tint-based rendering.\n * @param {object} image - The p5.Image to convert.\n */\n imageToWhite(image) {\n image.loadPixels();\n for (let i = 0; i < 4 * image.width * image.height; i += 4) {\n let average =\n (image.pixels[i] + image.pixels[i + 1] + image.pixels[i + 2]) / 3;\n image.pixels[i] = image.pixels[i + 1] = image.pixels[i + 2] = 255;\n image.pixels[i + 3] = 255 - average;\n }\n image.updatePixels();\n },\n\n /**\n * Loads all registered image tips. Returns a promise that resolves\n * when all images are loaded and processed.\n * @returns {Promise}\n */\n async load() {\n const entries = [...this.tips.keys()].filter((k) => !this.tips.get(k));\n await Promise.all(\n entries.map(\n (src) =>\n new Promise((resolve, reject) => {\n const nativeImg = new window.Image();\n nativeImg.onload = () => {\n const p5img = Renderer.createImage(\n nativeImg.naturalWidth,\n nativeImg.naturalHeight,\n );\n p5img.drawingContext.drawImage(nativeImg, 0, 0);\n T.imageToWhite(p5img);\n this.tips.set(src, p5img);\n resolve();\n };\n nativeImg.onerror = () =>\n reject(new Error(`Failed to load image tip: ${src}`));\n nativeImg.src = src;\n }),\n ),\n );\n },\n};\n\n/**\n * Loads all registered image tips. Must be awaited before setup/draw.\n * @returns {Promise}\n *\n * @example\n * // In your sketch:\n * await brush.preload();\n */\nexport async function preload() {\n await T.load();\n}\n","/**\n * Compiles a shader program from the given vertex and fragment sources.\n * @param {WebGL2RenderingContext} gl - The WebGL2 context.\n * @param {string} vert - Vertex shader source.\n * @param {string} frag - Fragment shader source.\n * @returns {WebGLProgram} The compiled and linked program.\n */\nexport const createProgram = (gl, vert, frag) => {\n const p = gl.createProgram();\n for (let [t, src] of [\n [gl.VERTEX_SHADER, vert],\n [gl.FRAGMENT_SHADER, frag],\n ]) {\n const s = gl.createShader(t);\n gl.shaderSource(s, src);\n gl.compileShader(s);\n gl.attachShader(p, s);\n }\n gl.linkProgram(p);\n return p;\n};","// =============================================================================\n// Module: Hatch\n// =============================================================================\n/**\n * The Hatch module contains functions and classes dedicated to applying\n * hatch patterns over shapes and polygons. It enables the simulation of\n * cross-hatching and shading effects by drawing parallel lines or strokes\n * across a geometry. The module supports adjustable spacing, angle, and\n * optional style parameters (such as randomness, continuity, and gradient),\n * giving an artistic representation similar to hand-drawn hatching techniques.\n *\n * The implementation allows for hatching to be applied either to a Polygon\n * directly or via a Plot, extending the drawing capabilities with layered,\n * stylized textures.\n */\n\nimport { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, cos, sin, rr } from \"../core/utils.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { BrushState, BrushSetState, set, line } from \"../stroke/stroke.js\";\n\n// ---------------------------------------------------------------------------\n// Hatch State and Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Global hatch state settings.\n */\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\n/**\n * Returns a shallow copy of the current hatch state.\n * @returns {object} The current hatch state.\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Updates the global hatch state.\n * @param {object} state - The new hatch state.\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Activates hatching for subsequent geometries.\n *\n * @param {number} dist - The distance between hatching lines.\n * @param {number} angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} options - Optional parameters to affect the hatching style:\n * - rand: Number value to introduce randomness.\n * - continuous: Boolean to connect adjacent lines.\n * - gradient: Number to gradually change spacing.\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Sets the hatch brush style for subsequent hatching.\n *\n * @param {string} brush - The brush name.\n * @param {string|Color} color - The brush color.\n * @param {number} weight - The brush weight (size).\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Disables hatching.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a hatching pattern over the given polygon(s).\n *\n * @param {Polygon|Polygon[]} polygons - A polygon or an array of polygons.\n */\nexport function createHatch(polygons) {\n let dist = State.hatch.dist;\n let angle = ((State.hatch.angle % 180) + 180) % 180;\n let options = State.hatch.options;\n\n // Save current stroke state\n let save = BrushState();\n // If a hatch brush is set, override with those parameters.\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n\n // Compute overall bounding box for all polygons.\n if (!Array.isArray(polygons)) polygons = [polygons];\n const overallBB = computeOverallBoundingBox(polygons);\n\n // Build a bounding polygon based on the overall bounding box.\n let ventana = new Polygon([\n [overallBB.minX, overallBB.minY],\n [overallBB.maxX, overallBB.minY],\n [overallBB.maxX, overallBB.maxY],\n [overallBB.minX, overallBB.maxY],\n ]);\n\n // Determine starting y coordinate based on angle.\n let startY = angle <= 90 && angle >= 0 ? overallBB.minY : overallBB.maxY;\n let gradient = options.gradient\n ? map(options.gradient, 0, 1, 1, 1.1, true)\n : 1;\n let dots = [];\n let i = 0;\n let dist1 = dist;\n\n // Function to generate a line for index i.\n let linea = (i) => {\n return {\n point1: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90),\n y: startY + dist1 * i * sin(-angle + 90),\n },\n point2: {\n x: overallBB.minX + dist1 * i * cos(-angle + 90) + cos(-angle),\n y: startY + dist1 * i * sin(-angle + 90) + sin(-angle),\n },\n };\n };\n\n // Generate lines and calculate intersections with polygons\n // Loop through the lines based on the distance and angle to calculate intersections with the polygons\n // The loop continues until a line does not intersect with the bounding window polygon\n // Each iteration accounts for the gradient effect by adjusting the distance between lines\n while (ventana.intersect(linea(i)).length > 0) {\n let tempArray = [];\n for (let p of polygons) {\n tempArray.push(p.intersect(linea(i)));\n }\n dots[i] = tempArray\n .flat()\n .sort((a, b) => (a.x === b.x ? a.y - b.y : a.x - b.x));\n dist1 *= gradient;\n i++;\n }\n\n // Filter out empty intersection sets.\n let gdots = dots.filter((dd) => typeof dd[0] !== \"undefined\");\n\n // Draw the hatching lines using the calculated intersections\n // If the 'rand' option is enabled, add randomness to the start and end points of the lines\n // If the 'continuous' option is set, connect the end of one line to the start of the next\n let r = options.rand || 0;\n for (let j = 0; j < gdots.length; j++) {\n let dd = gdots[j];\n let continuousLine = j > 0 && options.continuous;\n for (let i = 0; i < dd.length - 1; i += 2) {\n if (r !== 0) {\n dd[i].x += r * dist * rr(-1, 1);\n dd[i].y += r * dist * rr(-1, 1);\n dd[i + 1].x += r * dist * rr(-1, 1);\n dd[i + 1].y += r * dist * rr(-1, 1);\n }\n line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);\n if (continuousLine) {\n line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);\n }\n }\n }\n\n // Restore previous brush state.\n BrushSetState(save);\n}\n\n/**\n * Computes the bounding box for a single polygon.\n * @param {Polygon} polygon - The polygon to evaluate.\n * @returns {object} The bounding box as {minX, minY, maxX, maxY}.\n */\nfunction computeBoundingBoxForPolygon(polygon) {\n if (polygon._boundingBox) return polygon._boundingBox;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n for (let i = 0; i < polygon.a.length; i++) {\n const [x, y] = polygon.a[i];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n polygon._boundingBox = { minX, minY, maxX, maxY };\n return polygon._boundingBox;\n}\n\n/**\n * Computes an overall bounding box for an array of polygons.\n * @param {Array} polygons - Array of Polygon objects.\n * @returns {object} The overall bounding box {minX, minY, maxX, maxY}.\n */\nfunction computeOverallBoundingBox(polygons) {\n let overall = {\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity,\n };\n for (let poly of polygons) {\n const bb = computeBoundingBoxForPolygon(poly);\n overall.minX = Math.min(overall.minX, bb.minX);\n overall.minY = Math.min(overall.minY, bb.minY);\n overall.maxX = Math.max(overall.maxX, bb.maxX);\n overall.maxY = Math.max(overall.maxY, bb.maxY);\n }\n return overall;\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes\n// ---------------------------------------------------------------------------\n\n/**\n * Adds a hatch effect to the polygon.\n *\n * If a distance is provided, activates hatching with the given parameters.\n * Then, if hatch is active, applies the hatching pattern.\n *\n * @param {number} [_dist] - The distance between hatch lines.\n * @param {number} _angle - The hatch angle, interpreted using the current p5 angle mode.\n * @param {object} _options - Optional hatch options.\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) {\n createHatch(this);\n }\n HatchSetState(state);\n};\n\n/**\n * Applies hatching to a plot.\n *\n * If hatching is active, generates a polygon from the plot and applies hatch.\n *\n * @param {number} x - The x-coordinate to draw at.\n * @param {number} y - The y-coordinate to draw at.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.hatch = function (x, y, scale) {\n if (HatchState().isActive) {\n if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);\n this.pol = this.genPol(x, y, scale, 0.25);\n this.pol.hatch();\n }\n};\n","import { Mix } from \"./color.js\";\n\nfunction transformPoint(matrix, x, y) {\n return {\n x: matrix.a * x + matrix.c * y + matrix.e,\n y: matrix.b * x + matrix.d * y + matrix.f,\n };\n}\n\nfunction strokePadding(ctx, matrix) {\n const lineWidth = ctx.lineWidth || 0;\n if (lineWidth <= 0) return 1;\n\n return (\n 1 +\n (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /\n 2\n );\n}\n\n// =============================================================================\n// Section: Draw shapes to Mask Buffers\n// =============================================================================\n\n/**\n * Draws a polygon to the mask using the provided vertices.\n * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.\n */\nexport function drawPolygon(vertices) {\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n vertices.forEach((v, i) => {\n const point = transformPoint(matrix, v.x, v.y);\n minX = Math.min(minX, point.x);\n minY = Math.min(minY, point.y);\n maxX = Math.max(maxX, point.x);\n maxY = Math.max(maxY, point.y);\n\n if (i === 0) ctx.moveTo(v.x, v.y);\n else ctx.lineTo(v.x, v.y);\n });\n ctx.closePath();\n\n const padding = strokePadding(ctx, matrix);\n Mix.markDirtyRect(Mix.mask, {\n minX: minX - padding,\n minY: minY - padding,\n maxX: maxX + padding,\n maxY: maxY + padding,\n });\n}\n\n/**\n * Draws a circle to the mask.\n * @param {number} x - X-coordinate of the circle's center.\n * @param {number} y - Y-coordinate of the circle's center.\n * @param {number} d - Diameter of the circle.\n */\nexport function circle(x, y, d) {\n const PI2 = Math.PI * 2;\n const ctx = Mix.ctx;\n const matrix = ctx.getTransform();\n const radius = d / 2;\n const center = transformPoint(matrix, x, y);\n const rx = radius * Math.hypot(matrix.a, matrix.c);\n const ry = radius * Math.hypot(matrix.b, matrix.d);\n const padding = strokePadding(ctx, matrix);\n\n Mix.markDirtyRect(Mix.mask, {\n minX: center.x - rx - padding,\n minY: center.y - ry - padding,\n maxX: center.x + rx + padding,\n maxY: center.y + ry + padding,\n });\n\n ctx.moveTo(x + radius, y);\n ctx.arc(x, y, radius, 0, PI2);\n}\n","// =============================================================================\n// Module: Fill\n// =============================================================================\n/**\n * The Fill module contains functions and classes dedicated to handling\n * the fill properties of shapes within the drawing context. It supports complex fill\n * operations with effects such as bleeding to simulate watercolor-like textures. The\n * methods provided allow for setting the fill color with opacity, controlling the\n * intensity of the bleed effect, and enabling or disabling the fill operation.\n *\n * The watercolor effect implementation is inspired by Tyler Hobbs'\n * techniques for simulating watercolor paints.\n */\n\nimport { Renderer, Mix, State, Cwidth, Cheight, Density } from \"../core/color.js\";\nimport { drawPolygon, circle } from \"../core/mask.js\";\nimport {\n constrain,\n weightedRand,\n rr,\n map,\n randInt,\n gaussian,\n rotate,\n cos,\n sin,\n _onSeed,\n} from \"../core/utils.js\";\nimport { isFieldReady, Matrix } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// =============================================================================\n// Fill State and helpers\n// =============================================================================\n\n// Vertex cap for grow() — set to 0 or false to disable\nconst GROW_MAX_VERTS = 1024;\n\n/**\n * Global fill state settings.\n */\nState.fill = {\n opacity: 150,\n bleed_strength: 0.07,\n texture_strength: 0.8,\n border_strength: 0.5,\n direction: \"out\",\n isActive: false,\n};\n\n// Cache the current state\nconst FillState = () => ({ ...State.fill });\nconst FillSetState = (state) => {\n State.fill = { ...state };\n};\n\n// ---------------------------------------------------------------------------\n// Fill Style Functions\n// ---------------------------------------------------------------------------\n\n/**\n * Sets the fill color and opacity for subsequent drawing operations.\n * @param {number|string|Color} a - Either the red component, a CSS color string, or a Color object.\n * @param {number} [b] - The green component or the opacity if using grayscale.\n * @param {number} [c] - The blue component.\n * @param {number} [d] - The opacity.\n */\nexport function fill(a, b, c, d) {\n State.fill.opacity = (arguments.length < 4 ? b : d) || 150;\n State.fill.color =\n arguments.length < 3 ? Renderer.color(a) : Renderer.color(a, b, c);\n State.fill.isActive = true;\n}\n\n/**\n * Sets the bleed (watercolor) intensity and direction.\n * @param {number} _i - The bleed intensity (clamped to [0,1]).\n * @param {string} [_direction=\"out\"] - The bleeding direction.\n */\nexport function fillBleed(_i, _direction = \"out\") {\n State.fill.bleed_strength = constrain(_i, 0, 1);\n State.fill.direction = _direction;\n}\n\n/**\n * Sets the texture and border strengths for the fill.\n * @param {number} [_texture=0.4] - The texture strength (clamped to [0,1]).\n * @param {number} [_border=0.4] - The border strength (clamped to [0,1]).\n */\nexport function fillTexture(_texture = 0.4, _border = 0.4) {\n State.fill.texture_strength = constrain(_texture, 0, 1);\n State.fill.border_strength = constrain(_border, 0, 1);\n}\n\n/**\n * Disables fill for subsequent drawing operations.\n */\nexport function noFill() {\n State.fill.isActive = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fill Manager Functions\n// ---------------------------------------------------------------------------\n\nlet _polygon;\n\n// Pre-compute gaussians for reuse\nconst GAUSSIAN_POOL_SIZE = 512;\nconst _gaussians = [[], []]; // [a, b]\nfunction _fillGaussianPools() {\n for (let i = 0; i < GAUSSIAN_POOL_SIZE; i++) {\n _gaussians[0][i] = gaussian(0.5, 0.2);\n _gaussians[1][i] = gaussian(0, 0.02);\n }\n}\n_onSeed(_fillGaussianPools);\n\n// Helper for direction checking - extracted to reduce duplication\nfunction _isLeft(a, b, c) {\n return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) > 0.01;\n}\n\n/**\n * Calculates the centroid of a polygon from its vertices.\n * @param {Object[]} pts - Array of points with {x, y}.\n * @returns {Object} The center point {x, y}.\n */\nfunction _center(pts) {\n if (pts.length < 8) {\n // Simple average for small polygons\n return pts\n .reduce((c, p) => ({ x: c.x + p.x, y: c.y + p.y }), { x: 0, y: 0 })\n .map((v) => v / pts.length);\n }\n\n // Close polygon if needed\n const v = [...pts];\n if (v[0].x !== v[v.length - 1].x || v[0].y !== v[v.length - 1].y)\n v.push(v[0]);\n\n // Calculate using shoelace formula (more efficient implementation)\n let area = 0,\n cx = 0,\n cy = 0;\n for (let i = 0; i < v.length - 1; i++) {\n const cross = v[i].x * v[i + 1].y - v[i + 1].x * v[i].y;\n area += cross;\n cx += (v[i].x + v[i + 1].x) * cross;\n cy += (v[i].y + v[i + 1].y) * cross;\n }\n\n area *= 0.5;\n return area\n ? { x: cx / (6 * area), y: cy / (6 * area) }\n : { x: v[0].x, y: v[0].y };\n}\n\n/**\n * Fills a given polygon with a watercolor effect.\n * @param {Polygon} polygon - The polygon to fill.\n */\nexport function createFill(polygon) {\n if (!State.fill.isActive || !State.fill.color) {\n throw new Error(\n \"No fill color set. Call brush.fill(color) before drawing shapes.\",\n );\n }\n _polygon = polygon;\n const v = [...polygon.vertices];\n\n // Map vertices\n const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n\n // Create bleed modifiers\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.2) * strength,\n );\n\n // Randomize starting point\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n\n // Calculate center and create FillPolygon\n const center = _center(shifted);\n new FillPoly(shifted, modifiers, center, [], true).fill(\n State.fill.color,\n map(State.fill.opacity, 0, 255, 0, 1, true),\n State.fill.texture_strength,\n );\n}\n\n// ---------------------------------------------------------------------------\n// FillPolygon Class\n// ---------------------------------------------------------------------------\n\n/**\n * The FillPolygon class is used to create and manage the properties of the polygons that produces\n * the watercolor effect. It includes methods to grow (expand) the polygon and apply layers\n * of color with varying intensity and erase parts to simulate a natural watercolor bleed.\n * The implementation follows Tyler Hobbs' guide to simulating watercolor:\n * https://tylerxhobbs.com/essays/2017/a-generative-approach-to-simulating-watercolor-paints\n */\nclass FillPoly {\n /**\n * Constructs a FillPolygon.\n * @param {Object[]} _v - Vertices of the polygon.\n * @param {number[]} _m - Multipliers for the bleed effect at each vertex.\n * @param {Object} _center - The polygon's center {x, y}.\n * @param {boolean[]} dir - Array indicating bleed direction per vertex.\n * @param {boolean} isFirst - True for initial polygon.\n */\n constructor(v, m, center, dir = [], isFirst = false, sx, sy) {\n // Initialize properties\n this.v = v;\n this.m = m;\n this.dir = dir;\n this.midP = center;\n\n // Initialize size and direction for first polygon\n if (isFirst) {\n // Calculate size bounds\n let maxX = 0,\n maxY = 0;\n const rayCalc = [];\n\n for (let i = 0; i < v.length; i++) {\n // Store vertex distances to center for size calculation\n const dx = Math.abs(center.x - v[i].x);\n const dy = Math.abs(center.y - v[i].y);\n maxX = Math.max(maxX, dx);\n maxY = Math.max(maxY, dy);\n\n // Store edge info for ray calculations\n const v1 = v[i],\n v2 = v[(i + 1) % v.length];\n const side = { x: v2.x - v1.x, y: v2.y - v1.y };\n const rt = rotate(0, 0, side.x, side.y, 90);\n const mid = { x: v1.x + side.x / 2, y: v1.y + side.y / 2 };\n\n rayCalc.push({\n v1,\n v2,\n ray: {\n point1: mid,\n point2: { x: mid.x + rt.x, y: mid.y + rt.y },\n },\n });\n }\n\n // Store sizes\n this.sizeX = maxX;\n this.sizeY = maxY;\n\n // Calculate directions\n this.dir = Array(v.length);\n rayCalc.forEach((rc, i) => {\n let count = 0;\n for (const isect of _polygon.intersect(rc.ray)) {\n if (_isLeft(rc.v1, rc.v2, isect)) count++;\n }\n this.dir[i] = count % 2 === 0;\n });\n\n // Randomize center (single calculation)\n const rx = rr(-0.6, 0.6) * maxX;\n const ry = rr(-0.6, 0.6) * maxY;\n this.midP = { x: center.x + rx, y: center.y + ry };\n } else {\n this.sizeX = sx;\n this.sizeY = sy;\n }\n }\n\n /**\n * Trims vertices from the polygon based on a factor.\n * @param {number} [factor=1] - Factor determining amount of trimming.\n * @returns {Object} An object containing trimmed vertices, multipliers, and direction.\n */\n trim(f = 1) {\n // Fast path for common case\n if (f >= 1 || f < 0 || this.v.length <= 8) {\n return { v: [...this.v], m: [...this.m], dir: [...this.dir] };\n }\n\n // Trim from middle for balance\n const n = ~~((1 - f) * this.v.length);\n const s = ~~(this.v.length / 2 - n / 2);\n\n // Clone and splice\n const v = [...this.v],\n m = [...this.m],\n dir = [...this.dir];\n v.splice(s, n);\n m.splice(s, n);\n dir.splice(s, n);\n\n return { v, m, dir };\n }\n\n /**\n * Randomly samples a fraction of vertices, keeping their order.\n * Any sampled vertex outside the original polygon is pulled inward.\n * @param {number} [ratio=0.3] - Fraction of vertices to keep.\n * @returns {FillPoly} A new FillPoly with fewer vertices, guaranteed inside the original.\n */\n scatter(ratio = 0.3) {\n const L = this.v.length;\n const keep = Math.max(3, ~~(L * ratio));\n\n // Build sorted random indices\n const indices = [];\n const step = L / keep;\n for (let i = 0; i < keep; i++) {\n indices.push(~~(i * step + rr(0, step * 0.8)));\n }\n\n const sv = [], sm = [], sd = [];\n const mid = this.midP;\n const sides = _polygon.sides;\n\n for (const idx of indices) {\n const j = idx % L;\n let p = this.v[j];\n\n // Ray-cast: count intersections from p to far right\n let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y, by = b.y;\n if ((ay > p.y) === (by > p.y)) continue;\n const t = (p.y - ay) / (by - ay);\n if (p.x < a.x + t * (b.x - a.x)) crossings++;\n }\n // If outside (even crossings), pull toward center\n if (crossings % 2 === 0) {\n p = {\n x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),\n y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),\n };\n }\n\n sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]); // flip direction → grow inward\n }\n\n return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Returns a copy with all bleed directions flipped.\n */\n flipDirs() {\n return new FillPoly(this.v, this.m, this.midP, this.dir.map(d => !d), false, this.sizeX, this.sizeY);\n }\n\n /**\n * Grows (or shrinks) the polygon vertices to simulate watercolor spread.\n * @param {number} [growthFactor=1] - Factor controlling growth.\n * @returns {FillPoly} A new FillPoly with adjusted vertices.\n */\n grow(f = 1) {\n // Get trimmed vertices\n const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n \n // Pre-allocate output arrays\n const outLen = len * 2;\n const newVerts = new Array(outLen);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\n \n // Determine bleed direction\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n \n // Ensure gaussian pool is filled\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0], gPoolLen = gPool.length;\n const g2Pool = _gaussians[1], g2PoolLen = g2Pool.length;\n \n let idx = 0;\n let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;\n \n for (let i = 0; i < len; i++) {\n const cv = tr_v[i];\n const nv = tr_v[i + 1 < len ? i + 1 : 0];\n const mi = tr_m[i];\n const di = tr_dir[i];\n \n if (f < 997) mod = mi;\n \n // Inline rotate: rotDeg = ±bleedDirDeg + small jitter\n const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\n \n const sideX = nv.x - cv.x;\n const sideY = nv.y - cv.y;\n const dirX = c * sideX + s * sideY;\n const dirY = c * sideY - s * sideX;\n \n // Outward distance: inline rArray + rr\n const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n \n // First vertex: original\n newVerts[idx] = cv;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n \n // Second vertex: midpoint + outward push\n newVerts[idx] = {\n x: cv.x + sideX * 0.5 + dirX * d,\n y: cv.y + sideY * 0.5 + dirY * d,\n };\n newMods[idx] = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n newDirs[idx] = di;\n idx++;\n }\n \n // Cap vertex count to prevent exponential blowup.\n let fv = newVerts, fm = newMods, fd = newDirs;\n let growe = GROW_MAX_VERTS / (State.fill.texture_strength);\n if (growe && idx > growe) {\n const step = Math.ceil(idx / growe);\n fv = []; fm = []; fd = [];\n for (let j = 0; j < idx; j += step) {\n fv.push(newVerts[j]);\n fm.push(newMods[j]);\n fd.push(newDirs[j]);\n }\n } else {\n // Trim pre-allocated arrays to actual size\n fv.length = idx;\n fm.length = idx;\n fd.length = idx;\n }\n \n return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);\n }\n\n /**\n * Fills the polygon with multiple layers to simulate a watercolor effect.\n * @param {Color|string} color - The fill color.\n * @param {number} intensity - Opacity intensity (mapped from 0 to 1).\n * @param {number} tex - Texture factor.\n */\n fill(color, intensity, tex) {\n // Precalculate stuff\n const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\n // Perform initial setup only once\n const switchingToFill = Mix.isBrush !== false;\n Mix.isBrush = false;\n if (switchingToFill) Mix.justChanged = true;\n Mix.blend(color);\n\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * Matrix.a(), Density * Matrix.b(),\n Density * Matrix.c(), Density * Matrix.d(),\n Density * (Matrix.x() + Cwidth / 2),\n Density * (Matrix.y() + Cheight / 2),\n );\n\n Mix.ctx.strokeStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${\n 0.005 * State.fill.border_strength\n })`;\n Mix.ctx.lineCap = \"round\";\n\n const size = Math.max(this.sizeX, this.sizeY);\n const darker = rr(0.15, 0.7);\n\n // Create initial polygon\n let pol = this.grow();\n // Create sparse inner polygon from original (pre-grow) vertices\n const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();\n let pols;\n\n for (let i = 0; i < numLayers; i++) {\n // Grow polygon every 4 layers\n if (i % 4 === 0) pol = pol.grow();\n\n // Create variant polygons\n if (i % 2 === 0) {\n pols = [\n pol.grow(1 - 0.0125 * i),\n pol.grow(0.7 - 0.0125 * i),\n pol.grow(0.4 - 0.0125 * i),\n ];\n }\n\n // Draw layers\n for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);\n sparse.grow(999).flipDirs().grow(997).layer(i, size, int * 1.5 * texture, color);\n if (i % 2 === 0)\n pol\n .grow(darker)\n .grow(999)\n .layer(i, size, int * 2, color);\n\n // Apply texture and blend periodically\n if (i % 5 === 0 || i === numLayers - 1) {\n if (texture !== 0) pol.erase(texture * 3, intensity);\n Mix.blend(color, true, false, true);\n }\n }\n\n Mix.ctx.restore();\n }\n\n /**\n * Draws a layer of the fill polygon with stroke and fill.\n * @param {number} i - The layer index.\n */\n layer(i, size, int, color) {\n Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);\n Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\n drawPolygon(this.v);\n Mix.ctx.fill();\n Mix.ctx.stroke();\n }\n\n /**\n * Erases parts of the polygon to create a natural watercolor texture.\n * @param {number} texture - Texture strength factor.\n * @param {number} intensity - Intensity value for size scaling.\n */\n erase(texture, intensity) {\n Mix.ctx.save();\n\n // Optimize by pre-calculating values\n const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));\n const halfSizeX = this.sizeX / 1.3;\n const halfSizeY = this.sizeY / 1.3;\n const minSize =\n Math.min(this.sizeX, this.sizeY) * (1.4 - State.fill.bleed_strength);\n const minSizeFactor = 0.05 * minSize;\n const maxSizeFactor = 0.4 * minSize;\n const { x: midX, y: midY } = this.midP;\n\n // Set up erase mode\n Mix.ctx.globalCompositeOperation = \"destination-out\";\n\n // Calculate transparency\n const alpha =\n ((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;\n Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;\n Mix.ctx.lineWidth = 0;\n\n // Draw erase circles\n for (let i = 0; i < numCircles; i++) {\n const x = midX + gaussian(0, halfSizeX);\n const y = midY + gaussian(0, halfSizeY);\n const size = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, size);\n if (i % 5 !== 0) Mix.ctx.fill();\n }\n\n Mix.ctx.globalCompositeOperation = \"source-over\";\n Mix.ctx.restore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Extend Polygon and Plot Prototypes for Fill\n// ---------------------------------------------------------------------------\n\n/**\n * Applies a fill effect to the polygon using the current fill state.\n * @param {Color|string} [_color] - The color for the fill.\n * @param {number} [_opacity] - The opacity value.\n * @param {number} [_bleed] - The bleed intensity.\n * @param {number} [_texture] - The texture strength.\n * @param {number} [_border] - The border strength.\n * @param {string} [_direction] - The bleed direction.\n */\nPolygon.prototype.fill = function (\n _color = false,\n _opacity,\n _bleed,\n _texture,\n _border,\n _direction,\n) {\n let state = FillState();\n if (_color) {\n fill(_color, _opacity);\n fillBleed(_bleed, _direction);\n fillTexture(_texture, _border);\n }\n if (state.isActive) {\n isFieldReady();\n createFill(this);\n }\n FillSetState(state);\n};\n\n/**\n * Fills a plot on the canvas by generating a polygon based on the provided coordinates.\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - Scaling factor.\n */\nPlot.prototype.fill = function (x, y, scale) {\n if (FillState().isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n this.pol = this.genPol(\n x,\n y,\n scale,\n map(State.fill.bleed_strength, 0, 0.6, 0.3, 0.45, true),\n );\n this.pol.fill();\n }\n};\n","import { State } from \"./color.js\";\nimport { isFieldReady } from \"./flowfield.js\";\n\n// =============================================================================\n// SAVE / RESTORE\n// =============================================================================\n\n/**\n * Stack of saved brush states for push/pop operations.\n * A stack (not a single slot) is required because applyShader() internally\n * calls Renderer.push()/pop(), which fires our hook — a flat object would be\n * overwritten mid-draw and pop() would restore the wrong state.\n */\nconst _stateStack = [];\n\n/**\n * Pushes the current brush state onto the stack.\n */\nexport function push() {\n isFieldReady();\n _stateStack.push({\n fill: { ...State.fill },\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n field: { ...State.field },\n });\n}\n\n/**\n * Pops the top brush state from the stack and restores it.\n */\nexport function pop() {\n const saved = _stateStack.pop();\n if (!saved) return;\n State.stroke = { ...saved.stroke };\n State.field = { ...saved.field };\n State.hatch = { ...saved.hatch };\n State.fill = { ...saved.fill };\n}\n","/**\n * @fileoverview p5.brush - A comprehensive toolset for brush management in p5.js.\n * @version 2.0.0-alpha\n * @license MIT\n * @author Alejandro Campos Uribe\n *\n * @description\n * p5.brush is a p5.js library dedicated to the creation and management of custom brushes.\n * It extends the drawing capabilities of p5.js by allowing users to simulate a wide range\n * of brush strokes, vector fields, hatching patterns, and fill textures. These features\n * are essential for emulating the nuanced effects found in traditional sketching and painting.\n * Whether for digital art applications or procedural generation of graphics, p5.brush provides\n * a robust framework for artists and developers to create rich, dynamic, and textured visuals.\n *\n * @example\n * // Basic usage:\n * brush.pick('marker'); // Select brush type\n * brush.stroke(255, 0, 0); // Set brush color\n * brush.strokeWeight(10); // Set brush size\n * brush.line(25, 25, 75, 75); // Draw a line\n *\n * // Add a new brush type:\n * brush.add('customBrush', { /* parameters for the brush *\\/ });\n * brush.pick('customBrush');\n *\n * // Use the custom brush for a vector-field line:\n * brush.field('field_name') // Pick a flowfield\n * brush.flowLine(50, 50, 100, PI / 4); // Draw a line within the vector-field; angle follows p5 angleMode()\n *\n * // Fill textures:\n * brush.noStroke();\n * brush.fill('#FF0000', 90); // Set fill color to red and opacity to 90\n * brush.bleed(0.3); // Set bleed effect for a watercolor-like appearance\n * brush.rect(100, 100, 50, 50); // Fill a rectangle with the bleed effect\n *\n * @license\n * MIT License\n *\n * Copyright (c) 2023-2024 Alejandro Campos Uribe\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n// Randomness and other auxiliary functions\nexport { weightedRand as wRand } from \"./core/utils.js\";\n\n// Color Blending\nexport { load, instance } from \"./core/color.js\";\n\n// Matrix transformations, FlowField and Position Class\nexport {\n field,\n noField,\n addField,\n refreshField,\n listFields,\n Position,\n wiggle,\n} from \"./core/flowfield.js\";\n\n// Polygon and Plot classes\nexport { Polygon } from \"./core/polygon.js\";\nexport { Plot } from \"./core/plot.js\";\n\n// Primitives\nexport {\n rect,\n circle,\n arc,\n beginShape,\n vertex,\n endShape,\n beginStroke,\n move,\n endStroke,\n spline,\n polygon,\n} from \"./core/primitives.js\";\n\n// Brushes\nexport {\n add,\n box,\n scaleBrushes,\n pick,\n stroke,\n strokeWeight,\n set,\n noStroke,\n clip,\n noClip,\n line,\n flowLine,\n} from \"./stroke/stroke.js\";\n\n// Section: Hatching\nexport {\n hatch,\n hatchStyle,\n noHatch,\n createHatch as hatchArray,\n} from \"./hatch/hatch.js\";\n\n// Fill\nexport { fill, noFill, fillTexture, fillBleed } from \"./fill/fill.js\";\n\n// p5 addon registration\nimport { Mix } from \"./core/color.js\";\nimport { push as brushPush, pop as brushPop } from \"./core/save.js\";\nimport { seed as brushSeed, noiseSeed as brushNoiseSeed } from \"./core/utils.js\";\n\nfunction registerAddon(_p5, fn, lifecycles) {\n lifecycles.postsetup = () => Mix.blend(false, true);\n lifecycles.postdraw = () => Mix.blend(false, true);\n\n const _push = fn.push;\n const _pop = fn.pop;\n const _randomSeed = fn.randomSeed;\n const _noiseSeed = fn.noiseSeed;\n\n fn.push = function () {\n _push.call(this);\n brushPush();\n };\n\n fn.pop = function () {\n _pop.call(this);\n brushPop();\n };\n\n fn.randomSeed = function (s) {\n _randomSeed.call(this, s);\n brushSeed(s);\n };\n\n fn.noiseSeed = function (s) {\n _noiseSeed.call(this, s);\n brushNoiseSeed(s);\n };\n}\n\nif (typeof p5 !== \"undefined\") p5.registerAddon(registerAddon);\n"],"names":["Cwidth","Cheight","Instance","Renderer","Density","isFramebufferTarget","target","begin","end","renderer","_pInst","getSketchRenderer","_isInstanced","window","self","p5","instance","removeTargetBuffer","buffer","remove","getActiveFramebuffer","_renderer","activeFramebuffer","getTargetPixelSize","width","Math","max","round","height","normalizeDirtyRect","rect","minX","floor","min","maxX","minY","maxY","ceil","getFullDirtyRect","withScissor","gl","draw","box","normalized","x","y","toScissorBox","wasEnabled","isEnabled","SCISSOR_TEST","prevBox","getParameter","SCISSOR_BOX","enable","scissor","disable","load","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","isMixReady","isBlending","cachedColor","Object","markDirtyRect","a","b","dirtyRect","isDrawn","markFull","clearMask","clear","getCompositeRect","isBrushMask","padding","expandDirtyRect","captureBlendSource","framebuffer","blendSourceFramebuffer","pixelDensity","createFramebuffer","density","antialias","depth","stencil","source","drawingContext","push","imageMode","CENTER","image","pop","graphicsFactory","createGraphics","p2dMode","P2D","webglMode","WEBGL","mask","glMask","this","ctx","shaderProgram","createShader","angleMode","DEGREES","lineWidth","uModelMatrix","blend","_color","_isLast","activeIsBrush","isBrush","no_mask","nextColor","_array","colorChanged","justChanged","applyShader","shader","targetIsFramebuffer","hadDepthTest","DEPTH_TEST","translate","setUniform","fill","noStroke","resetShader","SQRT3","sqrt","F2","G2","fastFloor","grad2","Float64Array","createNoise2D","random","perm","p","Uint8Array","i","tableSize","r","aux","buildPermutationTable","permGrad2x","map","v","permGrad2y","n0","n1","n2","s","j","t","x0","y0","i1","j1","x1","y1","x2","y2","ii","jj","t0","gi0","t1","gi1","t2","gi2","prng_alea","seed","opts","xg","AleaGen","prng","next","double","int32","quick","constructor","Date","n","mash","data","String","length","charCodeAt","h","c","s0","s1","s2","copy","f","rng","_seedCallbacks","_onSeed","cb","noise","rr","e","rArray","array","randInt","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","d","withinBounds","constrain","low","high","nAngle","angle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","NaN","sLookup","idx","sin","toDegrees","rad","isRad","RADIANS","toDegreesSigned","rotate","cx","cy","coseno","seno","dist","hypot","calcAngle","atan2","intersectLines","s1a","s1b","s2a","s2b","includeSegmentExtension","x3","y3","x4","y4","deltaX1","deltaY1","deltaX2","deltaY2","denominator","ua","ub","Matrix","mat4","isLoaded","isFieldReady","resolution","left_x","top_y","num_columns","num_rows","addField","field","bs","ba","fillField","ar","abs","dif","sr","cr","_t","dir","offset","attractors","Array","from","wx","wy","att","dx","dy","w","freq","amp","_r","Position","update","plotted","colIdx","getColIndex","rowIdx","getRowIndex","reset","isIn","isActive","isInCanvas","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","y_offset","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","has","generateField","entry","normalizeFieldAngles","gen","keys","join","name","funct","set","fn","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","intersection","show","stroke","hatch","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","_current","_curvature","_strokeArray","_strokeOrigin","SubPath","isClosed","curvature","vert","vertex","_createSpline","beginShape","endShape","close","PI2","pep","tep","pep2","done","p1","p2","p3","d1","d2","a1","a2","curvAdjust","dmax","temp","temp2","point3","point4","intPt","radius","halfDist","arcLength","asin","origin","projMatrix","vao","buf","program","loadedWidth","loadedHeight","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circle","diameter","alpha","newData","px","py","screenX","screenY","glDraw","color","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","uniform4f","u_color","uniformMatrix4fv","u_matrix","drawArrays","POINTS","_curShader","weight","clipWindow","opacity","_position","Mask","_strokeTransform","tx","ty","BrushState","BrushSetState","state","add","params","includes","undefined","vibration","scatter","definition","sharpness","quality","grain","isArray","min_max","curve","m","range","ns","nm","ne","normalizePressure","src","T","tip","tips","param","colors","buffers","pick","brushName","g","arguments","strokeWeight","snapshotTransform","transformPoint","transform","normalizeRegion","region","screenPointFromPosition","point","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","noiseoffset","dirRad","nextGl","needsContextRefresh","createProgram","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","isReady","switchingToBrush","isInsideClippingArea","calculateAlpha","markerTip","saveState","stepSize","spacing","totalSteps","customPressure","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","local","inverse","bounds","o","vibrate","rx","ry","setAlpha","tint","adjustSizeAndRotation","halfWeight","radians","cosAngle","sinAngle","userCenterX","userCenterY","corners","Infinity","markImageTipDirty","_vals","_standard_brushes","obj","_m","prototype","_brush","_weight","imageToWhite","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","p5img","createImage","naturalWidth","naturalHeight","drawImage","onerror","HatchState","rand","continuous","gradient","createHatch","polygons","save","hBrush","values","overallBB","overall","poly","bb","computeBoundingBoxForPolygon","computeOverallBoundingBox","ventana","startY","dots","dist1","linea","tempArray","flat","sort","gdots","dd","continuousLine","polygon","_boundingBox","matrix","strokePadding","getTransform","center","arc","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","sx","sy","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","splice","ratio","L","keep","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","newVerts","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","fv","fm","fd","growe","intensity","tex","texture","int","switchingToFill","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","size","darker","sparse","pols","layer","numLayers","erase","restore","fillStyle","beginPath","lineTo","closePath","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","_opacity","_bleed","fluid","strength","modifiers","_","shift","shifted","slice","pts","area","cross","_center","createFill","FillSetState","_stateStack","registerAddon","_p5","lifecycles","postsetup","postdraw","_push","_pop","_randomSeed","randomSeed","_noiseSeed","noiseSeed","call","saved","brushPop","callback","brushSeed","brushNoiseSeed","startDeg","sweepDeg","segmentCount","segmentSweep","startX","angleOffset","randomFactor","randomAngle","offsetX","offsetY","det","invertTransform","brush","inst","mode","currentField","_array_points"],"mappings":"6BAYO,IAAIA,EAAQC,EAASC,EAAUC,EAAUC,EAEhD,MAAMC,EAAuBC,KACzBA,GACsB,mBAAjBA,EAAOC,OACQ,mBAAfD,EAAOE,OACZF,EAAOG,YACPH,EAAOG,SAASC,OAEdC,EAAoB,IACxBC,EAAeV,EAAWW,OAAOC,KAAKC,GAAGC,SA4CrCC,EAAsBC,IACtBA,GAAmC,mBAAlBA,EAAOC,QAC1BD,EAAOC,UAOLC,EAAuB,IAC3BjB,GACAA,EAASkB,WACuC,mBAAzClB,EAASkB,UAAUC,kBACtBnB,EAASkB,UAAUC,oBACnB,KAoBAC,EAAqB,KAAA,CACzBC,MAAOC,KAAKC,IAAI,EAAGD,KAAKE,MAAM3B,EAASI,IACvCwB,OAAQH,KAAKC,IAAI,EAAGD,KAAKE,MAAM1B,EAAUG,MAarCyB,EAAsBC,IAC1B,IAAKA,EAAM,OAAO,KAElB,MAAMN,MAAEA,EAAKI,OAAEA,GAAWL,IACpBQ,EAAON,KAAKC,IAAI,EAAGD,KAAKO,MAAMP,KAAKQ,IAAIH,EAAKC,KAAMD,EAAKI,QACvDC,EAAOV,KAAKC,IAAI,EAAGD,KAAKO,MAAMP,KAAKQ,IAAIH,EAAKK,KAAML,EAAKM,QACvDF,EAAOT,KAAKQ,IAAIT,EAAOC,KAAKY,KAAKZ,KAAKC,IAAII,EAAKC,KAAMD,EAAKI,QAC1DE,EAAOX,KAAKQ,IAAIL,EAAQH,KAAKY,KAAKZ,KAAKC,IAAII,EAAKK,KAAML,EAAKM,QAEjE,OAAIF,GAAQH,GAAQK,GAAQD,EAAa,KAElC,CAAEJ,OAAMI,OAAMD,OAAME,SAevBE,EAAmB,KACvB,MAAMd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sBlQ,EAAI,GAC/B,IAAK/F,EAAM4N,MAAMiC,WAAa7P,EAAM4N,MAAMqC,QACxC,MAAM,IAAIxQ,MACR,6FAGJ,MAAM0wB,EAAepgB,GAAKC,IAAIhQ,EAAM4N,MAAMqC,SAC1CkgB,EAAaviB,MAAQ6D,GAAc0e,EAAcpqB,EACnD,iBK9GO,SAAsB+K,GAC3B,IAAK,MAAMkM,MAAEA,KAAWjN,GAAK8U,SACvB7H,IACFA,EAAMlC,QAAUhK,EAChBkM,EAAMlB,SAAWhL,EACjBkM,EAAMkD,SAAWpP,EAGvB,oBF4EO,SAAgBsf,EAAe7a,EAAa,IACjD,IAAK6a,GAAiBA,EAAcpoB,OAAS,EAC3C,MAAM,IAAIvI,MACR,+EAGIsW,GAAcqa,EAAe7a,GACnC9W,MACJ,+DHmFO,SAAgB6B,EAAI,GACzBsN,GAAM,QACN5N,EAAM4N,MAAMsC,OAAS5P,CACvB","x_google_ignoreList":[1,2]}
\ No newline at end of file
+{"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/core/gl/utils.js","../src/stroke/gl_draw.js","../src/stroke/stroke.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// Module: 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\n// =============================================================================\n// Section: Composite Profiling\n// =============================================================================\nconst CompositeProfile = {\n enabled: false,\n stats: new Map(),\n timer: null,\n};\n\nconst getCompositeProfileFlag = () => {\n if (typeof window === \"undefined\") return false;\n if (window.__P5_BRUSH_COMPOSITE_PROFILE__ != null) {\n return !!window.__P5_BRUSH_COMPOSITE_PROFILE__;\n }\n return new URLSearchParams(window.location.search).get(\"compositeProfile\") === \"on\";\n};\n\nconst now = () => globalThis.performance?.now?.() ?? Date.now();\n\nconst profileComposite = (name, fn) => {\n if (!CompositeProfile.enabled) return fn();\n const start = now();\n try {\n return fn();\n } finally {\n const stat = CompositeProfile.stats.get(name) ?? { total: 0, count: 0 };\n stat.total += now() - start;\n stat.count += 1;\n CompositeProfile.stats.set(name, stat);\n if (CompositeProfile.timer) clearTimeout(CompositeProfile.timer);\n CompositeProfile.timer = setTimeout(() => {\n const rows = [...CompositeProfile.stats.entries()]\n .map(([operation, stat]) => ({\n operation,\n total_ms: stat.total.toFixed(2),\n count: stat.count,\n avg_ms: (stat.total / stat.count).toFixed(4),\n }))\n .sort((a, b) => Number(b.total_ms) - Number(a.total_ms));\n console.log(\n `[p5.brush composite profile] entries=${rows.length}`,\n );\n console.table(rows);\n }, 300);\n }\n};\n\n// =============================================================================\n// Section: Target Resolution\n// =============================================================================\n\n/**\n * Checks whether the given draw target is a p5.Framebuffer-like object.\n * @param {*} target - Candidate draw target.\n * @returns {boolean} True when the target behaves like a p5.Framebuffer.\n */\nconst isFramebufferTarget = (target) =>\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer &&\n !!target.renderer._pInst;\n\n/**\n * Resolves the sketch renderer that owns the current drawing session.\n * @returns {p5|Window[\"p5\"][\"instance\"]} The active sketch renderer.\n */\nconst getSketchRenderer = () =>\n _isInstanced ? Instance : window.self.p5.instance;\n\n/**\n * Verifies that a framebuffer belongs to the currently active sketch.\n * @param {p5.Framebuffer} target - Framebuffer candidate.\n * @returns {boolean} True when the framebuffer belongs to the active sketch.\n */\nconst isSupportedFramebufferTarget = (target) =>\n isFramebufferTarget(target) && target.renderer._pInst === getSketchRenderer();\n\n/**\n * Resolves the renderer and pixel size used by `brush.load()`.\n * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional draw target.\n * @returns {{renderer: object, width: number, height: number}} Active renderer info.\n */\nconst resolveTarget = (buffer = false) => {\n // brush.load() can target the main sketch renderer, a p5.Graphics surface,\n // or an active framebuffer owned by the current sketch.\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\",\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\n/**\n * Returns the currently bound sketch framebuffer when drawing into one.\n * @returns {p5.Framebuffer|null} Active framebuffer or null.\n */\nconst getActiveFramebuffer = () =>\n Renderer &&\n Renderer._renderer &&\n typeof Renderer._renderer.activeFramebuffer === \"function\"\n ? Renderer._renderer.activeFramebuffer()\n : null;\n\n// =============================================================================\n// Section: Dirty Rect Utilities\n// =============================================================================\nconst DIRTY_BRUSH_PADDING = 2;\nconst DIRTY_FILL_PADDING = 4;\n\n/**\n * Returns the current render target size in physical pixels.\n * @returns {{width: number, height: number}} Pixel size of the active target.\n */\nconst getTargetPixelSize = () => ({\n width: Math.max(1, Math.round(Cwidth * Density)),\n height: Math.max(1, Math.round(Cheight * Density)),\n});\n\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to expand.\n * @param {number} [padding=0] - Padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Expanded rect.\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\n/**\n * Clamps a dirty rectangle to the current target bounds.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\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\n/**\n * Returns the union of two dirty rectangles.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} a - First rect.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} b - Second rect.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Union rect.\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\n/**\n * Returns a dirty rectangle covering the full active target.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nconst getFullDirtyRect = () => {\n const { width, height } = getTargetPixelSize();\n return { minX: 0, minY: 0, maxX: width, maxY: height };\n};\n\n// =============================================================================\n// Section: Scissor Helpers\n// =============================================================================\n/**\n * Converts a top-left-based dirty rectangle into a WebGL scissor box.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @returns {{x:number,y:number,width:number,height:number}|null} Scissor box or null.\n */\nconst toScissorBox = (rect) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n // WebGL scissor coordinates are bottom-left based, unlike p5's top-left\n // oriented screen-space bookkeeping.\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\n/**\n * Runs a draw callback with a temporary scissor region.\n * @param {WebGL2RenderingContext} gl - Active WebGL context.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.\n * @param {Function} draw - Draw callback executed under the scissor box.\n * @returns {boolean} True when a valid scissor box was applied.\n */\nconst withScissor = (gl, rect, draw) => {\n const box = toScissorBox(rect);\n if (!box) return false;\n\n // Scissor is never nested in this module, so we can set/clear it directly\n // without saving previous GL state.\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 gl.disable(gl.SCISSOR_TEST);\n }\n\n return true;\n};\n\n// =============================================================================\n// Section: Load and State\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 * 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// Section: Color Blending / Rendering\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\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 /**\n * Merges a new dirty rectangle into the target's accumulated draw bounds.\n * @param {object} target - Mask buffer receiving draw output.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to merge.\n */\n markDirtyRect(target, rect) {\n const normalized = normalizeDirtyRect(rect);\n if (!target || !normalized) return;\n target.dirtyRect = unionDirtyRect(target.dirtyRect, normalized);\n target.isDrawn = true;\n },\n\n /**\n * Clears a mask buffer and resets its dirty-rect tracking.\n * @param {object} target - Mask buffer to reset.\n */\n clearMask(target) {\n if (!target) return;\n\n target.clear();\n target.isDrawn = false;\n target.dirtyRect = null;\n },\n\n /**\n * Resolves the region that should be composited back into the destination.\n * @param {object} target - Mask buffer being sampled.\n * @param {boolean} isBrushMask - True when compositing the WEBGL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n\n // Brush masks are generated in a separate WEBGL surface and sampled back\n // into the active renderer. Framebuffer output can disagree about Y\n // orientation there, so brush-mask compositing falls back to full-frame.\n if (isBrushMask && getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(\n target.dirtyRect,\n isBrushMask ? DIRTY_BRUSH_PADDING : DIRTY_FILL_PADDING,\n ),\n );\n },\n\n /**\n * Captures the current framebuffer contents into a reusable source texture.\n * For main-canvas draws this simply returns the sketch renderer directly.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}} dirtyRect - Region to copy.\n * @returns {object} Renderer or framebuffer source to sample in the blend shader.\n */\n captureBlendSource(dirtyRect) {\n const activeFramebuffer = getActiveFramebuffer();\n if (!activeFramebuffer) return Renderer._renderer;\n\n // Framebuffer compositing cannot safely sample from the active framebuffer\n // while drawing back into it, so we copy the relevant area first.\n const source = Renderer.blendSourceFramebuffer;\n const needsSource =\n !source ||\n source.width !== Cwidth ||\n source.height !== Cheight ||\n (typeof source.pixelDensity === \"function\" &&\n source.pixelDensity() !== Density);\n\n if (needsSource) {\n if (source?.remove) source.remove();\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 Renderer.blendSourceFramebuffer.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 return Renderer.blendSourceFramebuffer;\n },\n\n // =============================================================================\n // Section: Setup and load shaders\n // =============================================================================\n /**\n * Ensures the mask buffers and blend shader exist for the current renderer.\n */\n load() {\n CompositeProfile.enabled = getCompositeProfileFlag();\n const graphicsFactory =\n typeof Renderer.createGraphics === \"function\" ? Renderer : Renderer._pInst;\n const needsBuffers =\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 Density = Renderer.pixelDensity();\n const p2dMode = graphicsFactory.P2D ?? Renderer.P2D;\n const webglMode = graphicsFactory.WEBGL ?? Renderer.WEBGL;\n\n if (!Renderer.loaded || needsBuffers) {\n if (Renderer.mask?.remove) Renderer.mask.remove();\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n // Keep one 2D mask for fill/hatch work and one WEBGL mask for brush\n // stamps so each path can draw in the renderer that suits it best.\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\n this.mask = Renderer.mask;\n this.glMask = Renderer.glMask;\n this.ctx = this.mask.drawingContext;\n\n this.mask.pixelDensity(Density);\n this.mask.angleMode(Renderer.DEGREES);\n this.mask.dirtyRect ??= null;\n this.mask.noSmooth();\n this.mask.isDrawn ??= false;\n\n this.glMask.pixelDensity(Density);\n this.glMask.angleMode(this.glMask.DEGREES);\n this.glMask.drawingContext.lineWidth = 0;\n this.glMask.dirtyRect ??= null;\n this.glMask.isDrawn ??= false;\n\n // Link Matrix of GL mask to main Renderer\n this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;\n },\n\n // =============================================================================\n // Section: Compositing\n // =============================================================================\n /**\n * Flushes pending mask work when the blend color changes or a frame ends.\n * @param {Color|false} [_color=false] - New blend color.\n * @param {boolean} [_isLast=false] - True when this is the final blend flush.\n */\n blend(_color = false, _isLast = false) {\n isMixReady();\n\n // Only one mask is \"active\" for the current drawing mode; the other one\n // may still need flushing if the mode just changed mid-frame.\n const isBrushMask = this.isBrush === true;\n const mask = isBrushMask ? this.glMask : this.mask;\n const otherMask = isBrushMask ? 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 if (!this.isBlending && nextColor) {\n this.isBlending = true;\n this.cachedColor = nextColor;\n // Force p5 to bind its internal render target for glMask before the\n // first raw GL brush draw of the blend cycle.\n this.glMask.clear();\n }\n\n if (_isLast || colorChanged) {\n if (this.justChanged) {\n this.applyShader(otherMask, !isBrushMask);\n this.justChanged = false;\n }\n if (this.isBlending) {\n this.applyShader(mask, isBrushMask);\n }\n if (nextColor) this.cachedColor = nextColor;\n if (_isLast) this.isBlending = false;\n }\n },\n\n /**\n * Runs the blend shader over a mask and composites the result into the active renderer.\n * @param {object} mask - Mask buffer to composite.\n * @param {boolean} isBrushMask - True when compositing the WEBGL brush mask.\n */\n applyShader(mask, isBrushMask) {\n if (!mask?.isDrawn) return;\n const profilePrefix = isBrushMask ? \"brush\" : \"fill\";\n profileComposite(`${profilePrefix}.applyShader`, () => {\n // Brush masks are drawn via raw GL into a separate WEBGL graphics surface,\n // so flush that context before sampling it as a texture.\n if (isBrushMask && typeof mask.drawingContext?.flush === \"function\") {\n profileComposite(`${profilePrefix}.flushMask`, () =>\n mask.drawingContext.flush(),\n );\n }\n\n const dirtyRect = profileComposite(\n `${profilePrefix}.getCompositeRect`,\n () => this.getCompositeRect(mask, isBrushMask),\n );\n if (!dirtyRect) {\n profileComposite(`${profilePrefix}.clearMask`, () => this.clearMask(mask));\n return;\n }\n\n const gl = Renderer.drawingContext;\n const shader = Renderer.shaderProgram;\n const source = profileComposite(\n `${profilePrefix}.captureSource`,\n () => this.captureBlendSource(dirtyRect),\n );\n const flipOutputY = !!getActiveFramebuffer();\n const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);\n\n // This pass is a fullscreen compositing rect, not scene geometry, so it\n // should not participate in the sketch's depth buffer.\n gl.disable(gl.DEPTH_TEST);\n\n const drawShaderPass = () => {\n Renderer.push();\n Renderer.translate(0, 0);\n Renderer.shader(shader);\n\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n shader.setUniform(\"u_flipOutputY\", flipOutputY);\n shader.setUniform(\"u_mask\", mask);\n shader.setUniform(\"u_color\", this.cachedColor);\n\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 Renderer.pop();\n };\n\n profileComposite(`${profilePrefix}.shaderPass`, drawShaderPass);\n\n Renderer.resetShader();\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n profileComposite(`${profilePrefix}.clearMask`, () => this.clearMask(mask));\n });\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 * 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","// =============================================================================\n// Module: GL Draw\n// =============================================================================\n/**\n * The GL Draw module batches brush primitives for WebGL2 rendering. It initializes\n * the shader programs and buffers used by circle-based brushes and image-tip brushes,\n * then flushes those queues into the shared framebuffer-backed brush mask.\n */\n\nimport {\n Mix,\n Cwidth,\n Cheight,\n isMixReady,\n Density,\n State,\n Renderer,\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\";\nimport imgVertSrc from \"./image.vert\";\nimport imgFragSrc from \"./image.frag\";\n\n// =============================================================================\n// Section: Initialization and Setup\n// =============================================================================\n\n// Module state\nlet isLoaded = false,\n gl,\n projMatrix,\n framebufferProjMatrix,\n vao,\n buf,\n program;\nlet loadedWidth = 0,\n loadedHeight = 0;\nlet brushMaskTarget = null;\nlet prevMaskTarget = null;\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 _halfW = 0,\n _halfH = 0,\n _scale = 1,\n _density = 1;\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 _halfW = Cwidth / 2;\n _halfH = Cheight / 2;\n _scale = Math.sqrt(_ma * _ma + _mb * _mb);\n _density = Density;\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\nlet circleDirtyRect = null;\n\n// ---------------------------------------------------------------------------\n// Image instancing state\n// ---------------------------------------------------------------------------\nlet imgProgram = null;\nlet imgVao = null;\nlet imgCornerBuf = null;\nlet imgInstanceBuf = null;\nconst imgAttr = {};\nconst imgFrag = {};\nlet imgGpuSize = 0;\n\nconst IMG_FLOATS = 5; // screenX, screenY, halfSize, angle, alpha — per stamp\nconst IMG_INIT_CAP = 256;\nlet imgData = new Float32Array(IMG_INIT_CAP * IMG_FLOATS);\nlet imgCount = 0;\nlet imgCapacity = IMG_INIT_CAP;\nlet imgDirtyRect = null;\n\n// Texture cache: src string → WebGLTexture (cleared whenever the GL context changes)\nconst texCache = new Map();\n\n// Static unit-quad corners for gl.TRIANGLE_STRIP in quad-local space.\nconst QUAD_CORNERS = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);\n\nfunction isFramebufferMask(target) {\n return (\n !!target &&\n typeof target.begin === \"function\" &&\n typeof target.end === \"function\" &&\n !!target.renderer\n );\n}\n\nfunction resetMaskShaderTracking() {\n const target = Mix.glMask;\n const renderer = isFramebufferMask(target) ? target.renderer : target?._renderer;\n if (!renderer) return;\n renderer._curShader = null;\n renderer._cachedBlendMode = null;\n renderer._isBlending = null;\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n}\n\nfunction getFramebufferHandle(target) {\n if (!target) return null;\n if (typeof target._framebufferToBind === \"function\") return target._framebufferToBind();\n return target.framebuffer ?? null;\n}\n\nfunction ensureBrushMaskTarget() {\n const targetRenderer = Renderer?._renderer;\n const targetDensity = Density;\n const needsTarget =\n !brushMaskTarget ||\n brushMaskTarget.renderer !== targetRenderer ||\n brushMaskTarget.width !== Cwidth ||\n brushMaskTarget.height !== Cheight ||\n brushMaskTarget.density !== targetDensity;\n\n if (!needsTarget) {\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n }\n\n if (brushMaskTarget?.remove) brushMaskTarget.remove();\n\n const target = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: targetDensity,\n antialias: false,\n depth: false,\n stencil: false,\n });\n target.isDrawn = false;\n target.dirtyRect = null;\n target.clear = () => {\n const renderer = Renderer._renderer;\n const previous = renderer.activeFramebuffer?.() ?? null;\n if (previous?._beforeEnd) previous._beforeEnd();\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(target));\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n if (previous?._beforeBegin) {\n previous._beforeBegin();\n } else {\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n renderer.viewport(renderer._origViewport.width, renderer._origViewport.height);\n renderer._applyStencilTestIfClipping?.();\n }\n };\n\n brushMaskTarget = target;\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n}\n\nfunction getProjectionMatrix() {\n return isFramebufferMask(Mix.glMask) ? framebufferProjMatrix : projMatrix;\n}\n\nfunction beginMaskTarget() {\n const target = Mix.glMask;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = hadDepthTest;\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n if (isFramebufferMask(target)) {\n prevMaskTarget = Renderer._renderer.activeFramebuffer?.() ?? null;\n if (prevMaskTarget?._beforeEnd) prevMaskTarget._beforeEnd();\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(target));\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n return;\n }\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n}\n\nfunction endMaskTarget() {\n if (beginMaskTarget._hadDepthTest) gl.enable(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = false;\n if (!isFramebufferMask(Mix.glMask)) return;\n if (prevMaskTarget?._beforeBegin) {\n prevMaskTarget._beforeBegin();\n } else {\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n Renderer._renderer.viewport(\n Renderer._renderer._origViewport.width,\n Renderer._renderer._origViewport.height,\n );\n Renderer._renderer._applyStencilTestIfClipping?.();\n }\n prevMaskTarget = null;\n}\n\nfunction accumulateDirtyRect(currentRect, minX, minY, maxX, maxY) {\n if (!currentRect) return { minX, minY, maxX, maxY };\n if (minX < currentRect.minX) currentRect.minX = minX;\n if (minY < currentRect.minY) currentRect.minY = minY;\n if (maxX > currentRect.maxX) currentRect.maxX = maxX;\n if (maxY > currentRect.maxY) currentRect.maxY = maxY;\n return currentRect;\n}\n\n/**\n * Initializes WebGL objects if not done already.\n */\nexport function isReady() {\n isMixReady();\n ensureBrushMaskTarget();\n\n const nextGl = Renderer.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 framebufferProjMatrix = 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 // ------------------------------------------------------------------\n // Image-tip instancing program\n // ------------------------------------------------------------------\n texCache.clear();\n\n imgProgram = createProgram(gl, imgVertSrc, imgFragSrc);\n [\"a_corner\", \"a_pos\", \"a_size\", \"a_angle\", \"a_alpha\"].forEach(\n (n) => (imgAttr[n] = gl.getAttribLocation(imgProgram, n)),\n );\n [\"u_proj\", \"u_color\", \"u_tex\"].forEach(\n (n) => (imgFrag[n] = gl.getUniformLocation(imgProgram, n)),\n );\n\n imgVao = gl.createVertexArray();\n gl.bindVertexArray(imgVao);\n\n // Static corner VBO (per-vertex, no divisor)\n imgCornerBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgCornerBuf);\n gl.bufferData(gl.ARRAY_BUFFER, QUAD_CORNERS, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(imgAttr.a_corner);\n gl.vertexAttribPointer(imgAttr.a_corner, 2, gl.FLOAT, false, 0, 0);\n\n // Instance data VBO (per-instance)\n imgInstanceBuf = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n gl.bufferData(gl.ARRAY_BUFFER, imgData.byteLength, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n\n const istride = IMG_FLOATS * 4; // 20 bytes\n gl.enableVertexAttribArray(imgAttr.a_pos);\n gl.vertexAttribPointer(imgAttr.a_pos, 2, gl.FLOAT, false, istride, 0);\n gl.vertexAttribDivisor(imgAttr.a_pos, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_size);\n gl.vertexAttribPointer(imgAttr.a_size, 1, gl.FLOAT, false, istride, 8);\n gl.vertexAttribDivisor(imgAttr.a_size, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_angle);\n gl.vertexAttribPointer(imgAttr.a_angle, 1, gl.FLOAT, false, istride, 12);\n gl.vertexAttribDivisor(imgAttr.a_angle, 1);\n\n gl.enableVertexAttribArray(imgAttr.a_alpha);\n gl.vertexAttribPointer(imgAttr.a_alpha, 1, gl.FLOAT, false, istride, 16);\n gl.vertexAttribDivisor(imgAttr.a_alpha, 1);\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 - _halfW;\n const py = y - _halfH;\n\n const offset = circleCount * 4;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const radius = (_density * diameter * _scale) / 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 const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n circleDirtyRect = accumulateDirtyRect(\n circleDirtyRect,\n dScreenX - radius - 1,\n dScreenY - radius - 1,\n dScreenX + radius + 1,\n dScreenY + radius + 1,\n );\n\n circleCount++;\n}\n\n/**\n * Queue an image stamp to be drawn with instanced rendering.\n * Accepts the same coordinate conventions as circle(): x/y in position space\n * (user coords + Cwidth/2, Cheight/2), size in user-coord units, alpha in [0..255].\n * @param {number} x - X in position space.\n * @param {number} y - Y in position space.\n * @param {number} size - Full stamp diameter in user-coord units.\n * @param {number} angle - Rotation in radians.\n * @param {number} alpha - Opacity [0..255].\n */\nexport function stampImage(x, y, size, angle, alpha) {\n if (imgCount >= imgCapacity) {\n imgCapacity *= 2;\n const next = new Float32Array(imgCapacity * IMG_FLOATS);\n next.set(imgData);\n imgData = next;\n }\n\n const px = x - _halfW;\n const py = y - _halfH;\n const screenX = _ma * px + _mc * py + _mx + _halfW;\n const screenY = _mb * px + _md * py + _my + _halfH;\n const halfSize = (_density * size * _scale) / 2;\n\n const base = imgCount * IMG_FLOATS;\n imgData[base] = screenX;\n imgData[base + 1] = screenY;\n imgData[base + 2] = halfSize;\n imgData[base + 3] = angle;\n imgData[base + 4] = alpha / 255;\n\n // Bounding box: rotated square worst-case = circle of radius halfSize * √2\n const dScreenX = screenX * _density;\n const dScreenY = screenY * _density;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - halfSize * 1.42 - 1,\n dScreenY - halfSize * 1.42 - 1,\n dScreenX + halfSize * 1.42 + 1,\n dScreenY + halfSize * 1.42 + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {p5.Image} p5img - The preprocessed brush-tip image (from T.tips).\n * @param {string} src - The image src string, used as the texture cache key.\n */\nexport function glDrawImages(p5img, src) {\n if (imgCount === 0) return;\n\n Mix.glMask.isDrawn = true;\n beginMaskTarget();\n\n // Lazy-create the WebGL texture from the p5.Image canvas on first use\n let tex = texCache.get(src);\n if (!tex) {\n tex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, p5img.canvas);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n texCache.set(src, tex);\n }\n\n gl.useProgram(imgProgram);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.uniform1i(imgFrag.u_tex, 0);\n\n const color = State.stroke.color._array;\n gl.uniform4f(imgFrag.u_color, ...color);\n gl.uniformMatrix4fv(imgFrag.u_proj, false, getProjectionMatrix());\n\n gl.bindVertexArray(imgVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);\n\n const byteCount = imgCount * IMG_FLOATS * 4;\n const dataView = imgData.subarray(0, imgCount * IMG_FLOATS);\n if (byteCount > imgGpuSize) {\n gl.bufferData(gl.ARRAY_BUFFER, imgData, gl.DYNAMIC_DRAW);\n imgGpuSize = imgData.byteLength;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);\n }\n\n gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, imgCount);\n gl.flush();\n\n gl.bindVertexArray(null);\n gl.bindTexture(gl.TEXTURE_2D, null);\n endMaskTarget();\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let p5 know we changed the active program\n resetMaskShaderTracking();\n}\n\n/**\n * Removes a cached GL texture by key, forcing re-upload on next draw.\n * Call this when a custom tip function changes after brush.add().\n */\nexport function invalidateTexEntry(key) {\n const tex = texCache.get(key);\n if (tex && gl) gl.deleteTexture(tex);\n texCache.delete(key);\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 beginMaskTarget();\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, getProjectionMatrix());\n gl.drawArrays(gl.POINTS, 0, circleCount);\n gl.flush();\n\n gl.bindVertexArray(null);\n endMaskTarget();\n\n if (circleDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, circleDirtyRect);\n circleDirtyRect = null;\n }\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 resetMaskShaderTracking();\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 Instance,\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 {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} 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();\nlet _strokeTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n tx: 0,\n ty: 0,\n};\n\nfunction getBrushFactory() {\n return Renderer ?? Instance ?? window.self.p5.instance;\n}\n\nconst DEFAULT_CUSTOM_PRESSURE_VARIATION = {\n offset: 0.08,\n scale: 0.08,\n warp: 0.06,\n tilt: 0.06,\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 * { mode: \"gaussian\", curve, min_max } — advanced built-in pressure profile\n * { curve, min_max } — legacy gaussian format, preserved for compatibility\n */\nexport function normalizePressure(p) {\n if (!p) return p;\n if (typeof p === \"function\")\n return {\n type: \"custom\",\n min_max: [0, 1],\n curve: p,\n variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\n };\n if (typeof p === \"object\" && !Array.isArray(p)) {\n if (p.type === \"custom\" || p.mode === \"custom\") {\n const { mode, ...rest } = p;\n return {\n ...rest,\n type: \"custom\",\n variation: {\n ...DEFAULT_CUSTOM_PRESSURE_VARIATION,\n ...(rest.variation ?? {}),\n },\n };\n }\n if (\n p.type === \"gaussian\" ||\n p.mode === \"gaussian\" ||\n (Array.isArray(p.curve) && Array.isArray(p.min_max))\n ) {\n return {\n ...p,\n type: \"gaussian\",\n curve: p.curve,\n min_max: p.min_max,\n };\n }\n return p;\n }\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 variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },\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 === \"custom\") {\n if (typeof params.tip !== \"function\") {\n throw new Error(`Brush \"${name}\" is type \"custom\" but is missing a tip function.`);\n }\n // Rasterise the tip once into a 500×500 P2D buffer.\n // Users draw in a 100×100 coordinate space (origin at centre);\n // dark fills/strokes → high opacity, light/white → transparent.\n const key = `custom::${name}`;\n invalidateTexEntry(key); // discard stale GPU texture if tip changed\n const factory = getBrushFactory();\n const g = factory.createGraphics(500, 500);\n g.pixelDensity(1);\n g.background(255);\n g.noSmooth();\n g.push();\n g.translate(250, 250); // centre origin\n g.scale(5); // 100 user units → 500 px\n g.noStroke();\n params.tip(g);\n g.pop();\n T.imageToWhite(g); // dark → high alpha, RGB → white for tint\n T.tips.set(key, g);\n params.tipKey = key;\n list.set(name, { param: params, colors: [], buffers: [] });\n return;\n }\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 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 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\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 {Plot|false} [plot=false] - Plot object for path-following strokes.\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 // 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 if (pressure.type !== \"custom\") {\n current.cp = rr(3, 3.5);\n current.ct = 0;\n current.cs = 1;\n current.ck = 0;\n } else {\n const variation = pressure.variation ?? DEFAULT_CUSTOM_PRESSURE_VARIATION;\n current.cp = rr(-variation.offset, variation.offset);\n current.ct = rr(-variation.warp, variation.warp);\n current.cs = rr(1 - variation.scale, 1 + variation.scale);\n current.ck = rr(-variation.tilt, variation.tilt);\n }\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 Mix.blend(State.stroke.color);\n\n // Set additional state values\n current.alpha = calculateAlpha();\n\n // Pre-compute clip-check coefficients so isInsideClippingArea() needs no\n // temporary objects and only one matrix×vector multiply per step instead of two.\n {\n const cw2 = Cwidth / 2, ch2 = Cheight / 2;\n const T = _strokeTransform;\n if (State.stroke.clipWindow) {\n const { inverse: I, bounds: B } = State.stroke.clipWindow;\n // Compose (I ∘ T) and fold the -cw2/-ch2 position offset into the translation\n const ca = I.a * T.a + I.c * T.b, cc = I.a * T.c + I.c * T.d;\n const cb = I.b * T.a + I.d * T.b, cd = I.b * T.c + I.d * T.d;\n current.clipA = ca; current.clipB = cb;\n current.clipC = cc; current.clipD = cd;\n current.clipTX = I.a * T.tx + I.c * T.ty + I.tx - ca * cw2 - cc * ch2;\n current.clipTY = I.b * T.tx + I.d * T.ty + I.ty - cb * cw2 - cd * ch2;\n current.clipMinX = B.minX; current.clipMaxX = B.maxX;\n current.clipMinY = B.minY; current.clipMaxY = B.maxY;\n } else {\n const o = Cwidth * 0.05;\n current.clipA = T.a; current.clipB = T.b;\n current.clipC = T.c; current.clipD = T.d;\n current.clipTX = T.tx - T.a * cw2 - T.c * ch2;\n current.clipTY = T.ty - T.b * cw2 - T.d * ch2;\n current.clipMinX = -cw2 - o; current.clipMaxX = cw2 + o;\n current.clipMinY = -ch2 - o; current.clipMaxY = ch2 + o;\n }\n }\n\n markerTip();\n}\n\n/**\n * Restores drawing state after completing a stroke.\n */\nfunction restoreState() {\n markerTip();\n glDraw();\n const type = current.p?.type;\n if (type === \"image\") glDrawImages(T.tips.get(current.p.image.src), current.p.image.src);\n else if (type === \"custom\") glDrawImages(T.tips.get(current.p.tipKey), current.p.tipKey);\n}\n\n/**\n * Renders the brush tip based on current pressure and position.\n */\nfunction tip() {\n const insideClip = isInsideClippingArea();\n if (!insideClip) return;\n const pressure = calculatePressure();\n const 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 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 drawImageTip(pressure * lineNoise);\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 const value = current.p.pressure.type === \"custom\"\n ? map(\n current.p.pressure.curve(\n Math.max(\n 0,\n Math.min(\n 1,\n 0.5 + ((_position.plotted / _length) - 0.5 + current.ct) * current.cs,\n ),\n ),\n ) +\n current.cp +\n current.ck * ((_position.plotted / _length) - 0.5),\n 0,\n 1,\n current.min,\n current.max,\n true,\n )\n : gauss();\n return value;\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 * Uses coefficients pre-computed in saveState() — no object allocations,\n * one fused matrix×vector multiply (both transforms composed at setup time).\n * @returns {boolean} True if inside clipping area; false otherwise.\n */\nfunction isInsideClippingArea() {\n const lx = current.clipA * _position.x + current.clipC * _position.y + current.clipTX;\n if (lx < current.clipMinX || lx > current.clipMaxX) return false;\n const ly = current.clipB * _position.x + current.clipD * _position.y + current.clipTY;\n return ly >= current.clipMinY && ly <= current.clipMaxY;\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 * Math.max(0.8, pressure) * rr(0.9,1.1),\n );\n}\n\n/**\n * Queues a stamp for instanced GL rendering.\n * Handles both \"image\" and \"custom\" tip types.\n * @param {number} pressure - Current pressure.\n * @param {number} alpha - Opacity [0..255].\n */\nfunction drawImageTip(pressure, alpha = current.alpha) {\n const vibration = State.stroke.weight * current.p.scatter;\n const rx = vibration * rr(-1, 1);\n const ry = vibration * rr(-1, 1);\n const size = current.p.weight * State.stroke.weight * pressure;\n let angle = 0;\n if (current.p.rotate === \"random\") {\n angle = randInt(0, 360) * (Math.PI / 180);\n } else if (current.p.rotate === \"natural\") {\n angle = ((_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle()) * (Math.PI / 180);\n }\n stampImage(_position.x + rx, _position.y + ry, size, angle, alpha * Math.max(0.8, pressure) * rr(0.9,1.1));\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 const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\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 const diameter =\n pressure *\n pressure *\n current.p.weight *\n rr(0.85, 1.15) *\n State.stroke.weight;\n const alpha = Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1);\n circle(\n _position.x + dx,\n _position.y + dy,\n diameter,\n alpha,\n );\n }\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 = current.alpha;\n if (current.p.type === \"marker\") {\n for (let s = 1; s < 10; s++) {\n drawMarker((pressure * s) / 10, true, alpha * 8);\n }\n } else if (current.p.type === \"custom\" || current.p.type === \"image\") {\n for (let s = 1; s < 5; s++) {\n drawImageTip((pressure * s) / 10, alpha * 2);\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, scatter, sharpness, grain, 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\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 if (!this.tips.has(src)) 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 factory = getBrushFactory();\n const p5img = factory.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.crossOrigin = \"anonymous\";\n nativeImg.src = src;\n }),\n ),\n );\n },\n};\n","// =============================================================================\n// Module: Classic Hatch\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { toDegreesSigned, map, 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\n// ---------------------------------------------------------------------------\n\nState.hatch = {\n isActive: false,\n dist: 5,\n angle: 45,\n options: {},\n hBrush: false,\n};\n\nexport function HatchState() {\n return { ...State.hatch };\n}\n\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\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\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Hatching\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for a polygon via scanline intersection.\n * Rotates vertices so hatch lines become horizontal, scans for edge\n * crossings, then rotates intersections back to original space.\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad), sinA = Math.sin(rad);\n const cosB = Math.cos(-rad), sinB = Math.sin(-rad);\n\n const verts = polygon.a, n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity, maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0], y = verts[i][1];\n const r = [x * cosA - y * sinA, x * sinA + y * cosA];\n rotated[i] = r;\n if (r[1] < minY) minY = r[1];\n if (r[1] > maxY) maxY = r[1];\n }\n\n // Build edge list (skip horizontal edges)\n const edges = [];\n for (let i = 0; i < n; i++) {\n const a = rotated[i], b = rotated[(i + 1) % n];\n if (a[1] !== b[1]) edges.push(a, b);\n }\n const eLen = edges.length;\n\n // Scan, find crossings, rotate back\n const segments = [];\n let Y = minY + dist * 0.5, step = dist;\n while (Y < maxY) {\n const cx = [];\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1], y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0]));\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n x1: cx[i] * cosB - Y * sinB, y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB, y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n// ---------------------------------------------------------------------------\n// Create Hatch\n// ---------------------------------------------------------------------------\n\nexport function createHatch(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n if (!Array.isArray(polygons)) polygons = [polygons];\n\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n\n const segs = [];\n for (const poly of polygons)\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n segs.sort((a, b) => a.x1 === b.x1 ? a.y1 - b.y1 : a.x1 - b.x1);\n\n const r = options.rand || 0;\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n let x1 = s.x1, y1 = s.y1, x2 = s.x2, y2 = s.y2;\n if (r) {\n x1 += r * dist * rr(-1, 1);\n y1 += r * dist * rr(-1, 1);\n x2 += r * dist * rr(-1, 1);\n y2 += r * dist * rr(-1, 1);\n }\n line(x1, y1, x2, y2);\n if (j > 0 && options.continuous) line(segs[j - 1].x2, segs[j - 1].y2, x1, y1);\n }\n\n BrushSetState(save);\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (state.isActive) createHatch(this);\n HatchSetState(state);\n};\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 {\n Renderer,\n Mix,\n State,\n Cwidth,\n Cheight,\n Density,\n} 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 const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));\n const strength = State.fill.bleed_strength;\n const modifiers = v.map(\n (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.4) * strength,\n );\n const shift = randInt(0, v.length);\n const shifted = [...v.slice(shift), ...v.slice(0, shift)];\n const center = _center(shifted);\n return 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 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 = [],\n sm = [],\n 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 let crossings = 0;\n for (const [a, b] of sides) {\n const ay = a.y,\n 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 (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 sv.push(p);\n sm.push(this.m[j]);\n sd.push(!this.dir[j]);\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 const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);\n const len = tr_v.length;\n\n const outLen = len * 2;\n const newVerts = new Array(outLen);\n const newMods = new Array(outLen);\n const newDirs = new Array(outLen);\n const bleedDirDeg = State.fill.direction === \"out\" ? -90 : 90;\n\n if (_gaussians[0].length === 0) _fillGaussianPools();\n const gPool = _gaussians[0],\n gPoolLen = gPool.length;\n const g2Pool = _gaussians[1],\n 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 const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;\n const c = cos(rotDeg);\n const s = sin(rotDeg);\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 const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n\n newVerts[idx] = cv;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n\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 let fv = newVerts,\n fm = newMods,\n fd = newDirs;\n const growCap = GROW_MAX_VERTS / State.fill.texture_strength;\n if (growCap && idx > growCap) {\n const step = Math.ceil(idx / growCap);\n fv = [];\n fm = [];\n 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 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 const numLayers = 20;\n const texture = tex * 3;\n const int = 2 * intensity * (1 + tex / 2);\n\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(),\n Density * Matrix.b(),\n Density * Matrix.c(),\n 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 let pol = this.grow();\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 if (i % 4 === 0) pol = pol.grow();\n\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 for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);\n sparse\n .grow(999)\n .flipDirs()\n .grow(997)\n .layer(i, size, int * texture, color);\n if (i % 2 === 0) {\n pol.grow(darker).grow(999).layer(i, size, int * 2, color);\n }\n\n if (i % 8 === 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 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 Mix.ctx.globalCompositeOperation = \"destination-out\";\n\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 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 {\n fill,\n noFill,\n fillTexture,\n fillBleed,\n} 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","CompositeProfile","enabled","stats","Map","timer","now","globalThis","performance","Date","profileComposite","name","fn","start","stat","get","total","count","set","clearTimeout","setTimeout","rows","entries","map","operation","total_ms","toFixed","avg_ms","sort","a","b","Number","console","log","length","table","isFramebufferTarget","target","begin","end","renderer","_pInst","getSketchRenderer","_isInstanced","window","self","p5","instance","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","enable","SCISSOR_TEST","scissor","disable","load","buffer","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","isMixReady","isBlending","cachedColor","Object","markDirtyRect","dirtyRect","isDrawn","clearMask","clear","getCompositeRect","isBrushMask","padding","expandDirtyRect","captureBlendSource","source","blendSourceFramebuffer","pixelDensity","remove","createFramebuffer","density","antialias","depth","stencil","drawingContext","push","imageMode","CENTER","image","pop","__P5_BRUSH_COMPOSITE_PROFILE__","URLSearchParams","location","search","graphicsFactory","createGraphics","needsBuffers","mask","glMask","p2dMode","P2D","webglMode","WEBGL","shaderProgram","createShader","this","ctx","angleMode","DEGREES","noSmooth","lineWidth","uModelMatrix","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","profilePrefix","flush","shader","flipOutputY","hadDepthTest","getParameter","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","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","n","mash","data","String","charCodeAt","h","c","s0","s1","s2","copy","f","rng","_seedCallbacks","_onSeed","cb","noise","rr","e","rArray","array","randInt","gaussian","mean","stdev","u","cos","weightedRand","weights","totalWeight","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","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","y_offset","x_offset","col","row","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","has","generateField","entry","normalizeFieldAngles","gen","keys","join","funct","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","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","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","projMatrix","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","prevMaskTarget","Attr","Frag","_ma","_mb","_mc","_md","_mx","_my","_halfW","_halfH","_density","circleData","INITIAL_CAPACITY","circleCount","bufferCapacity","gpuBufferSize","circleDirtyRect","imgProgram","imgVao","imgCornerBuf","imgInstanceBuf","imgAttr","imgFrag","imgGpuSize","imgData","IMG_INIT_CAP","imgCount","imgCapacity","imgDirtyRect","texCache","QUAD_CORNERS","isFramebufferMask","resetMaskShaderTracking","_curShader","_cachedBlendMode","_isBlending","activeTexture","TEXTURE0","bindTexture","TEXTURE_2D","blendEquation","FUNC_ADD","blendFunc","ONE","ONE_MINUS_SRC_ALPHA","getFramebufferHandle","_framebufferToBind","framebuffer","getProjectionMatrix","beginMaskTarget","isEnabled","_hadDepthTest","_beforeEnd","bindFramebuffer","FRAMEBUFFER","viewport","drawingBufferWidth","drawingBufferHeight","endMaskTarget","_beforeBegin","_origViewport","_applyStencilTestIfClipping","accumulateDirtyRect","currentRect","circle","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","tex","createTexture","texImage2D","RGBA","UNSIGNED_BYTE","canvas","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","ONE_MINUS_DST_ALPHA","uniform1i","u_tex","color","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","weight","clipWindow","opacity","_strokeTransform","tx","ty","getBrushFactory","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","state","add","params","includes","undefined","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","mode","rest","m","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","g","background","T","imageToWhite","tips","tipKey","param","colors","buffers","pick","brushName","arguments","strokeWeight","snapshotTransform","normalizeRegion","region","_position","initializeDrawingState","plot","gaussians","angleScale","isPlot","cp","ct","cs","ck","noiseoffset","dirRad","targetRenderer","targetDensity","previous","clearColor","COLOR_BUFFER_BIT","ensureBrushMaskTarget","nextGl","needsContextRefresh","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","STATIC_DRAW","a_corner","a_pos","IMG_FLOATS","vertexAttribDivisor","a_size","a_angle","isReady","switchingToBrush","cw2","ch2","inverse","I","bounds","B","ca","cc","cd","clipA","clipB","clipC","clipD","clipTX","clipTY","clipMinX","clipMaxX","clipMinY","clipMaxY","o","markerTip","saveState","stepSize","spacing","totalSteps","u_matrix","drawArrays","POINTS","glDraw","restoreState","isInsideClippingArea","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawImageTip","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","lx","ly","vibrate","rx","ry","size","halfSize","base","stampImage","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","resolve","reject","nativeImg","Image","onload","createImage","naturalWidth","naturalHeight","drawImage","onerror","crossOrigin","HatchState","rand","continuous","gradient","scanlineHatch","polygon","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","createHatch","polygons","save","hBrush","values","segs","poly","transformPoint","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","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","growCap","intensity","texture","int","switchingToFill","setTransform","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","darker","sparse","pols","layer","numLayers","erase","restore","fillStyle","beginPath","point","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","startY","angleOffset","randomFactor","randomAngle","offsetX","offsetY","transform","det","invertTransform","brush","inst","currentField","_array_points"],"mappings":"6BAYO,IAAIA,EAAQC,EAASC,EAAUC,EAAUC,EAKhD,MAAMC,EAAmB,CACvBC,SAAS,EACTC,MAAO,IAAIC,IACXC,MAAO,MAWHC,EAAM,IAAMC,WAAWC,aAAaF,SAAWG,KAAKH,MAEpDI,EAAmB,CAACC,EAAMC,KAC9B,IAAKX,EAAiBC,QAAS,OAAOU,IACtC,MAAMC,EAAQP,IACd,IACE,OAAOM,GACT,CAAC,QACC,MAAME,EAAOb,EAAiBE,MAAMY,IAAIJ,IAAS,CAAEK,MAAO,EAAGC,MAAO,GACpEH,EAAKE,OAASV,IAAQO,EACtBC,EAAKG,OAAS,EACdhB,EAAiBE,MAAMe,IAAIP,EAAMG,GAC7Bb,EAAiBI,OAAOc,aAAalB,EAAiBI,OAC1DJ,EAAiBI,MAAQe,WAAW,KAClC,MAAMC,EAAO,IAAIpB,EAAiBE,MAAMmB,WACrCC,IAAI,EAAEC,EAAWV,MAAK,CACrBU,YACAC,SAAUX,EAAKE,MAAMU,QAAQ,GAC7BT,MAAOH,EAAKG,MACZU,QAASb,EAAKE,MAAQF,EAAKG,OAAOS,QAAQ,MAE3CE,KAAK,CAACC,EAAGC,IAAMC,OAAOD,EAAEL,UAAYM,OAAOF,EAAEJ,WAChDO,QAAQC,IACN,wCAAwCZ,EAAKa,UAE/CF,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","x_google_ignoreList":[1,2]}
\ No newline at end of file
diff --git a/example/sketch.js b/example/sketch.js
index 2574f6a..8469af9 100644
--- a/example/sketch.js
+++ b/example/sketch.js
@@ -65,14 +65,18 @@ async function setup() {
// Try the interactive Brush Maker to design your own:
// https://acamposuribe.github.io/p5.brush/tools/brush-maker.html
brush.add("watercolor", {
- type: "custom",
- weight: 5,
- scatter: 1, // sideways spread of each stamp
- opacity: 10, // very transparent — builds up like real watercolour
- spacing: 0.4, // stamps placed close together for a smooth wash
- pressure: [0.78, 1.3],// stroke grows from start to end
- tip: (_m) => { _m.rect(-5, -5, 10, 10); _m.rect(5, 5, 4, 4); },
- rotate: "natural" // tip rotates to follow the stroke direction
+ type: "custom",
+ weight: 10,
+ scatter: 1.05,
+ opacity: 9,
+ spacing: 0.3,
+ pressure: [0.8, 1.3],
+ rotate: "natural",
+ tip: (_m) => {
+ _m.fill(0, 200)
+ _m.rect(-20, -20, 50, 50)
+ _m.rect(25, 25, 20, 20)
+ },
});
// Fill the seeds array with stable randoms for deterministic drawing.
diff --git a/src/core/color.js b/src/core/color.js
index 814219a..850d178 100644
--- a/src/core/color.js
+++ b/src/core/color.js
@@ -2,7 +2,7 @@ import vertSrc from "./gl/shader.vert";
import fragSrc from "./gl/shader.frag";
// =============================================================================
-// Section: Configure and Initiate
+// Module: Configure and Initiate
// =============================================================================
/**
* This module handles the configuration and initialization of the drawing system.
@@ -12,6 +12,62 @@ import fragSrc from "./gl/shader.frag";
export let Cwidth, Cheight, Instance, Renderer, Density; // Global canvas properties
+// =============================================================================
+// Section: Composite Profiling
+// =============================================================================
+const CompositeProfile = {
+ enabled: false,
+ stats: new Map(),
+ timer: null,
+};
+
+const getCompositeProfileFlag = () => {
+ if (typeof window === "undefined") return false;
+ if (window.__P5_BRUSH_COMPOSITE_PROFILE__ != null) {
+ return !!window.__P5_BRUSH_COMPOSITE_PROFILE__;
+ }
+ return new URLSearchParams(window.location.search).get("compositeProfile") === "on";
+};
+
+const now = () => globalThis.performance?.now?.() ?? Date.now();
+
+const profileComposite = (name, fn) => {
+ if (!CompositeProfile.enabled) return fn();
+ const start = now();
+ try {
+ return fn();
+ } finally {
+ const stat = CompositeProfile.stats.get(name) ?? { total: 0, count: 0 };
+ stat.total += now() - start;
+ stat.count += 1;
+ CompositeProfile.stats.set(name, stat);
+ if (CompositeProfile.timer) clearTimeout(CompositeProfile.timer);
+ CompositeProfile.timer = setTimeout(() => {
+ const rows = [...CompositeProfile.stats.entries()]
+ .map(([operation, stat]) => ({
+ operation,
+ total_ms: stat.total.toFixed(2),
+ count: stat.count,
+ avg_ms: (stat.total / stat.count).toFixed(4),
+ }))
+ .sort((a, b) => Number(b.total_ms) - Number(a.total_ms));
+ console.log(
+ `[p5.brush composite profile] entries=${rows.length}`,
+ );
+ console.table(rows);
+ }, 300);
+ }
+};
+
+// =============================================================================
+// Section: Target Resolution
+// =============================================================================
+
+/**
+ * Checks whether the given draw target is a p5.Framebuffer-like object.
+ * @param {*} target - Candidate draw target.
+ * @returns {boolean} True when the target behaves like a p5.Framebuffer.
+ */
const isFramebufferTarget = (target) =>
!!target &&
typeof target.begin === "function" &&
@@ -19,13 +75,29 @@ const isFramebufferTarget = (target) =>
!!target.renderer &&
!!target.renderer._pInst;
+/**
+ * Resolves the sketch renderer that owns the current drawing session.
+ * @returns {p5|Window["p5"]["instance"]} The active sketch renderer.
+ */
const getSketchRenderer = () =>
_isInstanced ? Instance : window.self.p5.instance;
+/**
+ * Verifies that a framebuffer belongs to the currently active sketch.
+ * @param {p5.Framebuffer} target - Framebuffer candidate.
+ * @returns {boolean} True when the framebuffer belongs to the active sketch.
+ */
const isSupportedFramebufferTarget = (target) =>
isFramebufferTarget(target) && target.renderer._pInst === getSketchRenderer();
+/**
+ * Resolves the renderer and pixel size used by `brush.load()`.
+ * @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional draw target.
+ * @returns {{renderer: object, width: number, height: number}} Active renderer info.
+ */
const resolveTarget = (buffer = false) => {
+ // brush.load() can target the main sketch renderer, a p5.Graphics surface,
+ // or an active framebuffer owned by the current sketch.
if (_isInstanced && !buffer) {
return {
renderer: Instance,
@@ -46,7 +118,7 @@ const resolveTarget = (buffer = false) => {
if (isFramebufferTarget(buffer)) {
if (!isSupportedFramebufferTarget(buffer)) {
throw new Error(
- "p5.brush only supports p5.Framebuffer targets created from the active sketch. Framebuffers created from p5.Graphics are not supported.",
+ "p5.brush only supports p5.Framebuffer targets created from the active sketch",
);
}
@@ -64,15 +136,10 @@ const resolveTarget = (buffer = false) => {
};
};
-const removeTargetBuffer = (buffer) => {
- if (buffer && typeof buffer.remove === "function") {
- buffer.remove();
- }
-};
-
-const getGraphicsFactory = () =>
- typeof Renderer.createGraphics === "function" ? Renderer : Renderer._pInst;
-
+/**
+ * Returns the currently bound sketch framebuffer when drawing into one.
+ * @returns {p5.Framebuffer|null} Active framebuffer or null.
+ */
const getActiveFramebuffer = () =>
Renderer &&
Renderer._renderer &&
@@ -80,29 +147,27 @@ const getActiveFramebuffer = () =>
? Renderer._renderer.activeFramebuffer()
: null;
-const needsBlendSourceFramebuffer = (framebuffer) =>
- !framebuffer ||
- framebuffer.width !== Cwidth ||
- framebuffer.height !== Cheight ||
- (typeof framebuffer.pixelDensity === "function" &&
- framebuffer.pixelDensity() !== Density);
-
-const needsMixBuffers = () =>
- !Renderer.mask ||
- !Renderer.glMask ||
- Renderer.mask.width !== Cwidth ||
- Renderer.mask.height !== Cheight ||
- Renderer.glMask.width !== Cwidth ||
- Renderer.glMask.height !== Cheight;
-
+// =============================================================================
+// Section: Dirty Rect Utilities
+// =============================================================================
const DIRTY_BRUSH_PADDING = 2;
const DIRTY_FILL_PADDING = 4;
+/**
+ * Returns the current render target size in physical pixels.
+ * @returns {{width: number, height: number}} Pixel size of the active target.
+ */
const getTargetPixelSize = () => ({
width: Math.max(1, Math.round(Cwidth * Density)),
height: Math.max(1, Math.round(Cheight * Density)),
});
+/**
+ * Expands a dirty rectangle outward by a constant padding value.
+ * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to expand.
+ * @param {number} [padding=0] - Padding in pixels.
+ * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Expanded rect.
+ */
const expandDirtyRect = (rect, padding = 0) =>
rect
? {
@@ -113,6 +178,11 @@ const expandDirtyRect = (rect, padding = 0) =>
}
: null;
+/**
+ * Clamps a dirty rectangle to the current target bounds.
+ * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.
+ * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.
+ */
const normalizeDirtyRect = (rect) => {
if (!rect) return null;
@@ -127,6 +197,12 @@ const normalizeDirtyRect = (rect) => {
return { minX, minY, maxX, maxY };
};
+/**
+ * Returns the union of two dirty rectangles.
+ * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} a - First rect.
+ * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} b - Second rect.
+ * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Union rect.
+ */
const unionDirtyRect = (a, b) => {
if (!a) return b;
if (!b) return a;
@@ -139,15 +215,29 @@ const unionDirtyRect = (a, b) => {
};
};
+/**
+ * Returns a dirty rectangle covering the full active target.
+ * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.
+ */
const getFullDirtyRect = () => {
const { width, height } = getTargetPixelSize();
return { minX: 0, minY: 0, maxX: width, maxY: height };
};
+// =============================================================================
+// Section: Scissor Helpers
+// =============================================================================
+/**
+ * Converts a top-left-based dirty rectangle into a WebGL scissor box.
+ * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.
+ * @returns {{x:number,y:number,width:number,height:number}|null} Scissor box or null.
+ */
const toScissorBox = (rect) => {
const normalized = normalizeDirtyRect(rect);
if (!normalized) return null;
+ // WebGL scissor coordinates are bottom-left based, unlike p5's top-left
+ // oriented screen-space bookkeeping.
const { height } = getTargetPixelSize();
return {
x: normalized.minX,
@@ -157,29 +247,34 @@ const toScissorBox = (rect) => {
};
};
+/**
+ * Runs a draw callback with a temporary scissor region.
+ * @param {WebGL2RenderingContext} gl - Active WebGL context.
+ * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Dirty rect.
+ * @param {Function} draw - Draw callback executed under the scissor box.
+ * @returns {boolean} True when a valid scissor box was applied.
+ */
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);
-
+ // Scissor is never nested in this module, so we can set/clear it directly
+ // without saving previous GL state.
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);
- }
+ gl.disable(gl.SCISSOR_TEST);
}
return true;
};
+// =============================================================================
+// Section: Load and State
+// =============================================================================
/**
* Loads and initializes a canvas for the drawing system.
* @param {p5.Graphics|p5.Framebuffer|false} [buffer=false] - Optional offscreen target.
@@ -223,16 +318,14 @@ export const instance = (inst) => {
_isInstanced = true;
Instance = inst;
};
-
-
-// =============================================================================
-// Section: Color Blending
-// =============================================================================
/**
* Handles color blending using WebGL shaders. Implements advanced blending
* effects based on Kubelka-Munk theory. Relies on spectral.js for blending logic.
*/
+// =============================================================================
+// Section: Color Blending / Rendering
+// =============================================================================
/**
* Ensures the Mix object is initialized and ready for blending.
*/
@@ -243,8 +336,6 @@ export const isMixReady = () => {
}
};
-const disable = false;
-
/**
* Manages blending operations with WebGL shaders.
* @property {boolean} loaded - Indicates if shaders are loaded.
@@ -257,21 +348,22 @@ export const Mix = {
isBlending: false,
cachedColor: new Object(),
+ /**
+ * Merges a new dirty rectangle into the target's accumulated draw bounds.
+ * @param {object} target - Mask buffer receiving draw output.
+ * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Rect to merge.
+ */
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;
- },
-
+ /**
+ * Clears a mask buffer and resets its dirty-rect tracking.
+ * @param {object} target - Mask buffer to reset.
+ */
clearMask(target) {
if (!target) return;
@@ -280,10 +372,20 @@ export const Mix = {
target.dirtyRect = null;
},
+ /**
+ * Resolves the region that should be composited back into the destination.
+ * @param {object} target - Mask buffer being sampled.
+ * @param {boolean} isBrushMask - True when compositing the WEBGL brush mask.
+ * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.
+ */
getCompositeRect(target, isBrushMask) {
if (!target) return null;
if (!target.dirtyRect) return getFullDirtyRect();
+ // Brush masks are generated in a separate WEBGL surface and sampled back
+ // into the active renderer. Framebuffer output can disagree about Y
+ // orientation there, so brush-mask compositing falls back to full-frame.
+ if (isBrushMask && getActiveFramebuffer()) return getFullDirtyRect();
return normalizeDirtyRect(
expandDirtyRect(
target.dirtyRect,
@@ -292,13 +394,28 @@ export const Mix = {
);
},
+ /**
+ * Captures the current framebuffer contents into a reusable source texture.
+ * For main-canvas draws this simply returns the sketch renderer directly.
+ * @param {{minX:number,minY:number,maxX:number,maxY:number}} dirtyRect - Region to copy.
+ * @returns {object} Renderer or framebuffer source to sample in the blend shader.
+ */
captureBlendSource(dirtyRect) {
const activeFramebuffer = getActiveFramebuffer();
-
if (!activeFramebuffer) return Renderer._renderer;
- if (needsBlendSourceFramebuffer(Renderer.blendSourceFramebuffer)) {
- removeTargetBuffer(Renderer.blendSourceFramebuffer);
+ // Framebuffer compositing cannot safely sample from the active framebuffer
+ // while drawing back into it, so we copy the relevant area first.
+ const source = Renderer.blendSourceFramebuffer;
+ const needsSource =
+ !source ||
+ source.width !== Cwidth ||
+ source.height !== Cheight ||
+ (typeof source.pixelDensity === "function" &&
+ source.pixelDensity() !== Density);
+
+ if (needsSource) {
+ if (source?.remove) source.remove();
Renderer.blendSourceFramebuffer = Renderer.createFramebuffer({
width: Cwidth,
height: Cheight,
@@ -309,9 +426,7 @@ export const Mix = {
});
}
- const source = Renderer.blendSourceFramebuffer;
-
- source.draw(() => {
+ Renderer.blendSourceFramebuffer.draw(() => {
withScissor(Renderer.drawingContext, dirtyRect, () => {
Renderer.clear();
Renderer.push();
@@ -324,23 +439,36 @@ export const Mix = {
Renderer.pop();
});
});
-
- return source;
+ return Renderer.blendSourceFramebuffer;
},
+ // =============================================================================
+ // Section: Setup and load shaders
+ // =============================================================================
/**
- * Loads necessary resources and prepares the mask buffer and shader for colour blending.
+ * Ensures the mask buffers and blend shader exist for the current renderer.
*/
load() {
+ CompositeProfile.enabled = getCompositeProfileFlag();
+ const graphicsFactory =
+ typeof Renderer.createGraphics === "function" ? Renderer : Renderer._pInst;
+ const needsBuffers =
+ !Renderer.mask ||
+ !Renderer.glMask ||
+ Renderer.mask.width !== Cwidth ||
+ Renderer.mask.height !== Cheight ||
+ Renderer.glMask.width !== Cwidth ||
+ Renderer.glMask.height !== Cheight;
+
Density = Renderer.pixelDensity();
- const graphicsFactory = getGraphicsFactory();
const p2dMode = graphicsFactory.P2D ?? Renderer.P2D;
const webglMode = graphicsFactory.WEBGL ?? Renderer.WEBGL;
- if (!Renderer.loaded || needsMixBuffers()) {
- removeTargetBuffer(Renderer.mask);
- removeTargetBuffer(Renderer.glMask);
-
+ if (!Renderer.loaded || needsBuffers) {
+ if (Renderer.mask?.remove) Renderer.mask.remove();
+ if (Renderer.glMask?.remove) Renderer.glMask.remove();
+ // Keep one 2D mask for fill/hatch work and one WEBGL mask for brush
+ // stamps so each path can draw in the renderer that suits it best.
Renderer.mask = graphicsFactory.createGraphics(Cwidth, Cheight, p2dMode);
Renderer.glMask = graphicsFactory.createGraphics(
Cwidth,
@@ -349,50 +477,44 @@ export const Mix = {
);
Renderer.loaded = true;
Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);
+ }
- this.mask = Renderer.mask;
- this.mask.pixelDensity(Density);
- this.mask.clear();
- this.mask.angleMode(Renderer.DEGREES);
- this.mask.dirtyRect = null;
- this.mask.isDrawn = false;
+ this.mask = Renderer.mask;
+ this.glMask = Renderer.glMask;
+ this.ctx = this.mask.drawingContext;
- this.ctx = this.mask.drawingContext;
+ this.mask.pixelDensity(Density);
+ this.mask.angleMode(Renderer.DEGREES);
+ this.mask.dirtyRect ??= null;
+ this.mask.noSmooth();
+ this.mask.isDrawn ??= false;
- this.glMask = Renderer.glMask;
- this.glMask.pixelDensity(Density);
- 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;
- }
+ this.glMask.pixelDensity(Density);
+ this.glMask.angleMode(this.glMask.DEGREES);
+ this.glMask.drawingContext.lineWidth = 0;
+ this.glMask.dirtyRect ??= null;
+ this.glMask.isDrawn ??= false;
// Link Matrix of GL mask to main Renderer
this.glMask._renderer.uModelMatrix = Renderer._renderer.uModelMatrix;
},
+ // =============================================================================
+ // Section: Compositing
+ // =============================================================================
/**
- * Applies blending effects using the current color and mask.
- * @param {Color} _color - Color to blend.
- * @param {boolean} _isLast - If this is the final blend operation.
- * @param {boolean} _isImg - If blending an image.
- * @param {boolean} _isFillLayer - If this is a special case.
+ * Flushes pending mask work when the blend color changes or a frame ends.
+ * @param {Color|false} [_color=false] - New blend color.
+ * @param {boolean} [_isLast=false] - True when this is the final blend flush.
*/
blend(_color = false, _isLast = false) {
isMixReady();
- const activeIsBrush = this.isBrush === true;
- const mask = activeIsBrush ? this.glMask : this.mask;
- const no_mask = activeIsBrush ? this.mask : this.glMask;
+ // Only one mask is "active" for the current drawing mode; the other one
+ // may still need flushing if the mode just changed mid-frame.
+ const isBrushMask = this.isBrush === true;
+ const mask = isBrushMask ? this.glMask : this.mask;
+ const otherMask = isBrushMask ? this.mask : this.glMask;
const nextColor = _color?._array;
const colorChanged =
!!nextColor &&
@@ -400,89 +522,91 @@ export const Mix = {
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 now
- if (disable) {
- if (_isLast && mask.isDrawn) {
- Renderer.push();
- Renderer.translate(0, 0);
- Renderer.image(mask, 0, 0, Cwidth, Cheight);
- Renderer.pop();
- mask.isDrawn = false;
- }
- return;
- }
-
- // Initialize blending if not already active
if (!this.isBlending && nextColor) {
this.isBlending = true;
this.cachedColor = nextColor;
- // Force p5 to bind its internal render target for glMask,
- // so the first glDraw() writes to the correct framebuffer.
+ // Force p5 to bind its internal render target for glMask before the
+ // first raw GL brush draw of the blend cycle.
this.glMask.clear();
}
if (_isLast || colorChanged) {
if (this.justChanged) {
- this.applyShader(no_mask, !activeIsBrush);
+ this.applyShader(otherMask, !isBrushMask);
this.justChanged = false;
}
if (this.isBlending) {
- this.applyShader(mask, activeIsBrush);
+ this.applyShader(mask, isBrushMask);
}
if (nextColor) this.cachedColor = nextColor;
if (_isLast) this.isBlending = false;
}
},
+ /**
+ * Runs the blend shader over a mask and composites the result into the active renderer.
+ * @param {object} mask - Mask buffer to composite.
+ * @param {boolean} isBrushMask - True when compositing the WEBGL brush mask.
+ */
applyShader(mask, isBrushMask) {
if (!mask?.isDrawn) return;
+ const profilePrefix = isBrushMask ? "brush" : "fill";
+ profileComposite(`${profilePrefix}.applyShader`, () => {
+ // Brush masks are drawn via raw GL into a separate WEBGL graphics surface,
+ // so flush that context before sampling it as a texture.
+ if (isBrushMask && typeof mask.drawingContext?.flush === "function") {
+ profileComposite(`${profilePrefix}.flushMask`, () =>
+ mask.drawingContext.flush(),
+ );
+ }
- const dirtyRect = this.getCompositeRect(mask, isBrushMask);
- if (!dirtyRect) {
- this.clearMask(mask);
- return;
- }
+ const dirtyRect = profileComposite(
+ `${profilePrefix}.getCompositeRect`,
+ () => this.getCompositeRect(mask, isBrushMask),
+ );
+ if (!dirtyRect) {
+ profileComposite(`${profilePrefix}.clearMask`, () => this.clearMask(mask));
+ return;
+ }
- let shader = Renderer.shaderProgram;
- const gl = Renderer.drawingContext;
- const targetIsFramebuffer = !!getActiveFramebuffer();
- 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
- // subsequent p5 geometry drawn at the same depth to fail depth testing
- // and become invisible.
- const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);
- gl.disable(gl.DEPTH_TEST);
-
- Renderer.push();
- Renderer.translate(0, 0);
-
- // Use the blend shader for rendering
- Renderer.shader(shader);
-
- // Set shader uniforms
- shader.setUniform("u_source", source);
- 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
- withScissor(gl, dirtyRect, () => {
- Renderer.fill(0, 0, 0, 0);
- Renderer.noStroke();
- Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);
- });
+ const gl = Renderer.drawingContext;
+ const shader = Renderer.shaderProgram;
+ const source = profileComposite(
+ `${profilePrefix}.captureSource`,
+ () => this.captureBlendSource(dirtyRect),
+ );
+ const flipOutputY = !!getActiveFramebuffer();
+ const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);
- // Finish and clear mask
- Renderer.pop();
- Renderer.resetShader();
+ // This pass is a fullscreen compositing rect, not scene geometry, so it
+ // should not participate in the sketch's depth buffer.
+ gl.disable(gl.DEPTH_TEST);
- // Restore depth test state
- if (hadDepthTest) gl.enable(gl.DEPTH_TEST);
+ const drawShaderPass = () => {
+ Renderer.push();
+ Renderer.translate(0, 0);
+ Renderer.shader(shader);
- this.clearMask(mask);
+ shader.setUniform("u_source", source);
+ shader.setUniform("u_isBrush", isBrushMask);
+ shader.setUniform("u_flipOutputY", flipOutputY);
+ shader.setUniform("u_mask", mask);
+ shader.setUniform("u_color", this.cachedColor);
+
+ withScissor(gl, dirtyRect, () => {
+ Renderer.fill(0, 0, 0, 0);
+ Renderer.noStroke();
+ Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);
+ });
+
+ Renderer.pop();
+ };
+
+ profileComposite(`${profilePrefix}.shaderPass`, drawShaderPass);
+
+ Renderer.resetShader();
+ if (hadDepthTest) gl.enable(gl.DEPTH_TEST);
+ profileComposite(`${profilePrefix}.clearMask`, () => this.clearMask(mask));
+ });
},
};
diff --git a/src/core/gl/shader.frag b/src/core/gl/shader.frag
index 7022183..745d169 100644
--- a/src/core/gl/shader.frag
+++ b/src/core/gl/shader.frag
@@ -201,20 +201,17 @@ const float DARKEN_THRESHOLD = 0.7;
const float EDGE_MIN = 0.05, EDGE_MAX = 0.35;
void main(void) {
- // Calculate UV coordinates
vec2 uv = 0.5 * p + 0.5;
vec2 uv1 = vec2(uv.x, 1.0 - uv.y);
- // Get source and mask colors
- vec4 source = texture(u_source, uv1);
- vec4 maskColor = texture(u_mask, uv1);
+ vec4 source = texture(u_source, uv1);
+ vec4 maskColor = texture(u_mask, uv1);
if (maskColor.a == 0.0) {
outColor = source;
return;
}
- // Set up pigment color
vec4 pigment = vec4(u_color.xyz, 1.0);
if (maskColor.a > DARKEN_THRESHOLD) {
float blacken = 0.5 * (min(maskColor.a, 1.0) - DARKEN_THRESHOLD);
@@ -222,15 +219,12 @@ void main(void) {
pigment.rgb = max(pigment.rgb, vec3(0.0));
}
- // Determine blend intensity — clamp to [0,1] to prevent NaN in spectral math
float mixIntensity = min(maskColor.a, 1.0);
- // Apply edge detection for better blending
if (!u_isBrush) {
vec2 texelSize = 1.0 / vec2(textureSize(u_mask, 0));
float scaledAlpha = maskColor.a * 15.0;
- // Calculate edge factor from 9 samples
float blurEdge = 0.0;
for (int i = -2; i <= 2; i += 2) {
for (int j = -2; j <= 2; j += 2) {
@@ -244,9 +238,6 @@ void main(void) {
mixIntensity = clamp(maskColor.a + blurEdge * 0.1, 0.0, 1.0);
}
- // Transparent background pixels are treated as white paper
vec3 bgColor = mix(vec3(1.0), source.rgb, source.a);
-
- // Perform the spectral color mixing
outColor = vec4(spectral_mix(bgColor, pigment.rgb, mixIntensity), 1.0);
-}
\ No newline at end of file
+}
diff --git a/src/core/gl/utils.js b/src/core/gl/utils.js
index 530b3de..e57ba17 100644
--- a/src/core/gl/utils.js
+++ b/src/core/gl/utils.js
@@ -6,16 +6,16 @@
* @returns {WebGLProgram} The compiled and linked program.
*/
export const createProgram = (gl, vert, frag) => {
- const p = gl.createProgram();
- for (let [t, src] of [
- [gl.VERTEX_SHADER, vert],
- [gl.FRAGMENT_SHADER, frag],
- ]) {
- const s = gl.createShader(t);
- gl.shaderSource(s, src);
- gl.compileShader(s);
- gl.attachShader(p, s);
- }
- gl.linkProgram(p);
- return p;
-};
\ No newline at end of file
+ const p = gl.createProgram();
+ for (let [t, src] of [
+ [gl.VERTEX_SHADER, vert],
+ [gl.FRAGMENT_SHADER, frag],
+ ]) {
+ const s = gl.createShader(t);
+ gl.shaderSource(s, src);
+ gl.compileShader(s);
+ gl.attachShader(p, s);
+ }
+ gl.linkProgram(p);
+ return p;
+};
diff --git a/src/fill/fill.js b/src/fill/fill.js
index a750c05..8164441 100644
--- a/src/fill/fill.js
+++ b/src/fill/fill.js
@@ -12,7 +12,14 @@
* techniques for simulating watercolor paints.
*/
-import { Renderer, Mix, State, Cwidth, Cheight, Density } from "../core/color.js";
+import {
+ Renderer,
+ Mix,
+ State,
+ Cwidth,
+ Cheight,
+ Density,
+} from "../core/color.js";
import { drawPolygon, circle } from "../core/mask.js";
import {
constrain,
@@ -169,23 +176,15 @@ export function createFill(polygon) {
}
_polygon = polygon;
const v = [...polygon.vertices];
-
- // Map vertices
const fluid = ~~(v.length * 0.25 * weightedRand({ 1: 5, 2: 10, 3: 60 }));
const strength = State.fill.bleed_strength;
-
- // Create bleed modifiers
const modifiers = v.map(
- (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.2) * strength,
+ (_, i) => (i > fluid ? 1 : 0.3) * rr(0.85, 1.4) * strength,
);
-
- // Randomize starting point
const shift = randInt(0, v.length);
const shifted = [...v.slice(shift), ...v.slice(0, shift)];
-
- // Calculate center and create FillPolygon
const center = _center(shifted);
- new FillPoly(shifted, modifiers, center, [], true).fill(
+ return new FillPoly(shifted, modifiers, center, [], true).fill(
State.fill.color,
map(State.fill.opacity, 0, 255, 0, 1, true),
State.fill.texture_strength,
@@ -309,41 +308,38 @@ class FillPoly {
scatter(ratio = 0.3) {
const L = this.v.length;
const keep = Math.max(3, ~~(L * ratio));
-
- // Build sorted random indices
const indices = [];
const step = L / keep;
for (let i = 0; i < keep; i++) {
indices.push(~~(i * step + rr(0, step * 0.8)));
}
- const sv = [], sm = [], sd = [];
+ const sv = [],
+ sm = [],
+ sd = [];
const mid = this.midP;
const sides = _polygon.sides;
for (const idx of indices) {
const j = idx % L;
let p = this.v[j];
-
- // Ray-cast: count intersections from p to far right
let crossings = 0;
for (const [a, b] of sides) {
- const ay = a.y, by = b.y;
+ const ay = a.y,
+ by = b.y;
if ((ay > p.y) === (by > p.y)) continue;
const t = (p.y - ay) / (by - ay);
if (p.x < a.x + t * (b.x - a.x)) crossings++;
}
- // If outside (even crossings), pull toward center
if (crossings % 2 === 0) {
p = {
x: mid.x + (p.x - mid.x) * rr(0.3, 0.6),
y: mid.y + (p.y - mid.y) * rr(0.3, 0.6),
};
}
-
sv.push(p);
sm.push(this.m[j]);
- sd.push(!this.dir[j]); // flip direction → grow inward
+ sd.push(!this.dir[j]);
}
return new FillPoly(sv, sm, this.midP, sd, false, this.sizeX, this.sizeY);
@@ -362,84 +358,77 @@ class FillPoly {
* @returns {FillPoly} A new FillPoly with adjusted vertices.
*/
grow(f = 1) {
- // Get trimmed vertices
- const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);
- const len = tr_v.length;
-
- // Pre-allocate output arrays
- const outLen = len * 2;
- const newVerts = new Array(outLen);
- const newMods = new Array(outLen);
- const newDirs = new Array(outLen);
-
- // Determine bleed direction
- const bleedDirDeg = State.fill.direction === "out" ? -90 : 90;
-
- // Ensure gaussian pool is filled
- if (_gaussians[0].length === 0) _fillGaussianPools();
- const gPool = _gaussians[0], gPoolLen = gPool.length;
- const g2Pool = _gaussians[1], g2PoolLen = g2Pool.length;
-
- let idx = 0;
- let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;
-
- for (let i = 0; i < len; i++) {
- const cv = tr_v[i];
- const nv = tr_v[i + 1 < len ? i + 1 : 0];
- const mi = tr_m[i];
- const di = tr_dir[i];
-
- if (f < 997) mod = mi;
-
- // Inline rotate: rotDeg = ±bleedDirDeg + small jitter
- const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;
- const c = cos(rotDeg);
- const s = sin(rotDeg);
-
- const sideX = nv.x - cv.x;
- const sideY = nv.y - cv.y;
- const dirX = c * sideX + s * sideY;
- const dirY = c * sideY - s * sideX;
-
- // Outward distance: inline rArray + rr
- const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;
-
- // First vertex: original
- newVerts[idx] = cv;
- newMods[idx] = mi;
- newDirs[idx] = di;
- idx++;
-
- // Second vertex: midpoint + outward push
- newVerts[idx] = {
- x: cv.x + sideX * 0.5 + dirX * d,
- y: cv.y + sideY * 0.5 + dirY * d,
- };
- newMods[idx] = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];
- newDirs[idx] = di;
- idx++;
- }
-
- // Cap vertex count to prevent exponential blowup.
- let fv = newVerts, fm = newMods, fd = newDirs;
- let growe = GROW_MAX_VERTS / (State.fill.texture_strength);
- if (growe && idx > growe) {
- const step = Math.ceil(idx / growe);
- fv = []; fm = []; fd = [];
- for (let j = 0; j < idx; j += step) {
- fv.push(newVerts[j]);
- fm.push(newMods[j]);
- fd.push(newDirs[j]);
- }
- } else {
- // Trim pre-allocated arrays to actual size
- fv.length = idx;
- fm.length = idx;
- fd.length = idx;
- }
-
- return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);
+ const { v: tr_v, m: tr_m, dir: tr_dir } = this.trim(f);
+ const len = tr_v.length;
+
+ const outLen = len * 2;
+ const newVerts = new Array(outLen);
+ const newMods = new Array(outLen);
+ const newDirs = new Array(outLen);
+ const bleedDirDeg = State.fill.direction === "out" ? -90 : 90;
+
+ if (_gaussians[0].length === 0) _fillGaussianPools();
+ const gPool = _gaussians[0],
+ gPoolLen = gPool.length;
+ const g2Pool = _gaussians[1],
+ g2PoolLen = g2Pool.length;
+
+ let idx = 0;
+ let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;
+
+ for (let i = 0; i < len; i++) {
+ const cv = tr_v[i];
+ const nv = tr_v[i + 1 < len ? i + 1 : 0];
+ const mi = tr_m[i];
+ const di = tr_dir[i];
+
+ if (f < 997) mod = mi;
+
+ const rotDeg = (di ? bleedDirDeg : -bleedDirDeg) + rr(-1, 1) * 5;
+ const c = cos(rotDeg);
+ const s = sin(rotDeg);
+ const sideX = nv.x - cv.x;
+ const sideY = nv.y - cv.y;
+ const dirX = c * sideX + s * sideY;
+ const dirY = c * sideY - s * sideX;
+ const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;
+
+ newVerts[idx] = cv;
+ newMods[idx] = mi;
+ newDirs[idx] = di;
+ idx++;
+
+ newVerts[idx] = {
+ x: cv.x + sideX * 0.5 + dirX * d,
+ y: cv.y + sideY * 0.5 + dirY * d,
+ };
+ newMods[idx] = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];
+ newDirs[idx] = di;
+ idx++;
+ }
+
+ let fv = newVerts,
+ fm = newMods,
+ fd = newDirs;
+ const growCap = GROW_MAX_VERTS / State.fill.texture_strength;
+ if (growCap && idx > growCap) {
+ const step = Math.ceil(idx / growCap);
+ fv = [];
+ fm = [];
+ fd = [];
+ for (let j = 0; j < idx; j += step) {
+ fv.push(newVerts[j]);
+ fm.push(newMods[j]);
+ fd.push(newDirs[j]);
}
+ } else {
+ fv.length = idx;
+ fm.length = idx;
+ fd.length = idx;
+ }
+
+ return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);
+ }
/**
* Fills the polygon with multiple layers to simulate a watercolor effect.
@@ -448,12 +437,10 @@ class FillPoly {
* @param {number} tex - Texture factor.
*/
fill(color, intensity, tex) {
- // Precalculate stuff
const numLayers = 20;
const texture = tex * 3;
const int = 2 * intensity * (1 + tex / 2);
- // Perform initial setup only once
const switchingToFill = Mix.isBrush !== false;
Mix.isBrush = false;
if (switchingToFill) Mix.justChanged = true;
@@ -461,8 +448,10 @@ class FillPoly {
Mix.ctx.save();
Mix.ctx.setTransform(
- Density * Matrix.a(), Density * Matrix.b(),
- Density * Matrix.c(), Density * Matrix.d(),
+ Density * Matrix.a(),
+ Density * Matrix.b(),
+ Density * Matrix.c(),
+ Density * Matrix.d(),
Density * (Matrix.x() + Cwidth / 2),
Density * (Matrix.y() + Cheight / 2),
);
@@ -474,18 +463,13 @@ class FillPoly {
const size = Math.max(this.sizeX, this.sizeY);
const darker = rr(0.15, 0.7);
-
- // Create initial polygon
let pol = this.grow();
- // Create sparse inner polygon from original (pre-grow) vertices
const sparse = this.scatter(0.1).grow().scatter(0.75).flipDirs();
let pols;
for (let i = 0; i < numLayers; i++) {
- // Grow polygon every 4 layers
if (i % 4 === 0) pol = pol.grow();
- // Create variant polygons
if (i % 2 === 0) {
pols = [
pol.grow(1 - 0.0125 * i),
@@ -494,17 +478,17 @@ class FillPoly {
];
}
- // Draw layers
for (const p of pols) p.grow(999).grow(997).layer(i, size, int, color);
- sparse.grow(999).flipDirs().grow(997).layer(i, size, int * 1.5 * texture, color);
- if (i % 2 === 0)
- pol
- .grow(darker)
- .grow(999)
- .layer(i, size, int * 2, color);
-
- // Apply texture and blend periodically
- if (i % 5 === 0 || i === numLayers - 1) {
+ sparse
+ .grow(999)
+ .flipDirs()
+ .grow(997)
+ .layer(i, size, int * texture, color);
+ if (i % 2 === 0) {
+ pol.grow(darker).grow(999).layer(i, size, int * 2, color);
+ }
+
+ if (i % 8 === 0 || i === numLayers - 1) {
if (texture !== 0) pol.erase(texture * 3, intensity);
Mix.blend(color, true, false, true);
}
@@ -533,7 +517,6 @@ class FillPoly {
erase(texture, intensity) {
Mix.ctx.save();
- // Optimize by pre-calculating values
const numCircles = ~~(rr(80, 110) * map(texture, 0, 1, 2, 3.5));
const halfSizeX = this.sizeX / 1.3;
const halfSizeY = this.sizeY / 1.3;
@@ -543,16 +526,13 @@ class FillPoly {
const maxSizeFactor = 0.4 * minSize;
const { x: midX, y: midY } = this.midP;
- // Set up erase mode
Mix.ctx.globalCompositeOperation = "destination-out";
- // Calculate transparency
const alpha =
((5 - map(intensity, 80, 100, 0.3, 0.7, true)) * texture) / 255;
Mix.ctx.fillStyle = `rgb(255 0 0 / ${alpha})`;
Mix.ctx.lineWidth = 0;
- // Draw erase circles
for (let i = 0; i < numCircles; i++) {
const x = midX + gaussian(0, halfSizeX);
const y = midY + gaussian(0, halfSizeY);
diff --git a/src/hatch/hatch.js b/src/hatch/hatch.js
index e839300..ac265dd 100644
--- a/src/hatch/hatch.js
+++ b/src/hatch/hatch.js
@@ -1,32 +1,17 @@
// =============================================================================
-// Module: Hatch
+// Module: Classic Hatch
// =============================================================================
-/**
- * The Hatch module contains functions and classes dedicated to applying
- * hatch patterns over shapes and polygons. It enables the simulation of
- * cross-hatching and shading effects by drawing parallel lines or strokes
- * across a geometry. The module supports adjustable spacing, angle, and
- * optional style parameters (such as randomness, continuity, and gradient),
- * giving an artistic representation similar to hand-drawn hatching techniques.
- *
- * The implementation allows for hatching to be applied either to a Polygon
- * directly or via a Plot, extending the drawing capabilities with layered,
- * stylized textures.
- */
import { State } from "../core/color.js";
-import { toDegreesSigned, map, cos, sin, rr } from "../core/utils.js";
+import { toDegreesSigned, map, rr } from "../core/utils.js";
import { Polygon } from "../core/polygon.js";
import { Plot } from "../core/plot.js";
import { BrushState, BrushSetState, set, line } from "../stroke/stroke.js";
// ---------------------------------------------------------------------------
-// Hatch State and Helpers
+// Hatch State
// ---------------------------------------------------------------------------
-/**
- * Global hatch state settings.
- */
State.hatch = {
isActive: false,
dist: 5,
@@ -35,36 +20,18 @@ State.hatch = {
hBrush: false,
};
-/**
- * Returns a shallow copy of the current hatch state.
- * @returns {object} The current hatch state.
- */
export function HatchState() {
return { ...State.hatch };
}
-/**
- * Updates the global hatch state.
- * @param {object} state - The new hatch state.
- */
export function HatchSetState(state) {
State.hatch = { ...state };
}
// ---------------------------------------------------------------------------
-// Hatch Style Functions
+// Public API
// ---------------------------------------------------------------------------
-/**
- * Activates hatching for subsequent geometries.
- *
- * @param {number} dist - The distance between hatching lines.
- * @param {number} angle - The hatch angle, interpreted using the current p5 angle mode.
- * @param {object} options - Optional parameters to affect the hatching style:
- * - rand: Number value to introduce randomness.
- * - continuous: Boolean to connect adjacent lines.
- * - gradient: Number to gradually change spacing.
- */
export function hatch(
dist = 5,
angle = 45,
@@ -77,199 +44,121 @@ export function hatch(
s.options = options;
}
-/**
- * Sets the hatch brush style for subsequent hatching.
- *
- * @param {string} brush - The brush name.
- * @param {string|Color} color - The brush color.
- * @param {number} weight - The brush weight (size).
- */
export function hatchStyle(brush, color = "black", weight = 1) {
State.hatch.hBrush = { brush, color, weight };
}
-/**
- * Disables hatching.
- */
export function noHatch() {
State.hatch.isActive = false;
State.hatch.hBrush = false;
}
// ---------------------------------------------------------------------------
-// Fill Manager Functions
+// Scanline Hatching
// ---------------------------------------------------------------------------
/**
- * Creates a hatching pattern over the given polygon(s).
- *
- * @param {Polygon|Polygon[]} polygons - A polygon or an array of polygons.
+ * Computes hatch segments for a polygon via scanline intersection.
+ * Rotates vertices so hatch lines become horizontal, scans for edge
+ * crossings, then rotates intersections back to original space.
*/
-export function createHatch(polygons) {
- let dist = State.hatch.dist;
- let angle = ((State.hatch.angle % 180) + 180) % 180;
- let options = State.hatch.options;
-
- // Save current stroke state
- let save = BrushState();
- // If a hatch brush is set, override with those parameters.
- if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));
-
- // Compute overall bounding box for all polygons.
- if (!Array.isArray(polygons)) polygons = [polygons];
- const overallBB = computeOverallBoundingBox(polygons);
-
- // Build a bounding polygon based on the overall bounding box.
- let ventana = new Polygon([
- [overallBB.minX, overallBB.minY],
- [overallBB.maxX, overallBB.minY],
- [overallBB.maxX, overallBB.maxY],
- [overallBB.minX, overallBB.maxY],
- ]);
-
- // Determine starting y coordinate based on angle.
- let startY = angle <= 90 && angle >= 0 ? overallBB.minY : overallBB.maxY;
- let gradient = options.gradient
- ? map(options.gradient, 0, 1, 1, 1.1, true)
- : 1;
- let dots = [];
- let i = 0;
- let dist1 = dist;
-
- // Function to generate a line for index i.
- let linea = (i) => {
- return {
- point1: {
- x: overallBB.minX + dist1 * i * cos(-angle + 90),
- y: startY + dist1 * i * sin(-angle + 90),
- },
- point2: {
- x: overallBB.minX + dist1 * i * cos(-angle + 90) + cos(-angle),
- y: startY + dist1 * i * sin(-angle + 90) + sin(-angle),
- },
- };
- };
+function scanlineHatch(polygon, angle, dist, gradient) {
+ const rad = (angle * Math.PI) / 180;
+ const cosA = Math.cos(rad), sinA = Math.sin(rad);
+ const cosB = Math.cos(-rad), sinB = Math.sin(-rad);
+
+ const verts = polygon.a, n = verts.length;
+
+ // Rotate vertices; track Y extent
+ const rotated = new Array(n);
+ let minY = Infinity, maxY = -Infinity;
+ for (let i = 0; i < n; i++) {
+ const x = verts[i][0], y = verts[i][1];
+ const r = [x * cosA - y * sinA, x * sinA + y * cosA];
+ rotated[i] = r;
+ if (r[1] < minY) minY = r[1];
+ if (r[1] > maxY) maxY = r[1];
+ }
- // Generate lines and calculate intersections with polygons
- // Loop through the lines based on the distance and angle to calculate intersections with the polygons
- // The loop continues until a line does not intersect with the bounding window polygon
- // Each iteration accounts for the gradient effect by adjusting the distance between lines
- while (ventana.intersect(linea(i)).length > 0) {
- let tempArray = [];
- for (let p of polygons) {
- tempArray.push(p.intersect(linea(i)));
+ // Build edge list (skip horizontal edges)
+ const edges = [];
+ for (let i = 0; i < n; i++) {
+ const a = rotated[i], b = rotated[(i + 1) % n];
+ if (a[1] !== b[1]) edges.push(a, b);
+ }
+ const eLen = edges.length;
+
+ // Scan, find crossings, rotate back
+ const segments = [];
+ let Y = minY + dist * 0.5, step = dist;
+ while (Y < maxY) {
+ const cx = [];
+ for (let i = 0; i < eLen; i += 2) {
+ const y1 = edges[i][1], y2 = edges[i + 1][1];
+ if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))
+ cx.push(edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0]));
}
- dots[i] = tempArray
- .flat()
- .sort((a, b) => (a.x === b.x ? a.y - b.y : a.x - b.x));
- dist1 *= gradient;
- i++;
+ cx.sort((a, b) => a - b);
+ for (let i = 0; i < cx.length - 1; i += 2) {
+ segments.push({
+ x1: cx[i] * cosB - Y * sinB, y1: cx[i] * sinB + Y * cosB,
+ x2: cx[i + 1] * cosB - Y * sinB, y2: cx[i + 1] * sinB + Y * cosB,
+ });
+ }
+ Y += step;
+ step *= gradient;
}
+ return segments;
+}
- // Filter out empty intersection sets.
- let gdots = dots.filter((dd) => typeof dd[0] !== "undefined");
+// ---------------------------------------------------------------------------
+// Create Hatch
+// ---------------------------------------------------------------------------
- // Draw the hatching lines using the calculated intersections
- // If the 'rand' option is enabled, add randomness to the start and end points of the lines
- // If the 'continuous' option is set, connect the end of one line to the start of the next
- let r = options.rand || 0;
- for (let j = 0; j < gdots.length; j++) {
- let dd = gdots[j];
- let continuousLine = j > 0 && options.continuous;
- for (let i = 0; i < dd.length - 1; i += 2) {
- if (r !== 0) {
- dd[i].x += r * dist * rr(-1, 1);
- dd[i].y += r * dist * rr(-1, 1);
- dd[i + 1].x += r * dist * rr(-1, 1);
- dd[i + 1].y += r * dist * rr(-1, 1);
- }
- line(dd[i].x, dd[i].y, dd[i + 1].x, dd[i + 1].y);
- if (continuousLine) {
- line(gdots[j - 1][1].x, gdots[j - 1][1].y, dd[i].x, dd[i].y);
- }
- }
- }
+export function createHatch(polygons) {
+ const dist = State.hatch.dist;
+ const angle = ((State.hatch.angle % 180) + 180) % 180;
+ const options = State.hatch.options;
- // Restore previous brush state.
- BrushSetState(save);
-}
+ const save = BrushState();
+ if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));
+ if (!Array.isArray(polygons)) polygons = [polygons];
-/**
- * Computes the bounding box for a single polygon.
- * @param {Polygon} polygon - The polygon to evaluate.
- * @returns {object} The bounding box as {minX, minY, maxX, maxY}.
- */
-function computeBoundingBoxForPolygon(polygon) {
- if (polygon._boundingBox) return polygon._boundingBox;
- let minX = Infinity,
- minY = Infinity,
- maxX = -Infinity,
- maxY = -Infinity;
- for (let i = 0; i < polygon.a.length; i++) {
- const [x, y] = polygon.a[i];
- if (x < minX) minX = x;
- if (x > maxX) maxX = x;
- if (y < minY) minY = y;
- if (y > maxY) maxY = y;
+ const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;
+
+ const segs = [];
+ for (const poly of polygons)
+ for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);
+ segs.sort((a, b) => a.x1 === b.x1 ? a.y1 - b.y1 : a.x1 - b.x1);
+
+ const r = options.rand || 0;
+ for (let j = 0; j < segs.length; j++) {
+ const s = segs[j];
+ let x1 = s.x1, y1 = s.y1, x2 = s.x2, y2 = s.y2;
+ if (r) {
+ x1 += r * dist * rr(-1, 1);
+ y1 += r * dist * rr(-1, 1);
+ x2 += r * dist * rr(-1, 1);
+ y2 += r * dist * rr(-1, 1);
+ }
+ line(x1, y1, x2, y2);
+ if (j > 0 && options.continuous) line(segs[j - 1].x2, segs[j - 1].y2, x1, y1);
}
- polygon._boundingBox = { minX, minY, maxX, maxY };
- return polygon._boundingBox;
-}
-/**
- * Computes an overall bounding box for an array of polygons.
- * @param {Array} polygons - Array of Polygon objects.
- * @returns {object} The overall bounding box {minX, minY, maxX, maxY}.
- */
-function computeOverallBoundingBox(polygons) {
- let overall = {
- minX: Infinity,
- minY: Infinity,
- maxX: -Infinity,
- maxY: -Infinity,
- };
- for (let poly of polygons) {
- const bb = computeBoundingBoxForPolygon(poly);
- overall.minX = Math.min(overall.minX, bb.minX);
- overall.minY = Math.min(overall.minY, bb.minY);
- overall.maxX = Math.max(overall.maxX, bb.maxX);
- overall.maxY = Math.max(overall.maxY, bb.maxY);
- }
- return overall;
+ BrushSetState(save);
}
// ---------------------------------------------------------------------------
-// Extend Polygon and Plot Prototypes
+// Prototype Extensions
// ---------------------------------------------------------------------------
-/**
- * Adds a hatch effect to the polygon.
- *
- * If a distance is provided, activates hatching with the given parameters.
- * Then, if hatch is active, applies the hatching pattern.
- *
- * @param {number} [_dist] - The distance between hatch lines.
- * @param {number} _angle - The hatch angle, interpreted using the current p5 angle mode.
- * @param {object} _options - Optional hatch options.
- */
Polygon.prototype.hatch = function (_dist = false, _angle, _options) {
let state = HatchState();
if (_dist) hatch(_dist, _angle, _options);
- if (state.isActive) {
- createHatch(this);
- }
+ if (state.isActive) createHatch(this);
HatchSetState(state);
};
-/**
- * Applies hatching to a plot.
- *
- * If hatching is active, generates a polygon from the plot and applies hatch.
- *
- * @param {number} x - The x-coordinate to draw at.
- * @param {number} y - The y-coordinate to draw at.
- * @param {number} scale - Scaling factor.
- */
Plot.prototype.hatch = function (x, y, scale) {
if (HatchState().isActive) {
if (this.origin) (x = this.origin[0]), (y = this.origin[1]), (scale = 1);
diff --git a/src/index.js b/src/index.js
index 9f4feaf..1163391 100644
--- a/src/index.js
+++ b/src/index.js
@@ -118,7 +118,12 @@ export {
} from "./hatch/hatch.js";
// Fill
-export { fill, noFill, fillTexture, fillBleed } from "./fill/fill.js";
+export {
+ fill,
+ noFill,
+ fillTexture,
+ fillBleed,
+} from "./fill/fill.js";
// p5 addon registration
import { Mix } from "./core/color.js";
diff --git a/src/stroke/gl_draw.js b/src/stroke/gl_draw.js
index 718ea09..3b641f4 100644
--- a/src/stroke/gl_draw.js
+++ b/src/stroke/gl_draw.js
@@ -2,11 +2,9 @@
// Module: GL Draw
// =============================================================================
/**
- * The GL Draw module provides functions for rendering shapes (circles and squares)
- * using WebGL2. It initializes the WebGL context and shader programs, prepares buffers,
- * and implements drawing routines based on queued drawing primitives. The module uses
- * an orthographic projection to map canvas coordinates to clip space and supports adjustable
- * blending for translucent effects.
+ * The GL Draw module batches brush primitives for WebGL2 rendering. It initializes
+ * the shader programs and buffers used by circle-based brushes and image-tip brushes,
+ * then flushes those queues into the shared framebuffer-backed brush mask.
*/
import {
@@ -16,11 +14,14 @@ import {
isMixReady,
Density,
State,
+ Renderer,
} from "../core/color.js";
import { Matrix } from "../core/flowfield.js";
import { createProgram } from "../core/gl/utils.js";
import vertSrc from "./shader.vert";
import fragSrc from "./shader.frag";
+import imgVertSrc from "./image.vert";
+import imgFragSrc from "./image.frag";
// =============================================================================
// Section: Initialization and Setup
@@ -30,11 +31,14 @@ import fragSrc from "./shader.frag";
let isLoaded = false,
gl,
projMatrix,
+ framebufferProjMatrix,
vao,
buf,
program;
let loadedWidth = 0,
loadedHeight = 0;
+let brushMaskTarget = null;
+let prevMaskTarget = null;
const Attr = {},
Frag = {};
@@ -44,7 +48,11 @@ let _ma = 1,
_mc = 0,
_md = 1,
_mx = 0,
- _my = 0;
+ _my = 0,
+ _halfW = 0,
+ _halfH = 0,
+ _scale = 1,
+ _density = 1;
/**
* Snapshots the current p5 model matrix. Call once at the start of each stroke.
@@ -56,6 +64,10 @@ export function snapshotMatrix() {
_md = Matrix.d();
_mx = Matrix.x();
_my = Matrix.y();
+ _halfW = Cwidth / 2;
+ _halfH = Cheight / 2;
+ _scale = Math.sqrt(_ma * _ma + _mb * _mb);
+ _density = Density;
}
// Pre-allocated flat buffer for circle data (x, y, radius, alpha per circle)
@@ -64,14 +76,163 @@ let circleData = new Float32Array(INITIAL_CAPACITY * 4);
let circleCount = 0;
let bufferCapacity = INITIAL_CAPACITY;
let gpuBufferSize = INITIAL_CAPACITY * 4 * 4; // bytes allocated on GPU
+let circleDirtyRect = null;
+
+// ---------------------------------------------------------------------------
+// Image instancing state
+// ---------------------------------------------------------------------------
+let imgProgram = null;
+let imgVao = null;
+let imgCornerBuf = null;
+let imgInstanceBuf = null;
+const imgAttr = {};
+const imgFrag = {};
+let imgGpuSize = 0;
+
+const IMG_FLOATS = 5; // screenX, screenY, halfSize, angle, alpha — per stamp
+const IMG_INIT_CAP = 256;
+let imgData = new Float32Array(IMG_INIT_CAP * IMG_FLOATS);
+let imgCount = 0;
+let imgCapacity = IMG_INIT_CAP;
+let imgDirtyRect = null;
+
+// Texture cache: src string → WebGLTexture (cleared whenever the GL context changes)
+const texCache = new Map();
+
+// Static unit-quad corners for gl.TRIANGLE_STRIP in quad-local space.
+const QUAD_CORNERS = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);
+
+function isFramebufferMask(target) {
+ return (
+ !!target &&
+ typeof target.begin === "function" &&
+ typeof target.end === "function" &&
+ !!target.renderer
+ );
+}
+
+function resetMaskShaderTracking() {
+ const target = Mix.glMask;
+ const renderer = isFramebufferMask(target) ? target.renderer : target?._renderer;
+ if (!renderer) return;
+ renderer._curShader = null;
+ renderer._cachedBlendMode = null;
+ renderer._isBlending = null;
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.blendEquation(gl.FUNC_ADD);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+}
+
+function getFramebufferHandle(target) {
+ if (!target) return null;
+ if (typeof target._framebufferToBind === "function") return target._framebufferToBind();
+ return target.framebuffer ?? null;
+}
+
+function ensureBrushMaskTarget() {
+ const targetRenderer = Renderer?._renderer;
+ const targetDensity = Density;
+ const needsTarget =
+ !brushMaskTarget ||
+ brushMaskTarget.renderer !== targetRenderer ||
+ brushMaskTarget.width !== Cwidth ||
+ brushMaskTarget.height !== Cheight ||
+ brushMaskTarget.density !== targetDensity;
+
+ if (!needsTarget) {
+ Mix.glMask = brushMaskTarget;
+ return brushMaskTarget;
+ }
+
+ if (brushMaskTarget?.remove) brushMaskTarget.remove();
+
+ const target = Renderer.createFramebuffer({
+ width: Cwidth,
+ height: Cheight,
+ density: targetDensity,
+ antialias: false,
+ depth: false,
+ stencil: false,
+ });
+ target.isDrawn = false;
+ target.dirtyRect = null;
+ target.clear = () => {
+ const renderer = Renderer._renderer;
+ const previous = renderer.activeFramebuffer?.() ?? null;
+ if (previous?._beforeEnd) previous._beforeEnd();
+ gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(target));
+ gl.viewport(0, 0, target.width * target.density, target.height * target.density);
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ if (previous?._beforeBegin) {
+ previous._beforeBegin();
+ } else {
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ renderer.viewport(renderer._origViewport.width, renderer._origViewport.height);
+ renderer._applyStencilTestIfClipping?.();
+ }
+ };
+
+ brushMaskTarget = target;
+ Mix.glMask = brushMaskTarget;
+ return brushMaskTarget;
+}
+
+function getProjectionMatrix() {
+ return isFramebufferMask(Mix.glMask) ? framebufferProjMatrix : projMatrix;
+}
+
+function beginMaskTarget() {
+ const target = Mix.glMask;
+ const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);
+ beginMaskTarget._hadDepthTest = hadDepthTest;
+ if (hadDepthTest) gl.disable(gl.DEPTH_TEST);
+ if (isFramebufferMask(target)) {
+ prevMaskTarget = Renderer._renderer.activeFramebuffer?.() ?? null;
+ if (prevMaskTarget?._beforeEnd) prevMaskTarget._beforeEnd();
+ gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(target));
+ gl.viewport(0, 0, target.width * target.density, target.height * target.density);
+ return;
+ }
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
+}
+
+function endMaskTarget() {
+ if (beginMaskTarget._hadDepthTest) gl.enable(gl.DEPTH_TEST);
+ beginMaskTarget._hadDepthTest = false;
+ if (!isFramebufferMask(Mix.glMask)) return;
+ if (prevMaskTarget?._beforeBegin) {
+ prevMaskTarget._beforeBegin();
+ } else {
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ Renderer._renderer.viewport(
+ Renderer._renderer._origViewport.width,
+ Renderer._renderer._origViewport.height,
+ );
+ Renderer._renderer._applyStencilTestIfClipping?.();
+ }
+ prevMaskTarget = null;
+}
+
+function accumulateDirtyRect(currentRect, minX, minY, maxX, maxY) {
+ if (!currentRect) return { minX, minY, maxX, maxY };
+ if (minX < currentRect.minX) currentRect.minX = minX;
+ if (minY < currentRect.minY) currentRect.minY = minY;
+ if (maxX > currentRect.maxX) currentRect.maxX = maxX;
+ if (maxY > currentRect.maxY) currentRect.maxY = maxY;
+ return currentRect;
+}
/**
* Initializes WebGL objects if not done already.
*/
export function isReady() {
isMixReady();
+ ensureBrushMaskTarget();
- const nextGl = Mix.glMask.drawingContext;
+ const nextGl = Renderer.drawingContext;
const needsContextRefresh = !isLoaded || gl !== nextGl;
const needsProjectionRefresh =
needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;
@@ -95,6 +256,24 @@ export function isReady() {
0,
1,
]);
+ framebufferProjMatrix = new Float32Array([
+ 2 / Cwidth,
+ 0,
+ 0,
+ 0,
+ 0,
+ 2 / Cheight,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ -1,
+ -1,
+ 0,
+ 1,
+ ]);
loadedWidth = Cwidth;
loadedHeight = Cheight;
}
@@ -137,6 +316,54 @@ export function isReady() {
gl.bindVertexArray(null);
+ // ------------------------------------------------------------------
+ // Image-tip instancing program
+ // ------------------------------------------------------------------
+ texCache.clear();
+
+ imgProgram = createProgram(gl, imgVertSrc, imgFragSrc);
+ ["a_corner", "a_pos", "a_size", "a_angle", "a_alpha"].forEach(
+ (n) => (imgAttr[n] = gl.getAttribLocation(imgProgram, n)),
+ );
+ ["u_proj", "u_color", "u_tex"].forEach(
+ (n) => (imgFrag[n] = gl.getUniformLocation(imgProgram, n)),
+ );
+
+ imgVao = gl.createVertexArray();
+ gl.bindVertexArray(imgVao);
+
+ // Static corner VBO (per-vertex, no divisor)
+ imgCornerBuf = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, imgCornerBuf);
+ gl.bufferData(gl.ARRAY_BUFFER, QUAD_CORNERS, gl.STATIC_DRAW);
+ gl.enableVertexAttribArray(imgAttr.a_corner);
+ gl.vertexAttribPointer(imgAttr.a_corner, 2, gl.FLOAT, false, 0, 0);
+
+ // Instance data VBO (per-instance)
+ imgInstanceBuf = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);
+ gl.bufferData(gl.ARRAY_BUFFER, imgData.byteLength, gl.DYNAMIC_DRAW);
+ imgGpuSize = imgData.byteLength;
+
+ const istride = IMG_FLOATS * 4; // 20 bytes
+ gl.enableVertexAttribArray(imgAttr.a_pos);
+ gl.vertexAttribPointer(imgAttr.a_pos, 2, gl.FLOAT, false, istride, 0);
+ gl.vertexAttribDivisor(imgAttr.a_pos, 1);
+
+ gl.enableVertexAttribArray(imgAttr.a_size);
+ gl.vertexAttribPointer(imgAttr.a_size, 1, gl.FLOAT, false, istride, 8);
+ gl.vertexAttribDivisor(imgAttr.a_size, 1);
+
+ gl.enableVertexAttribArray(imgAttr.a_angle);
+ gl.vertexAttribPointer(imgAttr.a_angle, 1, gl.FLOAT, false, istride, 12);
+ gl.vertexAttribDivisor(imgAttr.a_angle, 1);
+
+ gl.enableVertexAttribArray(imgAttr.a_alpha);
+ gl.vertexAttribPointer(imgAttr.a_alpha, 1, gl.FLOAT, false, istride, 16);
+ gl.vertexAttribDivisor(imgAttr.a_alpha, 1);
+
+ gl.bindVertexArray(null);
+
isLoaded = true;
}
@@ -162,14 +389,13 @@ export function circle(x, y, diameter, alpha) {
// x/y arrive in "position space": user coords + (Cwidth/2, Cheight/2).
// Subtract the offset to recover user coords, apply the full matrix, then re-add
// the offset so the result is in screen pixel space [0..Cwidth, 0..Cheight].
- const px = x - Cwidth / 2;
- const py = y - Cheight / 2;
+ const px = x - _halfW;
+ const py = y - _halfH;
const offset = circleCount * 4;
- 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;
+ const screenX = _ma * px + _mc * py + _mx + _halfW;
+ const screenY = _mb * px + _md * py + _my + _halfH;
+ const radius = (_density * diameter * _scale) / 2;
circleData[offset] = screenX;
circleData[offset + 1] = screenY;
@@ -177,16 +403,140 @@ export function circle(x, y, diameter, alpha) {
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,
- });
+ const dScreenX = screenX * _density;
+ const dScreenY = screenY * _density;
+ circleDirtyRect = accumulateDirtyRect(
+ circleDirtyRect,
+ dScreenX - radius - 1,
+ dScreenY - radius - 1,
+ dScreenX + radius + 1,
+ dScreenY + radius + 1,
+ );
circleCount++;
}
+/**
+ * Queue an image stamp to be drawn with instanced rendering.
+ * Accepts the same coordinate conventions as circle(): x/y in position space
+ * (user coords + Cwidth/2, Cheight/2), size in user-coord units, alpha in [0..255].
+ * @param {number} x - X in position space.
+ * @param {number} y - Y in position space.
+ * @param {number} size - Full stamp diameter in user-coord units.
+ * @param {number} angle - Rotation in radians.
+ * @param {number} alpha - Opacity [0..255].
+ */
+export function stampImage(x, y, size, angle, alpha) {
+ if (imgCount >= imgCapacity) {
+ imgCapacity *= 2;
+ const next = new Float32Array(imgCapacity * IMG_FLOATS);
+ next.set(imgData);
+ imgData = next;
+ }
+
+ const px = x - _halfW;
+ const py = y - _halfH;
+ const screenX = _ma * px + _mc * py + _mx + _halfW;
+ const screenY = _mb * px + _md * py + _my + _halfH;
+ const halfSize = (_density * size * _scale) / 2;
+
+ const base = imgCount * IMG_FLOATS;
+ imgData[base] = screenX;
+ imgData[base + 1] = screenY;
+ imgData[base + 2] = halfSize;
+ imgData[base + 3] = angle;
+ imgData[base + 4] = alpha / 255;
+
+ // Bounding box: rotated square worst-case = circle of radius halfSize * √2
+ const dScreenX = screenX * _density;
+ const dScreenY = screenY * _density;
+ imgDirtyRect = accumulateDirtyRect(
+ imgDirtyRect,
+ dScreenX - halfSize * 1.42 - 1,
+ dScreenY - halfSize * 1.42 - 1,
+ dScreenX + halfSize * 1.42 + 1,
+ dScreenY + halfSize * 1.42 + 1,
+ );
+
+ imgCount++;
+}
+
+/**
+ * Flush all queued image stamps in a single instanced draw call.
+ * @param {p5.Image} p5img - The preprocessed brush-tip image (from T.tips).
+ * @param {string} src - The image src string, used as the texture cache key.
+ */
+export function glDrawImages(p5img, src) {
+ if (imgCount === 0) return;
+
+ Mix.glMask.isDrawn = true;
+ beginMaskTarget();
+
+ // Lazy-create the WebGL texture from the p5.Image canvas on first use
+ let tex = texCache.get(src);
+ if (!tex) {
+ tex = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, tex);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, p5img.canvas);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ texCache.set(src, tex);
+ }
+
+ gl.useProgram(imgProgram);
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE_MINUS_DST_ALPHA, gl.ONE);
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, tex);
+ gl.uniform1i(imgFrag.u_tex, 0);
+
+ const color = State.stroke.color._array;
+ gl.uniform4f(imgFrag.u_color, ...color);
+ gl.uniformMatrix4fv(imgFrag.u_proj, false, getProjectionMatrix());
+
+ gl.bindVertexArray(imgVao);
+ gl.bindBuffer(gl.ARRAY_BUFFER, imgInstanceBuf);
+
+ const byteCount = imgCount * IMG_FLOATS * 4;
+ const dataView = imgData.subarray(0, imgCount * IMG_FLOATS);
+ if (byteCount > imgGpuSize) {
+ gl.bufferData(gl.ARRAY_BUFFER, imgData, gl.DYNAMIC_DRAW);
+ imgGpuSize = imgData.byteLength;
+ } else {
+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, dataView);
+ }
+
+ gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, imgCount);
+ gl.flush();
+
+ gl.bindVertexArray(null);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ endMaskTarget();
+
+ if (imgDirtyRect) {
+ Mix.markDirtyRect(Mix.glMask, imgDirtyRect);
+ imgDirtyRect = null;
+ }
+
+ imgCount = 0;
+
+ // Let p5 know we changed the active program
+ resetMaskShaderTracking();
+}
+
+/**
+ * Removes a cached GL texture by key, forcing re-upload on next draw.
+ * Call this when a custom tip function changes after brush.add().
+ */
+export function invalidateTexEntry(key) {
+ const tex = texCache.get(key);
+ if (tex && gl) gl.deleteTexture(tex);
+ texCache.delete(key);
+}
+
/**
* Draw all queued circles using WebGL
*/
@@ -194,6 +544,7 @@ export function glDraw() {
if (circleCount === 0) return;
Mix.glMask.isDrawn = true;
+ beginMaskTarget();
const color = State.stroke.color._array;
@@ -217,10 +568,17 @@ export function glDraw() {
// Set uniforms and draw
gl.uniform4f(Frag.u_color, ...color);
- gl.uniformMatrix4fv(Frag.u_matrix, false, projMatrix);
+ gl.uniformMatrix4fv(Frag.u_matrix, false, getProjectionMatrix());
gl.drawArrays(gl.POINTS, 0, circleCount);
+ gl.flush();
gl.bindVertexArray(null);
+ endMaskTarget();
+
+ if (circleDirtyRect) {
+ Mix.markDirtyRect(Mix.glMask, circleDirtyRect);
+ circleDirtyRect = null;
+ }
// Reset queue (no deallocation)
circleCount = 0;
@@ -229,5 +587,5 @@ export function glDraw() {
// Reset it to null so p5 is forced to re-activate its own shader next time
// it draws — otherwise p5 skips gl.useProgram() and sets uniforms on the
// wrong active program, causing "location is not from the associated program".
- Mix.glMask._renderer._curShader = null;
+ resetMaskShaderTracking();
}
diff --git a/src/stroke/image.frag b/src/stroke/image.frag
new file mode 100644
index 0000000..0bb5b1a
--- /dev/null
+++ b/src/stroke/image.frag
@@ -0,0 +1,16 @@
+#version 300 es
+precision highp float;
+
+in vec2 v_uv;
+in float v_alpha;
+
+uniform sampler2D u_tex; // preprocessed brush-tip (white RGB, ink density in alpha)
+uniform vec4 u_color; // stroke colour (same channel layout as the circle shader)
+
+out vec4 outColor;
+
+void main() {
+ float inkAlpha = texture(u_tex, v_uv).a;
+ if (inkAlpha < 0.01) discard;
+ outColor = vec4(u_color.rgb, inkAlpha * v_alpha);
+}
diff --git a/src/stroke/image.vert b/src/stroke/image.vert
new file mode 100644
index 0000000..29d4fb8
--- /dev/null
+++ b/src/stroke/image.vert
@@ -0,0 +1,29 @@
+#version 300 es
+
+// Per-vertex: one of the four unit-quad corners
+in vec2 a_corner;
+
+// Per-instance
+in vec2 a_pos; // stamp centre in screen-pixel space
+in float a_size; // half-size in screen pixels (already scaled by Density & matrix)
+in float a_angle; // rotation in radians
+in float a_alpha; // opacity [0..1]
+
+uniform mat4 u_proj;
+
+out vec2 v_uv;
+out float v_alpha;
+
+void main() {
+ float c = cos(a_angle);
+ float s = sin(a_angle);
+ vec2 rotated = vec2(
+ c * a_corner.x - s * a_corner.y,
+ s * a_corner.x + c * a_corner.y
+ );
+ gl_Position = u_proj * vec4(a_pos + rotated * a_size, 0.0, 1.0);
+ // Map corner [-1,1] → uv [0,1]; without UNPACK_FLIP_Y this gives the
+ // correct orientation because our projection already has Y increasing downward.
+ v_uv = a_corner * 0.5 + 0.5;
+ v_alpha = a_alpha;
+}
diff --git a/src/stroke/stroke.js b/src/stroke/stroke.js
index 7625530..11c8be9 100644
--- a/src/stroke/stroke.js
+++ b/src/stroke/stroke.js
@@ -17,6 +17,7 @@ import {
Cheight,
State,
Renderer,
+ Instance,
isCanvasReady,
} from "../core/color.js";
import {
@@ -34,7 +35,15 @@ import {
import { Position, Matrix, isFieldReady } from "../core/flowfield.js";
import { Polygon } from "../core/polygon.js";
import { Plot } from "../core/plot.js";
-import { isReady, glDraw, circle, snapshotMatrix } from "./gl_draw.js";
+import {
+ isReady,
+ glDraw,
+ glDrawImages,
+ circle,
+ stampImage,
+ invalidateTexEntry,
+ snapshotMatrix,
+} from "./gl_draw.js";
// ---------------------------------------------------------------------------
// Brush State and Helpers
@@ -53,8 +62,6 @@ State.stroke = {
};
let list = new Map();
-
-let Mask = null;
let _strokeTransform = {
a: 1,
b: 0,
@@ -64,6 +71,17 @@ let _strokeTransform = {
ty: 0,
};
+function getBrushFactory() {
+ return Renderer ?? Instance ?? window.self.p5.instance;
+}
+
+const DEFAULT_CUSTOM_PRESSURE_VARIATION = {
+ offset: 0.08,
+ scale: 0.08,
+ warp: 0.06,
+ tilt: 0.06,
+};
+
/**
* Retrieves a shallow copy of the current stroke state.
* @returns {object} The stroke state.
@@ -95,12 +113,44 @@ export function BrushSetState(state) {
* [start, end] — linear ramp between two pressure values
* [start, mid, end] — piecewise linear (e.g. [1.5, 0.5, 1.5] for U-curve)
* (t) => value — custom function, t ∈ [0,1], return value ∈ [0,1]
- * { type, min_max, curve } — old internal format, passed through unchanged
+ * { mode: "gaussian", curve, min_max } — advanced built-in pressure profile
+ * { curve, min_max } — legacy gaussian format, preserved for compatibility
*/
-function normalizePressure(p) {
- if (!p || (typeof p === "object" && !Array.isArray(p))) return p;
+export function normalizePressure(p) {
+ if (!p) return p;
if (typeof p === "function")
- return { type: "custom", min_max: [0, 1], curve: p };
+ return {
+ type: "custom",
+ min_max: [0, 1],
+ curve: p,
+ variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },
+ };
+ if (typeof p === "object" && !Array.isArray(p)) {
+ if (p.type === "custom" || p.mode === "custom") {
+ const { mode, ...rest } = p;
+ return {
+ ...rest,
+ type: "custom",
+ variation: {
+ ...DEFAULT_CUSTOM_PRESSURE_VARIATION,
+ ...(rest.variation ?? {}),
+ },
+ };
+ }
+ if (
+ p.type === "gaussian" ||
+ p.mode === "gaussian" ||
+ (Array.isArray(p.curve) && Array.isArray(p.min_max))
+ ) {
+ return {
+ ...p,
+ type: "gaussian",
+ curve: p.curve,
+ min_max: p.min_max,
+ };
+ }
+ return p;
+ }
if (Array.isArray(p)) {
const [s, m, e] = p.length === 2 ? [p[0], (p[0] + p[1]) / 2, p[1]] : p;
const min = Math.min(s, m, e),
@@ -114,6 +164,7 @@ function normalizePressure(p) {
return {
type: "custom",
min_max: [min, max],
+ variation: { ...DEFAULT_CUSTOM_PRESSURE_VARIATION },
curve: (t) =>
t < 0.5 ? ns + (nm - ns) * t * 2 : nm + (ne - nm) * (t - 0.5) * 2,
};
@@ -131,6 +182,32 @@ export function add(name, params) {
if (params.quality !== undefined && params.grain === undefined)
params.grain = params.quality;
params.pressure = normalizePressure(params.pressure);
+ if (params.type === "custom") {
+ if (typeof params.tip !== "function") {
+ throw new Error(`Brush "${name}" is type "custom" but is missing a tip function.`);
+ }
+ // Rasterise the tip once into a 500×500 P2D buffer.
+ // Users draw in a 100×100 coordinate space (origin at centre);
+ // dark fills/strokes → high opacity, light/white → transparent.
+ const key = `custom::${name}`;
+ invalidateTexEntry(key); // discard stale GPU texture if tip changed
+ const factory = getBrushFactory();
+ const g = factory.createGraphics(500, 500);
+ g.pixelDensity(1);
+ g.background(255);
+ g.noSmooth();
+ g.push();
+ g.translate(250, 250); // centre origin
+ g.scale(5); // 100 user units → 500 px
+ g.noStroke();
+ params.tip(g);
+ g.pop();
+ T.imageToWhite(g); // dark → high alpha, RGB → white for tint
+ T.tips.set(key, g);
+ params.tipKey = key;
+ list.set(name, { param: params, colors: [], buffers: [] });
+ return;
+ }
if (params.type === "image") {
if (!params.image || !params.image.src) {
throw new Error(
@@ -138,15 +215,6 @@ export function add(name, params) {
);
}
T.add(params.image.src);
- params.tip = () => {
- Mask.image(
- T.tips.get(current.p.image.src),
- -current.p.weight / 2,
- -current.p.weight / 2,
- current.p.weight,
- current.p.weight,
- );
- };
list.set(name, { param: params, colors: [], buffers: [] });
return T.load(); // returns a Promise; only loads images not yet loaded
}
@@ -252,13 +320,6 @@ function invertTransform(transform) {
};
}
-function transformPoint(transform, x, y) {
- return {
- x: transform.a * x + transform.c * y + transform.tx,
- y: transform.b * x + transform.d * y + transform.ty,
- };
-}
-
function normalizeRegion(region) {
const [x1, y1, x2, y2] = region;
return {
@@ -269,60 +330,6 @@ function normalizeRegion(region) {
};
}
-function currentPointInUserSpace() {
- return transformPoint(
- _strokeTransform,
- _position.x - Cwidth / 2,
- _position.y - Cheight / 2,
- );
-}
-
-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,
@@ -361,8 +368,7 @@ const current = {};
* @param {number} x - Starting x-coordinate.
* @param {number} y - Starting y-coordinate.
* @param {number} length - Length of stroke.
- * @param {boolean} flow - Flag for vector-field following.
- * @param {Object|boolean} plot - Plot object or false.
+ * @param {Plot|false} [plot=false] - Plot object for path-following strokes.
*/
function initializeDrawingState(x, y, length, plot = false) {
snapshotMatrix();
@@ -419,13 +425,22 @@ function saveState() {
if (!param) return;
current.p = param;
- Mask = Mix.glMask;
-
// Set pressure values for the stroke
const { pressure } = param;
current.a = pressure.type !== "custom" ? rr(-1, 1) : 0;
current.b = pressure.type !== "custom" ? rr(1, 1.5) : 0;
- current.cp = pressure.type !== "custom" ? rr(3, 3.5) : rr(-0.2, 0.2);
+ if (pressure.type !== "custom") {
+ current.cp = rr(3, 3.5);
+ current.ct = 0;
+ current.cs = 1;
+ current.ck = 0;
+ } else {
+ const variation = pressure.variation ?? DEFAULT_CUSTOM_PRESSURE_VARIATION;
+ current.cp = rr(-variation.offset, variation.offset);
+ current.ct = rr(-variation.warp, variation.warp);
+ current.cs = rr(1 - variation.scale, 1 + variation.scale);
+ current.ck = rr(-variation.tilt, variation.tilt);
+ }
[current.min, current.max] = pressure.min_max;
current.noiseoffset = 0.03;
@@ -442,10 +457,38 @@ function saveState() {
const switchingToBrush = Mix.isBrush !== true;
Mix.isBrush = true;
if (switchingToBrush) Mix.justChanged = true;
- if (isInsideClippingArea()) Mix.blend(State.stroke.color);
+ Mix.blend(State.stroke.color);
// Set additional state values
current.alpha = calculateAlpha();
+
+ // Pre-compute clip-check coefficients so isInsideClippingArea() needs no
+ // temporary objects and only one matrix×vector multiply per step instead of two.
+ {
+ const cw2 = Cwidth / 2, ch2 = Cheight / 2;
+ const T = _strokeTransform;
+ if (State.stroke.clipWindow) {
+ const { inverse: I, bounds: B } = State.stroke.clipWindow;
+ // Compose (I ∘ T) and fold the -cw2/-ch2 position offset into the translation
+ const ca = I.a * T.a + I.c * T.b, cc = I.a * T.c + I.c * T.d;
+ const cb = I.b * T.a + I.d * T.b, cd = I.b * T.c + I.d * T.d;
+ current.clipA = ca; current.clipB = cb;
+ current.clipC = cc; current.clipD = cd;
+ current.clipTX = I.a * T.tx + I.c * T.ty + I.tx - ca * cw2 - cc * ch2;
+ current.clipTY = I.b * T.tx + I.d * T.ty + I.ty - cb * cw2 - cd * ch2;
+ current.clipMinX = B.minX; current.clipMaxX = B.maxX;
+ current.clipMinY = B.minY; current.clipMaxY = B.maxY;
+ } else {
+ const o = Cwidth * 0.05;
+ current.clipA = T.a; current.clipB = T.b;
+ current.clipC = T.c; current.clipD = T.d;
+ current.clipTX = T.tx - T.a * cw2 - T.c * ch2;
+ current.clipTY = T.ty - T.b * cw2 - T.d * ch2;
+ current.clipMinX = -cw2 - o; current.clipMaxX = cw2 + o;
+ current.clipMinY = -ch2 - o; current.clipMaxY = ch2 + o;
+ }
+ }
+
markerTip();
}
@@ -453,26 +496,27 @@ function saveState() {
* Restores drawing state after completing a stroke.
*/
function restoreState() {
- glDraw();
markerTip();
+ glDraw();
+ const type = current.p?.type;
+ if (type === "image") glDrawImages(T.tips.get(current.p.image.src), current.p.image.src);
+ else if (type === "custom") glDrawImages(T.tips.get(current.p.tipKey), current.p.tipKey);
}
/**
* Renders the brush tip based on current pressure and position.
- * @param {number} [customPressure=false] - Optional custom pressure.
*/
-function tip(customPressure = false) {
- if (!isInsideClippingArea()) return;
- let pressure = customPressure || calculatePressure();
-
- let lineNoise = map(
+function tip() {
+ const insideClip = isInsideClippingArea();
+ if (!insideClip) return;
+ const pressure = calculatePressure();
+ const lineNoise = map(
noise(current.seed + _position.plotted * 0.002, 0),
0,
1,
1 - current.noiseoffset,
1 + current.noiseoffset,
);
-
switch (current.p.type) {
case "spray":
drawSpray(pressure * lineNoise);
@@ -482,7 +526,7 @@ function tip(customPressure = false) {
break;
case "custom":
case "image":
- drawTip(pressure * lineNoise, current.alpha);
+ drawImageTip(pressure * lineNoise);
break;
default:
drawDefault(pressure * lineNoise);
@@ -505,9 +549,19 @@ function calculatePressure() {
* @returns {number} Simulated pressure value.
*/
function simPressure() {
- return current.p.pressure.type === "custom"
+ const value = current.p.pressure.type === "custom"
? map(
- current.p.pressure.curve(_position.plotted / _length) + current.cp,
+ current.p.pressure.curve(
+ Math.max(
+ 0,
+ Math.min(
+ 1,
+ 0.5 + ((_position.plotted / _length) - 0.5 + current.ct) * current.cs,
+ ),
+ ),
+ ) +
+ current.cp +
+ current.ck * ((_position.plotted / _length) - 0.5),
0,
1,
current.min,
@@ -515,6 +569,7 @@ function simPressure() {
true,
)
: gauss();
+ return value;
}
/**
@@ -559,33 +614,15 @@ function calculateAlpha() {
/**
* Checks if the current drawing position is within the clipping region.
+ * Uses coefficients pre-computed in saveState() — no object allocations,
+ * one fused matrix×vector multiply (both transforms composed at setup time).
* @returns {boolean} True if inside clipping area; false otherwise.
*/
function isInsideClippingArea() {
- const point = currentPointInUserSpace();
-
- if (State.stroke.clipWindow) {
- const local = transformPoint(
- State.stroke.clipWindow.inverse,
- point.x,
- point.y,
- );
- const { bounds } = State.stroke.clipWindow;
- return (
- local.x >= bounds.minX &&
- local.x <= bounds.maxX &&
- local.y >= bounds.minY &&
- local.y <= bounds.maxY
- );
- }
-
- let o = Cwidth * 0.05;
- return (
- point.x >= -Cwidth / 2 - o &&
- point.x <= Cwidth / 2 + o &&
- point.y >= -Cheight / 2 - o &&
- point.y <= Cheight / 2 + o
- );
+ const lx = current.clipA * _position.x + current.clipC * _position.y + current.clipTX;
+ if (lx < current.clipMinX || lx > current.clipMaxX) return false;
+ const ly = current.clipB * _position.x + current.clipD * _position.y + current.clipTY;
+ return ly >= current.clipMinY && ly <= current.clipMaxY;
}
/**
@@ -639,37 +676,28 @@ function drawMarker(pressure, vibrate = true, alpha = current.alpha) {
_position.x + rx,
_position.y + ry,
State.stroke.weight * current.p.weight * pressure,
- alpha,
+ alpha * Math.max(0.8, pressure) * rr(0.9,1.1),
);
}
/**
- * Draws a custom or image-based brush tip.
+ * Queues a stamp for instanced GL rendering.
+ * Handles both "image" and "custom" tip types.
* @param {number} pressure - Current pressure.
- * @param {number} alpha - Alpha (opacity) for drawing.
- * @param {boolean} [vibrate=true] - Whether to apply vibration.
+ * @param {number} alpha - Opacity [0..255].
*/
-function drawTip(pressure, alpha, vibrate = true) {
- Mix.glMask.isDrawn = true;
- Mask.push();
- Mask.noStroke();
- let color = State.stroke.color;
- color.setAlpha(alpha);
- Mask.fill(State.stroke.color);
- const vibration = vibrate ? State.stroke.weight * current.p.scatter : 0;
- 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);
- 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);
+function drawImageTip(pressure, alpha = current.alpha) {
+ const vibration = State.stroke.weight * current.p.scatter;
+ const rx = vibration * rr(-1, 1);
+ const ry = vibration * rr(-1, 1);
+ const size = current.p.weight * State.stroke.weight * pressure;
+ let angle = 0;
+ if (current.p.rotate === "random") {
+ angle = randInt(0, 360) * (Math.PI / 180);
+ } else if (current.p.rotate === "natural") {
+ angle = ((_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle()) * (Math.PI / 180);
}
+ stampImage(_position.x + rx, _position.y + ry, size, angle, alpha * Math.max(0.8, pressure) * rr(0.9,1.1));
}
/**
@@ -684,7 +712,8 @@ function drawDefault(pressure, wiggle = 1) {
current.p.scatter *
(current.p.sharpness +
((1 - current.p.sharpness) * rArray(gaussians)) / pressure);
- if (rr(0, current.p.grain * pressure) > 0.4) {
+ const passesGate = rr(0, current.p.grain * pressure) > 0.4;
+ if (passesGate) {
let dx, dy;
if (_plot) {
dx = 0.7 * vibration * rr(-1, 1);
@@ -695,54 +724,36 @@ function drawDefault(pressure, wiggle = 1) {
dx = perp * -current.sin + along * current.cos;
dy = perp * current.cos + along * current.sin;
}
+ const diameter =
+ pressure *
+ pressure *
+ current.p.weight *
+ rr(0.85, 1.15) *
+ State.stroke.weight;
+ const alpha = Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1);
circle(
_position.x + dx,
_position.y + dy,
- pressure *
- pressure *
- current.p.weight *
- rr(0.85, 1.15) *
- State.stroke.weight,
- Math.max(0.9, pressure) * current.alpha * rr(0.75, 1.1),
+ diameter,
+ alpha,
);
}
}
-/**
- * Adjusts the size and rotation of the brush tip before rendering.
- * @param {number} pressure - Pressure-based scaling factor.
- * @param {number} alpha - Opacity value.
- */
-function adjustSizeAndRotation(pressure, alpha) {
- Mask.scale(pressure);
- if (current.p.type === "image") {
- Mask.tint(255, 0, 0, alpha / 2);
- }
- let angle = 0;
- if (current.p.rotate === "random") angle = randInt(0, 360);
- else if (current.p.rotate === "natural") {
- angle =
- (_plot ? -_plot.angle(_position.plotted) : -_dir) + _position.angle();
- }
- Mask.rotate(angle);
- return angle;
-}
-
/**
* Draws the marker tip with a blend effect.
*/
function markerTip() {
if (isInsideClippingArea()) {
let pressure = calculatePressure();
- let alpha = calculateAlpha(pressure);
+ let alpha = current.alpha;
if (current.p.type === "marker") {
for (let s = 1; s < 10; s++) {
- drawMarker((pressure * s) / 10, false, alpha * 5);
+ drawMarker((pressure * s) / 10, true, alpha * 8);
}
- glDraw();
} else if (current.p.type === "custom" || current.p.type === "image") {
for (let s = 1; s < 5; s++) {
- drawTip((pressure * s) / 5, alpha, false);
+ drawImageTip((pressure * s) / 10, alpha * 2);
}
}
}
@@ -810,7 +821,7 @@ function plot(p, x, y, scale) {
/**
* Defines a set of standard brushes with specific characteristics. Each brush is defined
- * with properties such as weight, vibration, definition, quality, opacity, spacing, and
+ * with properties such as weight, scatter, sharpness, grain, opacity, spacing, and
* pressure sensitivity. Some brushes have additional properties like type, tip, and rotate.
*/
const _vals = [
@@ -952,7 +963,7 @@ const T = {
* @param {string} src - The source URL of the image.
*/
add(src) {
- this.tips.set(src, false);
+ if (!this.tips.has(src)) this.tips.set(src, false);
},
/**
@@ -983,7 +994,8 @@ const T = {
new Promise((resolve, reject) => {
const nativeImg = new window.Image();
nativeImg.onload = () => {
- const p5img = Renderer.createImage(
+ const factory = getBrushFactory();
+ const p5img = factory.createImage(
nativeImg.naturalWidth,
nativeImg.naturalHeight,
);
@@ -1001,15 +1013,3 @@ const T = {
);
},
};
-
-/**
- * Loads all registered image tips. Must be awaited before setup/draw.
- * @returns {Promise}
- *
- * @example
- * // In your sketch:
- * await brush.preload();
- */
-export async function preload() {
- await T.load();
-}
diff --git a/test/canvas_upload_benchmark.html b/test/canvas_upload_benchmark.html
new file mode 100644
index 0000000..718ccb8
--- /dev/null
+++ b/test/canvas_upload_benchmark.html
@@ -0,0 +1,414 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Canvas Upload Benchmark</title>
+ <style>
+ :root {
+ --bg: #f4efe6;
+ --panel: #fffaf1;
+ --ink: #1f2d3a;
+ --muted: #6a7684;
+ --line: #d8ccba;
+ --accent: #234e70;
+ }
+
+ * {
+ box-sizing: border-box;
+ }
+
+ body {
+ margin: 0;
+ min-height: 100vh;
+ background:
+ radial-gradient(circle at top left, rgba(35, 78, 112, 0.08), transparent 28%),
+ linear-gradient(180deg, #fbf8f1 0%, var(--bg) 100%);
+ color: var(--ink);
+ font-family: "Iowan Old Style", "Palatino Linotype", Palatino, serif;
+ }
+
+ main {
+ width: min(1080px, calc(100vw - 40px));
+ margin: 0 auto;
+ padding: 32px 0 48px;
+ }
+
+ h1 {
+ margin: 0 0 10px;
+ font-size: clamp(32px, 4vw, 52px);
+ line-height: 0.95;
+ letter-spacing: -0.04em;
+ }
+
+ p {
+ margin: 0;
+ color: var(--muted);
+ line-height: 1.55;
+ }
+
+ .panel {
+ margin-top: 24px;
+ border: 1px solid var(--line);
+ border-radius: 20px;
+ background: var(--panel);
+ padding: 20px;
+ box-shadow: 0 18px 40px rgba(41, 34, 24, 0.06);
+ }
+
+ .controls {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 12px;
+ align-items: end;
+ }
+
+ label {
+ display: grid;
+ gap: 6px;
+ color: var(--muted);
+ font-size: 14px;
+ }
+
+ input,
+ button {
+ font: inherit;
+ }
+
+ input {
+ width: 120px;
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ padding: 10px 12px;
+ background: white;
+ color: var(--ink);
+ }
+
+ button {
+ border: 0;
+ border-radius: 999px;
+ padding: 11px 18px;
+ background: var(--accent);
+ color: white;
+ cursor: pointer;
+ }
+
+ button:disabled {
+ opacity: 0.6;
+ cursor: wait;
+ }
+
+ .status {
+ margin-top: 14px;
+ min-height: 22px;
+ color: var(--accent);
+ font-size: 14px;
+ }
+
+ .results {
+ margin-top: 18px;
+ overflow-x: auto;
+ }
+
+ table {
+ width: 100%;
+ border-collapse: collapse;
+ font-family: Menlo, Monaco, "Courier New", monospace;
+ font-size: 13px;
+ }
+
+ th,
+ td {
+ padding: 10px 12px;
+ border-bottom: 1px solid var(--line);
+ text-align: left;
+ white-space: nowrap;
+ }
+
+ th {
+ color: var(--muted);
+ font-weight: 600;
+ }
+
+ .canvases {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
+ gap: 16px;
+ margin-top: 20px;
+ }
+
+ .canvas-card {
+ border: 1px solid var(--line);
+ border-radius: 16px;
+ padding: 12px;
+ background: rgba(255, 255, 255, 0.7);
+ }
+
+ .canvas-card h2 {
+ margin: 0 0 10px;
+ font-size: 15px;
+ color: var(--muted);
+ letter-spacing: 0.02em;
+ }
+
+ canvas {
+ width: 100%;
+ height: auto;
+ aspect-ratio: 1 / 1;
+ display: block;
+ border-radius: 12px;
+ background: #0f1720;
+ }
+ </style>
+ </head>
+ <body>
+ <main>
+ <h1>Canvas Upload Benchmark</h1>
+ <p>
+ Compares texture upload cost from a CPU-style 2D canvas versus a GPU-backed WEBGL canvas
+ in this browser. Results are also printed with <code>console.table()</code>.
+ </p>
+
+ <section class="panel">
+ <div class="controls">
+ <label>
+ Canvas size
+ <input id="size" type="number" min="64" step="64" value="1024" />
+ </label>
+ <label>
+ Iterations
+ <input id="iterations" type="number" min="10" step="10" value="120" />
+ </label>
+ <button id="run">Run benchmark</button>
+ </div>
+ <div class="status" id="status"></div>
+ <div class="results" id="results"></div>
+ </section>
+
+ <section class="canvases">
+ <article class="canvas-card">
+ <h2>2D source</h2>
+ <canvas id="source2d"></canvas>
+ </article>
+ <article class="canvas-card">
+ <h2>WEBGL source</h2>
+ <canvas id="sourcegl"></canvas>
+ </article>
+ <article class="canvas-card">
+ <h2>Destination uploader canvas</h2>
+ <canvas id="uploadgl"></canvas>
+ </article>
+ </section>
+ </main>
+
+ <script>
+ const sizeInput = document.getElementById("size");
+ const iterationsInput = document.getElementById("iterations");
+ const runButton = document.getElementById("run");
+ const statusEl = document.getElementById("status");
+ const resultsEl = document.getElementById("results");
+
+ const source2dCanvas = document.getElementById("source2d");
+ const sourceGlCanvas = document.getElementById("sourcegl");
+ const uploadCanvas = document.getElementById("uploadgl");
+
+ const ctx2d = source2dCanvas.getContext("2d", { alpha: true });
+ const srcGl =
+ sourceGlCanvas.getContext("webgl2", { antialias: false, alpha: true }) ||
+ sourceGlCanvas.getContext("webgl", { antialias: false, alpha: true });
+ const uploadGl =
+ uploadCanvas.getContext("webgl2", { antialias: false, alpha: true }) ||
+ uploadCanvas.getContext("webgl", { antialias: false, alpha: true });
+
+ if (!ctx2d || !srcGl || !uploadGl) {
+ statusEl.textContent = "This browser could not create the required canvas contexts.";
+ runButton.disabled = true;
+ }
+
+ function resizeCanvases(size) {
+ source2dCanvas.width = size;
+ source2dCanvas.height = size;
+ sourceGlCanvas.width = size;
+ sourceGlCanvas.height = size;
+ uploadCanvas.width = size;
+ uploadCanvas.height = size;
+ if (srcGl) srcGl.viewport(0, 0, size, size);
+ if (uploadGl) uploadGl.viewport(0, 0, size, size);
+ }
+
+ function draw2dFrame(iteration, size) {
+ const t = iteration * 0.07;
+ ctx2d.clearRect(0, 0, size, size);
+
+ const gradient = ctx2d.createLinearGradient(0, 0, size, size);
+ gradient.addColorStop(0, `hsl(${(iteration * 9) % 360} 70% 60%)`);
+ gradient.addColorStop(1, `hsl(${(iteration * 9 + 120) % 360} 55% 40%)`);
+ ctx2d.fillStyle = gradient;
+ ctx2d.fillRect(0, 0, size, size);
+
+ ctx2d.globalCompositeOperation = "destination-out";
+ ctx2d.beginPath();
+ ctx2d.arc(
+ size * (0.5 + Math.cos(t) * 0.18),
+ size * (0.5 + Math.sin(t * 1.7) * 0.2),
+ size * 0.18,
+ 0,
+ Math.PI * 2,
+ );
+ ctx2d.fill();
+
+ ctx2d.globalCompositeOperation = "source-over";
+ ctx2d.fillStyle = "rgba(255,255,255,0.82)";
+ ctx2d.font = `${Math.max(24, Math.round(size * 0.09))}px Georgia`;
+ ctx2d.fillText(`2D ${iteration}`, size * 0.08, size * 0.18);
+
+ for (let i = 0; i < 10; i += 1) {
+ const x = ((i * 0.13 + t * 0.11) % 1) * size;
+ const y = ((i * 0.19 + t * 0.07) % 1) * size;
+ ctx2d.fillStyle = `hsla(${(iteration * 11 + i * 27) % 360} 80% 52% / 0.65)`;
+ ctx2d.fillRect(x, y, size * 0.16, size * 0.03);
+ }
+ }
+
+ function drawWebglFrame(iteration, size) {
+ const gl = srcGl;
+ const t = iteration * 0.05;
+
+ gl.disable(gl.SCISSOR_TEST);
+ gl.clearColor(
+ 0.25 + 0.25 * Math.sin(t),
+ 0.2 + 0.2 * Math.sin(t * 1.3 + 1.0),
+ 0.28 + 0.24 * Math.cos(t * 0.9),
+ 1,
+ );
+ gl.clear(gl.COLOR_BUFFER_BIT);
+
+ gl.enable(gl.SCISSOR_TEST);
+ for (let i = 0; i < 8; i += 1) {
+ const x = Math.floor((((i * 0.17) + t * 0.09) % 1) * size);
+ const y = Math.floor((((i * 0.21) + t * 0.13) % 1) * size);
+ const w = Math.max(1, Math.floor(size * (0.08 + ((i % 3) * 0.03))));
+ const h = Math.max(1, Math.floor(size * (0.06 + ((i % 4) * 0.02))));
+ gl.scissor(x, y, w, h);
+ gl.clearColor(
+ 0.5 + 0.5 * Math.sin(t + i),
+ 0.5 + 0.5 * Math.cos(t * 1.4 + i * 0.3),
+ 0.5 + 0.5 * Math.sin(t * 1.8 + i * 0.7),
+ 0.85,
+ );
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ }
+ gl.disable(gl.SCISSOR_TEST);
+ gl.flush();
+ }
+
+ function makeTexture(gl, size) {
+ const texture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ size,
+ size,
+ 0,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ null,
+ );
+ return texture;
+ }
+
+ function measureUpload(label, sourceCanvas, prepareFrame, size, iterations) {
+ const gl = uploadGl;
+ const texture = makeTexture(gl, size);
+ let total = 0;
+ let min = Number.POSITIVE_INFINITY;
+ let max = 0;
+
+ for (let i = 0; i < 6; i += 1) {
+ prepareFrame(i, size);
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, sourceCanvas);
+ }
+ gl.finish();
+
+ for (let i = 0; i < iterations; i += 1) {
+ prepareFrame(i + 10, size);
+ const start = performance.now();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, sourceCanvas);
+ gl.finish();
+ const elapsed = performance.now() - start;
+ total += elapsed;
+ if (elapsed < min) min = elapsed;
+ if (elapsed > max) max = elapsed;
+ }
+
+ gl.deleteTexture(texture);
+
+ return {
+ source: label,
+ total_ms: total.toFixed(2),
+ avg_ms: (total / iterations).toFixed(4),
+ min_ms: min.toFixed(4),
+ max_ms: max.toFixed(4),
+ iterations,
+ };
+ }
+
+ function renderResults(rows) {
+ const html = [
+ "<table>",
+ "<thead><tr><th>source</th><th>total_ms</th><th>avg_ms</th><th>min_ms</th><th>max_ms</th><th>iterations</th></tr></thead>",
+ "<tbody>",
+ ...rows.map(
+ (row) =>
+ `<tr><td>${row.source}</td><td>${row.total_ms}</td><td>${row.avg_ms}</td><td>${row.min_ms}</td><td>${row.max_ms}</td><td>${row.iterations}</td></tr>`,
+ ),
+ "</tbody></table>",
+ ].join("");
+ resultsEl.innerHTML = html;
+ }
+
+ async function runBenchmark() {
+ const size = Math.max(64, Number(sizeInput.value) || 1024);
+ const iterations = Math.max(10, Number(iterationsInput.value) || 120);
+
+ resizeCanvases(size);
+ runButton.disabled = true;
+ statusEl.textContent = "Running benchmark...";
+ resultsEl.innerHTML = "";
+
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+
+ const rows = [
+ measureUpload("2d canvas", source2dCanvas, draw2dFrame, size, iterations),
+ measureUpload("webgl canvas", sourceGlCanvas, drawWebglFrame, size, iterations),
+ ];
+
+ rows.sort((a, b) => Number(a.avg_ms) - Number(b.avg_ms));
+ renderResults(rows);
+ console.log("[canvas upload benchmark]", { size, iterations });
+ console.table(rows);
+
+ const ratio =
+ Number(rows[1].avg_ms) > 0
+ ? (Number(rows[1].avg_ms) / Number(rows[0].avg_ms)).toFixed(2)
+ : "n/a";
+ statusEl.textContent =
+ `${rows[0].source} is faster in this run. Ratio: ${ratio}x against ${rows[1].source}.`;
+ runButton.disabled = false;
+ }
+
+ runButton.addEventListener("click", runBenchmark);
+ resizeCanvases(Number(sizeInput.value) || 1024);
+ draw2dFrame(0, Number(sizeInput.value) || 1024);
+ drawWebglFrame(0, Number(sizeInput.value) || 1024);
+ </script>
+ </body>
+</html>
diff --git a/test/hatch_test.html b/test/hatch_test.html
new file mode 100644
index 0000000..69bdea2
--- /dev/null
+++ b/test/hatch_test.html
@@ -0,0 +1,33 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <title>p5.brush Hatch Test</title>
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>
+ <script src="../dist/p5.brush.js"></script>
+ <style>
+ * { box-sizing: border-box; }
+ body {
+ margin: 0;
+ background: #111;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ }
+ .nav {
+ width: 100%;
+ padding: 12px 18px;
+ font: 12px/1.2 Menlo, Monaco, "Courier New", monospace;
+ background: rgba(12, 12, 12, 0.92);
+ border-bottom: 1px solid rgba(255, 255, 255, 0.08);
+ }
+ .nav a { color: #f0dca8; text-decoration: none; }
+ .nav a:hover { text-decoration: underline; }
+ canvas { display: block; }
+ </style>
+ </head>
+ <body>
+ <div class="nav"><a href="./index.html">All tests</a></div>
+ <script src="./hatch_test.js"></script>
+ </body>
+</html>
diff --git a/test/hatch_test.js b/test/hatch_test.js
new file mode 100644
index 0000000..1b3be9a
--- /dev/null
+++ b/test/hatch_test.js
@@ -0,0 +1,351 @@
+// ============================================================
+// p5.brush Hatch Test
+//
+// Exercises the hatch module: angle sweep, spacing, rand,
+// gradient, continuous, cross-hatching, brush types, polygon
+// shapes, large polygons, and combined options.
+//
+// Run: open test/hatch_test.html
+// ============================================================
+
+const CANVAS_W = 1360;
+const CANVAS_H = 1800;
+const MARGIN = 36;
+const LABEL_W = 170;
+const PANEL_GAP = 14;
+const ROW_H = 160;
+
+const INK = "#183a59";
+const FRAME = "#cdbfae";
+const PANEL_BG = "#fcf7ef";
+
+const palette = ["#002185", "#c0392b", "#27ae60", "#8e44ad", "#e67e22", "#16a085", "#d35400"];
+function col(i) { return palette[i % palette.length]; }
+
+let currentY = MARGIN;
+let labelBuf;
+
+// ---- Layout helpers (matches angle_mode_test pattern) ----
+
+function section(title, note) {
+ labelBuf.noStroke();
+ labelBuf.fill(29);
+ labelBuf.textStyle(BOLD);
+ labelBuf.textSize(13);
+ labelBuf.text(title, MARGIN, currentY + 14);
+ if (note) {
+ labelBuf.fill(92);
+ labelBuf.textStyle(NORMAL);
+ labelBuf.textSize(10);
+ labelBuf.text(note, MARGIN, currentY + 30);
+ }
+ push();
+ stroke(215, 205, 191);
+ strokeWeight(1);
+ line(MARGIN, currentY + 40, CANVAS_W - MARGIN, currentY + 40);
+ pop();
+ currentY += 58;
+}
+
+function drawRow(label, panels) {
+ const available = CANVAS_W - 2 * MARGIN - LABEL_W;
+ const panelW = (available - PANEL_GAP * (panels.length - 1)) / panels.length;
+
+ // Row label
+ labelBuf.noStroke();
+ labelBuf.fill(251, 247, 239, 240);
+ labelBuf.rect(MARGIN - 2, currentY + 6, LABEL_W - 10, ROW_H - 18, 10);
+ labelBuf.fill(46);
+ labelBuf.textStyle(BOLD);
+ labelBuf.textSize(11);
+ labelBuf.text(label, MARGIN, currentY + 20, LABEL_W - 18, ROW_H - 30);
+
+ panels.forEach((panel, index) => {
+ const x = MARGIN + LABEL_W + index * (panelW + PANEL_GAP);
+ const y = currentY;
+
+ // Panel frame
+ push();
+ fill(PANEL_BG);
+ stroke(FRAME);
+ strokeWeight(1);
+ rect(x, y, panelW, ROW_H - 8, 14);
+ pop();
+
+ // Panel title
+ labelBuf.noStroke();
+ labelBuf.fill(255, 255, 255, 220);
+ labelBuf.rect(x + 8, y + 8, panelW - 16, 18, 9);
+ labelBuf.fill(74);
+ labelBuf.textStyle(NORMAL);
+ labelBuf.textSize(9);
+ labelBuf.text(panel.title, x + 14, y + 21);
+
+ panel.render(x + 10, y + 32, panelW - 20, ROW_H - 48);
+ });
+
+ currentY += ROW_H;
+}
+
+// ---- Hatch-in-panel helper ----
+
+function hatchInPanel(x, y, w, h, polyFn, hatchSetup, brushName, brushColor) {
+ const poly = polyFn(x, y, w, h);
+ brush.noField();
+ brush.noStroke();
+ brush.noFill();
+ hatchSetup();
+ brush.hatchStyle(brushName || "HB", brushColor || INK, 1);
+ brush.clip([x, y, x + w, y + h]);
+ poly.hatch();
+ brush.noClip();
+ brush.noHatch();
+}
+
+// ---- Polygon factories (take panel-local x, y, w, h) ----
+
+function makeRect(x, y, w, h) {
+ return new brush.Polygon([
+ [x, y], [x + w, y], [x + w, y + h], [x, y + h],
+ ]);
+}
+
+function makeTriangle(x, y, w, h) {
+ return new brush.Polygon([
+ [x + w / 2, y], [x + w, y + h], [x, y + h],
+ ]);
+}
+
+function makeDiamond(x, y, w, h) {
+ return new brush.Polygon([
+ [x + w / 2, y], [x + w, y + h / 2], [x + w / 2, y + h], [x, y + h / 2],
+ ]);
+}
+
+function makeIrregular(x, y, w, h) {
+ return new brush.Polygon([
+ [x + w * 0.1, y + h * 0.2],
+ [x + w * 0.4, y],
+ [x + w * 0.8, y + h * 0.1],
+ [x + w, y + h * 0.5],
+ [x + w * 0.7, y + h],
+ [x + w * 0.3, y + h * 0.9],
+ [x, y + h * 0.6],
+ ]);
+}
+
+function makeStar(x, y, w, h) {
+ const cx = x + w / 2, cy = y + h / 2;
+ const outerR = Math.min(w, h) * 0.48;
+ const innerR = outerR * 0.4;
+ const verts = [];
+ for (let i = 0; i < 10; i++) {
+ const angle = (i * Math.PI) / 5 - Math.PI / 2;
+ const r = i % 2 === 0 ? outerR : innerR;
+ verts.push([cx + Math.cos(angle) * r, cy + Math.sin(angle) * r]);
+ }
+ return new brush.Polygon(verts);
+}
+
+function makeCircleApprox(x, y, w, h, n) {
+ const cx = x + w / 2, cy = y + h / 2;
+ const rx = w * 0.45, ry = h * 0.45;
+ const verts = [];
+ for (let i = 0; i < n; i++) {
+ const a = (i / n) * Math.PI * 2;
+ verts.push([cx + Math.cos(a) * rx, cy + Math.sin(a) * ry]);
+ }
+ return new brush.Polygon(verts);
+}
+
+// ============================================================
+// Main sketch
+// ============================================================
+
+function setup() {
+ randomSeed(42);
+ noiseSeed(42);
+ createCanvas(CANVAS_W, CANVAS_H, WEBGL);
+ brush.load();
+ brush.scaleBrushes(2.4);
+ angleMode(DEGREES);
+ noLoop();
+
+ labelBuf = createGraphics(CANVAS_W, CANVAS_H);
+ labelBuf.pixelDensity(1);
+ labelBuf.textFont("monospace");
+}
+
+function draw() {
+ background("#f4ede0");
+ translate(-width / 2, -height / 2);
+
+ // ================================================================
+ // 1 — Angle sweep
+ // ================================================================
+ section("ANGLE SWEEP", "Same rectangle, angle from 0 to 170 degrees");
+
+ const angles = [0, 30, 45, 60, 90, 135, 170];
+ drawRow("angle variations", angles.map((a, i) => ({
+ title: a + "°",
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect,
+ () => brush.hatch(6, a), "HB", col(i)),
+ })));
+
+ // ================================================================
+ // 2 — Spacing
+ // ================================================================
+ section("SPACING", "Same angle (45°), varying dist");
+
+ const spacings = [3, 6, 10, 18, 30];
+ drawRow("dist variations", spacings.map((d, i) => ({
+ title: "dist=" + d,
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect,
+ () => brush.hatch(d, 45), "HB", col(i)),
+ })));
+
+ // ================================================================
+ // 3 — Rand option
+ // ================================================================
+ section("RAND OPTION", "Increasing randomness displaces line endpoints");
+
+ const rands = [0, 0.3, 0.6, 1.0, 1.5];
+ drawRow("rand values", rands.map((r, i) => ({
+ title: "rand=" + r,
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect,
+ () => brush.hatch(7, 45, { rand: r }), "HB", col(i)),
+ })));
+
+ // ================================================================
+ // 4 — Gradient option
+ // ================================================================
+ section("GRADIENT OPTION", "Line spacing grows multiplicatively per line");
+
+ const grads = [0, 0.3, 0.6, 0.8, 1.0];
+ drawRow("gradient values", grads.map((g, i) => ({
+ title: "grad=" + g,
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect,
+ () => brush.hatch(5, 30, { gradient: g }), "HB", col(i)),
+ })));
+
+ // ================================================================
+ // 5 — Continuous
+ // ================================================================
+ section("CONTINUOUS OPTION", "Connected lines vs independent segments");
+
+ drawRow("continuous", [
+ {
+ title: "continuous: false",
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect,
+ () => brush.hatch(12, 45, { continuous: false }), "HB", col(0)),
+ },
+ {
+ title: "continuous: true",
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect,
+ () => brush.hatch(12, 45, { continuous: true }), "HB", col(1)),
+ },
+ ]);
+
+ // ================================================================
+ // 6 — Polygon shapes
+ // ================================================================
+ section("POLYGON SHAPES", "Same hatch (45°, dist=6) on different shapes");
+
+ const shapeFns = [
+ { title: "Rectangle", fn: makeRect },
+ { title: "Triangle", fn: makeTriangle },
+ { title: "Diamond", fn: makeDiamond },
+ { title: "Irregular", fn: makeIrregular },
+ { title: "Star", fn: makeStar },
+ ];
+ drawRow("shape variety", shapeFns.map((s, i) => ({
+ title: s.title,
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, s.fn,
+ () => brush.hatch(6, 45), "HB", col(i)),
+ })));
+
+ // ================================================================
+ // 7 — Cross-hatching
+ // ================================================================
+ section("CROSS-HATCHING", "Two hatch passes at different angles");
+
+ const crossPairs = [
+ { a1: 45, a2: -45, label: "45 / -45" },
+ { a1: 0, a2: 90, label: "0 / 90" },
+ { a1: 30, a2: 120, label: "30 / 120" },
+ ];
+ drawRow("cross-hatch", crossPairs.map((cp, i) => ({
+ title: cp.label,
+ render: (x, y, w, h) => {
+ const poly = makeRect(x, y, w, h);
+ brush.noField(); brush.noStroke(); brush.noFill();
+
+ brush.hatch(8, cp.a1);
+ brush.hatchStyle("HB", col(i * 2), 1);
+ brush.clip([x, y, x + w, y + h]);
+ poly.hatch();
+ brush.noClip(); brush.noHatch();
+
+ brush.hatch(8, cp.a2);
+ brush.hatchStyle("HB", col(i * 2 + 1), 1);
+ brush.clip([x, y, x + w, y + h]);
+ poly.hatch();
+ brush.noClip(); brush.noHatch();
+ },
+ })));
+
+ // ================================================================
+ // 8 — Large polygon (many vertices)
+ // ================================================================
+ section("LARGE POLYGON", "64-vertex circle approximation with fine spacing");
+
+ drawRow("64-vert circle", [
+ {
+ title: "dist=4, angle=30",
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h,
+ (x, y, w, h) => makeCircleApprox(x, y, w, h, 64),
+ () => brush.hatch(4, 30), "HB", col(0)),
+ },
+ {
+ title: "dist=4, angle=75",
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h,
+ (x, y, w, h) => makeCircleApprox(x, y, w, h, 64),
+ () => brush.hatch(4, 75), "HB", col(3)),
+ },
+ {
+ title: "dist=3, angle=45, rand=0.3",
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h,
+ (x, y, w, h) => makeCircleApprox(x, y, w, h, 64),
+ () => brush.hatch(3, 45, { rand: 0.3 }), "HB", col(5)),
+ },
+ ]);
+
+ // ================================================================
+ // 9 — Combined options
+ // ================================================================
+ section("COMBINED OPTIONS", "Mixing rand, gradient, and continuous");
+
+ drawRow("combos", [
+ {
+ title: "rand + gradient",
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect,
+ () => brush.hatch(6, 45, { rand: 0.4, gradient: 0.5 }), "HB", col(0)),
+ },
+ {
+ title: "rand + continuous",
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect,
+ () => brush.hatch(8, 45, { rand: 0.3, continuous: true }), "HB", col(1)),
+ },
+ {
+ title: "all three",
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect,
+ () => brush.hatch(6, 45, { rand: 0.3, gradient: 0.3, continuous: true }), "HB", col(2)),
+ },
+ ]);
+
+ // ================================================================
+ // Composite labels on top
+ // ================================================================
+ image(labelBuf, 0, 0);
+ console.log("Hatch test complete");
+}
diff --git a/test/index.html b/test/index.html
index 0928c4d..29cf28a 100644
--- a/test/index.html
+++ b/test/index.html
@@ -231,18 +231,26 @@
<span class="path">test/pushpop_test.html</span>
</a>
+ <a class="card" href="./hatch_test.html">
+ <span class="tag warn">New</span>
+ <h3>Hatch Test</h3>
+ <p>Exercises hatch angles, spacing, rand/continuous/gradient options, cross-hatching, brush types, shapes, and multi-polygon arrays.</p>
+ <span class="path">test/hatch_test.html</span>
+ </a>
+
<a class="card" href="./field_explorer.html">
<span class="tag">Browser</span>
<h3>Flow Field Explorer</h3>
<p>Interactive field inspector for comparing built-in fields with adjustable density and line length.</p>
<span class="path">test/field_explorer.html</span>
</a>
+
</div>
</section>
<section class="band">
<h2>Automated Tests</h2>
- <p>The browser pages above are visual checks. The file below contains the scripted regression suite.</p>
+ <p>The browser pages above are visual checks. These files contain the scripted regression suites.</p>
<div class="grid">
<a class="card" href="./unit.test.js">
<span class="tag alt">Automated</span>
@@ -250,6 +258,13 @@
<p>Utility, angle conversion, hatch capture, Position movement, and custom field angle-mode regression tests.</p>
<span class="path">test/unit.test.js</span>
</a>
+
+ <a class="card" href="./stroke_pressure.test.js">
+ <span class="tag alt">Automated</span>
+ <h3>Stroke Pressure Tests</h3>
+ <p>Covers `brush.add()` pressure normalization, including the simple custom forms and the explicit Gaussian power-user mode.</p>
+ <span class="path">test/stroke_pressure.test.js</span>
+ </a>
</div>
</section>
</div>
diff --git a/test/sketch.js b/test/sketch.js
index 8021ac3..ee59813 100644
--- a/test/sketch.js
+++ b/test/sketch.js
@@ -20,6 +20,9 @@ let currentY = MARGIN;
let labelBuf; // P2D overlay for labels (composited at the end)
const palette = ["#002185", "#c0392b", "#27ae60", "#8e44ad", "#e67e22"];
+const query = new URLSearchParams(window.location.search);
+const nativeDebugStage = query.get("nativeDebug");
+
function col(i) {
return palette[i % palette.length];
}
@@ -573,6 +576,6 @@ async function setup() {
function draw() {
// WEBGL resets transforms each frame; re-translate to top-left
translate(-width / 2, -height / 2);
- image(labelBuf, 0, 0, width, height);
+ if (!nativeDebugStage) image(labelBuf, 0, 0, width, height);
noLoop(); // static sketch — draw only once
}
diff --git a/test/stroke_pressure.test.js b/test/stroke_pressure.test.js
new file mode 100644
index 0000000..36c8ecc
--- /dev/null
+++ b/test/stroke_pressure.test.js
@@ -0,0 +1,135 @@
+import { describe, it, expect, vi } from "vitest";
+
+vi.mock("../src/core/color.js", () => ({
+ Mix: {},
+ Cwidth: 800,
+ Cheight: 600,
+ State: {},
+ Renderer: {},
+ isCanvasReady: () => {},
+}));
+
+vi.mock("../src/core/utils.js", () => ({
+ rr: () => 0,
+ map: (value, start1, stop1, start2, stop2) =>
+ start2 + ((value - start1) / (stop1 - start1 || 1)) * (stop2 - start2),
+ dist: () => 0,
+ randInt: () => 0,
+ calcAngle: () => 0,
+ toDegrees: (v) => v,
+ gaussian: () => 0,
+ rArray: () => 0,
+ noise: () => 0,
+ _onSeed: () => {},
+}));
+
+vi.mock("../src/core/flowfield.js", () => ({
+ Position: class Position {},
+ Matrix: {
+ a: () => 1,
+ b: () => 0,
+ c: () => 0,
+ d: () => 1,
+ x: () => 0,
+ y: () => 0,
+ },
+ isFieldReady: () => {},
+}));
+
+vi.mock("../src/core/polygon.js", () => ({
+ Polygon: class Polygon {},
+}));
+
+vi.mock("../src/core/plot.js", () => ({
+ Plot: class Plot {},
+}));
+
+vi.mock("../src/stroke/gl_draw.js", () => ({
+ isReady: () => {},
+ glDraw: () => {},
+ glDrawImages: () => {},
+ circle: () => {},
+ stampImage: () => {},
+ invalidateTexEntry: () => {},
+ snapshotMatrix: () => {},
+}));
+
+import { add, box, normalizePressure } from "../src/stroke/stroke.js";
+
+describe("normalizePressure()", () => {
+ it("keeps function pressure in explicit custom mode", () => {
+ const curve = (t) => t;
+ expect(normalizePressure(curve)).toEqual({
+ type: "custom",
+ min_max: [0, 1],
+ curve,
+ variation: {
+ offset: 0.08,
+ scale: 0.08,
+ warp: 0.06,
+ tilt: 0.06,
+ },
+ });
+ });
+
+ it("normalizes explicit gaussian mode objects", () => {
+ expect(
+ normalizePressure({
+ mode: "gaussian",
+ curve: [0.15, 0.2],
+ min_max: [1.1, 0.9],
+ }),
+ ).toEqual({
+ mode: "gaussian",
+ type: "gaussian",
+ curve: [0.15, 0.2],
+ min_max: [1.1, 0.9],
+ });
+ });
+
+ it("preserves legacy gaussian objects while making the mode explicit", () => {
+ expect(
+ normalizePressure({
+ curve: [0.35, 0.25],
+ min_max: [1.2, 0.85],
+ }),
+ ).toEqual({
+ type: "gaussian",
+ curve: [0.35, 0.25],
+ min_max: [1.2, 0.85],
+ });
+ });
+
+ it("adds subtle default variation to simplified array pressure", () => {
+ expect(normalizePressure([0.5, 1.5, 0.5])).toMatchObject({
+ type: "custom",
+ min_max: [0.5, 1.5],
+ variation: {
+ offset: 0.08,
+ scale: 0.08,
+ warp: 0.06,
+ tilt: 0.06,
+ },
+ });
+ });
+});
+
+describe("brush.add()", () => {
+ it("accepts gaussian pressure objects for custom brushes", () => {
+ add("gaussian-test-brush", {
+ weight: 0.3,
+ scatter: 0.6,
+ sharpness: 0.3,
+ grain: 10,
+ opacity: 170,
+ spacing: 0.1,
+ pressure: {
+ mode: "gaussian",
+ curve: [0.15, 0.2],
+ min_max: [1.1, 0.9],
+ },
+ });
+
+ expect(box()).toContain("gaussian-test-brush");
+ });
+});
diff --git a/tools/brush-maker.html b/tools/brush-maker.html
index 9853e70..c43fbcf 100644
--- a/tools/brush-maker.html
+++ b/tools/brush-maker.html
@@ -202,19 +202,24 @@
margin: 14px 0;
}
- /* ── Code output ─────────────────────────────────────────── */
+ /* ── Code output (right column) ───────────────────────────── */
#code-panel {
+ width: 260px;
flex-shrink: 0;
- border-top: 1px solid var(--border);
+ display: flex;
+ flex-direction: column;
+ border-left: 1px solid var(--border);
background: var(--panel);
+ overflow: hidden;
}
#code-header {
display: flex;
align-items: center;
justify-content: space-between;
- padding: 8px 16px;
+ padding: 10px 16px;
border-bottom: 1px solid var(--border);
+ flex-shrink: 0;
}
#code-header span {
@@ -242,6 +247,7 @@
#copy-btn.copied { background: #5cb85c; color: white; }
#code-output {
+ flex: 1;
margin: 0;
padding: 12px 16px;
font-family: var(--font);
@@ -250,8 +256,7 @@
color: #9cdcfe;
background: transparent;
white-space: pre;
- overflow-x: auto;
- max-height: 170px;
+ overflow: auto;
}
/* ── Right: viewport ─────────────────────────────────────── */
@@ -470,6 +475,15 @@
<!-- Pressure -->
<div class="section-label">Pressure</div>
<div class="pressure-group">
+ <div class="control-row">
+ <label>mode</label>
+ <select id="pressure-mode">
+ <option value="simple">simple</option>
+ <option value="gaussian">gaussian</option>
+ </select>
+ </div>
+
+ <div id="pressure-simple">
<div class="control-row">
<label>start</label>
<input type="range" id="press-start" min="0.1" max="3" step="0.02" value="1.1" />
@@ -492,15 +506,49 @@
<span class="slider-track"></span>
</label>
</div>
+ </div>
+
+ <div id="pressure-gaussian" style="display:none">
+ <div class="control-row">
+ <label>curve a</label>
+ <input type="range" id="gauss-curve-a" min="0" max="0.6" step="0.01" value="0.15" />
+ <span class="val" id="gauss-curve-a-val">0.15</span>
+ </div>
+ <div class="control-row">
+ <label>curve b</label>
+ <input type="range" id="gauss-curve-b" min="0" max="0.6" step="0.01" value="0.2" />
+ <span class="val" id="gauss-curve-b-val">0.2</span>
+ </div>
+ <div class="control-row">
+ <label>min</label>
+ <input type="range" id="gauss-min" min="0.1" max="2" step="0.01" value="1.1" />
+ <span class="val" id="gauss-min-val">1.1</span>
+ </div>
+ <div class="control-row">
+ <label>max</label>
+ <input type="range" id="gauss-max" min="0.1" max="2" step="0.01" value="0.9" />
+ <span class="val" id="gauss-max-val">0.9</span>
+ </div>
+ </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);
+ <p style="font-size:9px;color:var(--text-dim);margin-bottom:6px;line-height:1.6">
+ Draw in a <span style="color:var(--accent)">100×100</span> coord space, origin at centre.<br>
+ Write plain p5 commands — <span style="color:#9cdcfe">fill()</span>, <span style="color:#9cdcfe">rect()</span>, etc.<br>
+ <span style="color:#666">Dark = opaque ink · Light/white = transparent</span>
+ </p>
+ <textarea id="tip-body" spellcheck="false">fill(0);
+rotate(45);
rect(-4, -4, 8, 8);
rect(2, 2, 2, 2);</textarea>
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-top:8px;margin-bottom:4px">
+ <span style="font-size:9px;color:var(--text-dim);letter-spacing:0.08em;text-transform:uppercase;font-weight:700">Preview</span>
+ <span id="tip-preview-error" style="font-size:9px;color:#f66;display:none">syntax error</span>
+ </div>
+ <div id="tip-preview-wrap" style="width:100px;height:100px;border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;"></div>
</div>
<!-- Image upload (image type only) -->
@@ -515,17 +563,9 @@ rect(2, 2, 2, 2);</textarea>
</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 ────────────────────────────────────────── -->
+<!-- ── Centre viewport ───────────────────────────────────────── -->
<div id="viewport">
<div id="viewport-header">
<span>Preview</span>
@@ -542,6 +582,15 @@ rect(2, 2, 2, 2);</textarea>
</div>
</div>
+<!-- ── Right code panel ──────────────────────────────────────── -->
+<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>
+
<script>
// ─────────────────────────────────────────────
// State
@@ -556,13 +605,18 @@ const params = {
opacity: 170,
spacing: 0.3,
rotate: 'natural',
+ pressureMode: 'simple',
pressStart: 1.1,
pressMid: 1.5,
pressEnd: 0.9,
pressure3pt: false,
+ gaussCurveA: 0.15,
+ gaussCurveB: 0.2,
+ gaussMin: 1.1,
+ gaussMax: 0.9,
multicolor: false,
referenceBrush: 'HB',
- tipBody: 'rotate(45);\nrect(-4, -4, 8, 8);\nrect(2, 2, 2, 2);',
+ tipBody: 'fill(0);\nrotate(45);\nrect(-4, -4, 8, 8);\nrect(2, 2, 2, 2);',
imageDataUrl: null,
imageSrc: './your-image.jpg',
bgColor: '#fffceb',
@@ -571,15 +625,19 @@ const params = {
let needsRebuild = true;
let brushReady = true;
+let loadedImageSrc = null; // tracks which src is already uploaded to the GPU
+let previewTipFn = (_m) => {};
// ─────────────────────────────────────────────
// Code generator
// ─────────────────────────────────────────────
function generateCode() {
const p = params;
- const pressure = p.pressure3pt
- ? `[${p.pressStart}, ${p.pressMid}, ${p.pressEnd}]`
- : `[${p.pressStart}, ${p.pressEnd}]`;
+ const pressure = p.pressureMode === 'gaussian'
+ ? `{\n mode: "gaussian",\n curve: [${p.gaussCurveA}, ${p.gaussCurveB}],\n min_max: [${p.gaussMin}, ${p.gaussMax}],\n }`
+ : (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`
@@ -640,6 +698,10 @@ wire('spacing', 'spacing', v => Math.max(0.001, Math.round(parseFloat(v) * 1
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);
+wire('gauss-curve-a', 'gaussCurveA', v => Math.round(parseFloat(v) * 100) / 100);
+wire('gauss-curve-b', 'gaussCurveB', v => Math.round(parseFloat(v) * 100) / 100);
+wire('gauss-min', 'gaussMin', v => Math.round(parseFloat(v) * 100) / 100);
+wire('gauss-max', 'gaussMax', v => Math.round(parseFloat(v) * 100) / 100);
// Grain uses custom mapping
(function() {
@@ -675,16 +737,16 @@ const SLIDER_RANGES = {
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 },
+ weight: { min: 1, max: 60, step: 1 },
+ scatter: { min: 0, max: 10, step: 0.05 },
+ opacity: { min: 1, max: 50, step: 1 },
+ spacing: { min: 0.1, max: 15, step: 0.1 },
},
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 },
+ spacing: { min: 0.1, max: 15, step: 0.1 },
},
};
@@ -693,30 +755,42 @@ 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,
+ gaussCurveA: 0.15, gaussCurveB: 0.2, gaussMin: 1.1, gaussMax: 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,
+ gaussCurveA: 0.2, gaussCurveB: 0.35, gaussMin: 0.7, gaussMax: 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,
+ gaussCurveA: 0.35, gaussCurveB: 0.25, gaussMin: 1.2, gaussMax: 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,
+ weight: 40, scatter: 0.15, sharpness: null, grain: null,
+ opacity: 10, spacing: 2.5, pressStart: 0.8, pressEnd: 1.2,
+ gaussCurveA: 0.15, gaussCurveB: 0.2, gaussMin: 1.1, gaussMax: 0.9,
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,
+ gaussCurveA: 0.15, gaussCurveB: 0.2, gaussMin: 1.1, gaussMax: 0.9,
rotate: 'random', referenceBrush: 'HB',
},
};
+function updatePressureModeUI() {
+ const isGaussian = params.pressureMode === 'gaussian';
+ document.getElementById('pressure-mode').value = params.pressureMode;
+ document.getElementById('pressure-simple').style.display = isGaussian ? 'none' : '';
+ document.getElementById('pressure-gaussian').style.display = isGaussian ? '' : 'none';
+}
+
function applySliderRange(id, cfg) {
const el = document.getElementById(id);
const valEl = document.getElementById(id + '-val');
@@ -749,6 +823,10 @@ function applyTypePreset(type) {
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.gaussCurveA = preset.gaussCurveA; applySliderValue('gauss-curve-a', preset.gaussCurveA);
+ params.gaussCurveB = preset.gaussCurveB; applySliderValue('gauss-curve-b', preset.gaussCurveB);
+ params.gaussMin = preset.gaussMin; applySliderValue('gauss-min', preset.gaussMin);
+ params.gaussMax = preset.gaussMax; applySliderValue('gauss-max', preset.gaussMax);
params.rotate = preset.rotate;
params.referenceBrush = preset.referenceBrush;
document.getElementById('rotate').value = preset.rotate;
@@ -770,7 +848,7 @@ document.getElementById('brush-type').addEventListener('change', e => {
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('weight-row').style.display = '';
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';
@@ -783,6 +861,7 @@ document.getElementById('brush-type').addEventListener('change', e => {
document.getElementById('tip-body').addEventListener('input', e => {
params.tipBody = e.target.value;
+ updatePreviewTipFn();
needsRebuild = true;
updateCode();
});
@@ -807,6 +886,13 @@ document.getElementById('pressure-3pt').addEventListener('change', e => {
updateCode();
});
+document.getElementById('pressure-mode').addEventListener('change', e => {
+ params.pressureMode = e.target.value;
+ updatePressureModeUI();
+ needsRebuild = true;
+ updateCode();
+});
+
const PALETTE = ["#002185", "#003c32", "#fcd300", "#ff2702", "#6b9404"];
document.getElementById('multicolor-btn').addEventListener('click', () => {
@@ -833,6 +919,7 @@ document.getElementById('copy-btn').addEventListener('click', () => {
});
updateCode();
+updatePressureModeUI();
// ─────────────────────────────────────────────
// Image upload
@@ -908,9 +995,15 @@ const sketch = (p) => {
};
async function rebuildBrush() {
- const pr = params.pressure3pt
- ? [params.pressStart, params.pressMid, params.pressEnd]
- : [params.pressStart, params.pressEnd];
+ const pr = params.pressureMode === 'gaussian'
+ ? {
+ mode: 'gaussian',
+ curve: [params.gaussCurveA, params.gaussCurveB],
+ min_max: [params.gaussMin, params.gaussMax],
+ }
+ : (params.pressure3pt
+ ? [params.pressStart, params.pressMid, params.pressEnd]
+ : [params.pressStart, params.pressEnd]);
const cfg = {
type: params.type,
@@ -935,9 +1028,16 @@ const sketch = (p) => {
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;
+ if (params.imageDataUrl !== loadedImageSrc) {
+ // New image — must wait for load before drawing
+ brushReady = false;
+ await brush.add(params.name, cfg);
+ loadedImageSrc = params.imageDataUrl;
+ brushReady = true;
+ } else {
+ // Same image, only params changed — update synchronously, no blink
+ brush.add(params.name, cfg);
+ }
} else {
brush.add(params.name, cfg);
}
@@ -1018,6 +1118,52 @@ const sketch = (p) => {
};
new p5(sketch);
+
+// ─────────────────────────────────────────────
+// Tip preview mini-sketch (custom type)
+// ─────────────────────────────────────────────
+function updatePreviewTipFn() {
+ const tipLines = params.tipBody.split('\n').map(l => l.trim()).filter(Boolean).map(l => `_m.${l}`).join('\n');
+ const errorEl = document.getElementById('tip-preview-error');
+ try {
+ previewTipFn = new Function('_m', tipLines);
+ if (errorEl) errorEl.style.display = 'none';
+ } catch(e) {
+ previewTipFn = (_m) => {};
+ if (errorEl) errorEl.style.display = '';
+ }
+}
+updatePreviewTipFn();
+
+const previewSketch = (p) => {
+ p.setup = () => {
+ const cnv = p.createCanvas(100, 100);
+ cnv.parent('tip-preview-wrap');
+ p.pixelDensity(1);
+ p.angleMode(p.DEGREES);
+ p.frameRate(30);
+ };
+ p.draw = () => {
+ p.background(255);
+ // faint boundary showing the full 100×100 space
+ p.push();
+ p.translate(50, 50);
+ p.stroke(220);
+ p.strokeWeight(0.5);
+ p.noFill();
+ p.rect(-49.5, -49.5, 99, 99);
+ // crosshair
+ p.stroke(235);
+ p.line(-49.5, 0, 49.5, 0);
+ p.line(0, -49.5, 0, 49.5);
+ // tip
+ p.fill(0);
+ p.noStroke();
+ try { previewTipFn(p); } catch(e) {}
+ p.pop();
+ };
+};
+new p5(previewSketch);
</script>
</body>
</html>
diff --git a/wp/hatch-test.html b/wp/hatch-test.html
new file mode 100644
index 0000000..8ef408a
--- /dev/null
+++ b/wp/hatch-test.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <title>Hatch Test</title>
+ <style>
+ body { margin: 0; background: #222; display: flex; justify-content: center; align-items: center; height: 100vh; }
+ canvas { border: 1px solid #444; }
+ </style>
+</head>
+<body>
+ <canvas id="canvas"></canvas>
+ <script src="hatch.js"></script>
+</body>
+</html>
diff --git a/wp/hatch.js b/wp/hatch.js
new file mode 100644
index 0000000..2e967fe
--- /dev/null
+++ b/wp/hatch.js
@@ -0,0 +1,493 @@
+// ── Seeded PRNG (sfc32) ──────────────────────────────────────────────
+function sfc32(a, b, c, d) {
+ return function () {
+ a |= 0; b |= 0; c |= 0; d |= 0;
+ const t = (((a + b) | 0) + d) | 0;
+ d = (d + 1) | 0;
+ a = b ^ (b >>> 9);
+ b = (c + (c << 3)) | 0;
+ c = ((c << 21) | (c >>> 11)) + t | 0;
+ return (t >>> 0) / 4294967296;
+ };
+}
+
+function makeRng(seed) {
+ let h = 1779033703 ^ seed.length;
+ for (let i = 0; i < seed.length; i++) {
+ h = Math.imul(h ^ seed.charCodeAt(i), 3432918353);
+ h = (h << 13) | (h >>> 19);
+ }
+ const s = () => {
+ h = Math.imul(h ^ (h >>> 16), 2246822507);
+ h = Math.imul(h ^ (h >>> 13), 3266489909);
+ h ^= h >>> 16;
+ return h >>> 0;
+ };
+ return sfc32(s(), s(), s(), s());
+}
+
+// ── Simplex 2D noise ─────────────────────────────────────────────────
+const F2 = 0.5 * (Math.sqrt(3) - 1);
+const G2 = (3 - Math.sqrt(3)) / 6;
+const grad2 = [[1,1],[-1,1],[1,-1],[-1,-1],[1,0],[-1,0],[0,1],[0,-1]];
+
+function createNoise2D(random) {
+ const perm = new Uint8Array(512);
+ const p = new Uint8Array(256);
+ for (let i = 0; i < 256; i++) p[i] = i;
+ for (let i = 255; i > 0; i--) {
+ const j = (random() * (i + 1)) | 0;
+ [p[i], p[j]] = [p[j], p[i]];
+ }
+ for (let i = 0; i < 512; i++) perm[i] = p[i & 255];
+
+ return function noise2D(x, y) {
+ const s = (x + y) * F2;
+ const i = Math.floor(x + s);
+ const j = Math.floor(y + s);
+ const t = (i + j) * G2;
+ const x0 = x - (i - t);
+ const y0 = y - (j - t);
+ const i1 = x0 > y0 ? 1 : 0;
+ const j1 = x0 > y0 ? 0 : 1;
+ const x1 = x0 - i1 + G2;
+ const y1 = y0 - j1 + G2;
+ const x2 = x0 - 1 + 2 * G2;
+ const y2 = y0 - 1 + 2 * G2;
+ const ii = i & 255;
+ const jj = j & 255;
+ let n0 = 0, n1 = 0, n2 = 0;
+ let t0 = 0.5 - x0 * x0 - y0 * y0;
+ if (t0 >= 0) {
+ const g = grad2[perm[ii + perm[jj]] % 8];
+ t0 *= t0;
+ n0 = t0 * t0 * (g[0] * x0 + g[1] * y0);
+ }
+ let t1 = 0.5 - x1 * x1 - y1 * y1;
+ if (t1 >= 0) {
+ const g = grad2[perm[ii + i1 + perm[jj + j1]] % 8];
+ t1 *= t1;
+ n1 = t1 * t1 * (g[0] * x1 + g[1] * y1);
+ }
+ let t2 = 0.5 - x2 * x2 - y2 * y2;
+ if (t2 >= 0) {
+ const g = grad2[perm[ii + 1 + perm[jj + 1]] % 8];
+ t2 *= t2;
+ n2 = t2 * t2 * (g[0] * x2 + g[1] * y2);
+ }
+ return 70 * (n0 + n1 + n2);
+ };
+}
+
+// ── Curl noise from 2D simplex ───────────────────────────────────────
+function createCurl2D(noise) {
+ return function curl2D(x, y, eps) {
+ eps = eps || 1;
+ const dndx = (noise(x + eps, y) - noise(x - eps, y)) / (2 * eps);
+ const dndy = (noise(x, y + eps) - noise(x, y - eps)) / (2 * eps);
+ return [-dndy, dndx];
+ };
+}
+
+// ── Poisson disk sampling ────────────────────────────────────────────
+function poissonDisk(width, height, radius, rng) {
+ const cellSize = radius / Math.SQRT2;
+ const cols = Math.ceil(width / cellSize);
+ const rows = Math.ceil(height / cellSize);
+ const grid = new Int32Array(cols * rows).fill(-1);
+ const points = [];
+ const active = [];
+ const k = 30;
+
+ function gridIndex(x, y) {
+ return ((x / cellSize) | 0) + ((y / cellSize) | 0) * cols;
+ }
+
+ function addPoint(x, y) {
+ const idx = points.length;
+ points.push([x, y]);
+ active.push(idx);
+ grid[gridIndex(x, y)] = idx;
+ }
+
+ function tooClose(x, y) {
+ const col = (x / cellSize) | 0;
+ const row = (y / cellSize) | 0;
+ for (let dr = -2; dr <= 2; dr++) {
+ for (let dc = -2; dc <= 2; dc++) {
+ const c = col + dc;
+ const r = row + dr;
+ if (c < 0 || r < 0 || c >= cols || r >= rows) continue;
+ const gi = grid[c + r * cols];
+ if (gi === -1) continue;
+ const dx = x - points[gi][0];
+ const dy = y - points[gi][1];
+ if (dx * dx + dy * dy < radius * radius) return true;
+ }
+ }
+ return false;
+ }
+
+ addPoint(rng() * width, rng() * height);
+
+ while (active.length > 0) {
+ const ri = (rng() * active.length) | 0;
+ const pt = points[active[ri]];
+ let found = false;
+ for (let attempt = 0; attempt < k; attempt++) {
+ const angle = rng() * Math.PI * 2;
+ const dist = radius + rng() * radius;
+ const nx = pt[0] + Math.cos(angle) * dist;
+ const ny = pt[1] + Math.sin(angle) * dist;
+ if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;
+ if (tooClose(nx, ny)) continue;
+ addPoint(nx, ny);
+ found = true;
+ break;
+ }
+ if (!found) {
+ active[ri] = active[active.length - 1];
+ active.pop();
+ }
+ }
+ return points;
+}
+
+// ── Point-in-polygon (ray cast) ──────────────────────────────────────
+function pointInPolygon(px, py, poly) {
+ let inside = false;
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
+ const xi = poly[i][0], yi = poly[i][1];
+ const xj = poly[j][0], yj = poly[j][1];
+ if ((yi > py) !== (yj > py) && px < ((xj - xi) * (py - yi)) / (yj - yi) + xi) {
+ inside = !inside;
+ }
+ }
+ return inside;
+}
+
+// ── Generate ellipse polygon ─────────────────────────────────────────
+function ellipsePoly(cx, cy, rx, ry, rotation, steps) {
+ const pts = [];
+ for (let i = 0; i < steps; i++) {
+ const a = (i / steps) * Math.PI * 2;
+ const lx = Math.cos(a) * rx;
+ const ly = Math.sin(a) * ry;
+ pts.push([
+ cx + lx * Math.cos(rotation) - ly * Math.sin(rotation),
+ cy + lx * Math.sin(rotation) + ly * Math.cos(rotation),
+ ]);
+ }
+ return pts;
+}
+
+// ── Bounding box for any polygon ─────────────────────────────────────
+function polyBounds(poly) {
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+ for (const p of poly) {
+ if (p[0] < minX) minX = p[0];
+ if (p[1] < minY) minY = p[1];
+ if (p[0] > maxX) maxX = p[0];
+ if (p[1] > maxY) maxY = p[1];
+ }
+ return { minX, minY, maxX, maxY, w: maxX - minX, h: maxY - minY };
+}
+
+// ── Utility ──────────────────────────────────────────────────────────
+function lerp(a, b, t) { return a + (b - a) * t; }
+function map(v, inMin, inMax, outMin, outMax) {
+ return outMin + ((v - inMin) / (inMax - inMin)) * (outMax - outMin);
+}
+function clamp(v, lo, hi) { return Math.min(Math.max(v, lo), hi); }
+
+// =====================================================================
+// hatchShape — fill any polygon with hand-drawn hatching strokes
+// =====================================================================
+//
+// ctx: CanvasRenderingContext2D
+// poly: Array of [x, y] — closed polygon vertices
+// opts: {
+// rand, — seeded PRNG () => 0..1
+// noise, — simplex 2D (x,y) => -1..1
+// curl, — curl 2D (x,y,eps) => [dx,dy]
+// canvasW, — full canvas width (for coordinate normalization)
+// canvasH, — full canvas height
+// color, — stroke color string
+// tangentMode, — "h" | "v" | "n" | "c"
+// spacing, — Poisson disk radius (smaller = denser)
+// opacityRange, — [min, max] per-stroke alpha
+// strokeWidthScl, — multiplier for stroke width
+// hatchSpacing, — vertical-line pass spacing (px)
+// hatchOpacity, — vertical-line pass alpha
+// contourOpacity, — outline alpha (0 to skip)
+// margin, — px inset from canvas edges
+// }
+//
+function hatchShape(ctx, poly, opts) {
+ const {
+ rand, noise, curl,
+ canvasW: CW, canvasH: CH,
+ color = "#000000",
+ tangentMode = "c",
+ spacing = CW * 0.008,
+ opacityRange = [0.12, 0.24],
+ strokeWidthScl = 1,
+ hatchSpacing = 5,
+ hatchOpacity = 0.012,
+ contourOpacity = 0.06,
+ margin = 2,
+ } = opts;
+
+ const bb = polyBounds(poly);
+ const diag = Math.sqrt(bb.w * bb.w + bb.h * bb.h);
+ const noiseScl = 0.7;
+ const curlScl = 0.7;
+
+ // ── Seed stroke origins via Poisson disk ───────────────────────────
+ const rawSeeds = poissonDisk(bb.w, bb.h, spacing, rand);
+ const seeds = [];
+ for (const pt of rawSeeds) {
+ const wx = pt[0] + bb.minX;
+ const wy = pt[1] + bb.minY;
+ if (pointInPolygon(wx, wy, poly)) seeds.push([wx, wy]);
+ }
+
+ // ── Per-seed: main stroke + crayon sub-strokes ─────────────────────
+ ctx.lineJoin = "round";
+ ctx.lineCap = "round";
+
+ for (const [sx, sy] of seeds) {
+ const nx = sx / CW;
+ const ny = sy / CH;
+
+ // ── Tangent direction ────────────────────────────────────────────
+ let tx, ty;
+ if (tangentMode === "h") {
+ tx = 1; ty = (rand() - 0.5) * 0.15;
+ } else if (tangentMode === "v") {
+ tx = (rand() - 0.5) * 0.15; ty = 1;
+ } else if (tangentMode === "n") {
+ tx = noise(nx * noiseScl + 10, ny * noiseScl + 10) * Math.PI * 2;
+ ty = noise(nx * noiseScl + 50, ny * noiseScl + 50) * Math.PI * 2;
+ } else {
+ const c = curl(nx * curlScl, ny * curlScl, 0.01);
+ const q = 180;
+ tx = Math.sign(c[0]) * (Math.floor(Math.abs(c[0]) * q) / q);
+ ty = Math.sign(c[1]) * (Math.floor(Math.abs(c[1]) * q) / q);
+ }
+
+ const tLen = Math.sqrt(tx * tx + ty * ty) || 1;
+ tx /= tLen; ty /= tLen;
+ const pnx = -ty, pny = tx;
+
+ const tScl = map(noise(nx * 1.3, ny * 1.3), -1, 1, diag * 0.02, diag * 0.18);
+ const opacity = lerp(opacityRange[0], opacityRange[1], rand());
+ const strokeWidth = CW * 0.0001 * lerp(1, 2.3, rand()) * strokeWidthScl;
+ const blendMode = rand() < 0.15 ? "multiply" : "source-over";
+
+ // ── Main body stroke ─────────────────────────────────────────────
+ ctx.save();
+ ctx.globalAlpha = opacity;
+ ctx.globalCompositeOperation = blendMode;
+ ctx.strokeStyle = color;
+ ctx.lineWidth = strokeWidth;
+
+ const mainSteps = 5 + (rand() * 10) | 0;
+ const curvature = (rand() - 0.5) * tScl * 0.3;
+ const microNoise = lerp(0.001, 0.003, rand()) * CH;
+
+ ctx.beginPath();
+ ctx.moveTo(sx, sy);
+ for (let step = 1; step <= mainSteps; step++) {
+ const frac = step / mainSteps;
+ let px = sx + tx * tScl * frac;
+ let py = sy + ty * tScl * frac;
+ const bow = Math.sin(frac * Math.PI) * curvature;
+ px += pnx * bow; py += pny * bow;
+ const nf = 0.004;
+ const h = (frac + rand()) % 1;
+ px += pnx * noise(h + nx * nf, h + ny * nf) * microNoise;
+ py += pny * noise(h + nx * nf + 50, h + ny * nf + 50) * microNoise;
+ if (pointInPolygon(px, py, poly) && px > margin && px < CW - margin && py > margin && py < CH - margin) {
+ ctx.lineTo(px, py);
+ }
+ }
+ ctx.stroke();
+ ctx.restore();
+
+ // ── Crayon sub-strokes ───────────────────────────────────────────
+ let repCount = clamp(map(noise(nx * 2, ny * 2), -1, 1, 1, 8) | 0, 1, 8);
+ const baseArcRadius = tScl * map(Math.abs(noise(nx * 1.5 + 60, ny * 1.5 + 60)), 0, 1, 0.01, 0.05);
+
+ for (let rep = 0; rep < repCount; rep++) {
+ const offsetN = rep * strokeWidth * map(noise(nx * 0.7 + 1000 + rep, ny * 0.7 + 1000 + rep), -1, 1, 0.2, 1);
+ const jitterX = lerp(-0.005, 0.005, rand()) * CW;
+ const jitterY = lerp(-0.005, 0.005, rand()) * CH;
+ const arcR = lerp(baseArcRadius * 0.5, baseArcRadius * 2, rand());
+ const arcLen = tScl * map(noise(nx * 1.3 + 50, ny * 1.3 + 50), -1, 1, 0.1, 1);
+ const arcStart = rand() * Math.PI;
+ const arcEnd = lerp(arcStart, Math.PI, rand());
+ const arcStep = lerp(0.05, 0.1, rand());
+ const rotAngle = Math.atan2(ty, tx) + Math.PI / 2 + (rand() - 0.5) * 0.2;
+
+ ctx.save();
+ ctx.globalAlpha = opacity;
+ ctx.globalCompositeOperation = blendMode;
+ ctx.strokeStyle = color;
+ ctx.lineWidth = strokeWidth;
+ ctx.beginPath();
+
+ let started = false;
+ for (let a = arcStart; a <= arcEnd; a += arcStep) {
+ let lx = Math.cos(a * Math.PI * 2) * arcR + pnx * a * 5;
+ let ly = Math.sin(a * Math.PI * 2) * arcLen + pny * a * 5;
+ const rx2 = lx * Math.cos(rotAngle) - ly * Math.sin(rotAngle);
+ const ry2 = lx * Math.sin(rotAngle) + ly * Math.cos(rotAngle);
+ let fx = rx2 + sx + pnx * offsetN * lerp(0.5, 1, rand()) + jitterX;
+ let fy = ry2 + sy + pny * offsetN * lerp(0.5, 1, rand()) + jitterY;
+ fx += noise(nx * 1000, ny * 1000) * CW * lerp(0.005, 0.008, rand());
+ fy += noise(nx * 1000 + 500, ny * 1000 + 500) * CH * lerp(0.005, 0.008, rand());
+ if (!pointInPolygon(fx, fy, poly)) continue;
+ if (fx < margin || fx > CW - margin || fy < margin || fy > CH - margin) continue;
+ if (!started) { ctx.moveTo(fx, fy); started = true; }
+ else ctx.lineTo(fx, fy);
+ }
+ ctx.stroke();
+ ctx.restore();
+ }
+ }
+
+ // ── Vertical hatching pass ─────────────────────────────────────────
+ if (false && hatchOpacity > 0) {
+ ctx.save();
+ ctx.globalAlpha = hatchOpacity;
+ ctx.globalCompositeOperation = "multiply";
+ ctx.strokeStyle = color;
+ ctx.lineWidth = 0.5;
+ ctx.lineCap = "round";
+
+ for (let x = bb.minX; x <= bb.maxX; x += hatchSpacing) {
+ const jx = x + (rand() - 0.5) * hatchSpacing * 0.1;
+ const jy = (rand() - 0.5) * hatchSpacing * 0.1;
+ const segments = [];
+ let seg = [];
+
+ for (let y = bb.minY; y <= bb.maxY; y += 1) {
+ const py = y + jy;
+ if (pointInPolygon(jx, py, poly) && jx > margin && jx < CW - margin && py > margin && py < CH - margin) {
+ if (seg.length === 0 || Math.abs(py - seg[seg.length - 1]) <= 1.5) {
+ seg.push(py);
+ } else {
+ if (seg.length > 1) segments.push(seg);
+ seg = [py];
+ }
+ }
+ }
+ if (seg.length > 1) segments.push(seg);
+
+ for (const s of segments) {
+ ctx.beginPath();
+ ctx.moveTo(jx, s[0]);
+ for (let i = 1; i < s.length; i++) ctx.lineTo(jx, s[i]);
+ ctx.stroke();
+ }
+ }
+ ctx.restore();
+ }
+
+ // ── Contour stroke ─────────────────────────────────────────────────
+ if (contourOpacity > 0) {
+ ctx.save();
+ ctx.globalAlpha = contourOpacity;
+ ctx.globalCompositeOperation = "multiply";
+ ctx.strokeStyle = "#111111";
+ ctx.lineWidth = 0.3;
+ ctx.lineJoin = "round";
+ ctx.lineCap = "round";
+
+ ctx.beginPath();
+ ctx.moveTo(poly[0][0], poly[0][1]);
+ for (let i = 1; i < poly.length; i++) {
+ ctx.lineTo(
+ poly[i][0] + (rand() - 0.5) * CW * 0.001,
+ poly[i][1] + (rand() - 0.5) * CH * 0.001
+ );
+ }
+ ctx.closePath();
+ ctx.stroke();
+ ctx.restore();
+ }
+}
+
+// =====================================================================
+// DEMO — hatch a random ellipse
+// =====================================================================
+const seed = "etudes-" + Date.now();
+const rand = makeRng(seed);
+const noise = createNoise2D(rand);
+const curl = createCurl2D(noise);
+
+const W = 800;
+const H = 1100;
+const canvas = document.getElementById("canvas");
+canvas.width = W;
+canvas.height = H;
+const ctx = canvas.getContext("2d");
+
+// ── Background ───────────────────────────────────────────────────────
+ctx.fillStyle = "#eae4cc";
+ctx.fillRect(0, 0, W, H);
+
+// ── Random ellipse ───────────────────────────────────────────────────
+const cx = W * (0.3 + rand() * 0.4);
+const cy = H * (0.3 + rand() * 0.4);
+const rx = W * (0.15 + rand() * 0.15);
+const ry = H * (0.12 + rand() * 0.12);
+const rot = (rand() - 0.5) * Math.PI * 0.4;
+const ellipse = ellipsePoly(cx, cy, rx, ry, rot, 120);
+
+// ── Pick color + tangent mode ────────────────────────────────────────
+const PALETTE = [
+ "#D9E5EB","#557484","#2C697F","#034053","#000000",
+ "#FECD1A","#F7AA42","#803717","#EF7F00","#EB6A27",
+ "#D4011D","#C10121","#B5007C","#3E2A71","#003483",
+ "#00579D","#0092D2","#028D7A","#009B5A","#368F2D",
+ "#628B2A","#A4C401",
+];
+const color = PALETTE[(rand() * PALETTE.length) | 0];
+const TANGENT_MODES = ["h", "v", "n", "c"];
+const tangentMode = TANGENT_MODES[(rand() * TANGENT_MODES.length) | 0];
+console.log("tangent mode:", tangentMode, "| color:", color);
+
+// ── Hatch ellipse ────────────────────────────────────────────────────
+hatchShape(ctx, ellipse, {
+ rand, noise, curl,
+ canvasW: W, canvasH: H,
+ color,
+ tangentMode,
+});
+
+// ── Random polygon ───────────────────────────────────────────────────
+const polyN = 5 + (rand() * 4) | 0; // 5–8 vertices
+const polyCx = W * (0.25 + rand() * 0.5);
+const polyCy = H * (0.25 + rand() * 0.5);
+const polyR = W * (0.1 + rand() * 0.15);
+const polyVerts = [];
+for (let i = 0; i < polyN; i++) {
+ const angle = (i / polyN) * Math.PI * 2 + (rand() - 0.5) * 0.6;
+ const r = polyR * (0.6 + rand() * 0.8);
+ polyVerts.push([polyCx + Math.cos(angle) * r, polyCy + Math.sin(angle) * r]);
+}
+
+const color2 = PALETTE[(rand() * PALETTE.length) | 0];
+const tangentMode2 = TANGENT_MODES[(rand() * TANGENT_MODES.length) | 0];
+console.log("polygon tangent mode:", tangentMode2, "| color:", color2);
+
+hatchShape(ctx, polyVerts, {
+ rand, noise, curl,
+ canvasW: W, canvasH: H,
+ color: color2,
+ tangentMode: tangentMode2,
+});
+
+console.log("done");
diff --git a/wp/mapan.js b/wp/mapan.js
new file mode 100644
index 0000000..225ae94
--- /dev/null
+++ b/wp/mapan.js
@@ -0,0 +1,3649 @@
+(function () {
+ const n = document.createElement("link").relList;
+ if (n && n.supports && n.supports("modulepreload")) return;
+ for (const m of document.querySelectorAll('link[rel="modulepreload"]')) c(m);
+ new MutationObserver((m) => {
+ for (const R of m)
+ if (R.type === "childList")
+ for (const F of R.addedNodes) F.tagName === "LINK" && F.rel === "modulepreload" && c(F);
+ }).observe(document, { childList: !0, subtree: !0 });
+ function r(m) {
+ const R = {};
+ return (
+ m.integrity && (R.integrity = m.integrity),
+ m.referrerpolicy && (R.referrerPolicy = m.referrerpolicy),
+ m.crossorigin === "use-credentials"
+ ? (R.credentials = "include")
+ : m.crossorigin === "anonymous"
+ ? (R.credentials = "omit")
+ : (R.credentials = "same-origin"),
+ R
+ );
+ }
+ function c(m) {
+ if (m.ep) return;
+ m.ep = !0;
+ const R = r(m);
+ fetch(m.href, R);
+ }
+})();
+const $e = [
+ "#D9E5EB",
+ "#B5C0C6",
+ "#557484",
+ "#2C697F",
+ "#034053",
+ "#000000",
+ "#FECD1A",
+ "#EFED9B",
+ "#F7AA42",
+ "#803717",
+ "#EF7F00",
+ "#FABE5D",
+ "#D8C262",
+ "#C2AB60",
+ "#C67615",
+ "#7E7948",
+ "#F6AD6E",
+ "#FDD48F",
+ "#91816D",
+ "#544429",
+ "#EB6A27",
+ "#F29B81",
+ "#C73636",
+ "#955D40",
+ "#6B4833",
+ "#E85127",
+ "#CB653C",
+ "#A53722",
+ "#BD6B44",
+ "#D4011D",
+ "#F19C99",
+ "#C10121",
+ "#EB6E81",
+ "#B5007C",
+ "#6D3F6E",
+ "#6F195F",
+ "#3E2A71",
+ "#7C5D9F",
+ "#2B195F",
+ "#003483",
+ "#655A9F",
+ "#02315C",
+ "#00579D",
+ "#0092D2",
+ "#012857",
+ "#0262A7",
+ "#003556",
+ "#007FAC",
+ "#00A5CF",
+ "#00AEC6",
+ "#047E9D",
+ "#028D7A",
+ "#3AB6B8",
+ "#009B5A",
+ "#368F2D",
+ "#70BD95",
+ "#47732D",
+ "#039A47",
+ "#628B2A",
+ "#4E602C",
+ "#A4C401",
+ "#FCE90F",
+ "#F0D500",
+ "#AD9216",
+ "#FBEB46",
+ "#005A9A",
+ "#E53257",
+ "#F6AA24",
+ "#C7C2B4",
+ "#6E6168",
+ "#3E2F36",
+ "#D6855D",
+ "#C7CDD1",
+ "#C3A24E",
+ "#282838",
+ "#FFE7AB",
+ "#E53527",
+ "#86273D",
+ "#76ACD5",
+ "#00784F",
+ "#7AB63E",
+ "#C7D32D",
+ ],
+ Bn = typeof window < "u" ? window.location.search : "";
+new URLSearchParams(Bn);
+const Un = 0.5 * (Math.sqrt(3) - 1),
+ Me = (3 - Math.sqrt(3)) / 6,
+ Xn = 1 / 3,
+ ie = 1 / 6,
+ Vn = (Math.sqrt(5) - 1) / 4,
+ qt = (5 - Math.sqrt(5)) / 20,
+ $t = new Float32Array([
+ 1, 1, 0, -1, 1, 0, 1, -1, 0, -1, -1, 0, 1, 0, 1, -1, 0, 1, 1, 0, -1, -1, 0, -1, 0, 1, 1, 0, -1, 1, 0, 1, -1, 0,
+ -1, -1,
+ ]),
+ _t = new Float32Array([
+ 0, 1, 1, 1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 1,
+ 0, 1, 1, 1, 0, 1, -1, 1, 0, -1, 1, 1, 0, -1, -1, -1, 0, 1, 1, -1, 0, 1, -1, -1, 0, -1, 1, -1, 0, -1, -1, 1, 1,
+ 0, 1, 1, 1, 0, -1, 1, -1, 0, 1, 1, -1, 0, -1, -1, 1, 0, 1, -1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, -1, 1, 1, 1,
+ 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, 0, -1, 1, 1, 0, -1, 1, -1, 0, -1, -1, 1, 0, -1, -1, -1, 0,
+ ]);
+class Yn {
+ constructor(n = Math.random) {
+ const r = typeof n == "function" ? n : zn(n);
+ (this.p = _n(r)), (this.perm = new Uint8Array(512)), (this.permMod12 = new Uint8Array(512));
+ for (let c = 0; c < 512; c++) (this.perm[c] = this.p[c & 255]), (this.permMod12[c] = this.perm[c] % 12);
+ }
+ noise2D(n, r) {
+ const c = this.permMod12,
+ m = this.perm;
+ let R = 0,
+ F = 0,
+ U = 0;
+ const H = (n + r) * Un,
+ J = Math.floor(n + H),
+ L = Math.floor(r + H),
+ yt = (J + L) * Me,
+ vt = J - yt,
+ St = L - yt,
+ ot = n - vt,
+ mt = r - St;
+ let j, st;
+ ot > mt ? ((j = 1), (st = 0)) : ((j = 0), (st = 1));
+ const W = ot - j + Me,
+ K = mt - st + Me,
+ Q = ot - 1 + 2 * Me,
+ it = mt - 1 + 2 * Me,
+ M = J & 255,
+ I = L & 255;
+ let i = 0.5 - ot * ot - mt * mt;
+ if (i >= 0) {
+ const D = c[M + m[I]] * 3;
+ (i *= i), (R = i * i * ($t[D] * ot + $t[D + 1] * mt));
+ }
+ let k = 0.5 - W * W - K * K;
+ if (k >= 0) {
+ const D = c[M + j + m[I + st]] * 3;
+ (k *= k), (F = k * k * ($t[D] * W + $t[D + 1] * K));
+ }
+ let S = 0.5 - Q * Q - it * it;
+ if (S >= 0) {
+ const D = c[M + 1 + m[I + 1]] * 3;
+ (S *= S), (U = S * S * ($t[D] * Q + $t[D + 1] * it));
+ }
+ return 70 * (R + F + U);
+ }
+ noise3D(n, r, c) {
+ const m = this.permMod12,
+ R = this.perm;
+ let F, U, H, J;
+ const L = (n + r + c) * Xn,
+ yt = Math.floor(n + L),
+ vt = Math.floor(r + L),
+ St = Math.floor(c + L),
+ ot = (yt + vt + St) * ie,
+ mt = yt - ot,
+ j = vt - ot,
+ st = St - ot,
+ W = n - mt,
+ K = r - j,
+ Q = c - st;
+ let it, M, I, i, k, S;
+ W >= K
+ ? K >= Q
+ ? ((it = 1), (M = 0), (I = 0), (i = 1), (k = 1), (S = 0))
+ : W >= Q
+ ? ((it = 1), (M = 0), (I = 0), (i = 1), (k = 0), (S = 1))
+ : ((it = 0), (M = 0), (I = 1), (i = 1), (k = 0), (S = 1))
+ : K < Q
+ ? ((it = 0), (M = 0), (I = 1), (i = 0), (k = 1), (S = 1))
+ : W < Q
+ ? ((it = 0), (M = 1), (I = 0), (i = 0), (k = 1), (S = 1))
+ : ((it = 0), (M = 1), (I = 0), (i = 1), (k = 1), (S = 0));
+ const D = W - it + ie,
+ nt = K - M + ie,
+ Y = Q - I + ie,
+ w = W - i + 2 * ie,
+ X = K - k + 2 * ie,
+ V = Q - S + 2 * ie,
+ N = W - 1 + 3 * ie,
+ T = K - 1 + 3 * ie,
+ lt = Q - 1 + 3 * ie,
+ dt = yt & 255,
+ et = vt & 255,
+ ft = St & 255;
+ let xt = 0.6 - W * W - K * K - Q * Q;
+ if (xt < 0) F = 0;
+ else {
+ const It = m[dt + R[et + R[ft]]] * 3;
+ (xt *= xt), (F = xt * xt * ($t[It] * W + $t[It + 1] * K + $t[It + 2] * Q));
+ }
+ let rt = 0.6 - D * D - nt * nt - Y * Y;
+ if (rt < 0) U = 0;
+ else {
+ const It = m[dt + it + R[et + M + R[ft + I]]] * 3;
+ (rt *= rt), (U = rt * rt * ($t[It] * D + $t[It + 1] * nt + $t[It + 2] * Y));
+ }
+ let pt = 0.6 - w * w - X * X - V * V;
+ if (pt < 0) H = 0;
+ else {
+ const It = m[dt + i + R[et + k + R[ft + S]]] * 3;
+ (pt *= pt), (H = pt * pt * ($t[It] * w + $t[It + 1] * X + $t[It + 2] * V));
+ }
+ let At = 0.6 - N * N - T * T - lt * lt;
+ if (At < 0) J = 0;
+ else {
+ const It = m[dt + 1 + R[et + 1 + R[ft + 1]]] * 3;
+ (At *= At), (J = At * At * ($t[It] * N + $t[It + 1] * T + $t[It + 2] * lt));
+ }
+ return 32 * (F + U + H + J);
+ }
+ noise4D(n, r, c, m) {
+ const R = this.perm;
+ let F, U, H, J, L;
+ const yt = (n + r + c + m) * Vn,
+ vt = Math.floor(n + yt),
+ St = Math.floor(r + yt),
+ ot = Math.floor(c + yt),
+ mt = Math.floor(m + yt),
+ j = (vt + St + ot + mt) * qt,
+ st = vt - j,
+ W = St - j,
+ K = ot - j,
+ Q = mt - j,
+ it = n - st,
+ M = r - W,
+ I = c - K,
+ i = m - Q;
+ let k = 0,
+ S = 0,
+ D = 0,
+ nt = 0;
+ it > M ? k++ : S++,
+ it > I ? k++ : D++,
+ it > i ? k++ : nt++,
+ M > I ? S++ : D++,
+ M > i ? S++ : nt++,
+ I > i ? D++ : nt++;
+ const Y = k >= 3 ? 1 : 0,
+ w = S >= 3 ? 1 : 0,
+ X = D >= 3 ? 1 : 0,
+ V = nt >= 3 ? 1 : 0,
+ N = k >= 2 ? 1 : 0,
+ T = S >= 2 ? 1 : 0,
+ lt = D >= 2 ? 1 : 0,
+ dt = nt >= 2 ? 1 : 0,
+ et = k >= 1 ? 1 : 0,
+ ft = S >= 1 ? 1 : 0,
+ xt = D >= 1 ? 1 : 0,
+ rt = nt >= 1 ? 1 : 0,
+ pt = it - Y + qt,
+ At = M - w + qt,
+ It = I - X + qt,
+ Lt = i - V + qt,
+ C = it - N + 2 * qt,
+ P = M - T + 2 * qt,
+ A = I - lt + 2 * qt,
+ s = i - dt + 2 * qt,
+ h = it - et + 3 * qt,
+ o = M - ft + 3 * qt,
+ l = I - xt + 3 * qt,
+ a = i - rt + 3 * qt,
+ p = it - 1 + 4 * qt,
+ f = M - 1 + 4 * qt,
+ y = I - 1 + 4 * qt,
+ u = i - 1 + 4 * qt,
+ v = vt & 255,
+ _ = St & 255,
+ g = ot & 255,
+ b = mt & 255;
+ let E = 0.6 - it * it - M * M - I * I - i * i;
+ if (E < 0) F = 0;
+ else {
+ const O = (R[v + R[_ + R[g + R[b]]]] % 32) * 4;
+ (E *= E), (F = E * E * (_t[O] * it + _t[O + 1] * M + _t[O + 2] * I + _t[O + 3] * i));
+ }
+ let z = 0.6 - pt * pt - At * At - It * It - Lt * Lt;
+ if (z < 0) U = 0;
+ else {
+ const O = (R[v + Y + R[_ + w + R[g + X + R[b + V]]]] % 32) * 4;
+ (z *= z), (U = z * z * (_t[O] * pt + _t[O + 1] * At + _t[O + 2] * It + _t[O + 3] * Lt));
+ }
+ let G = 0.6 - C * C - P * P - A * A - s * s;
+ if (G < 0) H = 0;
+ else {
+ const O = (R[v + N + R[_ + T + R[g + lt + R[b + dt]]]] % 32) * 4;
+ (G *= G), (H = G * G * (_t[O] * C + _t[O + 1] * P + _t[O + 2] * A + _t[O + 3] * s));
+ }
+ let $ = 0.6 - h * h - o * o - l * l - a * a;
+ if ($ < 0) J = 0;
+ else {
+ const O = (R[v + et + R[_ + ft + R[g + xt + R[b + rt]]]] % 32) * 4;
+ ($ *= $), (J = $ * $ * (_t[O] * h + _t[O + 1] * o + _t[O + 2] * l + _t[O + 3] * a));
+ }
+ let Z = 0.6 - p * p - f * f - y * y - u * u;
+ if (Z < 0) L = 0;
+ else {
+ const O = (R[v + 1 + R[_ + 1 + R[g + 1 + R[b + 1]]]] % 32) * 4;
+ (Z *= Z), (L = Z * Z * (_t[O] * p + _t[O + 1] * f + _t[O + 2] * y + _t[O + 3] * u));
+ }
+ return 27 * (F + U + H + J + L);
+ }
+}
+function _n(e) {
+ const n = new Uint8Array(256);
+ for (let r = 0; r < 256; r++) n[r] = r;
+ for (let r = 0; r < 255; r++) {
+ const c = r + ~~(e() * (256 - r)),
+ m = n[r];
+ (n[r] = n[c]), (n[c] = m);
+ }
+ return n;
+}
+function zn(e) {
+ let n = 0,
+ r = 0,
+ c = 0,
+ m = 1;
+ const R = $n();
+ return (
+ (n = R(" ")),
+ (r = R(" ")),
+ (c = R(" ")),
+ (n -= R(e)),
+ n < 0 && (n += 1),
+ (r -= R(e)),
+ r < 0 && (r += 1),
+ (c -= R(e)),
+ c < 0 && (c += 1),
+ function () {
+ const F = 2091639 * n + m * 23283064365386963e-26;
+ return (n = r), (r = c), (c = F - (m = F | 0));
+ }
+ );
+}
+function $n() {
+ let e = 4022871197;
+ return function (n) {
+ n = n.toString();
+ for (let r = 0; r < n.length; r++) {
+ e += n.charCodeAt(r);
+ let c = 0.02519603282416938 * e;
+ (e = c >>> 0), (c -= e), (c *= e), (e = c >>> 0), (c -= e), (e += c * 4294967296);
+ }
+ return (e >>> 0) * 23283064365386963e-26;
+ };
+}
+const Wn = (e, n = 0, r = 1) => {
+ const c = { hash: e, editionNumber: n, totalEditions: r, input: {} };
+ return btoa(JSON.stringify(c).replace("==", ""));
+};
+let Fe = tokenData;
+function qn() {}
+setTimeout(qn, 0);
+console.log(Fe.hash);
+console.log(Wn(Fe.hash));
+const Zn = function (e) {
+ var n,
+ r,
+ c,
+ m,
+ R = (function (H) {
+ for (var J = 0, L = 1779033703 ^ H.length; J < H.length; J++)
+ L = ((L = Math.imul(L ^ H.charCodeAt(J), 3432918353)) << 13) | (L >>> 19);
+ return function () {
+ return (
+ (L = Math.imul((L = Math.imul(L ^ (L >>> 16), 2246822507)) ^ (L >>> 13), 3266489909)),
+ (L ^= L >>> 16) >>> 0
+ );
+ };
+ })(e),
+ F = {
+ rand:
+ ((n = R()),
+ (r = R()),
+ (c = R()),
+ (m = R()),
+ function () {
+ c |= 0;
+ var U = ((((n |= 0) + (r |= 0)) | 0) + (m |= 0)) | 0;
+ return (
+ (m = (m + 1) | 0),
+ (n = r ^ (r >>> 9)),
+ (r = (c + (c << 3)) | 0),
+ (c = ((c = (c << 21) | (c >>> 11)) + U) | 0),
+ (U >>> 0) / 4294967296
+ );
+ }),
+ randInt: function (U, H) {
+ return U + Math.floor((H - U) * F.rand());
+ },
+ };
+ return F;
+};
+class un {
+ constructor(n = !1) {
+ (this.useA = !1),
+ (this.tk = Fe),
+ (this.useNative = n),
+ (this.prng = Zn(Fe.hash)),
+ (this.simplex = new Yn(this.random()));
+ }
+ random() {
+ return this.useNative ? Math.random() : this.prng.rand();
+ }
+ range(n, r) {
+ return n + (r - n) * this.random();
+ }
+ int(n, r) {
+ return Math.floor(n + (r - n + 1) * this.random());
+ }
+ bool(n) {
+ return this.random() < n;
+ }
+ pick(n) {
+ return n[this.int(0, n.length - 1)];
+ }
+ n2D(n, r) {
+ return this.simplex.noise2D(n, r);
+ }
+ curl2D(n, r, c = 1) {
+ const m = this.n2D(n, r + c),
+ R = this.n2D(n, r - c),
+ F = this.n2D(n + c, r),
+ U = this.n2D(n - c, r),
+ H = (m - R) / (2 * c);
+ return [-((F - U) / (2 * c)), H];
+ }
+ randomPow(n) {
+ return Math.pow(this.random(), n);
+ }
+ random2(n) {
+ const r = Math.sin(n * 12.9898) * 43758.5453;
+ return r - Math.floor(r);
+ }
+}
+const t = new un();
+new un(!0);
+const We = (e) => {
+ const n = [...e];
+ for (let r = n.length - 1; r > 0; r--) {
+ const c = Math.floor(t.random() * (r + 1));
+ [n[r], n[c]] = [n[c], n[r]];
+ }
+ return n;
+ },
+ Wt = (e, n, r) => {
+ const c = Math.min(n, r),
+ m = Math.max(n, r);
+ return Math.min(Math.max(e, c), m);
+ },
+ Bt = (e, n, r, c, m, R = !1) => {
+ let F = c + ((m - c) * (e - n)) / (r - n);
+ return R && (F = Wt(F, c, m)), F;
+ },
+ Se = (e, n, r) => e * (1 - r) + n * r,
+ jn = ({ r: e, g: n, b: r }) => "#" + ((1 << 24) + (e << 16) + (n << 8) + r).toString(16).slice(1),
+ Hn = ({ h: e, s: n, l: r }) => {
+ (n /= 100), (r /= 100);
+ let c = (1 - Math.abs(2 * r - 1)) * n,
+ m = c * (1 - Math.abs(((e / 60) % 2) - 1)),
+ R = r - c / 2,
+ F = 0,
+ U = 0,
+ H = 0;
+ return (
+ 0 <= e && e < 60
+ ? ((F = c), (U = m), (H = 0))
+ : 60 <= e && e < 120
+ ? ((F = m), (U = c), (H = 0))
+ : 120 <= e && e < 180
+ ? ((F = 0), (U = c), (H = m))
+ : 180 <= e && e < 240
+ ? ((F = 0), (U = m), (H = c))
+ : 240 <= e && e < 300
+ ? ((F = m), (U = 0), (H = c))
+ : 300 <= e && e < 360 && ((F = c), (U = 0), (H = m)),
+ (F = Math.round((F + R) * 255)),
+ (U = Math.round((U + R) * 255)),
+ (H = Math.round((H + R) * 255)),
+ { r: F, g: U, b: H }
+ );
+ },
+ Xe = (e) => {
+ if (e.s) return e;
+ let n = 0,
+ r = 0,
+ c = 0;
+ e.length == 4
+ ? ((n = "0x" + e[1] + e[1]), (r = "0x" + e[2] + e[2]), (c = "0x" + e[3] + e[3]))
+ : e.length == 7 && ((n = "0x" + e[1] + e[2]), (r = "0x" + e[3] + e[4]), (c = "0x" + e[5] + e[6])),
+ (n /= 255),
+ (r /= 255),
+ (c /= 255);
+ let m = Math.min(n, r, c),
+ R = Math.max(n, r, c),
+ F = R - m,
+ U = 0,
+ H = 0,
+ J = 0;
+ return (
+ F == 0
+ ? (U = 0)
+ : R == n
+ ? (U = ((r - c) / F) % 6)
+ : R == r
+ ? (U = (c - n) / F + 2)
+ : (U = (n - r) / F + 4),
+ (U = Math.round(U * 60)),
+ U < 0 && (U += 360),
+ (J = (R + m) / 2),
+ (H = F == 0 ? 0 : F / (1 - Math.abs(2 * J - 1))),
+ (H = +(H * 100).toFixed(1)),
+ (J = +(J * 100).toFixed(1)),
+ { h: U, s: H, l: J }
+ );
+ },
+ Qn = (e) => {
+ e = e.replace(/^#/, "");
+ let n, r, c;
+ return (
+ e.length === 3
+ ? ((n = parseInt(e[0] + e[0], 16)), (r = parseInt(e[1] + e[1], 16)), (c = parseInt(e[2] + e[2], 16)))
+ : ((n = parseInt(e.slice(0, 2), 16)),
+ (r = parseInt(e.slice(2, 4), 16)),
+ (c = parseInt(e.slice(4, 6), 16))),
+ { r: n, g: r, b: c }
+ );
+ },
+ tn = (e) => {
+ const { r: n, g: r, b: c } = Qn(e);
+ return 0.2126 * n + 0.7152 * r + 0.0722 * c;
+ },
+ en = (e) => jn(Hn(e));
+for (let e = 0; e < 100; e++) t.random();
+const Jn = !0,
+ Kn = !1,
+ to = 4,
+ eo = "l";
+let gn = t.int(3, 15),
+ kt = eo,
+ yn = kt == "h" && t.bool(0);
+kt == "l" && t.bool(0.005) && (kt = "m");
+const no = "none",
+ pn = 1.2;
+let de = !1,
+ mn = kt !== "h" && t.bool(0.07);
+const oo = kt == "h" ? "grandeur" : "Un air de grandeur",
+ x = {
+ GRIBOUILLIS: "gribouillis",
+ GRANDEUR: oo,
+ VERTICAL: "vertical",
+ HORIZONTAL: "horizontal",
+ GRID: "grid",
+ UNGRID: "ungrid",
+ FIELD: "field",
+ LANDSCAPE: "landscape",
+ CONCENTRIC: "concentric",
+ LINEAR: "linear",
+ PRIMITIVES: "primitives",
+ INTERSECTIONS: "intersections",
+ OPRIMITIVES: "oprimitives",
+ OINTERSECTIONS: "ointersections",
+ ROOM: "room",
+ RANDOMLINES: "randomLines",
+ PRIMGRID: "primgrid",
+ ROTATEDGRID: "rotatedgrid",
+ FULLGRID: "fullgrid",
+ },
+ so = {
+ [x.GRIBOUILLIS]: "Gestuelle: gribouillis",
+ [x.GRANDEUR]: kt == "h" ? "Ext\xE9rieur" : "Gestuelle: gros gribouillis",
+ [x.VERTICAL]: "\xC9chauffement: vertical",
+ [x.HORIZONTAL]: "\xC9chauffement: horizontal",
+ [x.GRID]: "Structure: grille",
+ [x.UNGRID]: "Structure: grille moins uniforme",
+ [x.FIELD]: "La base",
+ [x.CONCENTRIC]: "Structure: r\xE9p\xE9tition concentrique",
+ [x.LINEAR]: "Structure: r\xE9p\xE9tition lin\xE9aire",
+ [x.PRIMITIVES]: "Structure: primitives opaques",
+ [x.INTERSECTIONS]: "Structure: primitives transparentes",
+ [x.OPRIMITIVES]: "Structure: primitives opaques et organiques",
+ [x.OINTERSECTIONS]: "Structure: primitives transparentes et organiques",
+ [x.LANDSCAPE]: "Structure: paysage",
+ [x.ROOM]: "Contexte: int\xE9rieur",
+ [x.RANDOMLINES]: "Structure: lignes al\xE9atoires",
+ [x.PRIMGRID]: "Structure: grille",
+ };
+let Jt = [x.PRIMITIVES, x.INTERSECTIONS, x.OPRIMITIVES, x.OINTERSECTIONS],
+ Ne = [];
+const io = t.random();
+io < 1e-4 && kt == "h" && (Ne = [x.FULLGRID]);
+t.bool(0.01) && kt !== "h" && (Ne = [x.GRIBOUILLIS]);
+t.bool(0.5) &&
+ ((de = kt !== "h" && t.bool(1 / 15)),
+ (Jt = Jt.concat([
+ x.VERTICAL,
+ x.HORIZONTAL,
+ x.GRID,
+ x.UNGRID,
+ x.FIELD,
+ x.CONCENTRIC,
+ x.LINEAR,
+ x.ROOM,
+ x.GRANDEUR,
+ ])));
+kt == "h" &&
+ ((de = t.bool(0.008)),
+ (Jt = Jt.filter((e) => e !== x.HORIZONTAL && e !== x.FIELD)),
+ (Jt = [
+ x.GRANDEUR,
+ x.UNGRID,
+ x.CONCENTRIC,
+ x.LINEAR,
+ x.PRIMITIVES,
+ x.INTERSECTIONS,
+ x.OPRIMITIVES,
+ x.OINTERSECTIONS,
+ x.ROOM,
+ x.PRIMGRID,
+ x.ROTATEDGRID,
+ ]));
+de && (Jt = [x.VERTICAL, x.PRIMITIVES, x.OPRIMITIVES]);
+let q = [];
+if (kt == "h") {
+ const e = t.random() < 0.5 ? 1 : t.int(2, 4);
+ if (t.bool(0.5) && e > 1) {
+ const r = t.bool(0.5);
+ r ? q.push(x.ROOM) : q.push(x.GRANDEUR), t.bool(0.5) && (r ? q.push(x.GRANDEUR) : q.push(x.ROOM));
+ }
+ for (; q.length < e; ) {
+ let r = Jt.filter((m) => m !== x.ROOM && m !== x.GRANDEUR);
+ const c = t.pick(r);
+ q.includes(c) || q.push(c);
+ }
+ if (
+ (t.bool(0.5) && !q.includes(x.ROOM) && q.push(x.ROOM),
+ q.length == 1 && (q[0] == x.PRIMGRID || q[0] == x.UNGRID || q[0] == x.ROTATEDGRID))
+ ) {
+ let r = Jt.filter((c) => c !== x.PRIMGRID && c !== x.UNGRID && c !== x.ROTATEDGRID);
+ q.push(t.pick(r));
+ }
+ q.includes(x.PRIMGRID) && (q = [x.PRIMGRID, ...q.filter((r) => r !== x.PRIMGRID)]);
+ let n = 0.5;
+ q.includes(x.GRANDEUR) && (n = 0.2), q.includes(x.FULLGRID) && (n = 0.8), t.bool(n) && q.push(x.RANDOMLINES);
+} else {
+ const e = t.int(0, Jt.length - 1),
+ n = Jt[e];
+ if ((q.push(n), t.bool(0.03))) {
+ const r = Jt.filter((c) => c !== x.FIELD && !q.includes(c));
+ r.length > 0 && q.push(r[t.int(0, r.length - 1)]);
+ }
+ if (de) {
+ const r = t.int(1, 3);
+ for (gn = t.int(1, 5), q = []; q.length < r; ) {
+ const c = t.pick(Jt);
+ q.includes(c) || q.push(c);
+ }
+ t.bool(0.3) && (q = [x.FIELD]);
+ }
+}
+t.bool(0.01) && (q = [x.ROOM]);
+t.bool(0.01) && (q = [x.GRANDEUR]);
+Ne.length > 0 && (q = Ne);
+kt !== "h" && q.includes(x.GRANDEUR) && (mn = !0);
+q.includes(x.ROOM) && t.bool(0.3) && (q = [...q.filter((e) => e !== x.ROOM), x.ROOM]);
+const bn = 100,
+ lo = [420, 595],
+ jt = lo,
+ nn = 1.5;
+{
+ const e = jt[0];
+ (jt[0] = jt[1]), (jt[1] = e);
+}
+jt[0] = jt[0] * (bn / 72);
+jt[1] = jt[1] * (bn / 72);
+jt[0] *= pn;
+jt[1] *= pn;
+const ro = 12;
+let xn = 1;
+if (t.bool(0.995)) {
+ const e = t.bool(0.7) ? 3 : 2;
+ xn = t.int(e, ro);
+}
+let ce = We([...$e]).slice(0, xn);
+t.bool(0.015) && (ce = ["#D4011D", "#EB6E81", "#FECD1A", "#0262A7", "#628B2A", "#000000"]);
+t.bool(0.001) && (ce = We($e));
+t.bool(0.02) &&
+ ((ce = ["#757575", "#616161", "#424242", "#212121", "#010101"]),
+ t.bool(0.5) && (ce = t.bool(0.5) ? ["#424242", "#212121"] : ["#757575"]));
+ce = We(ce);
+let Ve = Array.from(ce).sort((e, n) => {
+ const r = Math.round(tn(e) * 1e6) / 1e6;
+ return Math.round(tn(n) * 1e6) / 1e6 - r;
+});
+for (let e = 0; e < Ve.length; e++)
+ console.log(`%c ${Ve[e]} `, `background: ${Ve[e]}; color: white; padding: 2px 5px; border-radius: 2px;`);
+let In = kt == "h" ? t.bool(0.15) : t.bool(0.03),
+ Mn = "#eae4cc",
+ Sn = In ? t.pick(ce) : Mn,
+ co = kt == "h" ? t.bool(0) : !1,
+ ao = q.length == 1 && q[0] == x.GRANDEUR && t.bool(0.1),
+ ho = t.int(1, 5),
+ qe = ["c"];
+yn && ((kt = "m"), (qe = ["b", "c"]));
+let Kt = ["o", "oc"],
+ fo = !0,
+ Cn = t.bool(0.75) && !yn ? 1.2 : t.range(0, 0.4),
+ Ze = t.bool(0.99) ? 0 : t.range(0, 1),
+ je = t.random(),
+ xe = 1;
+je < 0.7 && (xe = 0);
+je < 0.5 && (xe = t.range(0.6, 1));
+je < 0.3 && (xe = t.range(0.15, 0.4));
+let Rn = [1],
+ kn = kt == "h" ? t.pick([0.6, 1]) : 1,
+ uo = t.bool(0.5) ? 0 : t.range(0.2, 1.4),
+ vn = t.bool(0.5) || t.bool(0.03) ? 1 : t.range(0, 1),
+ Ie = t.bool(0.9) ? t.range(0.05, 0.25) : 0.5,
+ go = t.bool(0.99) ? t.range(0.2, 0.27) * t.pick([1, 3, 5]) : 5,
+ yo = t.bool(0.2),
+ po = t.bool(0.3),
+ Te = !1;
+const mo = t.pick([
+ ["bottom", "right"],
+ ["bottom", "left"],
+ ["bottom", "left", "right"],
+]);
+let He = 1,
+ bo = t.pick([0.5, 0.9, 1, 1]);
+kt == "h" && ((Te = t.bool(0.0085)), (He = t.bool(0.8) ? 1 : 0.75));
+let wn = kt == "h" ? t.bool(0.92) : !0;
+q.length <= 2 && q.includes(x.CONCENTRIC) && (wn = !1);
+Te && q.includes(x.ROOM) && (q = [...q.filter((e) => e !== x.ROOM), x.ROOM]);
+He < 1 && ((Te = !1), (Ze = 0));
+let Dn = !1;
+kt !== "h" &&
+ q.length == 1 &&
+ (q[0] == x.PRIMITIVES || q[0] == x.INTERSECTIONS || q[0] == x.OPRIMITIVES || q[0] == x.OINTERSECTIONS) &&
+ (Dn = t.bool(0.01));
+const An = q.filter((e) => e !== x.ROOM && e !== x.GRANDEUR).length;
+let fe = t.bool(0.5);
+An >= 3 && !fe && (fe = t.bool(0.7));
+An == 1 && ((fe = t.bool(0.15)), q.includes(x.PRIMGRID) && !fe && (fe = t.bool(0.75)));
+kt !== "h" && (fe = !1);
+t.bool(0.02) && (Ie = 1);
+kt == "h" && (Ie = t.range(0.01, 0.1));
+((kt == "h" && t.bool(0.15)) || (kt !== "h" && t.bool(0.3))) && (Ie = 0);
+let we = kt == "h" || de ? !0 : t.bool(0.6);
+q.length == 1 && (q[0] == "horizontal" || q[0] == "vertical" || q[0] == "grid") && (we = !0);
+q.length == 1 && q[0] == x.GRIBOUILLIS && kt !== "h" && (we = !1);
+const xo = kt == "h" ? 0 : 0.3,
+ Io = kt == "h" ? 0.2 : 0.6;
+let Mo = t.bool(0.95) ? 0 : t.range(xo, Io),
+ On = 1,
+ En = Ie == 0 && kt == "h" ? t.range(0, 0.01) : 0.05,
+ _e = t.range(0.07, 0.15),
+ So = !1,
+ Co = kt == "h" ? t.bool(0.1) : t.bool(0.5),
+ Pn = kt == "h" ? t.bool(0.35) : t.bool(0.5);
+q.length == 1 && q[0] == x.GRANDEUR && (Pn = t.bool(0.65));
+(q.includes(x.VERTICAL) || q.includes(x.HORIZONTAL)) && (we = !0);
+let Ro = t.bool(0.5);
+kt !== "h" &&
+ qe.length == 1 &&
+ ((Cn = 2),
+ (Ze = 0),
+ (Sn = Mn),
+ (xe = t.bool(0.35) ? 1 : t.range(0, 0.6)),
+ !we && t.bool(0.5) && (xe = t.range(0, 0.7)),
+ (Rn = [1]),
+ (On = t.bool(0.5) ? 1 : t.range(0.1, 0.4)),
+ (En = t.bool(0.7) ? 0.05 : t.range(0.25, 0.5)),
+ (Kt = ["h", "o", "c", "v", "n"]),
+ t.bool(0.05) && (Kt = ["v"]),
+ (t.bool(0.005) || (de && t.bool(1.1))) && (Kt = ["h"]),
+ q.length == 1 && q[0] == "vertical" && (Kt = t.bool(0.5) ? ["h", "v", "n"] : ["v"]),
+ q.length == 1 && q[0] == "horizontal" && (Kt = t.bool(0.5) ? ["h", "v", "n"] : ["h"]),
+ q.length == 1 &&
+ q[0] == x.FIELD &&
+ ((kn = t.pick([0.3, 0.5, 0.5, 1, 1])),
+ t.bool(0.5) ? ((Kt = ["n"]), (_e = t.range(0.1, 0.35))) : ((Kt = ["c"]), (_e = t.range(0.3, 1))),
+ t.bool(0.05) && (kt = "m")));
+const ko = t.pick([[-5], [-0, -1, -2, -3, -4, -5]]),
+ vo = t.pick([[-5], [-5, -4, -3]]),
+ wo = t.pick([
+ [-5, -10],
+ [-6, -8],
+ ]);
+let Fn = { normOffsetOpts: wo, noiseScl: 3.5, noiseAmp: t.range(7, 15) },
+ Do = { normOffsetOpts: vo, noiseScl: 2, noiseAmp: t.range(7, 10) },
+ Qe = { normOffsetOpts: kt == "h" ? [-5] : ko, noiseScl: 3, noiseAmp: t.pick([1.5, 5, 1.5]) },
+ Ge = Qe;
+Ge = t.pick([Qe, Do, Fn]);
+Ge = Qe;
+Kt.length == 1 && Kt[0] == "v" && (Ge = Fn);
+Kt.length == 1 && Kt[0] == "h" && (vn = 0);
+const d = {
+ isBuild: Jn,
+ batching: Kn,
+ dimensions: { base: jt, final: [jt[0] * nn, jt[1] * nn], debugScl: 0.3, rebelleScl: 2 },
+ useColorBg: In,
+ backgroundColor: Sn,
+ palette: ce,
+ comps: q,
+ availableComps: Jt,
+ NB_FRAMES: 240,
+ targetFPS: 60,
+ animate: !1,
+ plotMode: no,
+ density: kt,
+ tangentModeOpts: Kt,
+ fillBackground: fo,
+ isLandscape: de,
+ presence: "l",
+ skipContour: xe,
+ simline: 1,
+ rotateSkew: uo,
+ contained: vn,
+ neg: Cn,
+ negMode: kt == "h" ? t.pick(["f", "f"]) : t.pick(["e"]),
+ bfill: we,
+ gradient: Ze,
+ colorrep: t.bool(0.7) ? "r" : "n",
+ isStrokeColorFromB: Mo,
+ othercolor: Ie,
+ othercolorScl: go,
+ darkOtherColorInBg: yo,
+ dirtyBgColor: po,
+ fuzinessOpts: Rn,
+ tScl: kn,
+ geomOffset: Ge,
+ multiplyAmount: En,
+ baseEllipseWidthScl: On,
+ compNseScl: _e,
+ mpress: So,
+ rough: mn,
+ sim: Co,
+ smalls: Pn,
+ uniformBg: co,
+ isolation: ao,
+ nbIsolated: ho,
+ bonly: Dn,
+ masks: fe,
+ windo: Ro,
+ light: Te,
+ lightSides: mo,
+ press: He,
+ vstrokes: wn,
+ vgridSpacing: t.pick([5, 10]),
+ maskChance: bo,
+ gridSpacing: to,
+ shapes: { count: gn, size: [0.05 * jt[1], 0.5 * jt[1]] },
+ layers: qe,
+};
+let Le = "";
+kt !== "h" && (Le = q.length == 1 ? so[q[0]] : "mixed");
+Le !== "" && console.log(Le);
+window.$artifact = { features: { trait: Le } };
+function Ao(e) {
+ return { strideX: e[1], data: new Uint32Array(e[0] * e[1]) };
+}
+var Oo = Ao,
+ Eo = Oo,
+ Nn = Math.PI / 3,
+ ze = [
+ [0, 0],
+ [0, -1],
+ [-1, 0],
+ [1, 0],
+ [0, 1],
+ [-1, -1],
+ [1, -1],
+ [-1, 1],
+ [1, 1],
+ [0, -2],
+ [-2, 0],
+ [2, 0],
+ [0, 2],
+ [-1, -2],
+ [1, -2],
+ [-2, -1],
+ [2, -1],
+ [-2, 1],
+ [2, 1],
+ [-1, 2],
+ [1, 2],
+ ],
+ Po = ze.length;
+function Ut(e, n) {
+ (this.width = e.shape[0]),
+ (this.height = e.shape[1]),
+ (this.radius = e.radius || e.minDistance),
+ (this.maxTries = Math.max(3, Math.ceil(e.tries || 30))),
+ (this.rng = n || Math.random);
+ const c = 1e-14 * Math.max(1, (Math.max(this.width, this.height) / 64) | 0),
+ m = 2e-14;
+ (this.squaredRadius = this.radius * this.radius),
+ (this.radiusPlusEpsilon = this.radius + c),
+ (this.cellSize = this.radius * Math.SQRT1_2),
+ (this.angleIncrement = (Math.PI * 2) / this.maxTries),
+ (this.angleIncrementOnSuccess = Nn + m),
+ (this.triesIncrementOnSuccess = Math.ceil(this.angleIncrementOnSuccess / this.angleIncrement)),
+ (this.processList = []),
+ (this.samplePoints = []),
+ (this.gridShape = [Math.ceil(this.width / this.cellSize), Math.ceil(this.height / this.cellSize)]),
+ (this.grid = Eo(this.gridShape));
+}
+Ut.prototype.width = null;
+Ut.prototype.height = null;
+Ut.prototype.radius = null;
+Ut.prototype.radiusPlusEpsilon = null;
+Ut.prototype.squaredRadius = null;
+Ut.prototype.cellSize = null;
+Ut.prototype.angleIncrement = null;
+Ut.prototype.angleIncrementOnSuccess = null;
+Ut.prototype.triesIncrementOnSuccess = null;
+Ut.prototype.maxTries = null;
+Ut.prototype.rng = null;
+Ut.prototype.processList = null;
+Ut.prototype.samplePoints = null;
+Ut.prototype.gridShape = null;
+Ut.prototype.grid = null;
+Ut.prototype.addRandomPoint = function () {
+ return this.directAddPoint([this.rng() * this.width, this.rng() * this.height, this.rng() * Math.PI * 2, 0]);
+};
+Ut.prototype.addPoint = function (e) {
+ var n = e.length === 2 && e[0] >= 0 && e[0] < this.width && e[1] >= 0 && e[1] < this.height;
+ return n ? this.directAddPoint([e[0], e[1], this.rng() * Math.PI * 2, 0]) : null;
+};
+Ut.prototype.directAddPoint = function (e) {
+ var n = [e[0], e[1]];
+ this.processList.push(e), this.samplePoints.push(n);
+ var r = ((e[0] / this.cellSize) | 0) * this.grid.strideX + ((e[1] / this.cellSize) | 0);
+ return (this.grid.data[r] = this.samplePoints.length), n;
+};
+Ut.prototype.inNeighbourhood = function (e) {
+ var n = this.grid.strideX,
+ r = this.gridShape[0],
+ c = this.gridShape[1],
+ m = (e[0] / this.cellSize) | 0,
+ R = (e[1] / this.cellSize) | 0,
+ F,
+ U,
+ H,
+ J,
+ L;
+ for (F = 0; F < Po; F++)
+ if (
+ ((H = m + ze[F][0]),
+ (J = R + ze[F][1]),
+ (U = H < 0 || J < 0 || H >= r || J >= c ? -1 : H * n + J),
+ U !== -1 &&
+ this.grid.data[U] !== 0 &&
+ ((L = this.samplePoints[this.grid.data[U] - 1]),
+ Math.pow(e[0] - L[0], 2) + Math.pow(e[1] - L[1], 2) < this.squaredRadius))
+ )
+ return !0;
+ return !1;
+};
+Ut.prototype.next = function () {
+ for (var e, n, r, c; this.processList.length > 0; ) {
+ var m = (this.processList.length * this.rng()) | 0;
+ for (
+ n = this.processList[m], r = n[2], e = n[3], e === 0 && (r = r + (this.rng() - 0.5) * Nn * 4);
+ e < this.maxTries;
+ e++
+ ) {
+ if (
+ ((c = [n[0] + Math.cos(r) * this.radiusPlusEpsilon, n[1] + Math.sin(r) * this.radiusPlusEpsilon, r, 0]),
+ c[0] >= 0 && c[0] < this.width && c[1] >= 0 && c[1] < this.height && !this.inNeighbourhood(c))
+ )
+ return (
+ (n[2] = r + this.angleIncrementOnSuccess + this.rng() * this.angleIncrement),
+ (n[3] = e + this.triesIncrementOnSuccess),
+ this.directAddPoint(c)
+ );
+ r = r + this.angleIncrement;
+ }
+ if (e >= this.maxTries) {
+ const R = this.processList.pop();
+ m < this.processList.length && (this.processList[m] = R);
+ }
+ }
+ return null;
+};
+Ut.prototype.fill = function () {
+ for (this.samplePoints.length === 0 && this.addRandomPoint(); this.next(); );
+ return this.samplePoints;
+};
+Ut.prototype.getAllPoints = function () {
+ return this.samplePoints;
+};
+Ut.prototype.reset = function () {
+ var e = this.grid.data,
+ n;
+ for (n = 0; n < e.length; n++) e[n] = 0;
+ (this.samplePoints = []), (this.processList.length = 0);
+};
+var Ln = Ut;
+const on = d.shapes.count,
+ Fo = () => {
+ t.random();
+ let e = d.dimensions.base[0],
+ n = d.dimensions.base[1],
+ r = e / n,
+ c = null,
+ m = null,
+ R = null,
+ F = null,
+ U = -1,
+ H = [],
+ J = 1;
+ d.density == "h" && (J = 4);
+ let L = [],
+ yt = [];
+ const vt = () => {},
+ St = () => c,
+ ot = () => R,
+ mt = () => {
+ const C = ft(e / 2 - e * 0.05, n - n * t.range(0.1, 0.18), e * 1.1, n * 0.4, 0, 10),
+ P = d.density == "h" ? !0 : t.bool(0.5);
+ let A = t.pick([0, 0.5, 1]);
+ const s = 0.03 * e;
+ for (let h = 0; h < C.length; h++) {
+ const o = C[h].x / e,
+ l = C[h].y / n,
+ a = 0,
+ p = 0;
+ let f = s;
+ (f *= Bt(l, 0.7, 1, 1, 0)),
+ (C[h].x += t.n2D((o * r + a) * A * r, (l + a) * A) * f),
+ (C[h].y += t.n2D((o * r + p) * A * r, (l + p) * A) * f);
+ }
+ L.push({ points: C, isFilled: P, fillColor: "white", strokeColor: "black" });
+ },
+ j = (C = e / 2, P = n / 2) => {
+ const A = t.range(0.8, 1.5),
+ s = e * t.range(0.2, 0.35) * A,
+ h = n * t.range(0.2, 0.6) * A;
+ let o = J == 1 ? t.bool(0.15) : t.bool(0.5);
+ d.light && (o = !1), (C = t.range(e * 0.25, e * 0.75)), (P = t.range(n * 0.25, n * 0.75));
+ const l = t.bool(0.5) ? 0 : t.range(-Math.PI / 6, Math.PI / 6);
+ let a = d.density == "h" ? t.bool(0.5) : !1;
+ d.windo && (a = !1), d.light && d.lightSides.includes("bottom") && (a = !0);
+ const p = C - s / 2,
+ f = C + s / 2,
+ y = P - h / 2,
+ u = P + h / 2,
+ v = (G, $, Z, O, B) => {
+ const bt = G - Z,
+ ut = $ - O;
+ return {
+ x: Z + (bt * Math.cos(B) - ut * Math.sin(B)),
+ y: O + (bt * Math.sin(B) + ut * Math.cos(B)),
+ };
+ },
+ _ = v(p, y, C, P, l),
+ g = v(f, y, C, P, l),
+ b = v(f, u, C, P, l),
+ E = v(p, u, C, P, l),
+ z = ft(C, P, s, h, l, 10);
+ if ((L.push({ points: z, isFilled: !1, fillColor: "white", strokeColor: "black" }), !o)) {
+ const G = (d.density == "h" && t.bool(0.05)) || (d.light && d.lightSides.includes("top"));
+ L.push({
+ points: [{ x: 0, y: 0 }, _, g, { x: e, y: 0 }],
+ isFilled: G,
+ isDoorSide: !0,
+ side: "top",
+ });
+ const $ = (d.density == "h" && t.bool(0.05)) || (d.light && d.lightSides.includes("right"));
+ L.push({
+ points: [{ x: e, y: 0 }, g, b, { x: e, y: n }],
+ isFilled: $,
+ isDoorSide: !0,
+ side: "right",
+ });
+ const Z = (d.density == "h" && t.bool(0.05)) || (d.light && d.lightSides.includes("left"));
+ L.push({
+ points: [{ x: 0, y: 0 }, _, E, { x: 0, y: n }],
+ isFilled: Z,
+ isDoorSide: !0,
+ side: "left",
+ });
+ }
+ L.push({
+ points: [{ x: 0, y: n }, E, b, { x: e, y: n }],
+ isFilled: a,
+ fillColor: "white",
+ strokeColor: "black",
+ isDoorSide: !0,
+ side: "bottom",
+ });
+ },
+ st = () => {
+ let C = t.bool(0.5) ? 1 : t.int(2, J);
+ for (let P = 0; P < C; P++) j();
+ },
+ W = (C, P, A, s, h, o = 0, l = 0, a = 1, p = 1) => {
+ const f = N(),
+ y = A / h,
+ u = s / h,
+ v = ft(C, P, A, s, o, 20);
+ L.push({
+ bb: { x: C, y: P, width: A, height: s, rotation: o },
+ points: v,
+ isFilled: !1,
+ fillColor: "white",
+ strokeColor: "black",
+ type: "boundingBox",
+ func: x.ROTATEDGRID,
+ mask: f,
+ }),
+ t.bool(l);
+ const _ = t.bool(a),
+ g = t.bool(p),
+ b = [5, 45, 60, 90, 120],
+ E = t.pick(b),
+ z = t.bool(0.5);
+ for (let G = 0; G < h; G++)
+ for (let $ = 0; $ < h; $++) {
+ let Z = C - A / 2 + y * G + y / 2,
+ O = P - s / 2 + u * $ + u / 2;
+ const B = Z - C,
+ bt = O - P,
+ ut = C + (B * Math.cos(o) - bt * Math.sin(o)),
+ Tt = P + (B * Math.sin(o) + bt * Math.cos(o)),
+ Et = ft(ut, Tt, y, u, o, 10);
+ t.range(10, 5) * 0.3;
+ for (let Ft = 0; Ft < Et.length; Ft++) Et[Ft].x / e, Et[Ft].y / n;
+ if (
+ (L.push({ points: Et, isFilled: _, fillColor: "white", strokeColor: "black", mask: f }),
+ t.bool(l))
+ ) {
+ const Ft = y > u ? u : y,
+ wt = z ? E : t.pick(b),
+ Gt = xt(ut, Tt, Ft * 0.45, o, wt);
+ L.push({ points: Gt, isFilled: g, fillColor: "white", strokeColor: "black", mask: f });
+ }
+ }
+ },
+ K = (C = 0, P = 1, A = 1) => {
+ const s = t.bool(0.5) ? 1 : t.int(2, 3),
+ h = t.bool(0.5),
+ o = t.bool(0.5),
+ l = t.bool(0.5) ? 1 : 0.5,
+ a = t.bool(0.5) ? 1 : 0.5;
+ for (let p = 0; p < s; p++) {
+ const f = t.range(0, e),
+ y = t.range(0, n),
+ u = f / e,
+ v = y / n,
+ _ = t.range(e * 0.2, e * l),
+ g = t.range(n * 0.2, n * a),
+ b = t.int(1, 4);
+ let E = o ? t.n2D(u, v) * Math.PI * 2 : t.range(0, Math.PI * 2);
+ h || (E = 0), W(f, y, _, g, b, E, C, P, A);
+ }
+ },
+ Q = () => {
+ const C = e / 2,
+ P = n / 2,
+ A = 1 * e,
+ s = 1 * n,
+ h = t.int(6, 10),
+ o = 0,
+ l = t.bool(0.5) ? 1 : t.range(0.2, 1),
+ a = t.bool(0.5) ? 1 : t.range(0.2, 1),
+ p = t.bool(0.5) ? 1 : t.range(0, 1);
+ W(C, P, A, s, h, o, l, a, p);
+ },
+ it = (C = "y", P = [0, 0]) => {
+ const A = t.int(2, 10),
+ s = C === "y",
+ h = N();
+ for (let o = 0; o < A; o++) {
+ const l = ((s ? e : n) / A) * o,
+ a = [],
+ p = t.range(P[0], P[1]),
+ f = 0;
+ if (t.bool(f)) continue;
+ const u = s ? n : e;
+ for (let v = 0; v <= u + A * 2; v += A) a.push({ x: s ? l : v + p, y: s ? v + p : l });
+ L.push({ points: a, isFilled: !1, mask: h });
+ }
+ },
+ M = () => {
+ const C = ft(e / 2, n / 2, e, n, 0, 10);
+ L.push({ points: C, isFilled: !0, fillColor: "white", strokeColor: "black" });
+ },
+ I = (C = [0, 0]) => {
+ it("y", C);
+ },
+ i = (C = [0, 0]) => {
+ it("x", C);
+ },
+ k = () => {
+ const C = { x: 0, y: 0, width: e, height: n },
+ P = t.int(4, 8),
+ A = e / (P + 1),
+ s = n * 0.3,
+ h = n * 0.8;
+ for (let o = 1; o <= P; o++) {
+ let l = A * o,
+ a = t.range(s, h),
+ p = (n - a) / 2,
+ f = p + a;
+ (l = Bt(l, 0, e, C.x, C.x + C.width)),
+ (p = Bt(p, 0, n, C.y, C.y + C.height)),
+ (f = Bt(f, 0, n, C.y, C.y + C.height));
+ const y = [
+ { x: l, y: p },
+ { x: l, y: f },
+ ];
+ L.push({ points: y, isFilled: !1 });
+ }
+ },
+ S = (C = 30, P = 100, A = e * 0.01, s = 5, h = [0.2, 0.8]) => {
+ for (let o = 0; o < C; o++) {
+ const l = [];
+ let a = t.range(e * h[0], e * h[1]),
+ p = t.range(n * h[0], n * h[1]),
+ f = t.range(0, Math.PI * 2);
+ l.push({ x: a, y: p });
+ for (let y = 0; y < P; y++) {
+ const u = t.n2D(a * 0.01, p * 0.01) * s;
+ (f += u),
+ (a += Math.cos(f) * A),
+ (p += Math.sin(f) * A),
+ (a = Wt(a, 0, e)),
+ (p = Wt(p, 0, n)),
+ l.push({ x: a, y: p });
+ }
+ L.push({ points: l, isFilled: !1 });
+ }
+ },
+ D = () => {
+ const C = t.int(1, 15),
+ P = t.bool(0.5) ? 0.5 : 0;
+ for (let A = 0; A < C; A++)
+ if (t.bool(P)) {
+ const h = t.range(0, e),
+ o = t.range(0, n),
+ l = t.range(0, Math.PI * 2),
+ a = t.range(e * 0.1, e * 0.3),
+ p = 100,
+ f = t.range(Math.PI * 0.7, Math.PI * 1.5),
+ y = [];
+ for (let u = 0; u < p; u++) {
+ const v = Bt(u, 0, p, 0, f),
+ _ = h + Math.cos(v + l) * a,
+ g = o + Math.sin(v + l) * a;
+ y.push({ x: _, y: g });
+ }
+ L.push({ points: y, isFilled: !1 });
+ } else {
+ const h = t.range(0, e),
+ o = t.range(0, n),
+ l = t.range(0, Math.PI * 2),
+ a = t.range(e * 0.2, e * 0.8),
+ p = h + Math.cos(l) * a,
+ f = o + Math.sin(l) * a,
+ y = [
+ { x: h, y: o },
+ { x: p, y: f },
+ ];
+ L.push({ points: y, isFilled: !1 });
+ }
+ },
+ nt = () => {
+ const C = N(),
+ P = t.range(0, Math.PI * 2),
+ A = t.int(3, 15),
+ s = t.bool(0.5),
+ h = t.pick([1, 10, 45, 90, 120]),
+ o = t.bool(0.5),
+ l = t.range(0, Math.PI * 2);
+ for (let a = A; a > 0; a--) {
+ let p = a / A,
+ f = (a + 1) / A,
+ y = 0.8 * e * f,
+ u = e / 2,
+ v = n / 2,
+ _ = o ? p + Math.sin(Math.PI * 2 * t.random()) * 0.1 + P : l,
+ g = ft(u, v, y, y, _, 10),
+ b = s ? h : t.pick([1, 10, 45, 90, 120]);
+ t.bool(1.5) && (g = xt(u, v, y, _, b));
+ const z = { points: g, isFilled: !1, mask: C };
+ L.push(z);
+ }
+ },
+ Y = () => {
+ const C = t.int(2, 3);
+ let P = d.windo ? e * t.range(0, 0.1) : 0,
+ A = d.windo ? n * t.range(0, 0.1) : 0;
+ t.bool(0.2) && (P = A = t.range(0, 0.1) * e);
+ const h = e - P * 2,
+ l = (n - A * 2) / C,
+ a = Math.floor(h / l),
+ p = l * 0.85,
+ f = l,
+ y = t.bool(0.5),
+ u = t.pick([1, 10, 45, 90, 120]);
+ t.range(0, Math.PI * 2);
+ const v = N();
+ for (let _ = 0; _ < C; _++)
+ for (let g = 0; g < a; g++) {
+ const b = P + g * l + l / 2,
+ E = A + _ * l + l / 2,
+ z = t.range(0, Math.PI * 2),
+ G = y ? u : t.pick([1, 10, 45, 90, 120]),
+ $ = ft(b, E, f, f, 0, G);
+ L.push({ points: $, isFilled: !1, fillColor: "white", strokeColor: "black", mask: v });
+ const Z = xt(b, E, p / 2, z, G);
+ L.push({ points: Z, isFilled: !1, fillColor: "white", strokeColor: "black", mask: v });
+ }
+ },
+ w = (C = 0.5, P = 0.5, A = 1) => {
+ const s = N(),
+ h = on,
+ o = t.bool(P),
+ l = n * t.range(0.5, 1),
+ a = t.bool(C),
+ p = t.pick([1, 45, 60, 90, 120]),
+ f = t.range(0, Math.PI),
+ y = e / h,
+ u = t.bool(0.5);
+ for (let v = 0; v < h * 2; v++) {
+ const _ = u ? e - v * y : v * y,
+ g = n / 2,
+ b = o ? l : l * t.range(1, 0.5),
+ E = f,
+ z = a ? p : t.pick([1, 5, 10, 45, 90, 120]),
+ G = xt(_, g, b, E, z);
+ t.pick([1, 5]);
+ let $ = t.bool(A);
+ for (let Z = 0; Z < G.length; Z++) G[Z].x / e, G[Z].y / n;
+ L.push({ points: G, isFilled: $, fillColor: "white", strokeColor: "black", mask: s });
+ }
+ },
+ X = (C = 1, P = 0) => {
+ const A = N(),
+ s = e / n,
+ h = t.range(0, Math.PI * 2),
+ o = t.bool(0.5);
+ let l = t.pick([1, 1, 10, 45, 90, 120]);
+ const a = t.bool(0.5) ? 1 : 0.5,
+ p = t.range(0.65, 1.5) * a;
+ let f = d.density == "h" ? t.bool(0.5) : !0,
+ y = 360;
+ d.density == "h" && (y = t.bool(0.7) ? 360 : 270);
+ const u = t.pick([1, 3, 5, t.pick([1, 5])]);
+ for (let v = 0; v < on; v++) {
+ let _ = Bt(Math.pow(t.random(), 1), 0, 1, 0.1, 0.6) * n * p;
+ const g = 0.1 * e;
+ let b = t.range(g, e - g),
+ E = t.range(g, n - g),
+ z = t.bool(P);
+ const G = 0.7,
+ $ = 1;
+ let Z = h + t.n2D(b * G, E * G) * $,
+ O = t.bool(C),
+ B = o ? l : t.pick([1, 1, 10, 45, 90, 120]),
+ bt = [],
+ ut = y;
+ d.density == "h" && !f && (ut = t.bool(0.5) ? 270 : 360), (bt = xt(b, E, _, Z, B, ut));
+ let Tt = u;
+ Array.isArray(u) && (Tt = t.pick(u));
+ const Et = 0.07 * e;
+ for (let wt = 0; wt < bt.length; wt++) {
+ const Gt = bt[wt].x / e,
+ Rt = bt[wt].y / n,
+ Ht = b,
+ Nt = E;
+ let Ot = Et;
+ z &&
+ ((bt[wt].x += t.n2D((Gt * s + Ht) * Tt * s, (Rt + Ht) * Tt) * Ot),
+ (bt[wt].y += t.n2D((Gt * s + Nt) * Tt * s, (Rt + Nt) * Tt) * Ot));
+ }
+ const Ft = { points: bt, isFilled: O, mask: A };
+ O && ((Ft.fillColor = "white"), (Ft.strokeColor = "black")), L.push(Ft);
+ }
+ },
+ V = (C = 0.5, P = 4) => {
+ const A = N(),
+ s = (a, p, f, y, u, v) => {
+ if (u <= 0 || (f < e * 0.1 && y < n * 0.1)) {
+ const b = t.range(-0.2, 0.2) * 0;
+ let E = ft(a + f / 2, p + y / 2, f, y, b, 10);
+ for (let z = 0; z < E.length; z++) {
+ const G = E[z].x / e,
+ $ = E[z].y / n;
+ t.n2D(G * 4, $ * 4) * 0.1 * e;
+ }
+ L.push({ points: E, isFilled: t.bool(0.5), mask: A });
+ return;
+ }
+ const _ = Bt(u, P, 0, 0.2, 0.4),
+ g = Bt(u, P, 0, 0.8, 0.6);
+ if (v) {
+ const b = f * t.range(_, g);
+ s(a, p, b, y, u - 1, !1), s(a + b, p, f - b, y, u - 1, !1);
+ } else {
+ const b = y * t.range(_, g);
+ s(a, p, f, b, u - 1, !0), s(a, p + b, f, y - b, u - 1, !0);
+ }
+ },
+ h = d.windo ? e * 0.1 : 0,
+ o = d.windo ? n * 0.05 : 0,
+ l = t.bool(0.5);
+ s(h, o, e - h * 2, n - o * 2, P, l);
+ },
+ N = () => (U++, U >= yt.length && (U = 0), yt[U]),
+ T = () => {
+ yt = [];
+ const C = (o, l, a, p, f, y) => {
+ if (f <= 0 || (a < e * 0.1 && p < n * 0.1)) {
+ const _ = ft(o + a / 2, l + p / 2, a, p, 0, 10),
+ g = t.pick([1, 2, 1, 2, 1, 2, 10]);
+ let b = t.bool(0.9) ? 0.07 : 0.17;
+ (b *= e), t.bool(0.5) && (b *= 0);
+ for (let E = 0; E < _.length; E++) {
+ const z = _[E].x / e,
+ G = _[E].y / n,
+ $ = o,
+ Z = l;
+ let O = b;
+ (_[E].x += t.n2D((z * r + $) * g * r, (G + $) * g) * O),
+ (_[E].y += t.n2D((z * r + Z) * g * r, (G + Z) * g) * O);
+ }
+ yt.push({ points: _, isFilled: !1, fillColor: "white", strokeColor: "black" });
+ return;
+ }
+ const u = Bt(f, s, 0, 0.1, 0.3),
+ v = Bt(f, s, 0, 0.9, 0.7);
+ if (y) {
+ const _ = a * t.range(u, v);
+ C(o, l, _, p, f - 1, !1), C(o + _, l, a - _, p, f - 1, !1);
+ } else {
+ const _ = p * t.range(u, v);
+ C(o, l, a, _, f - 1, !0), C(o, l + _, a, p - _, f - 1, !0);
+ }
+ },
+ P = d.windo ? e * 0.1 : 0,
+ A = d.windo ? n * 0.05 : 0;
+ H = d.comps.filter((o) => o !== x.ROOM && o !== x.GRANDEUR && o !== x.RANDOMLINES);
+ let s = H.length;
+ t.bool(0.5) && (s -= 1), (s = Wt(s, 1, 2)), t.bool(0.15) && (s = t.bool(0.5) ? 3 : 4);
+ const h = t.bool(0.5);
+ C(P, A, e - P * 2, n - A * 2, s, h),
+ (yt = yt
+ .map((o) => ({ value: o, sort: t.random() }))
+ .sort((o, l) => o.sort - l.sort)
+ .map(({ value: o }) => o)),
+ yt.length > 8 && d.smalls && (d.smalls = t.bool(0.2));
+ },
+ lt = (C) => {
+ for (let P = 0; P < C.length; P++) {
+ const A = C[P];
+ if (A === x.VERTICAL) t.bool(0.5) ? I() : V(1, t.int(3, 4));
+ else if (A === x.HORIZONTAL) i();
+ else if (A === x.GRID) I(), i();
+ else if (A === x.UNGRID) {
+ let s = t.range(0.15, 0.8);
+ (s = t.bool(0.2) ? 1 : s), (s = t.bool(0.2) ? 0 : s);
+ const h = d.density == "h" ? t.int(2, 4) : t.int(2, 6);
+ V(s, h);
+ } else if (A === x.FIELD) M();
+ else if (A === x.CONCENTRIC) nt();
+ else if (A === x.LINEAR) {
+ const s = d.density == "l" || t.bool(0.5) ? 1 : 0,
+ h = t.bool(0.5) ? 1 : 0,
+ o = t.bool(0.5) ? 1 : 0;
+ w(h, o, s);
+ } else if (A === x.PRIMITIVES) X(1, 0);
+ else if (A === x.INTERSECTIONS) {
+ const s = t.bool(0.5) ? t.range(0, 0.5) : 0;
+ X(s, 0);
+ } else if (A === x.OPRIMITIVES) X(1, 1);
+ else if (A === x.OINTERSECTIONS) {
+ const s = t.bool(0.5) ? t.range(0, 0.5) : 0;
+ X(s, 1);
+ } else if (A === x.ROOM) st();
+ else if (A === x.RANDOMLINES) D(), t.bool(0.3) && k();
+ else if (A === x.GRIBOUILLIS && d.density !== "h") {
+ const s = t.int(10, 30);
+ S(s);
+ } else if (A === x.GRIBOUILLIS && d.density == "h") {
+ let s = [0.1, 0.9],
+ h = 100,
+ o = 10,
+ l = e * 0.01;
+ S(h, o, l, 5, s);
+ } else if (A === x.GRANDEUR) {
+ let s = [0.2, 0.8],
+ h = 20,
+ o = 10,
+ l = e * 0.2,
+ a = 1;
+ t.bool(0.5) && ((h = 10), (o = t.pick([10])), (l = e * 0.2), (a = 2)), S(h, o, l, a, s);
+ } else if (A === x.PRIMGRID) Y();
+ else if (A === x.ROTATEDGRID) {
+ const s = t.bool(0.5) ? t.range(0.5, 1) : 0,
+ h = t.bool(0.5) ? 1 : 0,
+ o = t.bool(0.5) ? 1 : 0;
+ K(s, h, o);
+ } else A === x.FULLGRID && Q();
+ d.isLandscape && mt();
+ }
+ },
+ dt = (C = d.comps) => {
+ lt(C);
+ },
+ et = () => {
+ let C = d.comps;
+ if (
+ ((c = document.createElement("canvas")),
+ (c.width = e),
+ (c.height = n),
+ (c.style.width = `${e * d.dimensions.debugScl}px`),
+ (c.style.height = `${n * d.dimensions.debugScl}px`),
+ (m = c.getContext("2d")),
+ (R = document.createElement("canvas")),
+ (R.width = e),
+ (R.height = n),
+ (R.style.width = `${e * d.dimensions.debugScl}px`),
+ (R.style.height = `${n * d.dimensions.debugScl}px`),
+ (F = R.getContext("2d")),
+ (F.lineWidth = 4),
+ d.masks && T(),
+ d.masks && H.length < yt.length && t.bool(0.5))
+ ) {
+ const P = yt.length - H.length,
+ A = [
+ x.CONCENTRIC,
+ x.LINEAR,
+ x.PRIMITIVES,
+ x.INTERSECTIONS,
+ x.OPRIMITIVES,
+ x.OINTERSECTIONS,
+ x.VERTICAL,
+ x.HORIZONTAL,
+ ],
+ s = [];
+ for (let h = 0; h < P; h++) s.push(t.pick(A));
+ (C = [...C, ...s]), t.bool(0.3) && (C = [...C.filter((h) => h !== x.ROOM), x.ROOM]);
+ }
+ dt(C);
+ },
+ ft = (C, P, A, s, h, o) => {
+ const l = [],
+ a = { x: C, y: P },
+ p = C - A / 2,
+ f = P - s / 2;
+ for (let y = 0; y <= s; y += o) {
+ let u = p,
+ v = f + y;
+ (u = Wt(u, 0, e)), (v = Wt(v, 0, n)), l.push({ x: u, y: v });
+ }
+ for (let y = 0; y <= A; y += o) {
+ let u = p + y,
+ v = f + s;
+ (u = Wt(u, 0, e)), (v = Wt(v, 0, n)), l.push({ x: u, y: v });
+ }
+ for (let y = s; y >= 0; y -= o) {
+ let u = p + A,
+ v = f + y;
+ (u = Wt(u, 0, e)), (v = Wt(v, 0, n)), l.push({ x: u, y: v });
+ }
+ for (let y = A; y >= 0; y -= o) {
+ let u = p + y,
+ v = f;
+ (u = Wt(u, 0, e)), (v = Wt(v, 0, n)), l.push({ x: u, y: v });
+ }
+ for (let y = 0; y < l.length; y++) {
+ const u = l[y].x - a.x,
+ v = l[y].y - a.y;
+ l[y] = {
+ x: Wt(a.x + (u * Math.cos(h) - v * Math.sin(h)), 0, e),
+ y: Wt(a.y + (u * Math.sin(h) + v * Math.cos(h)), 0, n),
+ };
+ }
+ return l;
+ },
+ xt = (C, P, A, s, h, o = 360) => {
+ const l = [],
+ a = { x: C, y: P },
+ p = o;
+ for (let f = 0; f <= p; f += h) {
+ const y = (f * Math.PI) / 180;
+ l.push({ x: C + A * Math.cos(y), y: P + A * Math.sin(y) });
+ }
+ for (let f = 0; f < l.length; f++) {
+ const y = l[f].x - a.x,
+ u = l[f].y - a.y;
+ l[f] = {
+ x: Wt(a.x + (y * Math.cos(s) - u * Math.sin(s)), 0, e),
+ y: Wt(a.y + (y * Math.sin(s) + u * Math.cos(s)), 0, n),
+ };
+ }
+ for (let f = 0; f < l.length; f++) (l[f].x = Wt(l[f].x, 0, e)), (l[f].y = Wt(l[f].y, 0, n));
+ return l;
+ },
+ rt = (C, P = m) => {
+ const A = C.points,
+ s = C.isFilled,
+ h = C.fillColor || "white";
+ let o = A[0].x,
+ l = A[0].y;
+ P.save(), P.beginPath(), P.moveTo(o, l);
+ for (let a = 1; a < A.length; a++) {
+ const p = A[a];
+ let f = p.x,
+ y = p.y;
+ P.lineTo(f, y);
+ }
+ s
+ ? ((P.fillStyle = h), P.fill(), C.strokeColor && ((P.strokeStyle = C.strokeColor), P.stroke()))
+ : P.stroke(),
+ P.restore();
+ },
+ pt = () => {
+ F.clearRect(0, 0, e, n), (F.fillStyle = "white"), F.fillRect(0, 0, e, n);
+ for (let C = 0; C < yt.length; C++) rt(yt[C], F);
+ },
+ At = () => {
+ m.clearRect(0, 0, e, n), (m.fillStyle = "white"), m.fillRect(0, 0, e, n), (m.lineWidth = 4);
+ for (let C = 0; C < L.length; C++)
+ m.save(),
+ L[C].mask && d.masks && t.bool(d.maskChance) && (rt(L[C].mask), m.clip()),
+ rt(L[C]),
+ m.restore();
+ m.save(),
+ (m.strokeStyle = "black"),
+ (m.fillStyle = "white"),
+ (m.lineWidth = 4),
+ m.beginPath(),
+ m.rect(0, 0, e, n),
+ m.stroke(),
+ m.restore(),
+ pt();
+ },
+ It = () => {
+ At();
+ },
+ Lt = () => L;
+ return et(), { getCanvas: St, getShapes: Lt, getMasksCanvas: ot, pause: vt, render: It };
+ },
+ No = () => {
+ let e = d.dimensions.base[0],
+ n = d.dimensions.base[1],
+ r = null,
+ c = [];
+ const m = (L, yt) => {
+ const vt = L / e,
+ St = yt / n;
+ let ot = !1;
+ const mt = 5.5;
+ return t.n2D(vt * mt, St * mt) > d.neg && (ot = !0), ot;
+ },
+ R = (L, yt) => {
+ const vt = L / e,
+ St = yt / n;
+ let ot = t.pick(d.palette);
+ if (d.colorrep == "n") {
+ const mt = t.bool(0.85) ? 5.5 : 1.5;
+ let j = t.n2D(vt * mt, St * mt);
+ const st = Math.floor(Bt(j, -1, 1, 0, d.palette.length - 1));
+ ot = d.palette[st];
+ }
+ return ot;
+ },
+ F = () => {
+ let L = [];
+ const yt = e * t.range(0.07, 0.1);
+ L = new Ln({ shape: [e, n], radius: yt, tries: 20 }, t.random.bind(t));
+ var vt = L.fill();
+ for (let St = 0; St < vt.length; St++) {
+ const ot = vt[St];
+ let mt = R(ot[0], ot[1]);
+ const j = t.bool(0.5);
+ let st = {
+ skip: t.bool(d.skipContour),
+ opacity: t.range(0.03, 0.08) * 0.8,
+ strokeWidth: j ? 0.2 : t.range(0.07, 0.2),
+ },
+ W = m(ot[0], ot[1]);
+ W && (mt = d.backgroundColor),
+ c.push({ x: ot[0], y: ot[1], radius: yt * 0.5, color: mt, neg: W, contour: st });
+ }
+ },
+ U = () => {
+ F();
+ },
+ H = () => r,
+ J = () => c;
+ return U(), { getCanvas: H, getZones: J };
+ };
+var Lo = function () {
+ function e(M, I) {
+ (this.x = M), (this.y = I);
+ }
+ e.prototype.copy = function () {
+ return new e(this.x, this.y);
+ };
+ function n(M, I) {
+ (this.w = M),
+ (this.h = I),
+ (this.size = M * I),
+ (this.arraybuffer = new ArrayBuffer(this.size)),
+ (this.data = new Int8Array(this.arraybuffer));
+ }
+ (n.prototype.at = function (M, I) {
+ return M >= 0 && M < this.w && I >= 0 && I < this.h && this.data[this.w * I + M] === 1;
+ }),
+ (n.prototype.index = function (M) {
+ var I = new e();
+ return (I.y = Math.floor(M / this.w)), (I.x = M - I.y * this.w), I;
+ }),
+ (n.prototype.flip = function (M, I) {
+ this.at(M, I) ? (this.data[this.w * I + M] = 0) : (this.data[this.w * I + M] = 1);
+ }),
+ (n.prototype.copy = function () {
+ var M = new n(this.w, this.h),
+ I;
+ for (I = 0; I < this.size; I++) M.data[I] = this.data[I];
+ return M;
+ });
+ function r() {
+ (this.area = 0),
+ (this.len = 0),
+ (this.curve = {}),
+ (this.pt = []),
+ (this.minX = 1e5),
+ (this.minY = 1e5),
+ (this.maxX = -1),
+ (this.maxY = -1);
+ }
+ function c(M) {
+ (this.n = M),
+ (this.tag = new Array(M)),
+ (this.c = new Array(M * 3)),
+ (this.alphaCurve = 0),
+ (this.vertex = new Array(M)),
+ (this.alpha = new Array(M)),
+ (this.alpha0 = new Array(M)),
+ (this.beta = new Array(M));
+ }
+ var m = document.createElement("img"),
+ R = document.createElement("canvas"),
+ F = null,
+ U = [],
+ H,
+ J = { isReady: !1, turnpolicy: "minority", turdsize: 2, optcurve: !0, alphamax: 1, opttolerance: 0.2 };
+ m.onload = L;
+ function L() {
+ mt(), j();
+ }
+ function yt(M) {
+ J.isReady && Q(), (m.file = M);
+ var I = new FileReader();
+ (I.onload = (function (i) {
+ return function (k) {
+ i.src = k.target.result;
+ };
+ })(m)),
+ I.readAsDataURL(M);
+ }
+ function vt(M) {
+ J.isReady && Q(), (m.src = M);
+ }
+ function St(M) {
+ var I;
+ for (I in M) M.hasOwnProperty(I) && (J[I] = M[I]);
+ }
+ function ot(M) {
+ m = M;
+ }
+ function mt() {
+ (R.width = m.width), (R.height = m.height);
+ var M = R.getContext("2d");
+ M.drawImage(m, 0, 0);
+ }
+ function j() {
+ var M = R.getContext("2d");
+ F = new n(R.width, R.height);
+ var I = M.getImageData(0, 0, F.w, F.h),
+ i = I.data.length,
+ k,
+ S,
+ D;
+ for (k = 0, S = 0; k < i; k += 4, S++)
+ (D = 0.2126 * I.data[k] + 0.7153 * I.data[k + 1] + 0.0721 * I.data[k + 2]), (F.data[S] = D < 128 ? 1 : 0);
+ J.isReady = !0;
+ }
+ function st() {
+ var M = F.copy(),
+ I = new e(0, 0),
+ i;
+ function k(Y) {
+ for (var w = M.w * Y.y + Y.x; w < M.size && M.data[w] !== 1; ) w++;
+ return w < M.size && M.index(w);
+ }
+ function S(Y, w) {
+ var X, V, N;
+ for (X = 2; X < 5; X++) {
+ for (N = 0, V = -X + 1; V <= X - 1; V++)
+ (N += M.at(Y + V, w + X - 1) ? 1 : -1),
+ (N += M.at(Y + X - 1, w + V - 1) ? 1 : -1),
+ (N += M.at(Y + V - 1, w - X) ? 1 : -1),
+ (N += M.at(Y - X, w + V) ? 1 : -1);
+ if (N > 0) return 1;
+ if (N < 0) return 0;
+ }
+ return 0;
+ }
+ function D(Y) {
+ var w = new r(),
+ X = Y.x,
+ V = Y.y,
+ N = 0,
+ T = 1,
+ lt;
+ for (
+ w.sign = F.at(Y.x, Y.y) ? "+" : "-";
+ w.pt.push(new e(X, V)),
+ X > w.maxX && (w.maxX = X),
+ X < w.minX && (w.minX = X),
+ V > w.maxY && (w.maxY = V),
+ V < w.minY && (w.minY = V),
+ w.len++,
+ (X += N),
+ (V += T),
+ (w.area -= X * T),
+ !(X === Y.x && V === Y.y);
+
+ ) {
+ var dt = M.at(X + (N + T - 1) / 2, V + (T - N - 1) / 2),
+ et = M.at(X + (N - T - 1) / 2, V + (T + N - 1) / 2);
+ et && !dt
+ ? J.turnpolicy === "right" ||
+ (J.turnpolicy === "black" && w.sign === "+") ||
+ (J.turnpolicy === "white" && w.sign === "-") ||
+ (J.turnpolicy === "majority" && S(X, V)) ||
+ (J.turnpolicy === "minority" && !S(X, V))
+ ? ((lt = N), (N = -T), (T = lt))
+ : ((lt = N), (N = T), (T = -lt))
+ : et
+ ? ((lt = N), (N = -T), (T = lt))
+ : dt || ((lt = N), (N = T), (T = -lt));
+ }
+ return w;
+ }
+ function nt(Y) {
+ var w = Y.pt[0].y,
+ X = Y.len,
+ V,
+ N,
+ T,
+ lt,
+ dt,
+ et;
+ for (dt = 1; dt < X; dt++)
+ if (((V = Y.pt[dt].x), (N = Y.pt[dt].y), N !== w)) {
+ for (lt = w < N ? w : N, T = Y.maxX, et = V; et < T; et++) M.flip(et, lt);
+ w = N;
+ }
+ }
+ for (; (I = k(I)); ) (i = D(I)), nt(i), i.area > J.turdsize && U.push(i);
+ }
+ function W() {
+ function M() {
+ this.data = [0, 0, 0, 0, 0, 0, 0, 0, 0];
+ }
+ M.prototype.at = function (s, h) {
+ return this.data[s * 3 + h];
+ };
+ function I(s, h, o, l, a) {
+ (this.x = s), (this.y = h), (this.xy = o), (this.x2 = l), (this.y2 = a);
+ }
+ function i(s, h) {
+ return s >= h ? s % h : s >= 0 ? s : h - 1 - ((-1 - s) % h);
+ }
+ function k(s, h) {
+ return s.x * h.y - s.y * h.x;
+ }
+ function S(s, h, o) {
+ return s <= o ? s <= h && h < o : s <= h || h < o;
+ }
+ function D(s) {
+ return s > 0 ? 1 : s < 0 ? -1 : 0;
+ }
+ function nt(s, h) {
+ var o = new Array(3),
+ l,
+ a,
+ p;
+ for (o[0] = h.x, o[1] = h.y, o[2] = 1, p = 0, l = 0; l < 3; l++)
+ for (a = 0; a < 3; a++) p += o[l] * s.at(l, a) * o[a];
+ return p;
+ }
+ function Y(s, h, o) {
+ var l = new e();
+ return (l.x = h.x + s * (o.x - h.x)), (l.y = h.y + s * (o.y - h.y)), l;
+ }
+ function w(s, h) {
+ var o = new e();
+ return (o.y = D(h.x - s.x)), (o.x = -D(h.y - s.y)), o;
+ }
+ function X(s, h) {
+ var o = w(s, h);
+ return o.y * (h.x - s.x) - o.x * (h.y - s.y);
+ }
+ function V(s, h, o) {
+ var l, a, p, f;
+ return (l = h.x - s.x), (a = h.y - s.y), (p = o.x - s.x), (f = o.y - s.y), l * f - p * a;
+ }
+ function N(s, h, o, l) {
+ var a, p, f, y;
+ return (a = h.x - s.x), (p = h.y - s.y), (f = l.x - o.x), (y = l.y - o.y), a * y - f * p;
+ }
+ function T(s, h, o) {
+ var l, a, p, f;
+ return (l = h.x - s.x), (a = h.y - s.y), (p = o.x - s.x), (f = o.y - s.y), l * p + a * f;
+ }
+ function lt(s, h, o, l) {
+ var a, p, f, y;
+ return (a = h.x - s.x), (p = h.y - s.y), (f = l.x - o.x), (y = l.y - o.y), a * f + p * y;
+ }
+ function dt(s, h) {
+ return Math.sqrt((s.x - h.x) * (s.x - h.x) + (s.y - h.y) * (s.y - h.y));
+ }
+ function et(s, h, o, l, a) {
+ var p = 1 - s,
+ f = new e();
+ return (
+ (f.x = p * p * p * h.x + 3 * (p * p * s) * o.x + 3 * (s * s * p) * l.x + s * s * s * a.x),
+ (f.y = p * p * p * h.y + 3 * (p * p * s) * o.y + 3 * (s * s * p) * l.y + s * s * s * a.y),
+ f
+ );
+ }
+ function ft(s, h, o, l, a, p) {
+ var f, y, u, v, _, g, b, E, z, G;
+ return (
+ (f = N(s, h, a, p)),
+ (y = N(h, o, a, p)),
+ (u = N(o, l, a, p)),
+ (v = f - 2 * y + u),
+ (_ = -2 * f + 2 * y),
+ (g = f),
+ (b = _ * _ - 4 * v * g),
+ v === 0 || b < 0
+ ? -1
+ : ((E = Math.sqrt(b)),
+ (z = (-_ + E) / (2 * v)),
+ (G = (-_ - E) / (2 * v)),
+ z >= 0 && z <= 1 ? z : G >= 0 && G <= 1 ? G : -1)
+ );
+ }
+ function xt(s) {
+ var h, o, l;
+ (s.x0 = s.pt[0].x), (s.y0 = s.pt[0].y), (s.sums = []);
+ var a = s.sums;
+ for (a.push(new I(0, 0, 0, 0, 0)), h = 0; h < s.len; h++)
+ (o = s.pt[h].x - s.x0),
+ (l = s.pt[h].y - s.y0),
+ a.push(new I(a[h].x + o, a[h].y + l, a[h].xy + o * l, a[h].x2 + o * o, a[h].y2 + l * l));
+ }
+ function rt(s) {
+ var h = s.len,
+ o = s.pt,
+ l,
+ a = new Array(h),
+ p = new Array(h),
+ f = new Array(4);
+ s.lon = new Array(h);
+ var y = [new e(), new e()],
+ u = new e(),
+ v = new e(),
+ _ = new e(),
+ g,
+ b,
+ E,
+ z,
+ G,
+ $,
+ Z,
+ O,
+ B = 0;
+ for (b = h - 1; b >= 0; b--) o[b].x != o[B].x && o[b].y != o[B].y && (B = b + 1), (p[b] = B);
+ for (b = h - 1; b >= 0; b--) {
+ for (
+ f[0] = f[1] = f[2] = f[3] = 0,
+ l = (3 + 3 * (o[i(b + 1, h)].x - o[b].x) + (o[i(b + 1, h)].y - o[b].y)) / 2,
+ f[l]++,
+ y[0].x = 0,
+ y[0].y = 0,
+ y[1].x = 0,
+ y[1].y = 0,
+ B = p[b],
+ z = b;
+ ;
+
+ ) {
+ if (
+ ((g = 0),
+ (l = (3 + 3 * D(o[B].x - o[z].x) + D(o[B].y - o[z].y)) / 2),
+ f[l]++,
+ f[0] && f[1] && f[2] && f[3])
+ ) {
+ (a[b] = z), (g = 1);
+ break;
+ }
+ if (
+ ((u.x = o[B].x - o[b].x),
+ (u.y = o[B].y - o[b].y),
+ k(y[0], u) < 0 ||
+ k(y[1], u) > 0 ||
+ ((Math.abs(u.x) <= 1 && Math.abs(u.y) <= 1) ||
+ ((v.x = u.x + (u.y >= 0 && (u.y > 0 || u.x < 0) ? 1 : -1)),
+ (v.y = u.y + (u.x <= 0 && (u.x < 0 || u.y < 0) ? 1 : -1)),
+ k(y[0], v) >= 0 && ((y[0].x = v.x), (y[0].y = v.y)),
+ (v.x = u.x + (u.y <= 0 && (u.y < 0 || u.x < 0) ? 1 : -1)),
+ (v.y = u.y + (u.x >= 0 && (u.x > 0 || u.y < 0) ? 1 : -1)),
+ k(y[1], v) <= 0 && ((y[1].x = v.x), (y[1].y = v.y))),
+ (z = B),
+ (B = p[z]),
+ !S(B, b, z)))
+ )
+ break;
+ }
+ g === 0 &&
+ ((_.x = D(o[B].x - o[z].x)),
+ (_.y = D(o[B].y - o[z].y)),
+ (u.x = o[z].x - o[b].x),
+ (u.y = o[z].y - o[b].y),
+ (G = k(y[0], u)),
+ ($ = k(y[0], _)),
+ (Z = k(y[1], u)),
+ (O = k(y[1], _)),
+ (E = 1e7),
+ $ < 0 && (E = Math.floor(G / -$)),
+ O > 0 && (E = Math.min(E, Math.floor(-Z / O))),
+ (a[b] = i(z + E, h)));
+ }
+ for (E = a[h - 1], s.lon[h - 1] = E, b = h - 2; b >= 0; b--)
+ S(b + 1, a[b], E) && (E = a[b]), (s.lon[b] = E);
+ for (b = h - 1; S(i(b + 1, h), E, s.lon[b]); b--) s.lon[b] = E;
+ }
+ function pt(s) {
+ function h($, Z, O) {
+ var B = $.len,
+ bt = $.pt,
+ ut = $.sums,
+ Tt,
+ Et,
+ Ft,
+ wt,
+ Gt,
+ Rt,
+ Ht,
+ Nt,
+ Ot,
+ Yt,
+ tt,
+ ct,
+ at,
+ Ct,
+ Zt = 0;
+ return (
+ O >= B && ((O -= B), (Zt = 1)),
+ Zt === 0
+ ? ((Tt = ut[O + 1].x - ut[Z].x),
+ (Et = ut[O + 1].y - ut[Z].y),
+ (wt = ut[O + 1].x2 - ut[Z].x2),
+ (Ft = ut[O + 1].xy - ut[Z].xy),
+ (Gt = ut[O + 1].y2 - ut[Z].y2),
+ (Rt = O + 1 - Z))
+ : ((Tt = ut[O + 1].x - ut[Z].x + ut[B].x),
+ (Et = ut[O + 1].y - ut[Z].y + ut[B].y),
+ (wt = ut[O + 1].x2 - ut[Z].x2 + ut[B].x2),
+ (Ft = ut[O + 1].xy - ut[Z].xy + ut[B].xy),
+ (Gt = ut[O + 1].y2 - ut[Z].y2 + ut[B].y2),
+ (Rt = O + 1 - Z + B)),
+ (tt = (bt[Z].x + bt[O].x) / 2 - bt[0].x),
+ (ct = (bt[Z].y + bt[O].y) / 2 - bt[0].y),
+ (Ct = bt[O].x - bt[Z].x),
+ (at = -(bt[O].y - bt[Z].y)),
+ (Ht = (wt - 2 * Tt * tt) / Rt + tt * tt),
+ (Nt = (Ft - Tt * ct - Et * tt) / Rt + tt * ct),
+ (Ot = (Gt - 2 * Et * ct) / Rt + ct * ct),
+ (Yt = at * at * Ht + 2 * at * Ct * Nt + Ct * Ct * Ot),
+ Math.sqrt(Yt)
+ );
+ }
+ var o,
+ l,
+ a,
+ p,
+ f = s.len,
+ y = new Array(f + 1),
+ u = new Array(f + 1),
+ v = new Array(f),
+ _ = new Array(f + 1),
+ g = new Array(f + 1),
+ b = new Array(f + 1),
+ E,
+ z,
+ G;
+ for (o = 0; o < f; o++)
+ (G = i(s.lon[i(o - 1, f)] - 1, f)), G == o && (G = i(o + 1, f)), G < o ? (v[o] = f) : (v[o] = G);
+ for (l = 1, o = 0; o < f; o++) for (; l <= v[o]; ) (_[l] = o), l++;
+ for (o = 0, l = 0; o < f; l++) (g[l] = o), (o = v[o]);
+ for (g[l] = f, a = l, o = f, l = a; l > 0; l--) (b[l] = o), (o = _[o]);
+ for (b[0] = 0, y[0] = 0, l = 1; l <= a; l++)
+ for (o = b[l]; o <= g[l]; o++) {
+ for (z = -1, p = g[l - 1]; p >= _[o]; p--)
+ (E = h(s, p, o) + y[p]), (z < 0 || E < z) && ((u[o] = p), (z = E));
+ y[o] = z;
+ }
+ for (s.m = a, s.po = new Array(a), o = f, l = a - 1; o > 0; l--) (o = u[o]), (s.po[l] = o);
+ }
+ function At(s) {
+ function h(Ht, Nt, Ot, Yt, tt) {
+ for (var ct = Ht.len, at = Ht.sums, Ct, Zt, Xt, ee, ne, zt, ht, gt, Mt, Dt, Pt, Vt = 0; Ot >= ct; )
+ (Ot -= ct), (Vt += 1);
+ for (; Nt >= ct; ) (Nt -= ct), (Vt -= 1);
+ for (; Ot < 0; ) (Ot += ct), (Vt -= 1);
+ for (; Nt < 0; ) (Nt += ct), (Vt += 1);
+ (Ct = at[Ot + 1].x - at[Nt].x + Vt * at[ct].x),
+ (Zt = at[Ot + 1].y - at[Nt].y + Vt * at[ct].y),
+ (Xt = at[Ot + 1].x2 - at[Nt].x2 + Vt * at[ct].x2),
+ (ee = at[Ot + 1].xy - at[Nt].xy + Vt * at[ct].xy),
+ (ne = at[Ot + 1].y2 - at[Nt].y2 + Vt * at[ct].y2),
+ (zt = Ot + 1 - Nt + Vt * ct),
+ (Yt.x = Ct / zt),
+ (Yt.y = Zt / zt),
+ (ht = (Xt - (Ct * Ct) / zt) / zt),
+ (gt = (ee - (Ct * Zt) / zt) / zt),
+ (Mt = (ne - (Zt * Zt) / zt) / zt),
+ (Dt = (ht + Mt + Math.sqrt((ht - Mt) * (ht - Mt) + 4 * gt * gt)) / 2),
+ (ht -= Dt),
+ (Mt -= Dt),
+ Math.abs(ht) >= Math.abs(Mt)
+ ? ((Pt = Math.sqrt(ht * ht + gt * gt)), Pt !== 0 && ((tt.x = -gt / Pt), (tt.y = ht / Pt)))
+ : ((Pt = Math.sqrt(Mt * Mt + gt * gt)), Pt !== 0 && ((tt.x = -Mt / Pt), (tt.y = gt / Pt))),
+ Pt === 0 && (tt.x = tt.y = 0);
+ }
+ var o = s.m,
+ l = s.po,
+ a = s.len,
+ p = s.pt,
+ f = s.x0,
+ y = s.y0,
+ u = new Array(o),
+ v = new Array(o),
+ _ = new Array(o),
+ g = new Array(3),
+ b,
+ E,
+ z,
+ G,
+ $,
+ Z = new e();
+ for (s.curve = new c(o), E = 0; E < o; E++)
+ (z = l[i(E + 1, o)]),
+ (z = i(z - l[E], a) + l[E]),
+ (u[E] = new e()),
+ (v[E] = new e()),
+ h(s, l[E], z, u[E], v[E]);
+ for (E = 0; E < o; E++)
+ if (((_[E] = new M()), (b = v[E].x * v[E].x + v[E].y * v[E].y), b === 0))
+ for (z = 0; z < 3; z++) for (G = 0; G < 3; G++) _[E].data[z * 3 + G] = 0;
+ else
+ for (g[0] = v[E].y, g[1] = -v[E].x, g[2] = -g[1] * u[E].y - g[0] * u[E].x, $ = 0; $ < 3; $++)
+ for (G = 0; G < 3; G++) _[E].data[$ * 3 + G] = (g[$] * g[G]) / b;
+ var O, B, bt, ut, Tt, Et, Ft, wt, Gt, Rt;
+ for (E = 0; E < o; E++) {
+ for (
+ O = new M(), B = new e(), Z.x = p[l[E]].x - f, Z.y = p[l[E]].y - y, z = i(E - 1, o), $ = 0;
+ $ < 3;
+ $++
+ )
+ for (G = 0; G < 3; G++) O.data[$ * 3 + G] = _[z].at($, G) + _[E].at($, G);
+ for (;;) {
+ if (((Tt = O.at(0, 0) * O.at(1, 1) - O.at(0, 1) * O.at(1, 0)), Tt !== 0)) {
+ (B.x = (-O.at(0, 2) * O.at(1, 1) + O.at(1, 2) * O.at(0, 1)) / Tt),
+ (B.y = (O.at(0, 2) * O.at(1, 0) - O.at(1, 2) * O.at(0, 0)) / Tt);
+ break;
+ }
+ for (
+ O.at(0, 0) > O.at(1, 1)
+ ? ((g[0] = -O.at(0, 1)), (g[1] = O.at(0, 0)))
+ : O.at(1, 1)
+ ? ((g[0] = -O.at(1, 1)), (g[1] = O.at(1, 0)))
+ : ((g[0] = 1), (g[1] = 0)),
+ b = g[0] * g[0] + g[1] * g[1],
+ g[2] = -g[1] * Z.y - g[0] * Z.x,
+ $ = 0;
+ $ < 3;
+ $++
+ )
+ for (G = 0; G < 3; G++) O.data[$ * 3 + G] += (g[$] * g[G]) / b;
+ }
+ if (((bt = Math.abs(B.x - Z.x)), (ut = Math.abs(B.y - Z.y)), bt <= 0.5 && ut <= 0.5)) {
+ s.curve.vertex[E] = new e(B.x + f, B.y + y);
+ continue;
+ }
+ if (((Et = nt(O, Z)), (wt = Z.x), (Gt = Z.y), O.at(0, 0) !== 0))
+ for (Rt = 0; Rt < 2; Rt++)
+ (B.y = Z.y - 0.5 + Rt),
+ (B.x = -(O.at(0, 1) * B.y + O.at(0, 2)) / O.at(0, 0)),
+ (bt = Math.abs(B.x - Z.x)),
+ (Ft = nt(O, B)),
+ bt <= 0.5 && Ft < Et && ((Et = Ft), (wt = B.x), (Gt = B.y));
+ if (O.at(1, 1) !== 0)
+ for (Rt = 0; Rt < 2; Rt++)
+ (B.x = Z.x - 0.5 + Rt),
+ (B.y = -(O.at(1, 0) * B.x + O.at(1, 2)) / O.at(1, 1)),
+ (ut = Math.abs(B.y - Z.y)),
+ (Ft = nt(O, B)),
+ ut <= 0.5 && Ft < Et && ((Et = Ft), (wt = B.x), (Gt = B.y));
+ for ($ = 0; $ < 2; $++)
+ for (G = 0; G < 2; G++)
+ (B.x = Z.x - 0.5 + $),
+ (B.y = Z.y - 0.5 + G),
+ (Ft = nt(O, B)),
+ Ft < Et && ((Et = Ft), (wt = B.x), (Gt = B.y));
+ s.curve.vertex[E] = new e(wt + f, Gt + y);
+ }
+ }
+ function It(s) {
+ var h = s.curve,
+ o = h.n,
+ l = h.vertex,
+ a,
+ p,
+ f;
+ for (a = 0, p = o - 1; a < p; a++, p--) (f = l[a]), (l[a] = l[p]), (l[p] = f);
+ }
+ function Lt(s) {
+ var h = s.curve.n,
+ o = s.curve,
+ l,
+ a,
+ p,
+ f,
+ y,
+ u,
+ v,
+ _,
+ g;
+ for (l = 0; l < h; l++)
+ (a = i(l + 1, h)),
+ (p = i(l + 2, h)),
+ (g = Y(1 / 2, o.vertex[p], o.vertex[a])),
+ (y = X(o.vertex[l], o.vertex[p])),
+ y !== 0
+ ? ((f = V(o.vertex[l], o.vertex[a], o.vertex[p]) / y),
+ (f = Math.abs(f)),
+ (u = f > 1 ? 1 - 1 / f : 0),
+ (u = u / 0.75))
+ : (u = 4 / 3),
+ (o.alpha0[a] = u),
+ u >= J.alphamax
+ ? ((o.tag[a] = "CORNER"), (o.c[3 * a + 1] = o.vertex[a]), (o.c[3 * a + 2] = g))
+ : (u < 0.55 ? (u = 0.55) : u > 1 && (u = 1),
+ (v = Y(0.5 + 0.5 * u, o.vertex[l], o.vertex[a])),
+ (_ = Y(0.5 + 0.5 * u, o.vertex[p], o.vertex[a])),
+ (o.tag[a] = "CURVE"),
+ (o.c[3 * a + 0] = v),
+ (o.c[3 * a + 1] = _),
+ (o.c[3 * a + 2] = g)),
+ (o.alpha[a] = u),
+ (o.beta[a] = 0.5);
+ o.alphacurve = 1;
+ }
+ function C(s) {
+ function h() {
+ (this.pen = 0), (this.c = [new e(), new e()]), (this.t = 0), (this.s = 0), (this.alpha = 0);
+ }
+ function o(Ft, wt, Gt, Rt, Ht, Nt, Ot) {
+ var Yt = Ft.curve.n,
+ tt = Ft.curve,
+ ct = tt.vertex,
+ at,
+ Ct,
+ Zt,
+ Xt,
+ ee,
+ ne,
+ zt,
+ ht,
+ gt,
+ Mt,
+ Dt,
+ Pt,
+ Vt,
+ oe,
+ ue,
+ Be,
+ Je,
+ De,
+ ge,
+ Ae,
+ Ke,
+ Ue,
+ se;
+ if (wt == Gt || ((at = wt), (ee = i(wt + 1, Yt)), (Ct = i(at + 1, Yt)), (Xt = Nt[Ct]), Xt === 0))
+ return 1;
+ for (ht = dt(ct[wt], ct[ee]), at = Ct; at != Gt; at = Ct)
+ if (
+ ((Ct = i(at + 1, Yt)),
+ (Zt = i(at + 2, Yt)),
+ Nt[Ct] != Xt ||
+ D(N(ct[wt], ct[ee], ct[Ct], ct[Zt])) != Xt ||
+ lt(ct[wt], ct[ee], ct[Ct], ct[Zt]) < ht * dt(ct[Ct], ct[Zt]) * -0.999847695156)
+ )
+ return 1;
+ if (
+ ((Dt = tt.c[i(wt, Yt) * 3 + 2].copy()),
+ (Pt = ct[i(wt + 1, Yt)].copy()),
+ (Vt = ct[i(Gt, Yt)].copy()),
+ (oe = tt.c[i(Gt, Yt) * 3 + 2].copy()),
+ (ne = Ot[Gt] - Ot[wt]),
+ (ne -= V(ct[0], tt.c[wt * 3 + 2], tt.c[Gt * 3 + 2]) / 2),
+ wt >= Gt && (ne += Ot[Yt]),
+ (De = V(Dt, Pt, Vt)),
+ (ge = V(Dt, Pt, oe)),
+ (Ae = V(Dt, Vt, oe)),
+ (Ke = De + Ae - ge),
+ ge == De || ((se = Ae / (Ae - Ke)), (Ue = ge / (ge - De)), (Be = (ge * se) / 2), Be === 0))
+ )
+ return 1;
+ for (
+ Je = ne / Be,
+ zt = 2 - Math.sqrt(4 - Je / 0.3),
+ Rt.c[0] = Y(se * zt, Dt, Pt),
+ Rt.c[1] = Y(Ue * zt, oe, Vt),
+ Rt.alpha = zt,
+ Rt.t = se,
+ Rt.s = Ue,
+ Pt = Rt.c[0].copy(),
+ Vt = Rt.c[1].copy(),
+ Rt.pen = 0,
+ at = i(wt + 1, Yt);
+ at != Gt;
+ at = Ct
+ ) {
+ if (
+ ((Ct = i(at + 1, Yt)),
+ (se = ft(Dt, Pt, Vt, oe, ct[at], ct[Ct])),
+ se < -0.5 ||
+ ((ue = et(se, Dt, Pt, Vt, oe)), (ht = dt(ct[at], ct[Ct])), ht === 0) ||
+ ((gt = V(ct[at], ct[Ct], ue) / ht), Math.abs(gt) > Ht) ||
+ T(ct[at], ct[Ct], ue) < 0 ||
+ T(ct[Ct], ct[at], ue) < 0)
+ )
+ return 1;
+ Rt.pen += gt * gt;
+ }
+ for (at = wt; at != Gt; at = Ct) {
+ if (
+ ((Ct = i(at + 1, Yt)),
+ (se = ft(Dt, Pt, Vt, oe, tt.c[at * 3 + 2], tt.c[Ct * 3 + 2])),
+ se < -0.5 ||
+ ((ue = et(se, Dt, Pt, Vt, oe)), (ht = dt(tt.c[at * 3 + 2], tt.c[Ct * 3 + 2])), ht === 0) ||
+ ((gt = V(tt.c[at * 3 + 2], tt.c[Ct * 3 + 2], ue) / ht),
+ (Mt = V(tt.c[at * 3 + 2], tt.c[Ct * 3 + 2], ct[Ct]) / ht),
+ (Mt *= 0.75 * tt.alpha[Ct]),
+ Mt < 0 && ((gt = -gt), (Mt = -Mt)),
+ gt < Mt - Ht))
+ )
+ return 1;
+ gt < Mt && (Rt.pen += (gt - Mt) * (gt - Mt));
+ }
+ return 0;
+ }
+ var l = s.curve,
+ a = l.n,
+ p = l.vertex,
+ f = new Array(a + 1),
+ y = new Array(a + 1),
+ u = new Array(a + 1),
+ v = new Array(a + 1),
+ _,
+ g,
+ b,
+ E,
+ z = new h(),
+ G,
+ $,
+ Z,
+ O,
+ B,
+ bt,
+ ut,
+ Tt = new Array(a),
+ Et = new Array(a + 1);
+ for (g = 0; g < a; g++)
+ l.tag[g] == "CURVE" ? (Tt[g] = D(V(p[i(g - 1, a)], p[g], p[i(g + 1, a)]))) : (Tt[g] = 0);
+ for (Z = 0, Et[0] = 0, G = l.vertex[0], g = 0; g < a; g++)
+ ($ = i(g + 1, a)),
+ l.tag[$] == "CURVE" &&
+ ((O = l.alpha[$]),
+ (Z += (0.3 * O * (4 - O) * V(l.c[g * 3 + 2], p[$], l.c[$ * 3 + 2])) / 2),
+ (Z += V(G, l.c[g * 3 + 2], l.c[$ * 3 + 2]) / 2)),
+ (Et[g + 1] = Z);
+ for (f[0] = -1, y[0] = 0, u[0] = 0, b = 1; b <= a; b++)
+ for (
+ f[b] = b - 1, y[b] = y[b - 1], u[b] = u[b - 1] + 1, g = b - 2;
+ g >= 0 && ((E = o(s, g, i(b, a), z, J.opttolerance, Tt, Et)), !E);
+ g--
+ )
+ (u[b] > u[g] + 1 || (u[b] == u[g] + 1 && y[b] > y[g] + z.pen)) &&
+ ((f[b] = g), (y[b] = y[g] + z.pen), (u[b] = u[g] + 1), (v[b] = z), (z = new h()));
+ for (_ = u[a], B = new c(_), bt = new Array(_), ut = new Array(_), b = a, g = _ - 1; g >= 0; g--)
+ f[b] == b - 1
+ ? ((B.tag[g] = l.tag[i(b, a)]),
+ (B.c[g * 3 + 0] = l.c[i(b, a) * 3 + 0]),
+ (B.c[g * 3 + 1] = l.c[i(b, a) * 3 + 1]),
+ (B.c[g * 3 + 2] = l.c[i(b, a) * 3 + 2]),
+ (B.vertex[g] = l.vertex[i(b, a)]),
+ (B.alpha[g] = l.alpha[i(b, a)]),
+ (B.alpha0[g] = l.alpha0[i(b, a)]),
+ (B.beta[g] = l.beta[i(b, a)]),
+ (bt[g] = ut[g] = 1))
+ : ((B.tag[g] = "CURVE"),
+ (B.c[g * 3 + 0] = v[b].c[0]),
+ (B.c[g * 3 + 1] = v[b].c[1]),
+ (B.c[g * 3 + 2] = l.c[i(b, a) * 3 + 2]),
+ (B.vertex[g] = Y(v[b].s, l.c[i(b, a) * 3 + 2], p[i(b, a)])),
+ (B.alpha[g] = v[b].alpha),
+ (B.alpha0[g] = v[b].alpha),
+ (bt[g] = v[b].s),
+ (ut[g] = v[b].t)),
+ (b = f[b]);
+ for (g = 0; g < _; g++) ($ = i(g + 1, _)), (B.beta[g] = bt[g] / (bt[g] + ut[$]));
+ (B.alphacurve = 1), (s.curve = B);
+ }
+ for (var P = 0; P < U.length; P++) {
+ var A = U[P];
+ xt(A), rt(A), pt(A), At(A), A.sign === "-" && It(A), Lt(A), J.optcurve && C(A);
+ }
+ }
+ function K(M) {
+ if ((M && (H = M), !J.isReady)) {
+ setTimeout(K, 100);
+ return;
+ }
+ st(), W(), H(), (H = null);
+ }
+ function Q() {
+ (F = null), (U = []), (H = null), (J.isReady = !1);
+ }
+ function it(M, I) {
+ function i(T) {
+ function lt(rt) {
+ var pt = "C " + (T.c[rt * 3 + 0].x * M).toFixed(3) + " " + (T.c[rt * 3 + 0].y * M).toFixed(3) + ",";
+ return (
+ (pt += (T.c[rt * 3 + 1].x * M).toFixed(3) + " " + (T.c[rt * 3 + 1].y * M).toFixed(3) + ","),
+ (pt += (T.c[rt * 3 + 2].x * M).toFixed(3) + " " + (T.c[rt * 3 + 2].y * M).toFixed(3) + " "),
+ pt
+ );
+ }
+ function dt(rt) {
+ var pt = "L " + (T.c[rt * 3 + 1].x * M).toFixed(3) + " " + (T.c[rt * 3 + 1].y * M).toFixed(3) + " ";
+ return (pt += (T.c[rt * 3 + 2].x * M).toFixed(3) + " " + (T.c[rt * 3 + 2].y * M).toFixed(3) + " "), pt;
+ }
+ var et = T.n,
+ ft,
+ xt =
+ "M" +
+ (T.c[(et - 1) * 3 + 2].x * M).toFixed(3) +
+ " " +
+ (T.c[(et - 1) * 3 + 2].y * M).toFixed(3) +
+ " ";
+ for (ft = 0; ft < et; ft++)
+ T.tag[ft] === "CURVE" ? (xt += lt(ft)) : T.tag[ft] === "CORNER" && (xt += dt(ft));
+ return xt;
+ }
+ var k = F.w * M,
+ S = F.h * M,
+ D = U.length,
+ nt,
+ Y,
+ w,
+ X,
+ V,
+ N = '<svg id="svg" version="1.1" width="' + k + '" height="' + S + '" xmlns="http://www.w3.org/2000/svg">';
+ for (N += '<path d="', Y = 0; Y < D; Y++) (nt = U[Y].curve), (N += i(nt));
+ return (
+ I === "curve"
+ ? ((w = "black"), (X = "none"), (V = ""))
+ : ((w = "none"), (X = "black"), (V = ' fill-rule="evenodd"')),
+ (N += '" stroke="' + w + '" fill="' + X + '"' + V + "/></svg>"),
+ N
+ );
+ }
+ return {
+ loadImageFromFile: yt,
+ loadImageFromUrl: vt,
+ setParameter: St,
+ process: K,
+ getSVG: it,
+ setImg: ot,
+ setImg: ot,
+ onImgLoaded: L,
+ img: m,
+ };
+};
+const re = (e, n) => {
+ const r = e[0],
+ c = e[1];
+ let m = !1;
+ for (let R = 0, F = n.length - 2; R < n.length; F = R, R += 2) {
+ const U = n[R],
+ H = n[R + 1],
+ J = n[F],
+ L = n[F + 1];
+ H > c != L > c && r < ((J - U) * (c - H)) / (L - H) + U && (m = !m);
+ }
+ return m;
+ },
+ sn = (e) => {
+ if (e.length === 0)
+ return console.warn("[geom-utils:computeBoundingBox] No points to compute bounding box"), null;
+ const n = (L) => (Array.isArray(L) ? L[0] : L.x),
+ r = (L) => (Array.isArray(L) ? L[1] : L.y);
+ let c = n(e[0]),
+ m = r(e[0]),
+ R = n(e[0]),
+ F = r(e[0]);
+ e.forEach((L) => {
+ const yt = n(L),
+ vt = r(L);
+ yt < c && (c = yt), yt > R && (R = yt), vt < m && (m = vt), vt > F && (F = vt);
+ });
+ const U = R - c,
+ H = F - m,
+ J = U * H || 0.01;
+ return { minX: c, maxX: R, minY: m, maxY: F, area: J };
+ },
+ ln = (e) => {
+ let n = 0;
+ for (let r = 0; r < e.length; r += 2) {
+ const c = (r + 2) % e.length;
+ (n += e[r] * e[c + 1]), (n -= e[r + 1] * e[c]);
+ }
+ return Math.abs(n) / 2;
+ },
+ To = ["green", "purple", "#F48484", "brown", "#00337C", "orange"];
+let rn = null,
+ ae = null,
+ Go = null;
+const cn = ["color"],
+ an = [],
+ Oe = [],
+ Ee = 1,
+ Bo = () => {
+ let e = d.dimensions.base[0],
+ n = d.dimensions.base[1],
+ r = [],
+ c = [];
+ const m = (j) => {
+ (rn = j), F();
+ },
+ R = () => L("color").cvs,
+ F = () => {
+ const j = new Lo();
+ j.setImg(rn),
+ j.onImgLoaded(),
+ j.process(function () {
+ const st = j.getSVG(1);
+ (ae = new DOMParser().parseFromString(st, "image/svg+xml").querySelector("svg")),
+ document.body.appendChild(ae),
+ (ae.style.visibility = "hidden"),
+ (ae.style.position = "absolute"),
+ (ae.style.top = ae.style.left = "0px"),
+ U();
+ });
+ },
+ U = () => {
+ H(), J(), vt();
+ },
+ H = () => {
+ const j = ae.querySelector("path");
+ j.getBoundingClientRect();
+ const st = j.getAttribute("d") + "",
+ W = [...st.matchAll(new RegExp("M", "gi"))].map((K) => K.index);
+ for (let K = 0; K < W.length; K++) {
+ const Q = st.substring(W[K], W[K + 1]),
+ it = t.pick(To),
+ M = document.createElementNS("http://www.w3.org/2000/svg", "path");
+ M.setAttributeNS(null, "d", Q),
+ M.setAttributeNS(null, "fill", it),
+ M.setAttributeNS(null, "fill-rull", "even-odd"),
+ M.setAttributeNS(null, "stroke", "none");
+ let I = 0;
+ const i = {
+ path: M,
+ color: it,
+ points: [],
+ area: 0,
+ bounds: { minX: 1 / 0, minY: 1 / 0, maxX: -1 / 0, maxY: -1 / 0 },
+ },
+ k = M.getTotalLength();
+ let S = d.rough ? t.pick([60, 100, 150]) : 5,
+ D = t.pick(d.geomOffset.normOffsetOpts);
+ for (let Y = 0; Y < k - S; Y += S) {
+ const w = M.getPointAtLength(Y),
+ X = M.getPointAtLength(Y + S);
+ (w.x *= Ee), (w.y *= Ee), (X.x *= Ee), (X.y *= Ee);
+ const V = X.x - w.x,
+ N = X.y - w.y,
+ T = Math.atan2(N, V),
+ lt = T + Math.PI / 2,
+ dt = w.x / e,
+ et = w.y / n,
+ ft = d.geomOffset.noiseScl,
+ xt = d.geomOffset.noiseAmp,
+ rt = 10,
+ pt = t.n2D(dt * ft * 2 + K, et * ft * 2 + K),
+ At = rt * pt,
+ It = K * 10;
+ let Lt = Math.round((t.n2D(dt * ft + It, et * ft + It) * xt) / At) * At;
+ const C = D + Lt || 0;
+ (w.x += Math.cos(lt) * C),
+ (w.y += Math.sin(lt) * C),
+ (i.bounds.minX = Math.min(i.bounds.minX, w.x)),
+ (i.bounds.minY = Math.min(i.bounds.minY, w.y)),
+ (i.bounds.maxX = Math.max(i.bounds.maxX, w.x)),
+ (i.bounds.maxY = Math.max(i.bounds.maxY, w.y));
+ const P = { pt: w, a: T, color: it, islandIdx: K };
+ i.points.push(P);
+ }
+ if (
+ ((i.bounds.width = i.bounds.maxX - i.bounds.minX),
+ (i.bounds.height = i.bounds.maxY - i.bounds.minY),
+ (i.bounds.diag = Math.sqrt(
+ i.bounds.width * i.bounds.width + i.bounds.height * i.bounds.height
+ )),
+ i.points.length > 0)
+ ) {
+ for (let X = 0; X < i.points.length; X++) {
+ const V = i.points[X].pt,
+ N = i.points[(X + 1) % i.points.length].pt;
+ I += V.x * N.y - N.x * V.y;
+ }
+ i.area = Math.abs(I / 2);
+ let Y = 0,
+ w = 0;
+ i.points.forEach((X) => {
+ (Y += X.pt.x), (w += X.pt.y);
+ }),
+ (i.center = { x: Y / i.points.length, y: w / i.points.length });
+ }
+ let nt = !1;
+ for (const Y of c)
+ if (re([i.center.x, i.center.y], Y.flatPoints)) {
+ nt = !0;
+ break;
+ }
+ if (i.bounds.diag < 100) {
+ if (!d.smalls && !nt) continue;
+ const Y = -1;
+ i.points.forEach((w, X) => {
+ const V = w.pt.x / e,
+ N = w.pt.y / n,
+ T = t.range(1, 3),
+ lt = 5,
+ dt = t.n2D(V * T * 2 + X, N * T * 2 + X),
+ et = Y * dt;
+ Math.round((t.n2D(V * T + X, N * T + X) * lt) / et) * et, w.a + Math.PI / 2;
+ });
+ }
+ Oe.push(i);
+ }
+ Oe.length < 45 && (d.press = 1);
+ },
+ J = () => {
+ const j = e,
+ st = n;
+ for (let W = 0; W < cn.length; W++) {
+ const K = cn[W],
+ Q = document.createElement("canvas"),
+ it = Q.getContext("2d");
+ (Q.style.width = `${j * d.dimensions.debugScl}px`),
+ (Q.style.height = `${st * d.dimensions.debugScl}px`),
+ (Q.width = j),
+ (Q.height = st),
+ an.push({ id: K, cvs: Q, ctx: it });
+ }
+ },
+ L = (j) => {
+ const st = an.find((W) => W.id == j);
+ if (!st) {
+ console.error("[Tracer _getCanvasById] no canvas found for id", j);
+ return;
+ }
+ return st;
+ },
+ yt = () => {
+ const { ctx: j, cvs: st } = L("color");
+ j.save(),
+ (j.fillStyle = "black"),
+ (j.strokeStyle = "black"),
+ (j.lineWidth = 2),
+ Oe.forEach((W) => {
+ W.color;
+ const K = W.points;
+ if (K.length !== 0) {
+ j.beginPath(), j.moveTo(K[0].pt.x, K[0].pt.y);
+ for (let Q = 1; Q < K.length; Q++) {
+ const it = K[Q].pt;
+ j.lineTo(it.x, it.y);
+ }
+ j.closePath(), j.stroke();
+ }
+ }),
+ j.restore();
+ },
+ vt = () => {
+ const { cvs: j, ctx: st } = L("color");
+ st.clearRect(0, 0, e, n), (st.fillStyle = "#F48484"), st.fillRect(0, 0, e, n), yt();
+ };
+ return {
+ fromImage: m,
+ getColor: R,
+ getGeoms: () => Oe,
+ getCanvas: () => Go,
+ setBaseShapes: (j) => {
+ r = j;
+ for (let st = 0; st < r.length; st++) {
+ const W = r[st];
+ if (W.func == x.ROTATEDGRID) {
+ const K = [];
+ for (let Q = 0; Q < W.points.length; Q++) {
+ const it = W.points[Q];
+ K.push(it.x, it.y);
+ }
+ (W.flatPoints = K), c.push(W);
+ }
+ }
+ },
+ };
+ };
+let Uo = () => ({
+ emit(e, ...n) {
+ let r = this.events[e] || [];
+ for (let c = 0, m = r.length; c < m; c++) r[c](...n);
+ },
+ events: {},
+ on(e, n) {
+ return (
+ this.events[e]?.push(n) || (this.events[e] = [n]),
+ () => {
+ this.events[e] = this.events[e]?.filter((r) => n !== r);
+ }
+ );
+ },
+});
+const Tn = Uo(),
+ Gn = { RENDER_COMPLETE: "render_complete" };
+let ye = [];
+const Xo = () => {
+ let e = d.dimensions.base[0],
+ n = d.dimensions.base[1],
+ r = null,
+ c = null,
+ m = null,
+ R = null,
+ F = 0,
+ U = 5;
+ const H = () => {
+ (r = document.createElement("canvas")),
+ (r.width = e),
+ (r.height = n),
+ (r.id = "colorize"),
+ (c = r.getContext("2d")),
+ (m = document.createElement("canvas")),
+ (m.width = d.dimensions.final[0]),
+ (m.height = d.dimensions.final[1]),
+ (m.id = "artwork"),
+ (R = m.getContext("2d"));
+ const st = d.dimensions.final[0] / d.dimensions.final[1],
+ W = 20,
+ K = window.innerWidth - W,
+ Q = window.innerHeight - W;
+ let it = Math.min(d.dimensions.final[0], K),
+ M = it / st;
+ M > Q && ((M = Q), (it = M * st)),
+ (m.style.width = `${it}px`),
+ (m.style.height = `${M}px`),
+ (m.style.position = "absolute"),
+ (m.style.left = "50%"),
+ (m.style.top = "50%"),
+ (m.style.transform = "translate(-50%, -50%)"),
+ (m.style.border = "none");
+ },
+ J = () => {
+ F += U;
+ },
+ L = () => {
+ F <= U && (c.clearRect(0, 0, e, n), (c.fillStyle = d.backgroundColor), c.fillRect(0, 0, e, n));
+ const st = F,
+ W = Math.min(ye.length - 1, F + U);
+ for (let K = st; K <= W; K++) {
+ const Q = ye[K];
+ c.save(), (c.lineJoin = "round");
+ let it = 5;
+ d.density == "l" && (it = 8),
+ (c.globalAlpha = Q.style.opacity * it),
+ (c.lineWidth = Q.style.strokeWidth * 2),
+ (c.strokeStyle = Q.style.strokeColor),
+ (c.fillStyle = Q.style.strokeColor),
+ (c.globalCompositeOperation = Q.style.blendingMode);
+ const M = Q.path.split(" "),
+ I = M[0].slice(1).split(",").map(Number);
+ c.beginPath(), c.moveTo(I[0], I[1]);
+ for (let i = 1; i < M.length; i++) {
+ const k = M[i].slice(1).split(",").map(Number);
+ c.lineTo(k[0], k[1]);
+ }
+ c.stroke(), c.restore();
+ }
+ },
+ yt = () => {
+ R.clearRect(0, 0, m.width, m.height),
+ (R.fillStyle = d.backgroundColor),
+ R.drawImage(r, 0, 0, m.width, m.height);
+ },
+ vt = () => {
+ J(), L(), yt(), F < ye.length && requestAnimationFrame(vt), F >= ye.length && Tn.emit(Gn.RENDER_COMPLETE);
+ },
+ St = () => r,
+ ot = () => m,
+ mt = (st) => {
+ (ye = st.strokesData), st.strokePoints;
+ let W = d.density == "h" ? 90 : 270,
+ K = d.density == "h" ? 0.5 : 1;
+ U = Math.ceil((ye.length / W) * K);
+ },
+ j = (st) => {};
+ return H(), { setRawIslandsData: j, setStrokesData: mt, play: vt, getCanvas: St, getFinalCanvas: ot };
+};
+let hn = [],
+ he = [];
+const Vo = () => {
+ let e = d.dimensions.base[0],
+ n = d.dimensions.base[1],
+ r = null,
+ c = null;
+ const m = (St) => {
+ (hn = St), F();
+ },
+ R = () => r,
+ F = () => {
+ (he = []),
+ hn.forEach((St) => {
+ const ot = St.points;
+ for (let mt = 0; mt < ot.length; mt++) {
+ const j = ot[mt],
+ st = ot[mt + 1] || ot[0],
+ W = { x: st.pt.x - j.pt.x, y: st.pt.y - j.pt.y },
+ K = Math.sqrt(W.x * W.x + W.y * W.y);
+ (W.x /= K), (W.y /= K), he.push({ x: j.pt.x, y: j.pt.y, tangent: W });
+ }
+ });
+ },
+ U = () => {
+ (r = document.createElement("canvas")),
+ (r.width = e),
+ (r.height = n),
+ (r.style.width = `${e * 0.5}px`),
+ (r.style.height = `${n * 0.5}px`),
+ (r.id = "flow"),
+ (c = r.getContext("2d"));
+ },
+ H = () => {
+ c.clearRect(0, 0, e, n), (c.fillStyle = "white"), c.fillRect(0, 0, e, n);
+ for (let St = 0; St < he.length; St++) {
+ const ot = he[St],
+ mt = ot.tangent;
+ c.save(),
+ (c.fillStyle = "black"),
+ c.translate(ot.x, ot.y),
+ c.beginPath(),
+ c.arc(0, 0, 2, 0, Math.PI * 2),
+ c.closePath(),
+ c.fill(),
+ c.restore(),
+ c.save(),
+ (c.strokeStyle = "red"),
+ c.translate(ot.x, ot.y),
+ c.beginPath(),
+ c.moveTo(0, 0),
+ c.lineTo(mt.x * 30, mt.y * 30),
+ c.stroke(),
+ c.restore();
+ }
+ },
+ J = () => {
+ H();
+ },
+ L = (St, ot) => {
+ let mt = null,
+ j = 1 / 0;
+ return (
+ he.forEach((st) => {
+ const W = st.x - St,
+ K = st.y - ot,
+ Q = W * W + K * K;
+ Q < j && ((j = Q), (mt = st));
+ }),
+ mt ? j : 0
+ );
+ },
+ yt = (St, ot, mt = 1, j = 1 / 0) => {
+ let W = Array(mt)
+ .fill()
+ .map(() => ({ point: null, distance: 1 / 0 }));
+ if (
+ (he.forEach((I) => {
+ const i = I.x - St,
+ k = I.y - ot,
+ S = i * i + k * k;
+ if (!(S > j * j)) {
+ for (let D = 0; D < W.length; D++)
+ if (S < W[D].distance) {
+ for (let nt = W.length - 1; nt > D; nt--) W[nt] = { ...W[nt - 1] };
+ W[D] = { point: I, distance: S };
+ break;
+ }
+ }
+ }),
+ !W[0].point)
+ )
+ return null;
+ const K = W.filter((I) => I.point !== null).length;
+ if (K === 1) return W[0].point.tangent;
+ const Q = { x: 0, y: 0 };
+ let it = 0;
+ for (let I = 0; I < K; I++) {
+ const i = 1 / (W[I].distance + 1e-4);
+ (it += i), (Q.x += W[I].point.tangent.x * i), (Q.y += W[I].point.tangent.y * i);
+ }
+ (Q.x /= it), (Q.y /= it);
+ const M = Math.sqrt(Q.x * Q.x + Q.y * Q.y);
+ return (Q.x /= M), (Q.y /= M), Q;
+ },
+ vt = () => he;
+ return (
+ U(),
+ {
+ getCanvas: R,
+ getPoints: vt,
+ getTangentAtPosition: yt,
+ getDistanceFromGeomAtPosition: L,
+ setGeoms: m,
+ render: J,
+ }
+ );
+};
+let pe = [],
+ te = [],
+ me = [],
+ be = [],
+ Pe = [],
+ le = [],
+ Ye = [],
+ Qt = d.palette,
+ fn = d.tangentModeOpts;
+const Yo = () => {
+ let e = 0,
+ n = d.dimensions.base[0],
+ r = d.dimensions.base[1] - e;
+ const c = n / r;
+ let m = null,
+ R = [];
+ t.int(0, Qt.length - 1);
+ const F = t.pick($e),
+ U = 0.005 * n,
+ H = (I) => {
+ const i = I.min.x + I.dimensions.width / 2,
+ k = I.min.y + I.dimensions.height / 2,
+ S = Math.sqrt(Math.pow(I.dimensions.width / 2, 2) + Math.pow(I.dimensions.height / 2, 2));
+ return { center: { x: i, y: k }, radius: S };
+ },
+ J = (I, i, k) => {
+ let S = !1;
+ for (let D = 0; D < le.length; D++) {
+ const nt = le[D].points;
+ re([I, i], nt) && (S = !0);
+ }
+ return !S;
+ },
+ L = (I, i) => {
+ let k = !1;
+ for (let S = 0; S < Ye.length; S++) {
+ const D = Ye[S];
+ !d.lightSides.includes(D.side) || (re([I, i], D.points) && (k = !0));
+ }
+ return k;
+ },
+ yt = () => {
+ for (let I = 0; I < me.length; I++) {
+ const i = me[I],
+ k = i.x,
+ S = i.y;
+ k + i.tangent.x * i.tangentScl, S + i.tangent.y * i.tangentScl;
+ const D = i.geomIdx,
+ nt = i.geom ? i.geom : pe[D],
+ Y = i.isInBackground,
+ w = i.isFirstGeom,
+ X = nt.points;
+ i.fillProgress;
+ const V = i.fuziness || 1,
+ N = { x: -i.tangent.y, y: i.tangent.x };
+ let T = `M${k},${S}`;
+ const lt = t.int(5, 15),
+ dt = t.range(0.001, 0.003) * n,
+ et = t.range(-0.3, 0.3) * i.tangentScl * 0.3;
+ for (let pt = 0; pt < lt; pt++) {
+ const At = pt / lt;
+ let It = k + i.tangent.x * i.tangentScl * At,
+ Lt = S + i.tangent.y * i.tangentScl * At;
+ const C = Math.sin(At * Math.PI) * et;
+ (It += N.x * C), (Lt += N.y * C);
+ let P = It / n,
+ A = Lt / r;
+ const s = 0.004,
+ h = (At + t.random()) % 1,
+ o = t.n2D(h + P * s, h + A * s),
+ l = t.n2D(h + P * s + 50, h + A * s + 50);
+ (It += N.x * o * dt),
+ (Lt += N.y * l * dt),
+ !!re([It, Lt], X) && It > U && It < n - U && Lt > U && Lt < r - U && (T += ` L${It},${Lt}`);
+ }
+ let ft = Bt(t.n2D((k / n) * 3, (S / r) * 3), -1, 1, 1, 10);
+ d.density == "h" && (ft = 3);
+ let xt = Bt(t.n2D((k / n) * 2, (S / r) * 2), -1, 1, 1, ft),
+ rt = i.tangentScl * Bt(Math.abs(t.n2D((k / n) * 1.5 + 60, (S / r) * 1.5 + 60)), -1, 1, 0.01, 0.05);
+ Y && (rt *= t.range(0.2, 0.4)),
+ t.bool(0.2) && (rt *= d.baseEllipseWidthScl),
+ t.bool(0.2) && (rt *= 2),
+ d.isLandscape && S / r > 0.7 && ((xt = 1), (rt *= 0.5));
+ for (let pt = 0; pt < xt; pt++) {
+ const At = k / n,
+ It = S / r,
+ Lt = pt * i.thickness * Bt(t.n2D(At * 0.7 + 1e3 + pt, It * 0.7 + 1e3 + pt), -1, 1, 0.2, 1),
+ C = t.range(-0.005, 0.005) * n,
+ P = t.range(-0.005, 0.005) * r;
+ t.int(50, 50);
+ const A = t.range(rt * 0.5, rt * 2),
+ s = i.tangentScl * Bt(t.n2D(At * 1.3 + 50, It * 1.3 + 50), -1, 1, 0.1, 1);
+ Math.PI * t.range(0.1, 2);
+ const h = t.random() * Math.PI,
+ o = t.range(h, Math.PI),
+ l = t.range(0.05, 0.1);
+ let a = t.range(0.005, 0.008) * n;
+ const p = t.range(-0.1, 0.1) * i.tangentScl * 0;
+ for (let f = h; f <= o; f += l) {
+ let y = Math.cos(f * Math.PI * 2) * A + N.x * f * 5,
+ u = Math.sin(f * Math.PI * 2) * s + N.y * f * 5;
+ const v = (f - h) / (o - h),
+ _ = Math.sin(v * Math.PI) * p;
+ (y += N.x * _), (u += N.y * _);
+ let g = Math.atan2(i.tangent.y, i.tangent.x) + Math.PI / 2 + t.range(-0.1, 0.1) * V;
+ const b = y * Math.cos(g) - u * Math.sin(g),
+ E = y * Math.sin(g) + u * Math.cos(g);
+ (y = b + k),
+ (u = E + S),
+ (y += N.x * Lt * t.range(0.5, 1)),
+ (u += N.y * Lt * t.range(0.5, 1)),
+ (y += C),
+ (u += P),
+ (y += t.n2D(At * 1e3, It * 1e3) * a),
+ (u += t.n2D(At * 1e3 + 500, It * 1e3 + 500) * a),
+ re([y, u], X) && (y < U || y > n - U || u < U || u > r - U || (T += ` L${y},${u}`));
+ }
+ }
+ be.push({
+ path: T,
+ geom: nt,
+ style: {
+ opacity: i.opacity,
+ strokeWidth: i.thickness,
+ strokeColor: i.color,
+ strokeMixedColor: i.mixedColor,
+ blendingMode: i.blendingMode,
+ },
+ info: {
+ layer: "main",
+ isInBackground: Y,
+ isFirstGeom: w,
+ brushType: "crayon",
+ isOtherColor: i.isOtherColor,
+ },
+ });
+ }
+ },
+ vt = () => {
+ const I = Pe;
+ for (let i = 0; i < I.length; i++) {
+ const k = I[i],
+ S = k.points,
+ D = ot(le[i]).contour;
+ if (D.skip) continue;
+ const nt = D.opacity,
+ Y = D.strokeWidth;
+ let w = `M${S[0].x},${S[0].y}`;
+ for (let X = 1; X < S.length; X++) {
+ let V = S[X].x,
+ N = S[X].y;
+ (V += t.range(-1, 1) * 0.001 * n),
+ (N += t.range(-1, 1) * 0.001 * r),
+ !(V < 0 || V > n || N < 0 || N > r) && (w += ` L${V},${N}`);
+ }
+ be.push({
+ path: w,
+ geom: k,
+ style: {
+ opacity: nt,
+ strokeWidth: Y,
+ strokeColor: "#111111",
+ strokeMixedColor: "#111111",
+ blendingMode: "multiply",
+ },
+ info: { layer: "contour", isInBackground: !1, isFirstGeom: !1, brushType: "crayon", isContour: !0 },
+ });
+ }
+ },
+ St = () => {
+ if (d.rough || !d.vstrokes || (d.density !== "h" && d.comps.length == 1 && d.comps[0] == x.GRIBOUILLIS))
+ return;
+ const I = te;
+ let i = 5;
+ i = 5;
+ let k = d.density == "l" ? 0.01 : 0.04;
+ d.tScl < 0.6 && (k *= 0.3);
+ for (let S = 0; S < I.length; S++) {
+ const D = I[S];
+ D.points;
+ const nt = S == 0;
+ if (nt || !D.isFilled) continue;
+ const Y = D.color,
+ w = D.bb.dimensions.width,
+ X = D.bb.dimensions.height;
+ if (!(w > n / 1.5 && X > r / 1.5 && nt))
+ for (let V = D.bb.min.x; V <= D.bb.max.x; V += i) {
+ let N = [],
+ T = [];
+ const lt = t.range(-i, i) * 0.1,
+ dt = t.range(-i, i) * 0.1;
+ for (let et = D.bb.min.y; et <= D.bb.max.y; et += 1) {
+ let ft = J(V, et);
+ pe.length > 1 && (ft = !1);
+ let xt = L(V, et) && d.light;
+ if (re([V, et], D.points) && !ft) {
+ const rt = V + lt,
+ pt = et + dt;
+ if (rt < U || rt > n - U || pt < U || pt > r - U || xt) continue;
+ T.length === 0 || Math.abs(pt - T[T.length - 1][1]) <= 1
+ ? T.push([rt, pt])
+ : (T.length > 0 && N.push([...T]), (T = [[rt, pt]]));
+ }
+ }
+ T.length > 0 && N.push(T),
+ N.forEach((et) => {
+ if (et.length > 1) {
+ let ft = `M${et[0][0]},${et[0][1]}`;
+ for (let xt = 1; xt < et.length; xt++) ft += ` L${et[xt][0]},${et[xt][1]}`;
+ be.push({
+ path: ft,
+ geom: D,
+ style: {
+ opacity: k,
+ strokeWidth: 0.5,
+ strokeColor: Y,
+ strokeMixedColor: Y,
+ blendingMode: "multiply",
+ },
+ info: {
+ layer: "texture",
+ isInBackground: !1,
+ isFirstGeom: !1,
+ brushType: "crayon",
+ isContour: !1,
+ isTextureStroke: !0,
+ },
+ });
+ }
+ });
+ }
+ }
+ },
+ ot = (I) => {
+ let i = null,
+ k = 1 / 0,
+ S = R[0];
+ return (
+ R.forEach((D) => {
+ const nt = I.bb.center.x - D.x,
+ Y = I.bb.center.y - D.y,
+ w = Math.sqrt(nt * nt + Y * Y);
+ w < k && ((k = w), (i = D));
+ }),
+ i && (S = i),
+ S
+ );
+ },
+ mt = () => {
+ if (!t.bool(d.sim)) return;
+ const I = le;
+ let i = 0;
+ (i = 0.5),
+ I.forEach((k, S) => {
+ k.bb.dimensions.width, k.bb.dimensions.height, k.bb.center.x, k.bb.center.y, ln(k.points);
+ const D = H(k.bb);
+ let nt = k.color;
+ const Y = 10;
+ if (!t.bool(0.5))
+ for (let X = 0; X < Y; X++) {
+ const V = t.range(k.bb.min.x, k.bb.max.x),
+ N = t.range(k.bb.min.y, k.bb.max.y);
+ let T = { x: V, y: N },
+ lt = `M${T.x},${T.y}`;
+ for (let xt = 0; xt < 40; xt++) {
+ const rt = m.getTangentAtPosition(T.x, T.y, 1, D.radius);
+ if (!re([T.x, T.y], k.points)) {
+ (T.x = t.range(k.bb.min.x, k.bb.max.x)),
+ (T.y = t.range(k.bb.min.y, k.bb.max.y)),
+ (lt = `M${T.x},${T.y}`);
+ continue;
+ }
+ if (!rt?.x || !rt?.y) continue;
+ (rt.x *= t.range(0.2, 2)), (rt.y *= t.range(0.2, 2));
+ let pt = 10;
+ (T.x += rt.x * pt), (T.y += rt.y * pt), (lt += ` L${T.x},${T.y}`);
+ }
+ let dt = t.range(0.05, 0.15) * i,
+ et = t.range(0.1, 0.3) * 1.5,
+ ft = t.bool(0.5) ? "multiply" : "source-over";
+ be.push({
+ path: lt,
+ geom: k,
+ style: {
+ opacity: dt,
+ strokeWidth: et,
+ strokeColor: nt,
+ strokeMixedColor: nt,
+ blendingMode: ft,
+ },
+ info: {
+ layer: "sim",
+ isInBackground: !1,
+ isFirstGeom: !1,
+ brushType: "crayon",
+ isOtherColor: !1,
+ },
+ });
+ }
+ });
+ },
+ j = (I) => {
+ const i = I == "c" ? te : le,
+ k = d.layers.length > 1 && I == "c" ? d.neg : 0;
+ i.forEach((S, D) => {
+ const nt = [],
+ Y = D;
+ let w = D == 0;
+ const X = me.length,
+ V = t.pick(["c", "v", "h", "n"]);
+ let N = d.density;
+ if ((d.layers.length > 1 && I == "c" && (N = "h"), D / i.length, !S.isFilled || t.bool(k))) return;
+ const lt = S.bb.dimensions.width,
+ dt = S.bb.dimensions.height,
+ et = S.bb.center.x,
+ ft = S.bb.center.y;
+ ln(S.points);
+ let xt = Math.sqrt(lt * lt + dt * dt);
+ if (lt > n / 1.5 && dt > r / 1.5 && w) return;
+ let rt = w ? F : S.color,
+ pt = w ? F : t.pick(Qt);
+ d.colorrep == "n" &&
+ (pt =
+ Qt[
+ ~~Bt(
+ t.n2D((S.bb.center.x / n) * 1 * c + D, (S.bb.center.y / r) * 1 + D),
+ -1,
+ 1,
+ 0,
+ Qt.length - 1
+ )
+ ]);
+ let At = 0.015;
+ N == "l"
+ ? (At *= n * 1.2)
+ : N == "m"
+ ? (At *= n * 0.8 * t.range(0.75, 1))
+ : N == "h" && (At *= n * 0.25 * t.range(1, 1)),
+ N !== "h" && d.tScl == 1 && (At *= 1.3);
+ let It = [],
+ Lt = 0;
+ if (d.density !== "h") {
+ It = new Ln({ shape: [lt, dt], radius: At, tries: 20 }, t.random.bind(t));
+ var C = It.fill();
+ Lt = C.length;
+ }
+ let P = d.gridSpacing;
+ xt < 100 && (P = 1.5), t.n2D(et, ft) < 0.2;
+ const A = Math.ceil(lt / P),
+ s = Math.ceil(dt / P);
+ d.density == "h" && (Lt = A * s);
+ let h = rt == "#000000" ? 0 : t.range(d.othercolor * 0.8, d.othercolor * 1.2),
+ o = t.range(0.05, 0.25) * 0,
+ l = t.bool(o),
+ a = !0,
+ p = t.bool(d.contained);
+ const f = t.range(0.05, 0.15),
+ y = t.bool(d.gradient),
+ u = t.bool(0.5) ? 0 : t.range(-0.1, 0.1) * 0,
+ v = t.pick(d.fuzinessOpts),
+ _ = t.range(-0.2, 0.2) * 0.1;
+ let g = t.random() * 10,
+ b = !1,
+ E = t.range(0.07, 0.2);
+ d.tangentModeOpts.length == 1 &&
+ (d.tangentModeOpts[0] == "n" || d.tangentModeOpts[0] == "c") &&
+ (b = t.bool(0.5));
+ for (let z = 0; z < Lt; z++) {
+ let G = 0,
+ $ = 0;
+ const Z = z % A,
+ O = Math.floor(z / A);
+ d.density !== "h"
+ ? ((G = C[z][0] + S.bb.min.x), ($ = C[z][1] + S.bb.min.y))
+ : ((G = S.bb.min.x + Z * P), ($ = S.bb.min.y + O * P));
+ let B = G / n,
+ bt = $ / r;
+ const ut = Bt(G, S.bb.min.x, S.bb.max.x, 0, 1),
+ Tt = Bt($, S.bb.min.y, S.bb.max.y, 0, 1);
+ let Et = 0;
+ d.density == "h" ? (Et = z / Lt) : (Et = bt), Bt(G, S.bb.min.x, S.bb.max.x, 0, 1);
+ const Ft = Bt($, S.bb.min.y, S.bb.max.y, 0, 1),
+ wt = H(S.bb);
+ if (!re([G, $], S.points)) continue;
+ const Rt = J(G, $),
+ Ht = L(G, $);
+ let Nt = Rt && d.density !== "h" ? t.bool(0) : t.bool(h);
+ if ((h == 1 && ((Nt = !0), (h = 0.8)), (d.layers.length > 1 && I == "c" && Rt) || (d.bonly && !Rt)))
+ continue;
+ let Ot = Y > -1 ? i[Y].tangentMode : V;
+ const Yt = 20;
+ let tt = m.getTangentAtPosition(G, $, Yt, wt.radius);
+ if (!tt || isNaN(tt.x) || isNaN(tt.y)) continue;
+ m.getDistanceFromGeomAtPosition(G, $);
+ let ct = Bt(t.n2D(B * 1.3, bt * 1.3), -1, 1, (xt / n) * 0.01, (xt / n) * 0.3);
+ if (t.bool(1.5)) {
+ const ht = t.bool(0.5) ? 0.2 : 0.25,
+ gt = t.bool(0.5) ? 0.05 : 0.1;
+ let Mt = d.tScl;
+ d.comps.length == 1 && d.comps[0] == x.GRIBOUILLIS && (Mt = t.pick([0.3, 0.5, 1])),
+ (ct = Bt(t.n2D(B * 1.3, bt * 1.3), -1, 1, gt, ht) * Mt),
+ (Ot == "n" || (Ot == "c" && b)) && (ct = E * d.tScl);
+ }
+ if (
+ (t.bool(0.5) && ((tt.x = 0), (tt.y = 1)),
+ (Ot == "h" || (t.bool(0.05) && !Nt)) && ((tt.x = 1), (tt.y = t.range(-0.1, 0.1))),
+ Ot == "v" && ((tt.x = 0 + _), (tt.y = 1)),
+ Ot == "n" && (!Rt || i.length > 1))
+ ) {
+ const ht = d.compNseScl,
+ gt = (Y / i.length) * 0.15;
+ t.n2D(B * ht + gt + g, bt * ht + gt + g) * Math.PI * 2,
+ (tt.x = t.n2D(B * ht + gt + g, bt * ht + gt + g) * Math.PI * 2),
+ (tt.y = t.n2D(B * ht + gt + g * 2, bt * ht + gt + g * 2) * Math.PI * 2);
+ }
+ if (Ot == "c") {
+ let ht = 0.7;
+ d.comps.length == 1 && d.comps[0] == x.FIELD && (ht = d.compNseScl);
+ const gt = 180,
+ Mt = D,
+ Dt = t.curl2D(ut * c * ht + Mt, Tt * c * ht + Mt, 1);
+ (tt.x = Math.sign(Dt[0]) * (Math.floor(Math.abs(Dt[0]) * gt) / gt)),
+ (tt.y = Math.sign(Dt[1]) * (Math.floor(Math.abs(Dt[1]) * gt) / gt));
+ }
+ if (Ot == "oc") {
+ const Mt = D,
+ Dt = 0.1,
+ Pt = t.curl2D(ut * c * 0.7 + Mt, Tt * c * 0.7 + Mt, 1);
+ (Pt[0] = Math.sign(Pt[0]) * (Math.floor(Math.abs(Pt[0]) * 180) / 180)),
+ (Pt[1] = Math.sign(Pt[1]) * (Math.floor(Math.abs(Pt[1]) * 180) / 180)),
+ (tt.x = Se(tt.x, Pt[0], Dt)),
+ (tt.y = Se(tt.y, Pt[1], Dt));
+ }
+ if (!tt || isNaN(tt.x) || isNaN(tt.y)) continue;
+ if (Ot !== "o" && Ot !== "v" && d.rotateSkew) {
+ const ht = u + (Math.PI / 4) * Et,
+ gt = tt.x * Math.cos(ht) - tt.y * Math.sin(ht),
+ Mt = tt.x * Math.sin(ht) + tt.y * Math.cos(ht);
+ (tt.x = gt), (tt.y = Mt);
+ }
+ d.isLandscape && bt > 0.7 && ((tt.x = 1), (tt.y = 0)), (ct *= n);
+ let at = f * t.range(0.5, 1);
+ const Ct = 1e-4 * n * t.range(1, 2.3),
+ Zt = t.bool(d.multiplyAmount) ? "multiply" : "source-over";
+ let Xt = rt,
+ ee = rt,
+ ne = 1 / 0,
+ zt = -1;
+ for (let ht = 0; ht < le.length; ht++) {
+ const gt = le[ht].points;
+ if (re([G, $], gt)) {
+ let Mt = 1 / 0;
+ for (let Dt = 0; Dt < gt.length; Dt += 2) {
+ const Pt = gt[Dt],
+ Vt = gt[Dt + 1],
+ oe = Math.sqrt(Math.pow(G - Pt, 2) + Math.pow($ - Vt, 2));
+ Mt = Math.min(Mt, oe);
+ }
+ Mt < ne && ((ne = Mt), ht % Qt.length, (zt = ht));
+ }
+ }
+ if ((zt > -1 && t.bool(d.isStrokeColorFromB) && (Xt = le[zt].color), Nt)) {
+ if (
+ ((Xt = t.pick(Qt)),
+ t.bool(0.5) && (Xt = Qt[~~Bt(t.n2D(G / n, $ / r), -1, 1, 0, Qt.length - 1)]),
+ t.bool(0.5) && d.dirtyBgColor)
+ ) {
+ const ht = t.pick(Qt),
+ gt = Xe(ht),
+ Mt = t.range(0.3, 0.7),
+ Dt = Xe(Xt);
+ (Dt.h = Se(Dt.h, gt.h, Mt)),
+ (Dt.s = Se(Dt.s, gt.s, Mt)),
+ (Dt.l = Se(Dt.l, gt.l, Mt)),
+ (Xt = en(Dt));
+ }
+ if (
+ ((at *= t.range(0.4, 0.7)),
+ (!S.canUseGradient || rt == F) && ((at *= d.othercolorScl), d.darkOtherColorInBg))
+ ) {
+ const ht = Xe(Xt);
+ (ht.l *= t.range(0.4, 0.7)), (Xt = en(ht)), (at *= 0.5);
+ }
+ }
+ if (l) {
+ const ht = ~~Bt(t.n2D(G / n, $ / r), -1, 1, 0, Qt.length - 1);
+ Xt = Qt[ht];
+ }
+ Ot == "h" && !p && (a = t.bool(Math.pow(Et * 0.5, 2))),
+ !(Rt && (d.uniformBg && (Xt = F), !d.bfill)) &&
+ (I == "b" && (a = !0),
+ t.bool(Ft) && y && S.canUseGradient && (Xt = pt),
+ t.bool(1 - d.press) && ((Xt = d.backgroundColor), (at *= 0.7)),
+ d.light && t.bool(0.9) && Ht && !Nt && (Xt = "#FECD1A"),
+ nt.push({
+ x: G,
+ y: $,
+ tangent: tt,
+ tangentScl: ct,
+ opacity: at,
+ thickness: Ct,
+ color: Xt,
+ mixedColor: ee,
+ geomIdx: Y,
+ geom: S,
+ blendingMode: Zt,
+ stayWithinGeom: a,
+ isFirstGeom: w,
+ fillProgress: Et,
+ isOtherColor: Nt,
+ fuziness: v,
+ isInBackground: Rt,
+ }),
+ me.push({
+ x: G,
+ y: $,
+ tangent: tt,
+ tangentScl: ct,
+ opacity: at,
+ thickness: Ct,
+ color: Xt,
+ mixedColor: ee,
+ geomIdx: Y,
+ geom: S,
+ blendingMode: Zt,
+ stayWithinGeom: a,
+ isFirstGeom: w,
+ fillProgress: Et,
+ isOtherColor: Nt,
+ fuziness: v,
+ isInBackground: Rt,
+ }));
+ }
+ for (let z = X; z < me.length; z++);
+ });
+ };
+ return {
+ getStrokeData: () => ({ strokePoints: me, strokesData: be }),
+ getPalette: () => Qt,
+ setGeoms: (I) => {
+ (pe = I), (m = Vo()), m.setGeoms(pe), m.render();
+ for (let i = 0; i < pe.length; i++) {
+ const k = t.pick(fn),
+ S = pe[i],
+ D = { points: [], color: "0x000000", tangentMode: k, isFilled: !0, canUseGradient: !0 },
+ nt = S.points,
+ Y = [];
+ for (let et = 0; et < nt.length; et++) {
+ let ft = nt[et].pt.x,
+ xt = nt[et].pt.y;
+ D.points.push(ft, xt), Y.push([ft, xt]);
+ }
+ if (!Y.length) continue;
+ const w = sn(Y),
+ X = w.maxX - w.minX,
+ V = w.maxY - w.minY,
+ N = w.minX + X / 2,
+ T = w.minY + V / 2;
+ (D.bb = {
+ center: { x: N, y: T },
+ dimensions: { width: X, height: V },
+ min: { x: w.minX, y: w.minY },
+ max: { x: w.maxX, y: w.maxY },
+ }),
+ (D.area = X * V);
+ const lt = ot(D),
+ dt = lt.color;
+ (D.color = dt), (D.neg = lt.neg), D.neg && (D.canUseGradient = !1), te.push(D);
+ }
+ if (d.isolation) {
+ te.sort((k, S) => {
+ const D = S.area - k.area;
+ return D === 0 ? te.indexOf(k) - te.indexOf(S) : D;
+ });
+ const i = t.pick(Qt);
+ for (let k = 0; k < te.length; k++)
+ k <= d.nbIsolated
+ ? (te[k].color = i)
+ : ((te[k].canUseGradient = !1),
+ d.negMode == "e" ? (te[k].isFilled = !1) : (te[k].color = d.backgroundColor));
+ }
+ for (let i = 0; i < d.layers.length; i++) {
+ const k = d.layers[i];
+ j(k);
+ }
+ yt(), mt(), vt(), St();
+ },
+ getStrokesData: () => be,
+ setBaseShapes: (I) => {
+ (Pe = I), (le = []);
+ for (let i = 0; i < Pe.length; i++) {
+ const k = t.pick(fn),
+ S = Pe[i],
+ D = { points: [], color: "0x000000", tangentMode: k, isFilled: !0 },
+ nt = S.points,
+ Y = [];
+ for (let lt = 0; lt < nt.length; lt++) {
+ let dt = nt[lt].x,
+ et = nt[lt].y;
+ D.points.push(dt, et), Y.push([dt, et]);
+ }
+ if (!Y.length) continue;
+ const w = sn(Y),
+ X = w.maxX - w.minX,
+ V = w.maxY - w.minY,
+ N = w.minX + X / 2,
+ T = w.minY + V / 2;
+ (D.bb = {
+ center: { x: N, y: T },
+ dimensions: { width: X, height: V },
+ min: { x: w.minX, y: w.minY },
+ max: { x: w.maxX, y: w.maxY },
+ }),
+ S.isDoorSide && (D.side = S.side),
+ (D.color = ot(D).color),
+ t.n2D(N, T) < 0.05,
+ le.push(D),
+ S.isDoorSide && Ye.push(D);
+ }
+ },
+ setDataZones: (I) => {
+ R = I;
+ },
+ };
+};
+let Ce = null,
+ dn = null,
+ Re = null,
+ ke = null,
+ ve = null;
+const _o = async (e) => {
+ const n = document.createElement("div");
+ (n.textContent = "generating"), document.body.appendChild(n), performance.now(), (Ce = Fo());
+ const r = Ce.getCanvas();
+ await new Promise((c) => setTimeout(c, 100)),
+ Ce.render(),
+ (dn = No()),
+ (ke = Bo()),
+ ke.setBaseShapes(Ce.getShapes()),
+ ke.fromImage(r),
+ (ve = Yo()),
+ ve.setDataZones(dn.getZones()),
+ ve.setBaseShapes(Ce.getShapes()),
+ ve.setGeoms(ke.getGeoms()),
+ (Re = Xo()),
+ Re.setRawIslandsData(ke.getGeoms()),
+ Re.setStrokesData(ve.getStrokeData()),
+ Re.play?.(),
+ document.body.appendChild(Re.getFinalCanvas()),
+ Tn.on(Gn.RENDER_COMPLETE, () => {
+ console.log("render complete"), capturePreview();
+ }),
+ document.body.removeChild(n);
+};
+_o();