Unlock custom brushes, natural fill effects and intuitive hatching in p5.js
BIG performance improvements
acamposuribe92ce58763e4c
diff --git a/dist/p5.brush.esm.js b/dist/p5.brush.esm.jsindex e5ab2e1..1eb5846 100644--- a/dist/p5.brush.esm.js+++ b/dist/p5.brush.esm.js@@ -1,2 +1,2 @@-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};+let t,e,r,n,i,a=null;const o=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,s=()=>p?r:window.self.p5.instance,l=()=>n?._renderer?.activeFramebuffer?.()??null,c=t=>{if(!t)return;if(o(t))return void t.draw(()=>n.clear());const e=t.drawingContext;e.save(),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height),e.restore()},h=()=>({width:Math.max(1,Math.round(t*i)),height:Math.max(1,Math.round(e*i))}),u=t=>{if(!t)return null;const{width:e,height:r}=h(),n=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),i=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),a=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),o=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return a<=n||o<=i?null:{minX:n,minY:i,maxX:a,maxY:o}},f=()=>{const{width:t,height:e}=h();return{minX:0,minY:0,maxX:t,maxY:e}},m=(t,e=!0)=>{const r=u(t);if(!r)return null;const{height:n}=h();return{x:r.minX,y:e?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},d=(t,e,r,n=!0)=>{const i=m(e,n);if(i){t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{r()}finally{t.disable(t.SCISSOR_TEST)}}else r()},g=(i=!1)=>{const a=((t=!1)=>{if(p&&!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(t.renderer._pInst!==s())throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch");return{renderer:s(),width:t.width,height:t.height}}return{renderer:t,width:t.width,height:t.height}})(i);if(n=a.renderer,"webgl2"!==n.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");t=a.width,e=a.height,x=!0,n.loaded&&w.load()};let x=!1,p=!1;const y=()=>{x||g()},_={},b=t=>{p=!0,r=t},v=()=>{n?.loaded||(y(),w.load())},w={isBlending:!1,cachedColor:new Object,markDirtyRect(t,e){const r=u(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&&(c(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:(t,e)=>t?t.dirtyRect?e&&l()?f():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,load(){i=n.pixelDensity();const r=Math.max(1,Math.round(t*i)),a=Math.max(1,Math.round(e*i)),o=!n.mask||!n.glMask||n.mask.width!==r||n.mask.height!==a||n.glMask.width!==t||n.glMask.height!==e,s=!n.blendSourceFramebuffer||n.blendSourceFramebuffer.width!==t||n.blendSourceFramebuffer.height!==e||"function"==typeof n.blendSourceFramebuffer.pixelDensity&&n.blendSourceFramebuffer.pixelDensity()!==i,l=!n.fillMaskFramebuffer||n.fillMaskFramebuffer.width!==t||n.fillMaskFramebuffer.height!==e||"function"==typeof n.fillMaskFramebuffer.pixelDensity&&n.fillMaskFramebuffer.pixelDensity()!==i;n.loaded&&!o||(n.glMask?.remove&&n.glMask.remove(),n.mask=new OffscreenCanvas(r,a),n.mask.drawingContext=n.mask.getContext("2d"),n.glMask=n.createFramebuffer({width:t,height:e,density:i,antialias:!1,depth:!1,stencil:!1}),n.loaded=!0,n.shaderProgram??=n.createShader("#version 300 es\n#define GLSLIFY 1\nout vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,-v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform bool u_targetIsFramebuffer;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 sourceUV=vec2(uv.x,1.0-uv.y);vec2 maskUV=u_targetIsFramebuffer ? vec2(uv.x,1.0-uv.y): uv;vec4 source=texture(u_source,sourceUV);vec4 maskColor=texture(u_mask,maskUV);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=maskUV+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);}")),s&&(n.blendSourceFramebuffer?.remove&&n.blendSourceFramebuffer.remove(),n.blendSourceFramebuffer=n.createFramebuffer({width:t,height:e,density:i,antialias:!1,depth:!1,stencil:!1})),l&&(n.fillMaskFramebuffer?.remove&&n.fillMaskFramebuffer.remove(),n.fillMaskFramebuffer=n.createFramebuffer({width:t,height:e,density:i,antialias:!1,depth:!1,stencil:!1}),c(n.fillMaskFramebuffer)),this.mask=n.mask,this.glMask=n.glMask,this.ctx=this.mask.drawingContext,this.mask.dirtyRect??=null,this.mask.isDrawn??=!1,this.ctx.imageSmoothingEnabled=!1,this.glMask.dirtyRect??=null,this.glMask.isDrawn??=!1},blend(t=!1,e=!1){v();const r=!0===this.isBrush,n=r?this.glMask:this.mask,i=r?this.mask:this.glMask,a=t?._array,o=!!a&&(this.cachedColor[0]!==a[0]||this.cachedColor[1]!==a[1]||this.cachedColor[2]!==a[2]||this.cachedColor[3]!==a[3]);!this.isBlending&&a&&(this.isBlending=!0,this.cachedColor=a,c(this.glMask)),(e||o)&&(this.justChanged&&(this.applyShader(i,!r),this.justChanged=!1),this.isBlending&&this.applyShader(n,r),a&&(this.cachedColor=a),e&&(this.isBlending=!1))},applyShader(r,i){if(!r?.isDrawn)return;const o=this.getCompositeRect(r,i);if(!o)return void this.clearMask(r);const s=n.drawingContext,h=n.shaderProgram,m=l(),g=R(m??n,o),x=!!m,p=s.getParameter(s.DEPTH_TEST);s.disable(s.DEPTH_TEST),n.push(),n.translate(0,0),n.shader(h),h.setUniform("u_source",g),h.setUniform("u_targetIsFramebuffer",x),h.setUniform("u_isBrush",i),i?h.setUniform("u_mask",r):h.setUniform("u_mask",((t,e=null)=>{const r=n.fillMaskFramebuffer,i=n.drawingContext,o=u(e)??f(),s=o.maxX-o.minX,l=o.maxY-o.minY;a&&a.width===s&&a.height===l||(a=new OffscreenCanvas(s,l),a.drawingContext=a.getContext("2d"));const h=a.drawingContext;return h.clearRect(0,0,s,l),h.drawImage(t,o.minX,o.minY,s,l,0,0,s,l),c(r),i.bindTexture(i.TEXTURE_2D,r.colorTexture),i.texSubImage2D(i.TEXTURE_2D,0,o.minX,o.minY,i.RGBA,i.UNSIGNED_BYTE,a),r})(r,o)),h.setUniform("u_color",this.cachedColor),d(s,o,()=>{n.fill(0,0,0,0),n.noStroke(),n.rect(-t/2,-e/2,t,e)},!x),n.pop(),n.resetShader(),p&&s.enable(s.DEPTH_TEST),this.clearMask(r)}},R=(r,i=null)=>{const a=n.blendSourceFramebuffer,s=n.drawingContext,l=o(r),{width:c,height:u}=h(),f=i?m(i):null,g=s.getParameter(s.READ_FRAMEBUFFER_BINDING),x=s.getParameter(s.DRAW_FRAMEBUFFER_BINDING);return(l?r.renderer:n._renderer)?.flushDraw?.(),l?(a.draw(()=>{d(n.drawingContext,i,()=>{n.clear(),n.push(),n.imageMode(n.CENTER),n.image(r,0,0,t,e),n.pop()},!1)}),a):(s.bindFramebuffer(s.READ_FRAMEBUFFER,null),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,a.framebuffer),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT),s.blitFramebuffer(f?.x??0,f?.y??0,f?f.x+f.width:c,f?f.y+f.height:u,f?.x??0,f?.y??0,f?f.x+f.width:c,f?f.y+f.height:u,s.COLOR_BUFFER_BIT,s.NEAREST),s.bindFramebuffer(s.READ_FRAMEBUFFER,g),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,x),a)},A=Math.sqrt(3),E=.5*(A-1),M=(3-A)/6,S=t=>0|Math.floor(t),P=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 T(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=>P[t%12*2]),n=new Float64Array(e).map(t=>P[t%12*2+1]);return function(t,i){let a=0,o=0,s=0;const l=(t+i)*E,c=S(t+l),h=S(i+l),u=(c+h)*M,f=t-(c-u),m=i-(h-u);let d,g;f>m?(d=1,g=0):(d=0,g=1);const x=f-d+M,p=m-g+M,y=f-1+2*M,_=m-1+2*M,b=255&c,v=255&h;let w=.5-f*f-m*m;if(w>=0){const t=b+e[v];w*=w,a=w*w*(r[t]*f+n[t]*m)}let R=.5-x*x-p*p;if(R>=0){const t=b+d+e[v+g];R*=R,o=R*R*(r[t]*x+n[t]*p)}let A=.5-y*y-_*_;if(A>=0){const t=b+1+e[v+1];A*=A,s=A*A*(r[t]*y+n[t]*_)}return 70*(a+o+s)}}function k(t,e){let r=new I(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class I{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 C=k(Math.random());const L=[],F=t=>L.push(t);let D=T(k(Math.random()));const N=(t=0,e=1)=>t+C()*(e-t),Y=t=>t[~~(C()*t.length)],B=(t,e)=>~~N(t,e),X=(t=0,e=1)=>{const r=1-C(),n=C();return Math.sqrt(-2*Math.log(r))*j(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=C()*e;for(const{key:t,cumulative:e}of r)if(n<e)return isNaN(t)?t:parseInt(t)},O=(t,e,r,n,i,a=!1)=>{let o=n+(t-e)/(r-e)*(i-n);return a?n<i?U(o,n,i):U(o,i,n):o},U=(t,e,r)=>Math.max(Math.min(t,r),e),G=t=>(t%=360)<0?t+360:t,V=1440,W=2*Math.PI/V,$=new Float32Array(V).fill(NaN),H=new Float32Array(V).fill(NaN),j=t=>{const e=~~(4*G(t));let r=$[e];return isNaN(r)&&(r=Math.cos(e*W),$[e]=r),r},K=t=>{const e=~~(4*G(t));let r=H[e];return isNaN(r)&&(r=Math.sin(e*W),H[e]=r),r},Z=(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},q=(t,e=!1)=>e||n&&"function"==typeof n.angleMode&&n.angleMode()===n.RADIANS?180*t/Math.PI:t,J=(t,e,r,n,i)=>{let a=j(i),o=K(i);return{x:a*(r-t)+o*(n-e)+t,y:a*(n-e)-o*(r-t)+e}},Q=(t,e,r,n)=>Math.hypot(r-t,n-e),tt=(t,e,r,n)=>Z(Math.atan2(-(n-e),r-t),!0),et=(t,e,r,n,i=!1)=>{let a=t.x,o=t.y,s=e.x,l=e.y,c=r.x,h=r.y,u=n.x,f=n.y;if(a===s&&o===l||c===u&&h===f)return!1;let m=s-a,d=l-o,g=u-c,x=f-h,p=x*m-g*d;if(0===p)return!1;let y=(g*(o-h)-x*(a-c))/p,_=(m*(o-h)-d*(a-c))/p;return!(!i&&(_<0||_>1))&&{x:a+y*m,y:o+y*d}},rt=()=>n._renderer.uModelMatrix.mat4[12],nt=()=>n._renderer.uModelMatrix.mat4[13],it=()=>n._renderer.uModelMatrix.mat4[0],at=()=>n._renderer.uModelMatrix.mat4[1],ot=()=>n._renderer.uModelMatrix.mat4[4],st=()=>n._renderer.uModelMatrix.mat4[5];let lt=!1;function ct(){lt||(v(),ut=.01*t,ft=-.5*t,mt=-.5*e,dt=Math.round(2*t/ut),gt=Math.round(2*e/ut),Rt("hand",(t,e)=>{const r=N(.2,.8),n=B(5,10);return Mt(e,(e,i)=>.5*n*K(r*i*e+B(15,25))*.2*j(t)+D(e,i)*n*.7)}),Rt("curved",(t,e)=>{let r=B(-10,10);return B(0,100)%2==0&&(r*=-1),Mt(e,(e,n)=>3*O(D(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),Rt("zigzag",(t,e)=>{let r=B(-30,-15)+Math.abs(44*K(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<gt;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),Rt("waves",(t,e)=>{const r=B(10,15)+5*K(t),n=B(3,6)+3*j(t),i=B(20,35);return Mt(e,(t,e)=>K(r*t)*i*j(e*n)+B(-3,3))}),Rt("seabed",(t,e)=>{const r=N(.4,.8),n=B(18,26);return Mt(e,(e,i)=>1.1*n*K(r*i*e+B(15,20))*j(t))}),Rt("spiral",(t,e)=>{const r=B(5,10),n=2*B(0,2)-1,i=B(65,80),a=Array.from({length:r},()=>({x:N(.1,.9)*dt,y:N(.1,.9)*gt}));return Mt(e,(t,e)=>{let r=0,o=0;for(const s of a){const a=t-s.x,l=e-s.y,c=1/(a*a+l*l+1),h=Math.atan2(l,a)*(180/Math.PI),u=n*(h+i)*Math.PI/180;r+=c*Math.cos(u),o+=c*Math.sin(u)}return Math.atan2(o,r)*(180/Math.PI)})}),Rt("columns",(t,e)=>{const r=B(3,8),n=B(25,45);return Mt(e,(t,e)=>K(t*r)*n)}),lt=!0)}class ht{constructor(t,e){ct(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=ht.getColIndex(t),this.rowIdx=ht.getRowIndex(e)}reset(){this.plotted=0}isIn(){return _.field.isActive?ht.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const r=t,n=e,i=this.x+rt(),a=this.y+nt();return i>=-.3*r&&i<=1.3*r&&a>=-.3*n&&a<=1.3*n}angle(){return this.isIn()&&_.field.isActive?xt.get(_.field.current).field[this.colIdx][this.rowIdx]*_.field.wiggle:0}moveTo(t,e,r=1){this.movePos(q(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 a=0;a<e/r;a++){const e=this.angle()-(n?t.angle(this.plotted):t);this.update(this.x+r*j(e),this.y+r*K(e)),this.plotted+=r/i}else this.plotted+=r/i}static getRowIndex(t,e=1){const r=t+nt()-mt;return Math.round(r/ut/e)}static getColIndex(t,e=1){const r=t+rt()-ft;return Math.round(r/ut/e)}static isIn(t,e){return t>=0&&e>=0&&t<dt&&e<gt}}_.field={isActive:!1,current:null,wiggle:1};let ut,ft,mt,dt,gt,xt=new Map;const pt=new Set(["degrees","radians"]);function yt(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 _t(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]=q(t[e][r],!0);return t}(t.gen(e,new Array(dt).fill(null).map(()=>new Float32Array(gt))),t.angleMode)}function bt(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=xt.get(_.field.current);e.field=_t(e,t)}function vt(t){if(_.field.wiggle||(_.field.wiggle=1),ct(),!xt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(xt.keys()).join(", ")}.`);_.field.isActive=!0,_.field.current=t;const e=xt.get(t);e.field||(e.field=_t(e,0))}function wt(){ct(),_.field.isActive=!1}function Rt(t,e,r={}){xt.set(t,{gen:e,field:null,angleMode:yt(r)})}function At(){return ct(),Array.from(xt.keys())}function Et(t=1){vt("hand"),_.field.wiggle=t}function Mt(t,e){for(let r=0;r<dt;r++)for(let n=0;n<gt;n++)t[r][n]=e(r,n);return t}class St{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=et(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 Pt{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:Z(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:Z(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=Z(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,a){ct();const o=.5,s=[],l=Math.round(this.length/o),c=new ht(r+t/2,n+e/2);let h=0,u=0;for(let r=0;r<l;r++){c.plotTo(this,o,o);const r=this.calcIndex(c.plotted);h+=o,(h>=Math.max(this.segments[r]*a*N(.7,1.3),20)||r>=u)&&c.x&&(s.push([c.x-t/2,c.y-e/2]),h=0,r>=u&&u++)}return new St(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 Tt(t){new St(t).show()}function kt(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),Bt(0),Xt(t,e),Xt(t+r,e),Xt(t+r,e+n),Xt(t,e+n),zt(!0)}function It(t,e,r,n=!1){const i=new Pt("curve"),a=Math.PI*r,o=N(0,360),s=n?()=>1+.2*n*N():()=>1;for(let t=0;t<4;t++){const e=-90*t+o;i.addSegment(e*s(),a/2*s(),1,!0)}if(n){const t=n*B(-5,5);i.addSegment(o,Math.abs(t)*(Math.PI/180)*r,1,!0),i.endPlot(t+o,1,!0)}else i.endPlot(o,1,!0);const l=t-r*K(o),c=e-r*j(-o);i.show(l,c,1)}function Ct(t,e,r,n,i){const a=q(n),o=((q(i)-a)%360+360)%360;if(0===o)return;const s=new Pt("curve"),l=Math.max(1,Math.ceil(o/90)),c=o/l,h=Math.PI*r*c/180;for(let t=0;t<l;t++)s.addSegment(a+t*c+90,h,1,!0);s.endPlot(a+o+90,1,!0);const u=t+r*j(a),f=e-r*K(a);s.draw(u,f,1)}let Lt,Ft,Dt,Nt;class Yt{constructor(){this.isClosed=!1,this.curvature=Ft,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){Wt(this.vert,this.curvature,this.isClosed).show()}}function Bt(t=0){Ft=U(t,0,1),Lt=new Yt}function Xt(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}".`);Nt=[e,r],Dt=new Pt(t)}function Ut(t,e,r){if(!Dt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Dt.addSegment(t,e,r)}function Gt(t,e){if(!Dt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Dt.endPlot(t,e),Dt.draw(Nt[0],Nt[1],1),Dt=!1}function Vt(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");Wt(t,e).draw()}function Wt(t,e=.5,r=!1){const n=new Pt(0===e?"segments":"curve"),i=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let a,o,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=Q(h[0],h[1],u[0],u[1]),d=Q(u[0],u[1],f[0],f[1]),g=tt(h[0],h[1],u[0],u[1]),x=tt(u[0],u[1],f[0],f[1]),p=e*Math.min(m,d,.5*Math.min(m,d)),y=Math.max(m,d),_=m-p,b=d-p;if(Math.floor(g)===Math.floor(x)){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(x,i,u[2],!0),l=0,0===c&&(a=m,s=p,o=t[1],l=0)}else{const e={x:u[0]-p*j(-g),y:u[1]-p*K(-g)},f={x:e.x+y*j(90-g),y:e.y+y*K(90-g)},m={x:u[0]+p*j(-x),y:u[1]+p*K(-x)},d={x:m.x+y*j(90-x),y:m.y+y*K(90-x)},v=et(e,f,m,d,!0),w=Q(e.x,e.y,v.x,v.y),R=Q(e.x,e.y,m.x,m.y)/2,A=i*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=r&&0===c?0:_-l,M=c===t.length-3?r?a-p:b:0;n.addSegment(g,E,h[2],!0),n.addSegment(g,isNaN(A)?0:A,h[2],!0),n.addSegment(x,M,u[2],!0),l=p,0===c&&(a=_,s=p,o=[e.x,e.y])}c===t.length-3&&n.endPlot(x,u[2],!0)}else if(0===e){const e=t[c],r=t[c+1],i=Q(e[0],e[1],r[0],r[1]),a=tt(e[0],e[1],r[0],r[1]);n.addSegment(a,i,r[2],!0),c===t.length-2&&n.endPlot(a,1,!0)}n.origin=r&&0!==e?o:t[0]}return n}const $t=(t,e,r)=>{const n=t.createProgram();for(let[i,a]of[[t.VERTEX_SHADER,e],[t.FRAGMENT_SHADER,r]]){const e=t.createShader(i);t.shaderSource(e,a),t.compileShader(e),t.attachShader(n,e)}return t.linkProgram(n),n};let Ht,jt,Kt,Zt,qt,Jt=!1,Qt=0,te=0,ee=null,re=null;const ne={},ie={};let ae=1,oe=0,se=0,le=1,ce=0,he=0,ue=0,fe=0,me=1,de=1,ge=new Float32Array(8192),xe=0,pe=2048,ye=32768,_e=null,be=null,ve=null,we=null,Re=null;const Ae={},Ee={};let Me=0,Se=new Float32Array(1280),Pe=0,Te=256,ke=null;const Ie=new Map,Ce=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function Le(){const t=w.glMask?.renderer;t&&(t._curShader=null,t._cachedBlendMode=null,t._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(){return jt}function De(){const t=Ht.isEnabled(Ht.DEPTH_TEST);var e;De._hadDepthTest=t,t&&Ht.disable(Ht.DEPTH_TEST),re=n._renderer.activeFramebuffer?.()??null,re?._beforeEnd&&re._beforeEnd(),Ht.bindFramebuffer(Ht.FRAMEBUFFER,(e=w.glMask)?"function"==typeof e._framebufferToBind?e._framebufferToBind():e.framebuffer??null:null),Ht.viewport(0,0,w.glMask.width*w.glMask.density,w.glMask.height*w.glMask.density)}function Ne(){De._hadDepthTest&&Ht.enable(Ht.DEPTH_TEST),De._hadDepthTest=!1,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 Ye(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 Be(t,e,r,n){if(xe>=pe){pe*=2;const t=new Float32Array(4*pe);t.set(ge),ge=t}const i=t-ue,a=e-fe,o=4*xe,s=ae*i+se*a+ce+ue,l=oe*i+le*a+he+fe,c=de*r*me/2;ge[o]=s,ge[o+1]=l,ge[o+2]=c,ge[o+3]=n/255;const h=s*de,u=l*de;_e=Ye(_e,h-c-1,u-c-1,h+c+1,u+c+1),xe++}function Xe(t,e){if(0===Pe)return;w.glMask.isDrawn=!0,De();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(Ee.u_tex,0);const n=_.stroke.color._array;Ht.uniform4f(Ee.u_color,...n),Ht.uniformMatrix4fv(Ee.u_proj,!1,Fe()),Ht.bindVertexArray(ve),Ht.bindBuffer(Ht.ARRAY_BUFFER,Re);const i=5*Pe*4,a=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,a),Ht.drawArraysInstanced(Ht.TRIANGLE_STRIP,0,4,Pe),Ht.flush(),Ht.bindVertexArray(null),Ht.bindTexture(Ht.TEXTURE_2D,null),Ne(),ke&&(w.markDirtyRect(w.glMask,ke),ke=null),Pe=0,Le()}_.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let ze=new Map,Oe={a:1,b:0,c:0,d:1,tx:0,ty:0};function Ue(){return n??r??window.self.p5.instance}const Ge={offset:.08,scale:.08,warp:.06,tilt:.06};function Ve(){return{..._.stroke}}function We(t){_.stroke={...t}}function $e(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:{...Ge}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...Ge,...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),a=Math.max(e,r,n),o=a-i||1,[s,l,c]=[(e-i)/o,(r-i)/o,(n-i)/o];return{type:"custom",min_max:[i,a],variation:{...Ge},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=Ue().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(),Rr.imageToWhite(n),Rr.tips.set(r,n),e.tipKey=r,void ze.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 Rr.add(e.image.src),ze.set(t,{param:e,colors:[],buffers:[]}),Rr.load()}ze.set(t,{param:e,colors:[],buffers:[]})}function He(){return[...ze.keys()]}function je(t){for(const{param:e}of ze.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function Ke(t){if(!ze.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...ze.keys()].join(", ")}.`);_.stroke.type=t}function Ze(t,e,r){y(),_.stroke.color=n.color(...arguments),_.stroke.isActive=!0}function qe(t){_.stroke.weight=t}function Je(t,e,r=1){Ke(t),Ze(e),qe(r)}function Qe(){_.stroke.isActive=!1}function tr(){return{a:it(),b:at(),c:ot(),d:st(),tx:rt(),ty:nt()}}function er(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 rr(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}}(tr());if(!e)throw new Error("brush.clip() cannot be used with a non-invertible transform.");_.stroke.clipWindow={bounds:er(t),inverse:e}}function nr(){_.stroke.clipWindow=null}let ir,ar,or,sr;const lr={};function cr(r,n,a,o=!1){ae=it(),oe=at(),se=ot(),le=st(),ce=rt(),he=nt(),ue=t/2,fe=e/2,me=Math.sqrt(ae*ae+oe*oe),de=i,Oe=tr(),ir=new ht(r+t/2,n+e/2),ar=a,or=o,or&&or.calcIndex(0)}const hr=[];function ur(r,i){i||(sr=r),function(){lr.seed=999999*N();const{param:r}=ze.get(_.stroke.type)??{};if(!r)return;lr.p=r;const{pressure:i}=r;if(lr.a="custom"!==i.type?N(-1,1):0,lr.b="custom"!==i.type?N(1,1.5):0,"custom"!==i.type)lr.cp=N(3,3.5),lr.ct=0,lr.cs=1,lr.ck=0;else{const t=i.variation??Ge;lr.cp=N(-t.offset,t.offset),lr.ct=N(-t.warp,t.warp),lr.cs=N(1-t.scale,1+t.scale),lr.ck=N(-t.tilt,t.tilt)}if([lr.min,lr.max]=i.min_max,lr.noiseoffset=.03,!or){const t=sr*Math.PI/180;lr.cos=Math.cos(t),lr.sin=Math.sin(t)}!function(){v(),function(){const t=n?.glMask;t&&(ee=t,ee.dirtyRect??=null,ee.isDrawn??=!1,w.glMask=ee)}();const r=n.drawingContext,i=!Jt||Ht!==r;(i||Qt!==t||te!==e)&&(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),i&&(Ht=r,qt=$t(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=$t(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=>Ae[t]=Ht.getAttribLocation(be,t)),["u_proj","u_color","u_tex"].forEach(t=>Ee[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,Ce,Ht.STATIC_DRAW),Ht.enableVertexAttribArray(Ae.a_corner),Ht.vertexAttribPointer(Ae.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(Ae.a_pos),Ht.vertexAttribPointer(Ae.a_pos,2,Ht.FLOAT,!1,20,0),Ht.vertexAttribDivisor(Ae.a_pos,1),Ht.enableVertexAttribArray(Ae.a_size),Ht.vertexAttribPointer(Ae.a_size,1,Ht.FLOAT,!1,20,8),Ht.vertexAttribDivisor(Ae.a_size,1),Ht.enableVertexAttribArray(Ae.a_angle),Ht.vertexAttribPointer(Ae.a_angle,1,Ht.FLOAT,!1,20,12),Ht.vertexAttribDivisor(Ae.a_angle,1),Ht.enableVertexAttribArray(Ae.a_alpha),Ht.vertexAttribPointer(Ae.a_alpha,1,Ht.FLOAT,!1,20,16),Ht.vertexAttribDivisor(Ae.a_alpha,1),Ht.bindVertexArray(null),Jt=!0)}();const a=!0!==w.isBrush;w.isBrush=!0,a&&(w.justChanged=!0),w.blend(_.stroke.color),lr.alpha=["default","spray"].includes(lr.p.type)?lr.p.opacity:lr.p.opacity/Math.min(_.stroke.weight,1.3);{const r=t/2,n=e/2,i=Oe;if(_.stroke.clipWindow){const{inverse:t,bounds:e}=_.stroke.clipWindow,a=t.a*i.a+t.c*i.b,o=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;lr.clipA=a,lr.clipB=s,lr.clipC=o,lr.clipD=l,lr.clipTX=t.a*i.tx+t.c*i.ty+t.tx-a*r-o*n,lr.clipTY=t.b*i.tx+t.d*i.ty+t.ty-s*r-l*n,lr.clipMinX=e.minX,lr.clipMaxX=e.maxX,lr.clipMinY=e.minY,lr.clipMaxY=e.maxY}else{const e=.05*t;lr.clipA=i.a,lr.clipB=i.b,lr.clipC=i.c,lr.clipD=i.d,lr.clipTX=i.tx-i.a*r-i.c*n,lr.clipTY=i.ty-i.b*r-i.d*n,lr.clipMinX=-r-e,lr.clipMaxX=r+e,lr.clipMinY=-n-e,lr.clipMaxY=n+e}}yr()}();const a=function(){const{param:t}=ze.get(_.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(ar*(i?r:1)/a);for(let t=0;t<o;t++)hr.length<2*o&&hr.push(X()),fr(),i?ir.plotTo(or,a,a,r,t<10):ir._moveToDegrees(r,a,a);!function(){yr(),function(){if(0===xe)return;w.glMask.isDrawn=!0,De();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*xe,r=ge.subarray(0,4*xe);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,Fe()),Ht.drawArrays(Ht.POINTS,0,xe),Ht.flush(),Ht.bindVertexArray(null),Ne(),_e&&(w.markDirtyRect(w.glMask,_e),_e=null),xe=0,Le()}();const t=lr.p?.type;"image"===t?Xe(Rr.tips.get(lr.p.image.src),lr.p.image.src):"custom"===t&&Xe(Rr.tips.get(lr.p.tipKey),lr.p.tipKey)}()}function fr(){if(!gr())return;const t=mr(),e=O(D(lr.seed+.002*ir.plotted,0),0,1,1-lr.noiseoffset,1+lr.noiseoffset);switch(lr.p.type){case"spray":!function(t){const e=_.stroke.weight*lr.p.scatter*t+_.stroke.weight*Y(hr)*lr.p.scatter/3,r=lr.p.weight*N(.9,1.1),n=Math.ceil(lr.p.grain/t);for(let t=0;t<n;t++){const t=N(.9,1.1),n=t*e*N(-1,1),i=N(-1,1),a=Math.sqrt((t*e)**2-n**2);Be(ir.x+n,ir.y+i*a,r,lr.alpha)}}(t*e);break;case"marker":xr(t*e);break;case"custom":case"image":pr(t*e);break;default:!function(t,e=1){const r=(e=O(e,0,1,.9,1.05))*_.stroke.weight*lr.p.scatter*(lr.p.sharpness+(1-lr.p.sharpness)*Y(hr)/t);if(N(0,lr.p.grain*t)>.4){let e,n;if(or)e=.7*r*N(-1,1),n=r*N(-1,1);else{const t=r*N(-1,1),i=.3*r*N(-1,1);e=t*-lr.sin+i*lr.cos,n=t*lr.cos+i*lr.sin}const i=t*t*lr.p.weight*N(.85,1.15)*_.stroke.weight,a=Math.max(.9,t)*lr.alpha*N(.75,1.1);Be(ir.x+e,ir.y+n,i,a)}}(t*e)}}function mr(){return or?dr()*or.pressure(ir.plotted):dr()}function dr(){return"custom"===lr.p.pressure.type?O(lr.p.pressure.curve(Math.max(0,Math.min(1,.5+(ir.plotted/ar-.5+lr.ct)*lr.cs)))+lr.cp+lr.ck*(ir.plotted/ar-.5),0,1,lr.min,lr.max,!0):function(t=.5+lr.p.pressure.curve[0]*lr.a,e=1-lr.p.pressure.curve[1]*lr.b,r=lr.cp,n=lr.min,i=lr.max){const a=t*ar,o=(ir.plotted<a?1.2*e:.8*e)*(ar/2);return O(1/(1+Math.pow(Math.abs((ir.plotted-a)/o),2*r)),0,1,n,i)}()}function gr(){const t=lr.clipA*ir.x+lr.clipC*ir.y+lr.clipTX;if(t<lr.clipMinX||t>lr.clipMaxX)return!1;const e=lr.clipB*ir.x+lr.clipD*ir.y+lr.clipTY;return e>=lr.clipMinY&&e<=lr.clipMaxY}function xr(t,e=!0,r=lr.alpha){const n=e?_.stroke.weight*lr.p.scatter:0,i=e?n*N(-1,1):0,a=e?n*N(-1,1):0;Be(ir.x+i,ir.y+a,_.stroke.weight*lr.p.weight*t,r*Math.max(.8,t)*N(.9,1.1))}function pr(t,e=lr.alpha){const r=_.stroke.weight*lr.p.scatter,n=r*N(-1,1),i=r*N(-1,1),a=lr.p.weight*_.stroke.weight*t;let o=0;"random"===lr.p.rotate?o=B(0,360)*(Math.PI/180):"natural"===lr.p.rotate&&(o=((or?-or.angle(ir.plotted):-sr)+ir.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 a=t-ue,o=e-fe,s=ae*a+se*o+ce+ue,l=oe*a+le*o+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=Ye(ke,u-1.42*c-1,f-1.42*c-1,u+1.42*c+1,f+1.42*c+1),Pe++}(ir.x+n,ir.y+i,a,o,e*Math.max(.8,t)*N(.9,1.1))}function yr(){if(gr()){let t=mr(),e=lr.alpha;if("marker"===lr.p.type)for(let r=1;r<10;r++)xr(t*r/10,!0,8*e);else if("custom"===lr.p.type||"image"===lr.p.type)for(let r=1;r<5;r++)pr(t*r/10,2*e)}}function _r(t,e,r,n){if(!_.stroke.isActive||!_.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");ct();let i=Q(t,e,r,n);0!=i&&(cr(t,e,i),ur(tt(t,e,r,n),!1))}function br(t,e,r,n){if(!_.stroke.isActive||!_.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");ct(),cr(t,e,r),ur(Z(n),!1)}F(()=>{hr.length=0});const vr=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],wr=[["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 wr){let e={};for(let r=0;r<t[1].length;r++)e[vr[r]]=t[1][r];$e(t[0],e)}St.prototype.draw=function(t=!1,e,r){let n=Ve();if(t&&Je(t,e,r),n.isActive)for(let t of this.sides)_r(t[0].x,t[0].y,t[1].x,t[1].y);We(n)},Pt.prototype.draw=function(t,e,r){Ve().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,n){ct(),cr(e,r,t.length,t),ur(n,!0)}(this,t,e,r))};const Rr={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=Ue().createImage(n.naturalWidth,n.naturalHeight);r.drawingContext.drawImage(n,0,0),Rr.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 Ar(){return{..._.hatch}}function Er(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=_.hatch;n.isActive=!0,n.dist=t,n.angle=q(e),n.options=r}function Mr(t,e="black",r=1){_.hatch.hBrush={brush:t,color:e,weight:r}}function Sr(){_.hatch.isActive=!1,_.hatch.hBrush=!1}function Pr(t,e,r,n){const i=e*Math.PI/180,a=Math.cos(i),o=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*a-r*o,e*o+r*a];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,x=[];let p=f+.5*r,y=r;for(;p<m;){const t=[];for(let e=0;e<g;e+=2){const r=d[e][1],n=d[e+1][1];(r<=p&&p<n||n<=p&&p<r)&&t.push(d[e][0]+(p-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)x.push({x1:t[e]*s-p*l,y1:t[e]*l+p*s,x2:t[e+1]*s-p*l,y2:t[e+1]*l+p*s});p+=y,y*=n}return x}function Tr(t){const e=_.hatch.dist,r=(_.hatch.angle%180+180)%180,n=_.hatch.options,i=Ve();_.hatch.hBrush&&Je(...Object.values(_.hatch.hBrush)),Array.isArray(t)||(t=[t]);const a=n.gradient?O(n.gradient,0,1,1,1.1,!0):1,o=[];for(const n of t)for(const t of Pr(n,r,e,a))o.push(t);o.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<o.length;t++){const r=o[t];let i=r.x1,a=r.y1,l=r.x2,c=r.y2;s&&(i+=s*e*N(-1,1),a+=s*e*N(-1,1),l+=s*e*N(-1,1),c+=s*e*N(-1,1)),_r(i,a,l,c),t>0&&n.continuous&&_r(o[t-1].x2,o[t-1].y2,i,a)}We(i)}function kr(t,e,r){const n=2*Math.PI,i=w.ctx,a=r/2;i.moveTo(t+a,e),i.arc(t,e,a,0,n)}_.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},St.prototype.hatch=function(t=!1,e,r){let n=Ar();t&&Er(t,e,r),n.isActive&&Tr(this),function(t){_.hatch={...t}}(n)},Pt.prototype.hatch=function(t,e,r){Ar().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 Ir=()=>({..._.fill});function Cr(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 Lr(t,e="out"){_.fill.bleed_strength=U(t,0,1),_.fill.direction=e}function Fr(t=.4,e=.4){_.fill.texture_strength=U(t,0,1),_.fill.border_strength=U(e,0,1)}function Dr(){_.fill.isActive=!1}let Nr;const Yr=[[],[]];function Br(){for(let t=0;t<512;t++)Yr[0][t]=X(.5,.2),Yr[1][t]=X(0,.02)}function Xr(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}F(Br);class zr{constructor(t,e,r,n=[],i=!1,a,o){if(this.v=t,this.m=e,this.dir=n,this.midP=r,i){let e=0,n=0;const i=[];for(let a=0;a<t.length;a++){const o=Math.abs(r.x-t[a].x),s=Math.abs(r.y-t[a].y);e=Math.max(e,o),n=Math.max(n,s);const l=t[a],c=t[(a+1)%t.length],h={x:c.x-l.x,y:c.y-l.y},u=J(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 Nr.intersect(t.ray))Xr(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const a=N(-.6,.6)*e,o=N(-.6,.6)*n;this.midP={x:r.x+a,y:r.y+o}}else this.sizeX=a,this.sizeY=o}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.length-e,i=new Array(n),a=new Array(n),o=new Array(n);let s=0;for(let t=0;t<r;t++,s++)i[s]=this.v[t],a[s]=this.m[t],o[s]=this.dir[t];for(let t=r+e;t<this.v.length;t++,s++)i[s]=this.v[t],a[s]=this.m[t],o[s]=this.dir[t];return{v:i,m:a,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+N(0,.8*i)));const a=[],o=[],s=[],l=this.midP,c=Nr.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,a=e.y;if(r>n.y==a>n.y)continue;const o=(n.y-r)/(a-r);n.x<t.x+o*(e.x-t.x)&&i++}i%2==0&&(n={x:l.x+(n.x-l.x)*N(.3,.6),y:l.y+(n.y-l.y)*N(.3,.6)}),a.push(n),o.push(this.m[r]),s.push(!this.dir[r])}return new zr(a,o,this.midP,s,!1,this.sizeX,this.sizeY)}flipDirs(){return new zr(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,a=2*i,o=new Array(i),s=new Array(i),l=new Array(a),c=new Array(a),h="out"===_.fill.direction?-90:90;0===Yr[0].length&&Br();const u=Yr[0],f=u.length,m=Yr[1],d=m.length;let g,x,p,y=0,b=0,v=999===t?N(.6,.8):_.fill.bleed_strength;for(let a=0;a<i;a++){const g=e[a],x=e[a+1<i?a+1:0],p=r[a],_=n[a];t<997&&(v=p);const w=(_?h:-h)+5*N(-1,1),R=j(w),A=K(w),E=x.x-g.x,M=x.y-g.y,S=R*E+A*M,P=R*M-A*E,T=u[~~(N(0,1)*f)]*N(.65,1.35)*v,k=p+m[~~(N(0,1)*d)];l[y]=p,c[y]=_,y++,o[b]=g.x+.5*E+S*T,s[b]=g.y+.5*M+P*T,l[y]=k,c[y]=_,y++,b++}const w=1024/_.fill.texture_strength;if(w&&y>w){const t=Math.ceil(y/w),r=Math.ceil(y/t);g=new Array(r),x=new Array(r),p=new Array(r);let n=0;for(let r=0;r<y;r+=t,n++)g[n]=r%2==0?e[r>>1]:{x:o[r>>1],y:s[r>>1]},x[n]=l[r],p[n]=c[r]}else{g=new Array(y);for(let t=0;t<y;t++)g[t]=t%2==0?e[t>>1]:{x:o[t>>1],y:s[t>>1]};l.length=y,c.length=y,x=l,p=c}return new zr(g,x,this.midP,p,!1,this.sizeX,this.sizeY)}fill(r,n,a){const o=3*a,s=2*n*(1+a/2),l=!1!==w.isBrush;w.isBrush=!1,l&&(w.justChanged=!0),w.blend(r),w.ctx.save(),w.ctx.setTransform(i*it(),i*at(),i*ot(),i*st(),i*(rt()+t/2),i*(nt()+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=N(.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*o,r),t%2==0&&u.grow(h).grow(999).layer(t,c,2*s,r),t%8!=0&&19!==t||(0!==o&&u.erase(3*o,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(),n=r.a,i=r.b,a=r.c,o=r.d,s=r.e,l=r.f;let c=Infinity,h=Infinity,u=-Infinity,f=-Infinity;e.beginPath();const m=t[0];let d=n*m.x+a*m.y+s,g=i*m.x+o*m.y+l;c=u=d,h=f=g,e.moveTo(m.x,m.y);for(let r=1;r<t.length;r++){const m=t[r];d=n*m.x+a*m.y+s,g=i*m.x+o*m.y+l,c=Math.min(c,d),h=Math.min(h,g),u=Math.max(u,d),f=Math.max(f,g),e.lineTo(m.x,m.y)}e.closePath();const x=function(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}(e,r);w.markDirtyRect(w.mask,{minX:c-x,minY:h-x,maxX:u+x,maxY:f+x})}(this.v),w.ctx.fill(),w.ctx.stroke()}erase(t,e){w.ctx.save();const r=~~(N(80,110)*O(t,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,a=Math.min(this.sizeX,this.sizeY)*(1.4-_.fill.bleed_strength),o=.04*a,s=.35*a,{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+X(0,n),r=c+X(0,i),a=N(o,s);w.ctx.beginPath(),kr(e,r,a),t%5!=0&&w.ctx.fill()}w.ctx.globalCompositeOperation="source-over",w.ctx.restore()}}St.prototype.fill=function(t=!1,e,r,n,i,a){let o=Ir();t&&(Cr(t,e),Lr(r,a),Fr(n,i)),o.isActive&&(ct(),function(t){if(!_.fill.isActive||!_.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Nr=t;const e=[...t.vertices],r=~~(.25*e.length*z({1:5,2:10,3:60})),n=_.fill.bleed_strength,i=e.map((t,e)=>(e>r?1:.3)*N(.85,1.4)*n),a=B(0,e.length),o=[...e.slice(a),...e.slice(0,a)],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 a=e[t].x*e[t+1].y-e[t+1].x*e[t].y;r+=a,n+=(e[t].x+e[t+1].x)*a,i+=(e[t].y+e[t+1].y)*a}return r*=.5,r?{x:n/(6*r),y:i/(6*r)}:{x:e[0].x,y:e[0].y}}(o);new zr(o,i,s,[],!0).fill(_.fill.color,O(_.fill.opacity,0,255,0,1,!0),_.fill.texture_strength)}(this)),(t=>{_.fill={...t}})(o)},Pt.prototype.fill=function(t,e,r){Ir().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,.6,!0)),this.pol.fill())};const Or=[];"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,a=e.randomSeed,o=e.noiseSeed;e.push=function(){n.call(this),ct(),Or.push({fill:{..._.fill},stroke:{..._.stroke},hatch:{..._.hatch},field:{..._.field}})},e.pop=function(){i.call(this),function(){const t=Or.pop();t&&(_.stroke={...t.stroke},_.field={...t.field},_.hatch={...t.hatch},_.fill={...t.fill})}()},e.randomSeed=function(t){a.call(this,t),(t=>{C=k(t);for(const t of L)t()})(t)},e.noiseSeed=function(t){o.call(this,t),(t=>{D=T(k(t))})(t)}});export{Pt as Plot,St as Polygon,ht as Position,$e as add,Rt as addField,Ct as arc,Bt as beginShape,Ot as beginStroke,He as box,It as circle,rr as clip,zt as endShape,Gt as endStroke,vt as field,Cr as fill,Lr as fillBleed,Fr as fillTexture,br as flowLine,Er as hatch,Tr as hatchArray,Mr as hatchStyle,b as instance,_r as line,At as listFields,g as load,Ut as move,nr as noClip,wt as noField,Dr as noFill,Sr as noHatch,Qe as noStroke,Ke as pick,Tt as polygon,kt as rect,bt as refreshField,je as scaleBrushes,Je as set,Vt as spline,Ze as stroke,qe as strokeWeight,Xt as vertex,z as wRand,Et as wiggle};//# sourceMappingURL=p5.brush.esm.js.mapdiff --git a/dist/p5.brush.esm.js.map b/dist/p5.brush.esm.js.mapindex 5880d9c..9b74c0a 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/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,IAA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,SAAuBC,EAAK76B,EAAI86B,GAC9BA,EAAWC,UAAY,IAAMr2B,EAAIuD,OAAM,GAAO,GAC9C6yB,EAAWE,SAAW,IAAMt2B,EAAIuD,OAAM,GAAO,GAE7C,MAAMgzB,EAAQj7B,EAAGsG,KACX40B,EAAOl7B,EAAG0G,IACVy0B,EAAcn7B,EAAGo7B,WACjBC,EAAar7B,EAAGs7B,UAEtBt7B,EAAGsG,KAAO,WACR20B,EAAMM,KAAK7zB,MD3HbwK,KACAyoB,GAAYr0B,KAAK,CACf8C,KAAM,IAAKxE,EAAMwE,MACjB0O,OAAQ,IAAKlT,EAAMkT,QACnBC,MAAO,IAAKnT,EAAMmT,OAClBtF,MAAO,IAAK7N,EAAM6N,QCwHpB,EAEAzS,EAAG0G,IAAM,WACPw0B,EAAKK,KAAK7zB,MDpHP,WACL,MAAM8zB,EAAQb,GAAYj0B,MACrB80B,IACL52B,EAAMkT,OAAS,IAAK0jB,EAAM1jB,QAC1BlT,EAAM6N,MAAQ,IAAK+oB,EAAM/oB,OACzB7N,EAAMmT,MAAQ,IAAKyjB,EAAMzjB,OACzBnT,EAAMwE,KAAO,IAAKoyB,EAAMpyB,MAC1B,CC8GIqyB,EACF,EAEAz7B,EAAGo7B,WAAa,SAAUtwB,GACxBqwB,EAAYI,KAAK7zB,KAAMoD,GZzHP,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+{"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/fill/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\nlet FillMaskUploadCanvas = null;\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 * 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 (buffer.renderer._pInst !== getSketchRenderer()) {\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 = () => Renderer?._renderer?.activeFramebuffer?.() ?? null;\n\nconst clearTarget = (target) => {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n target.draw(() => Renderer.clear());\n return;\n }\n\n const ctx = target.drawingContext;\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, target.width, target.height);\n ctx.restore();\n};\n\nconst uploadFillMaskToMirror = (mask, dirtyRect = null) => {\n const target = Renderer.fillMaskFramebuffer;\n const gl = Renderer.drawingContext;\n const uploadRect = normalizeDirtyRect(dirtyRect) ?? getFullDirtyRect();\n const uploadWidth = uploadRect.maxX - uploadRect.minX;\n const uploadHeight = uploadRect.maxY - uploadRect.minY;\n\n if (\n !FillMaskUploadCanvas ||\n FillMaskUploadCanvas.width !== uploadWidth ||\n FillMaskUploadCanvas.height !== uploadHeight\n ) {\n FillMaskUploadCanvas = new OffscreenCanvas(uploadWidth, uploadHeight);\n FillMaskUploadCanvas.drawingContext = FillMaskUploadCanvas.getContext(\"2d\");\n }\n\n const uploadContext = FillMaskUploadCanvas.drawingContext;\n uploadContext.clearRect(0, 0, uploadWidth, uploadHeight);\n uploadContext.drawImage(\n mask,\n uploadRect.minX,\n uploadRect.minY,\n uploadWidth,\n uploadHeight,\n 0,\n 0,\n uploadWidth,\n uploadHeight,\n );\n\n clearTarget(target);\n gl.bindTexture(gl.TEXTURE_2D, target.colorTexture);\n gl.texSubImage2D(\n gl.TEXTURE_2D,\n 0,\n uploadRect.minX,\n uploadRect.minY,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n FillMaskUploadCanvas,\n );\n\n return target;\n};\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, flipY = true) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: flipY ? height - normalized.maxY : normalized.minY,\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 */\nconst withScissor = (gl, rect, draw, flipY = true) => {\n const box = toScissorBox(rect, flipY);\n if (!box) {\n draw();\n return;\n }\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\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 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 clearTarget(target);\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-mask dirty rects are still less predictable when the destination\n // is itself a framebuffer, so keep that path conservative.\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 // Section: Setup and load shaders\n // =============================================================================\n /**\n * Ensures the mask buffers and blend shader exist for the current renderer.\n */\n load() {\n Density = Renderer.pixelDensity();\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n const needsBuffers =\n !Renderer.mask ||\n !Renderer.glMask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight;\n const needsBlendSourceFramebuffer =\n !Renderer.blendSourceFramebuffer ||\n Renderer.blendSourceFramebuffer.width !== Cwidth ||\n Renderer.blendSourceFramebuffer.height !== Cheight ||\n (typeof Renderer.blendSourceFramebuffer.pixelDensity === \"function\" &&\n Renderer.blendSourceFramebuffer.pixelDensity() !== Density);\n const needsFillMaskFramebuffer =\n !Renderer.fillMaskFramebuffer ||\n Renderer.fillMaskFramebuffer.width !== Cwidth ||\n Renderer.fillMaskFramebuffer.height !== Cheight ||\n (typeof Renderer.fillMaskFramebuffer.pixelDensity === \"function\" &&\n Renderer.fillMaskFramebuffer.pixelDensity() !== Density);\n if (!Renderer.loaded || needsBuffers) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n // Keep one 2D mask for fill/hatch work and one framebuffer-backed mask\n // for brush stamps so the brush path stays in the main renderer context.\n Renderer.mask = new OffscreenCanvas(maskWidth, maskHeight);\n Renderer.mask.drawingContext = Renderer.mask.getContext(\"2d\");\n Renderer.glMask = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n Renderer.loaded = true;\n\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n }\n\n if (needsBlendSourceFramebuffer) {\n if (Renderer.blendSourceFramebuffer?.remove) {\n Renderer.blendSourceFramebuffer.remove();\n }\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 if (needsFillMaskFramebuffer) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n clearTarget(Renderer.fillMaskFramebuffer);\n }\n\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.ctx.imageSmoothingEnabled = false;\n\n this.glMask.dirtyRect ??= null;\n this.glMask.isDrawn ??= false;\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 // Reset the brush mask at the start of each blend cycle.\n clearTarget(this.glMask);\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\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n const gl = Renderer.drawingContext;\n const shader = Renderer.shaderProgram;\n const activeFramebuffer = getActiveFramebuffer();\n const source = blitToBlendSourceFramebuffer(activeFramebuffer ?? Renderer, dirtyRect);\n const targetIsFramebuffer = !!activeFramebuffer;\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 Renderer.push();\n Renderer.translate(0, 0);\n Renderer.shader(shader);\n\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n if (isBrushMask) {\n shader.setUniform(\"u_mask\", mask);\n } else {\n shader.setUniform(\"u_mask\", uploadFillMaskToMirror(mask, dirtyRect));\n }\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 }, !targetIsFramebuffer);\n\n Renderer.pop();\n Renderer.resetShader();\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n this.clearMask(mask);\n },\n};\n\n/**\n * Copies the current pixels of a renderer or framebuffer into the reusable\n * blend source framebuffer.\n * @param {p5|p5.Graphics|p5.Framebuffer} sourceTarget - Source to copy from.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} [dirtyRect=null] - Optional copy region.\n * @returns {p5.Framebuffer} Blend source framebuffer after the blit.\n */\nconst blitToBlendSourceFramebuffer = (sourceTarget, dirtyRect = null) => {\n const sourceFramebuffer = Renderer.blendSourceFramebuffer;\n const gl = Renderer.drawingContext;\n const sourceIsFramebuffer = isFramebufferTarget(sourceTarget);\n const { width, height } = getTargetPixelSize();\n const sourceBox = dirtyRect ? toScissorBox(dirtyRect) : null;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n\n (sourceIsFramebuffer ? sourceTarget.renderer : Renderer._renderer)?.flushDraw?.();\n\n if (sourceIsFramebuffer) {\n sourceFramebuffer.draw(() => {\n withScissor(Renderer.drawingContext, dirtyRect, () => {\n Renderer.clear();\n Renderer.push();\n Renderer.imageMode(Renderer.CENTER);\n Renderer.image(sourceTarget, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n }, false);\n });\n return sourceFramebuffer;\n }\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, sourceFramebuffer.framebuffer);\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.blitFramebuffer(\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST,\n );\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n\n return sourceFramebuffer;\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), 20);\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 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 resetMaskShaderTracking() {\n const renderer = Mix.glMask?.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 rendererMask = Renderer?.glMask;\n if (!rendererMask) return null;\n brushMaskTarget = rendererMask;\n brushMaskTarget.dirtyRect ??= null;\n brushMaskTarget.isDrawn ??= false;\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n}\n\nfunction getProjectionMatrix() {\n return framebufferProjMatrix;\n}\n\nfunction beginMaskTarget() {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = hadDepthTest;\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n prevMaskTarget = Renderer._renderer.activeFramebuffer?.() ?? null;\n if (prevMaskTarget?._beforeEnd) prevMaskTarget._beforeEnd();\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(Mix.glMask));\n gl.viewport(\n 0,\n 0,\n Mix.glMask.width * Mix.glMask.density,\n Mix.glMask.height * Mix.glMask.density,\n );\n}\n\nfunction endMaskTarget() {\n if (beginMaskTarget._hadDepthTest) gl.enable(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = false;\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 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 \"../core/color.js\";\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 // Cache the current 2D transform once so the hot loop can stay numeric and\n // avoid repeated property reads while we build bounds.\n const a = matrix.a;\n const b = matrix.b;\n const c = matrix.c;\n const d = matrix.d;\n const e = matrix.e;\n const f = matrix.f;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n\n // Seed both the path and the transformed bounds from the first vertex so the\n // loop below only needs to append line segments.\n const first = vertices[0];\n let tx = a * first.x + c * first.y + e;\n let ty = b * first.x + d * first.y + f;\n minX = maxX = tx;\n minY = maxY = ty;\n\n ctx.moveTo(first.x, first.y);\n\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i];\n\n // Track the transformed bounds in canvas space while we build the path so\n // dirty-rect bookkeeping does not need a second pass over the vertices.\n tx = a * v.x + c * v.y + e;\n ty = b * v.x + d * v.y + f;\n minX = Math.min(minX, tx);\n minY = Math.min(minY, ty);\n maxX = Math.max(maxX, tx);\n maxY = Math.max(maxY, ty);\n\n ctx.lineTo(v.x, v.y);\n }\n\n ctx.closePath();\n\n // Expand by stroke width so the later composite pass copies enough pixels\n // even when the polygon border extends outside the raw vertex bounds.\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 radius = d / 2;\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 \"./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 // Copy only the kept ranges instead of cloning the full arrays and splicing.\n const keep = this.v.length - n;\n const v = new Array(keep);\n const m = new Array(keep);\n const dir = new Array(keep);\n let dst = 0;\n\n for (let i = 0; i < s; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n for (let i = s + n; i < this.v.length; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\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 insertedX = new Array(len);\n const insertedY = new Array(len);\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 insertedIdx = 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\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 const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n const nextMod = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n\n insertedX[insertedIdx] = cv.x + sideX * 0.5 + dirX * d;\n insertedY[insertedIdx] = cv.y + sideY * 0.5 + dirY * d;\n newMods[idx] = nextMod;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n }\n\n let fv,\n fm,\n fd;\n const growCap = GROW_MAX_VERTS / State.fill.texture_strength;\n if (growCap && idx > growCap) {\n const step = Math.ceil(idx / growCap);\n const kept = Math.ceil(idx / step);\n fv = new Array(kept);\n fm = new Array(kept);\n fd = new Array(kept);\n let dst = 0;\n for (let j = 0; j < idx; j += step, dst++) {\n fv[dst] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n fm[dst] = newMods[j];\n fd[dst] = newDirs[j];\n }\n } else {\n fv = new Array(idx);\n for (let j = 0; j < idx; j++) {\n fv[j] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n }\n newMods.length = idx;\n newDirs.length = idx;\n fm = newMods;\n fd = newDirs;\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) {\n pol = pol.grow();\n }\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) {\n const grown = p.grow(999).grow(997);\n grown.layer(i, size, int, color);\n }\n const sparseLayer = sparse.grow(999).flipDirs().grow(997);\n sparseLayer.layer(i, size, int * texture, color);\n if (i % 2 === 0) {\n const darkerLayer = pol.grow(darker).grow(999);\n darkerLayer.layer(i, size, int * 2, color);\n }\n\n if (i % 8 === 0 || i === numLayers - 1) {\n if (texture !== 0) {\n pol.erase(texture * 3, intensity);\n }\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\n Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\n\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.04 * minSize;\n const maxSizeFactor = 0.35 * 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 radius = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, radius);\n if (i % 5 !== 0) {\n Mix.ctx.fill();\n }\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.60, 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","FillMaskUploadCanvas","isFramebufferTarget","target","begin","end","renderer","_pInst","getSketchRenderer","_isInstanced","window","self","p5","instance","getActiveFramebuffer","_renderer","activeFramebuffer","clearTarget","draw","clear","ctx","drawingContext","save","setTransform","clearRect","width","height","restore","getTargetPixelSize","Math","max","round","normalizeDirtyRect","rect","minX","floor","min","maxX","minY","maxY","ceil","getFullDirtyRect","toScissorBox","flipY","normalized","x","y","withScissor","gl","box","enable","SCISSOR_TEST","scissor","disable","load","buffer","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","inst","isMixReady","isBlending","cachedColor","Object","markDirtyRect","a","b","dirtyRect","isDrawn","clearMask","getCompositeRect","isBrushMask","padding","expandDirtyRect","pixelDensity","maskWidth","maskHeight","needsBuffers","mask","glMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","needsFillMaskFramebuffer","fillMaskFramebuffer","remove","OffscreenCanvas","getContext","createFramebuffer","density","antialias","depth","stencil","shaderProgram","createShader","this","imageSmoothingEnabled","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","source","blitToBlendSourceFramebuffer","targetIsFramebuffer","hadDepthTest","getParameter","DEPTH_TEST","push","translate","setUniform","uploadRect","uploadWidth","uploadHeight","uploadContext","drawImage","bindTexture","TEXTURE_2D","colorTexture","texSubImage2D","RGBA","UNSIGNED_BYTE","uploadFillMaskToMirror","fill","noStroke","pop","resetShader","sourceTarget","sourceFramebuffer","sourceIsFramebuffer","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","flushDraw","imageMode","CENTER","image","bindFramebuffer","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","framebuffer","clearColor","COLOR_BUFFER_BIT","blitFramebuffer","NEAREST","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","angleMode","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","uModelMatrix","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","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","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","resetMaskShaderTracking","_curShader","_cachedBlendMode","_isBlending","activeTexture","TEXTURE0","blendEquation","FUNC_ADD","blendFunc","ONE","ONE_MINUS_SRC_ALPHA","getProjectionMatrix","beginMaskTarget","isEnabled","_hadDepthTest","_beforeEnd","FRAMEBUFFER","_framebufferToBind","viewport","endMaskTarget","_beforeBegin","_origViewport","_applyStencilTestIfClipping","accumulateDirtyRect","currentRect","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","tex","createTexture","texImage2D","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","flush","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","createGraphics","background","noSmooth","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","rendererMask","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","onerror","crossOrigin","HatchState","rand","continuous","gradient","hatchStyle","brush","hBrush","noHatch","scanlineHatch","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","createHatch","polygons","segs","poly","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","noFill","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","center","isFirst","sx","sy","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","keep","dst","ratio","L","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","insertedX","insertedY","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","fv","fm","fd","insertedIdx","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","nextMod","growCap","kept","intensity","texture","int","switchingToFill","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","darker","sparse","pols","layer","numLayers","erase","lineWidth","fillStyle","matrix","getTransform","beginPath","first","lineTo","closePath","strokePadding","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","_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AAoBA,GAAGy6B,cA9BlC,SAAuBC,EAAKtjB,EAAIujB,GAC9BA,EAAWC,UAAY,IAAM33B,EAAIwC,OAAM,GAAO,GAC9Ck1B,EAAWE,SAAW,IAAM53B,EAAIwC,OAAM,GAAO,GAE7C,MAAMq1B,EAAQ1jB,EAAG1Q,KACXq0B,EAAO3jB,EAAGzP,IACVqzB,EAAc5jB,EAAG6jB,WACjBC,EAAa9jB,EAAG+jB,UAEtB/jB,EAAG1Q,KAAO,WACRo0B,EAAMM,KAAK71B,MDtHb4M,KACAqoB,GAAY9zB,KAAK,CACfe,KAAM,IAAKtE,EAAMsE,MACjB4Q,OAAQ,IAAKlV,EAAMkV,QACnBC,MAAO,IAAKnV,EAAMmV,OAClB5F,MAAO,IAAKvP,EAAMuP,QCmHpB,EAEA0E,EAAGzP,IAAM,WACPozB,EAAKK,KAAK71B,MD/GP,WACL,MAAM81B,EAAQb,GAAY7yB,MACrB0zB,IACLl4B,EAAMkV,OAAS,IAAKgjB,EAAMhjB,QAC1BlV,EAAMuP,MAAQ,IAAK2oB,EAAM3oB,OACzBvP,EAAMmV,MAAQ,IAAK+iB,EAAM/iB,OACzBnV,EAAMsE,KAAO,IAAK4zB,EAAM5zB,MAC1B,CCyGI6zB,EACF,EAEAlkB,EAAG6jB,WAAa,SAAUxwB,GACxBuwB,EAAYI,KAAK71B,KAAMkF,GZpHP,CAACA,IACnB4C,EAAMzB,EAAUnB,GAChB,IAAK,MAAM8wB,KAAYjuB,EACrBiuB,KYkHAC,CAAU/wB,EACZ,EAEA2M,EAAG+jB,UAAY,SAAU1wB,GACvBywB,EAAWE,KAAK71B,KAAMkF,GZvGD,CAACA,IACxBgD,EAAQjE,EAAcoC,EAAUnB,KYuG9BgxB,CAAehxB,EACjB,CACF","x_google_ignoreList":[1,2]}\ No newline at end of filediff --git a/dist/p5.brush.js b/dist/p5.brush.jsindex d16c7e1..3a7bc75 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,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={});+var t,e;t=this,e=function(t){let e,r,n,i,o,a=null;const s=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,l=()=>y?n:window.self.p5.instance,c=()=>i?._renderer?.activeFramebuffer?.()??null,h=t=>{if(!t)return;if(s(t))return void t.draw(()=>i.clear());const e=t.drawingContext;e.save(),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height),e.restore()},u=()=>({width:Math.max(1,Math.round(e*o)),height:Math.max(1,Math.round(r*o))}),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=!0)=>{const r=f(t);if(!r)return null;const{height:n}=u();return{x:r.minX,y:e?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},g=(t,e,r,n=!0)=>{const i=d(e,n);if(i){t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{r()}finally{t.disable(t.SCISSOR_TEST)}}else r()},p=(t=!1)=>{const o=((t=!1)=>{if(y&&!t)return{renderer:n,width:n.width,height:n.height};if(!t){const t=l();return{renderer:t,width:t.width,height:t.height}}if(s(t)){if(t.renderer._pInst!==l())throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch");return{renderer:l(),width:t.width,height:t.height}}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=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&&(h(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:(t,e)=>t?t.dirtyRect?e&&c()?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,load(){o=i.pixelDensity();const t=Math.max(1,Math.round(e*o)),n=Math.max(1,Math.round(r*o)),a=!i.mask||!i.glMask||i.mask.width!==t||i.mask.height!==n||i.glMask.width!==e||i.glMask.height!==r,s=!i.blendSourceFramebuffer||i.blendSourceFramebuffer.width!==e||i.blendSourceFramebuffer.height!==r||"function"==typeof i.blendSourceFramebuffer.pixelDensity&&i.blendSourceFramebuffer.pixelDensity()!==o,l=!i.fillMaskFramebuffer||i.fillMaskFramebuffer.width!==e||i.fillMaskFramebuffer.height!==r||"function"==typeof i.fillMaskFramebuffer.pixelDensity&&i.fillMaskFramebuffer.pixelDensity()!==o;i.loaded&&!a||(i.glMask?.remove&&i.glMask.remove(),i.mask=new OffscreenCanvas(t,n),i.mask.drawingContext=i.mask.getContext("2d"),i.glMask=i.createFramebuffer({width:e,height:r,density:o,antialias:!1,depth:!1,stencil:!1}),i.loaded=!0,i.shaderProgram??=i.createShader("#version 300 es\n#define GLSLIFY 1\nout vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,-v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform bool u_targetIsFramebuffer;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 sourceUV=vec2(uv.x,1.0-uv.y);vec2 maskUV=u_targetIsFramebuffer ? vec2(uv.x,1.0-uv.y): uv;vec4 source=texture(u_source,sourceUV);vec4 maskColor=texture(u_mask,maskUV);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=maskUV+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);}")),s&&(i.blendSourceFramebuffer?.remove&&i.blendSourceFramebuffer.remove(),i.blendSourceFramebuffer=i.createFramebuffer({width:e,height:r,density:o,antialias:!1,depth:!1,stencil:!1})),l&&(i.fillMaskFramebuffer?.remove&&i.fillMaskFramebuffer.remove(),i.fillMaskFramebuffer=i.createFramebuffer({width:e,height:r,density:o,antialias:!1,depth:!1,stencil:!1}),h(i.fillMaskFramebuffer)),this.mask=i.mask,this.glMask=i.glMask,this.ctx=this.mask.drawingContext,this.mask.dirtyRect??=null,this.mask.isDrawn??=!1,this.ctx.imageSmoothingEnabled=!1,this.glMask.dirtyRect??=null,this.glMask.isDrawn??=!1},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,h(this.glMask)),(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=this.getCompositeRect(t,n);if(!o)return void this.clearMask(t);const s=i.drawingContext,l=i.shaderProgram,u=c(),d=R(u??i,o),p=!!u,x=s.getParameter(s.DEPTH_TEST);s.disable(s.DEPTH_TEST),i.push(),i.translate(0,0),i.shader(l),l.setUniform("u_source",d),l.setUniform("u_targetIsFramebuffer",p),l.setUniform("u_isBrush",n),n?l.setUniform("u_mask",t):l.setUniform("u_mask",((t,e=null)=>{const r=i.fillMaskFramebuffer,n=i.drawingContext,o=f(e)??m(),s=o.maxX-o.minX,l=o.maxY-o.minY;a&&a.width===s&&a.height===l||(a=new OffscreenCanvas(s,l),a.drawingContext=a.getContext("2d"));const c=a.drawingContext;return c.clearRect(0,0,s,l),c.drawImage(t,o.minX,o.minY,s,l,0,0,s,l),h(r),n.bindTexture(n.TEXTURE_2D,r.colorTexture),n.texSubImage2D(n.TEXTURE_2D,0,o.minX,o.minY,n.RGBA,n.UNSIGNED_BYTE,a),r})(t,o)),l.setUniform("u_color",this.cachedColor),g(s,o,()=>{i.fill(0,0,0,0),i.noStroke(),i.rect(-e/2,-r/2,e,r)},!p),i.pop(),i.resetShader(),x&&s.enable(s.DEPTH_TEST),this.clearMask(t)}},R=(t,n=null)=>{const o=i.blendSourceFramebuffer,a=i.drawingContext,l=s(t),{width:c,height:h}=u(),f=n?d(n):null,m=a.getParameter(a.READ_FRAMEBUFFER_BINDING),p=a.getParameter(a.DRAW_FRAMEBUFFER_BINDING);return(l?t.renderer:i._renderer)?.flushDraw?.(),l?(o.draw(()=>{g(i.drawingContext,n,()=>{i.clear(),i.push(),i.imageMode(i.CENTER),i.image(t,0,0,e,r),i.pop()},!1)}),o):(a.bindFramebuffer(a.READ_FRAMEBUFFER,null),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,o.framebuffer),a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT),a.blitFramebuffer(f?.x??0,f?.y??0,f?f.x+f.width:c,f?f.y+f.height:h,f?.x??0,f?.y??0,f?f.x+f.width:c,f?f.y+f.height:h,a.COLOR_BUFFER_BIT,a.NEAREST),a.bindFramebuffer(a.READ_FRAMEBUFFER,m),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,p),o)},A=Math.sqrt(3),E=.5*(A-1),M=(3-A)/6,S=t=>0|Math.floor(t),P=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 T(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=>P[t%12*2]),n=new Float64Array(e).map(t=>P[t%12*2+1]);return function(t,i){let o=0,a=0,s=0;const l=(t+i)*E,c=S(t+l),h=S(i+l),u=(c+h)*M,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+M,x=m-g+M,y=f-1+2*M,_=m-1+2*M,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 A=.5-y*y-_*_;if(A>=0){const t=b+1+e[v+1];A*=A,s=A*A*(r[t]*y+n[t]*_)}return 70*(o+a+s)}}function k(t,e){let r=new I(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class I{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 C=k(Math.random());const L=[],F=t=>L.push(t);let D=T(k(Math.random()));const N=(t=0,e=1)=>t+C()*(e-t),B=t=>t[~~(C()*t.length)],Y=(t,e)=>~~N(t,e),X=(t=0,e=1)=>{const r=1-C(),n=C();return Math.sqrt(-2*Math.log(r))*j(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=C()*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?U(a,n,i):U(a,i,n):a},U=(t,e,r)=>Math.max(Math.min(t,r),e),G=t=>(t%=360)<0?t+360:t,V=1440,W=2*Math.PI/V,H=new Float32Array(V).fill(NaN),$=new Float32Array(V).fill(NaN),j=t=>{const e=~~(4*G(t));let r=H[e];return isNaN(r)&&(r=Math.cos(e*W),H[e]=r),r},K=t=>{const e=~~(4*G(t));let r=$[e];return isNaN(r)&&(r=Math.sin(e*W),$[e]=r),r},Z=(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},q=(t,e=!1)=>e||i&&"function"==typeof i.angleMode&&i.angleMode()===i.RADIANS?180*t/Math.PI:t,J=(t,e,r,n,i)=>{let o=j(i),a=K(i);return{x:o*(r-t)+a*(n-e)+t,y:o*(n-e)-a*(r-t)+e}},Q=(t,e,r,n)=>Math.hypot(r-t,n-e),tt=(t,e,r,n)=>Z(Math.atan2(-(n-e),r-t),!0),et=(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}},rt=()=>i._renderer.uModelMatrix.mat4[12],nt=()=>i._renderer.uModelMatrix.mat4[13],it=()=>i._renderer.uModelMatrix.mat4[0],ot=()=>i._renderer.uModelMatrix.mat4[1],at=()=>i._renderer.uModelMatrix.mat4[4],st=()=>i._renderer.uModelMatrix.mat4[5];let lt=!1;function ct(){lt||(v(),ut=.01*e,ft=-.5*e,mt=-.5*r,dt=Math.round(2*e/ut),gt=Math.round(2*r/ut),vt("hand",(t,e)=>{const r=N(.2,.8),n=Y(5,10);return wt(e,(e,i)=>.5*n*K(r*i*e+Y(15,25))*.2*j(t)+D(e,i)*n*.7)}),vt("curved",(t,e)=>{let r=Y(-10,10);return Y(0,100)%2==0&&(r*=-1),wt(e,(e,n)=>3*O(D(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),vt("zigzag",(t,e)=>{let r=Y(-30,-15)+Math.abs(44*K(t));Y(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t<dt;t++){for(let r=0;r<gt;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),vt("waves",(t,e)=>{const r=Y(10,15)+5*K(t),n=Y(3,6)+3*j(t),i=Y(20,35);return wt(e,(t,e)=>K(r*t)*i*j(e*n)+Y(-3,3))}),vt("seabed",(t,e)=>{const r=N(.4,.8),n=Y(18,26);return wt(e,(e,i)=>1.1*n*K(r*i*e+Y(15,20))*j(t))}),vt("spiral",(t,e)=>{const r=Y(5,10),n=2*Y(0,2)-1,i=Y(65,80),o=Array.from({length:r},()=>({x:N(.1,.9)*dt,y:N(.1,.9)*gt}));return wt(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)})}),vt("columns",(t,e)=>{const r=Y(3,8),n=Y(25,45);return wt(e,(t,e)=>K(t*r)*n)}),lt=!0)}class ht{constructor(t,e){ct(),this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=ht.getColIndex(t),this.rowIdx=ht.getRowIndex(e)}reset(){this.plotted=0}isIn(){return b.field.isActive?ht.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,n=r,i=this.x+rt(),o=this.y+nt();return i>=-.3*t&&i<=1.3*t&&o>=-.3*n&&o<=1.3*n}angle(){return this.isIn()&&b.field.isActive?pt.get(b.field.current).field[this.colIdx][this.rowIdx]*b.field.wiggle:0}moveTo(t,e,r=1){this.movePos(q(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*j(e),this.y+r*K(e)),this.plotted+=r/i}else this.plotted+=r/i}static getRowIndex(t,e=1){const r=t+nt()-mt;return Math.round(r/ut/e)}static getColIndex(t,e=1){const r=t+rt()-ft;return Math.round(r/ut/e)}static isIn(t,e){return t>=0&&e>=0&&t<dt&&e<gt}}b.field={isActive:!1,current:null,wiggle:1};let ut,ft,mt,dt,gt,pt=new Map;const xt=new Set(["degrees","radians"]);function yt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!xt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function _t(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]=q(t[e][r],!0);return t}(t.gen(e,new Array(dt).fill(null).map(()=>new Float32Array(gt))),t.angleMode)}function bt(t){if(b.field.wiggle||(b.field.wiggle=1),ct(),!pt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(pt.keys()).join(", ")}.`);b.field.isActive=!0,b.field.current=t;const e=pt.get(t);e.field||(e.field=_t(e,0))}function vt(t,e,r={}){pt.set(t,{gen:e,field:null,angleMode:yt(r)})}function wt(t,e){for(let r=0;r<dt;r++)for(let n=0;n<gt;n++)t[r][n]=e(r,n);return t}class Rt{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=et(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 At{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:Z(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:Z(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=Z(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){ct();const a=.5,s=[],l=Math.round(this.length/a),c=new ht(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*N(.7,1.3),20)||t>=u)&&c.x&&(s.push([c.x-e/2,c.y-r/2]),h=0,t>=u&&u++)}return new Rt(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,Mt,St,Pt;class Tt{constructor(){this.isClosed=!1,this.curvature=Mt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){Lt(this.vert,this.curvature,this.isClosed).show()}}function kt(t=0){Mt=U(t,0,1),Et=new Tt}function It(t,e,r=1){if(!Et)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Et.vertex(t,e,r)}function Ct(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 Lt(t,e=.5,r=!1){const n=new At(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=Q(h[0],h[1],u[0],u[1]),d=Q(u[0],u[1],f[0],f[1]),g=tt(h[0],h[1],u[0],u[1]),p=tt(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*j(-g),y:u[1]-x*K(-g)},f={x:e.x+y*j(90-g),y:e.y+y*K(90-g)},m={x:u[0]+x*j(-p),y:u[1]+x*K(-p)},d={x:m.x+y*j(90-p),y:m.y+y*K(90-p)},v=et(e,f,m,d,!0),w=Q(e.x,e.y,v.x,v.y),R=Q(e.x,e.y,m.x,m.y)/2,A=i*w*(2*Math.asin(R/w)*(180/Math.PI))/360,E=r&&0===c?0:_-l,M=c===t.length-3?r?o-x:b:0;n.addSegment(g,E,h[2],!0),n.addSegment(g,isNaN(A)?0:A,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=Q(e[0],e[1],r[0],r[1]),o=tt(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 Ft=(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 Dt,Nt,Bt,Yt,Xt,zt=!1,Ot=0,Ut=0,Gt=null,Vt=null;const Wt={},Ht={};let $t=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={},me={};let de=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(){const t=w.glMask?.renderer;t&&(t._curShader=null,t._cachedBlendMode=null,t._isBlending=null,Dt.activeTexture(Dt.TEXTURE0),Dt.bindTexture(Dt.TEXTURE_2D,null),Dt.blendEquation(Dt.FUNC_ADD),Dt.blendFunc(Dt.ONE,Dt.ONE_MINUS_SRC_ALPHA))}function we(){return Nt}function Re(){const t=Dt.isEnabled(Dt.DEPTH_TEST);var e;Re._hadDepthTest=t,t&&Dt.disable(Dt.DEPTH_TEST),Vt=i._renderer.activeFramebuffer?.()??null,Vt?._beforeEnd&&Vt._beforeEnd(),Dt.bindFramebuffer(Dt.FRAMEBUFFER,(e=w.glMask)?"function"==typeof e._framebufferToBind?e._framebufferToBind():e.framebuffer??null:null),Dt.viewport(0,0,w.glMask.width*w.glMask.density,w.glMask.height*w.glMask.density)}function Ae(){Re._hadDepthTest&&Dt.enable(Dt.DEPTH_TEST),Re._hadDepthTest=!1,Vt?._beforeBegin?Vt._beforeBegin():(Dt.bindFramebuffer(Dt.FRAMEBUFFER,null),i._renderer.viewport(i._renderer._origViewport.width,i._renderer._origViewport.height),i._renderer._applyStencilTestIfClipping?.()),Vt=null}function Ee(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 Me(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=$t*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=Ee(se,h-c-1,u-c-1,h+c+1,u+c+1),ie++}function Se(t,e){if(0===pe)return;w.glMask.isDrawn=!0,Re();let r=_e.get(e);r||(r=Dt.createTexture(),Dt.bindTexture(Dt.TEXTURE_2D,r),Dt.texImage2D(Dt.TEXTURE_2D,0,Dt.RGBA,Dt.RGBA,Dt.UNSIGNED_BYTE,t.canvas),Dt.texParameteri(Dt.TEXTURE_2D,Dt.TEXTURE_MIN_FILTER,Dt.LINEAR),Dt.texParameteri(Dt.TEXTURE_2D,Dt.TEXTURE_MAG_FILTER,Dt.LINEAR),Dt.texParameteri(Dt.TEXTURE_2D,Dt.TEXTURE_WRAP_S,Dt.CLAMP_TO_EDGE),Dt.texParameteri(Dt.TEXTURE_2D,Dt.TEXTURE_WRAP_T,Dt.CLAMP_TO_EDGE),_e.set(e,r)),Dt.useProgram(le),Dt.enable(Dt.BLEND),Dt.blendFunc(Dt.ONE_MINUS_DST_ALPHA,Dt.ONE),Dt.activeTexture(Dt.TEXTURE0),Dt.bindTexture(Dt.TEXTURE_2D,r),Dt.uniform1i(me.u_tex,0);const n=b.stroke.color._array;Dt.uniform4f(me.u_color,...n),Dt.uniformMatrix4fv(me.u_proj,!1,we()),Dt.bindVertexArray(ce),Dt.bindBuffer(Dt.ARRAY_BUFFER,ue);const i=5*pe*4,o=ge.subarray(0,5*pe);i>de?(Dt.bufferData(Dt.ARRAY_BUFFER,ge,Dt.DYNAMIC_DRAW),de=ge.byteLength):Dt.bufferSubData(Dt.ARRAY_BUFFER,0,o),Dt.drawArraysInstanced(Dt.TRIANGLE_STRIP,0,4,pe),Dt.flush(),Dt.bindVertexArray(null),Dt.bindTexture(Dt.TEXTURE_2D,null),Ae(),ye&&(w.markDirtyRect(w.glMask,ye),ye=null),pe=0,ve()}b.stroke={color:null,weight:1,clipWindow:null,type:"HB",isActive:!1,opacity:1};let Pe=new Map,Te={a:1,b:0,c:0,d:1,tx:0,ty:0};function ke(){return i??n??window.self.p5.instance}const Ie={offset:.08,scale:.08,warp:.06,tilt:.06};function Ce(){return{...b.stroke}}function Le(t){b.stroke={...t}}function Fe(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:{...Ie}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...Ie,...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:{...Ie},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&&Dt&&Dt.deleteTexture(e),_e.delete(t)}(r);const n=ke().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(),or.imageToWhite(n),or.tips.set(r,n),e.tipKey=r,void Pe.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 or.add(e.image.src),Pe.set(t,{param:e,colors:[],buffers:[]}),or.load()}Pe.set(t,{param:e,colors:[],buffers:[]})}function De(t){if(!Pe.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...Pe.keys()].join(", ")}.`);b.stroke.type=t}function Ne(t,e,r){_(),b.stroke.color=i.color(...arguments),b.stroke.isActive=!0}function Be(t){b.stroke.weight=t}function Ye(t,e,r=1){De(t),Ne(e),Be(r)}function Xe(){return{a:it(),b:ot(),c:at(),d:st(),tx:rt(),ty:nt()}}function ze(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 Oe,Ue,Ge,Ve;const We={};function He(t,n,i,a=!1){$t=it(),jt=ot(),Kt=at(),Zt=st(),qt=rt(),Jt=nt(),Qt=e/2,te=r/2,ee=Math.sqrt($t*$t+jt*jt),re=o,Te=Xe(),Oe=new ht(t+e/2,n+r/2),Ue=i,Ge=a,Ge&&Ge.calcIndex(0)}const $e=[];function je(t,n){n||(Ve=t),function(){We.seed=999999*N();const{param:t}=Pe.get(b.stroke.type)??{};if(!t)return;We.p=t;const{pressure:n}=t;if(We.a="custom"!==n.type?N(-1,1):0,We.b="custom"!==n.type?N(1,1.5):0,"custom"!==n.type)We.cp=N(3,3.5),We.ct=0,We.cs=1,We.ck=0;else{const t=n.variation??Ie;We.cp=N(-t.offset,t.offset),We.ct=N(-t.warp,t.warp),We.cs=N(1-t.scale,1+t.scale),We.ck=N(-t.tilt,t.tilt)}if([We.min,We.max]=n.min_max,We.noiseoffset=.03,!Ge){const t=Ve*Math.PI/180;We.cos=Math.cos(t),We.sin=Math.sin(t)}!function(){v(),function(){const t=i?.glMask;t&&(Gt=t,Gt.dirtyRect??=null,Gt.isDrawn??=!1,w.glMask=Gt)}();const t=i.drawingContext,n=!zt||Dt!==t;(n||Ot!==e||Ut!==r)&&(Nt=new Float32Array([2/e,0,0,0,0,2/r,0,0,0,0,1,0,-1,-1,0,1]),Ot=e,Ut=r),n&&(Dt=t,Xt=Ft(Dt,"#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);}"),Dt.useProgram(Xt),Dt.enable(Dt.BLEND),Dt.blendFunc(Dt.ONE_MINUS_DST_ALPHA,Dt.ONE),["a_position","a_radius","a_alpha"].forEach(t=>Wt[t]=Dt.getAttribLocation(Xt,t)),["u_matrix","u_color"].forEach(t=>Ht[t]=Dt.getUniformLocation(Xt,t)),Bt=Dt.createVertexArray(),Dt.bindVertexArray(Bt),Yt=Dt.createBuffer(),Dt.bindBuffer(Dt.ARRAY_BUFFER,Yt),Dt.bufferData(Dt.ARRAY_BUFFER,ne.byteLength,Dt.DYNAMIC_DRAW),ae=ne.byteLength,Dt.enableVertexAttribArray(Wt.a_position),Dt.vertexAttribPointer(Wt.a_position,2,Dt.FLOAT,!1,16,0),Dt.enableVertexAttribArray(Wt.a_radius),Dt.vertexAttribPointer(Wt.a_radius,1,Dt.FLOAT,!1,16,8),Dt.enableVertexAttribArray(Wt.a_alpha),Dt.vertexAttribPointer(Wt.a_alpha,1,Dt.FLOAT,!1,16,12),Dt.bindVertexArray(null),_e.clear(),le=Ft(Dt,"#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]=Dt.getAttribLocation(le,t)),["u_proj","u_color","u_tex"].forEach(t=>me[t]=Dt.getUniformLocation(le,t)),ce=Dt.createVertexArray(),Dt.bindVertexArray(ce),he=Dt.createBuffer(),Dt.bindBuffer(Dt.ARRAY_BUFFER,he),Dt.bufferData(Dt.ARRAY_BUFFER,be,Dt.STATIC_DRAW),Dt.enableVertexAttribArray(fe.a_corner),Dt.vertexAttribPointer(fe.a_corner,2,Dt.FLOAT,!1,0,0),ue=Dt.createBuffer(),Dt.bindBuffer(Dt.ARRAY_BUFFER,ue),Dt.bufferData(Dt.ARRAY_BUFFER,ge.byteLength,Dt.DYNAMIC_DRAW),de=ge.byteLength,Dt.enableVertexAttribArray(fe.a_pos),Dt.vertexAttribPointer(fe.a_pos,2,Dt.FLOAT,!1,20,0),Dt.vertexAttribDivisor(fe.a_pos,1),Dt.enableVertexAttribArray(fe.a_size),Dt.vertexAttribPointer(fe.a_size,1,Dt.FLOAT,!1,20,8),Dt.vertexAttribDivisor(fe.a_size,1),Dt.enableVertexAttribArray(fe.a_angle),Dt.vertexAttribPointer(fe.a_angle,1,Dt.FLOAT,!1,20,12),Dt.vertexAttribDivisor(fe.a_angle,1),Dt.enableVertexAttribArray(fe.a_alpha),Dt.vertexAttribPointer(fe.a_alpha,1,Dt.FLOAT,!1,20,16),Dt.vertexAttribDivisor(fe.a_alpha,1),Dt.bindVertexArray(null),zt=!0)}();const o=!0!==w.isBrush;w.isBrush=!0,o&&(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=Te;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}}er()}();const o=function(){const{param:t}=Pe.get(b.stroke.type)??{};return t?t.spacing:1}(),a=Math.round(Ue*(n?t:1)/o);for(let e=0;e<a;e++)$e.length<2*a&&$e.push(X()),Ke(),n?Oe.plotTo(Ge,o,o,t,e<10):Oe._moveToDegrees(t,o,o);!function(){er(),function(){if(0===ie)return;w.glMask.isDrawn=!0,Re();const t=b.stroke.color._array;Dt.useProgram(Xt),Dt.enable(Dt.BLEND),Dt.blendFunc(Dt.ONE_MINUS_DST_ALPHA,Dt.ONE),Dt.bindVertexArray(Bt),Dt.bindBuffer(Dt.ARRAY_BUFFER,Yt);const e=16*ie,r=ne.subarray(0,4*ie);e>ae?(Dt.bufferData(Dt.ARRAY_BUFFER,ne,Dt.DYNAMIC_DRAW),ae=ne.byteLength):Dt.bufferSubData(Dt.ARRAY_BUFFER,0,r),Dt.uniform4f(Ht.u_color,...t),Dt.uniformMatrix4fv(Ht.u_matrix,!1,we()),Dt.drawArrays(Dt.POINTS,0,ie),Dt.flush(),Dt.bindVertexArray(null),Ae(),se&&(w.markDirtyRect(w.glMask,se),se=null),ie=0,ve()}();const t=We.p?.type;"image"===t?Se(or.tips.get(We.p.image.src),We.p.image.src):"custom"===t&&Se(or.tips.get(We.p.tipKey),We.p.tipKey)}()}function Ke(){if(!Je())return;const t=Ze(),e=O(D(We.seed+.002*Oe.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*B($e)*We.p.scatter/3,r=We.p.weight*N(.9,1.1),n=Math.ceil(We.p.grain/t);for(let t=0;t<n;t++){const t=N(.9,1.1),n=t*e*N(-1,1),i=N(-1,1),o=Math.sqrt((t*e)**2-n**2);Me(Oe.x+n,Oe.y+i*o,r,We.alpha)}}(t*e);break;case"marker":Qe(t*e);break;case"custom":case"image":tr(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)*B($e)/t);if(N(0,We.p.grain*t)>.4){let e,n;if(Ge)e=.7*r*N(-1,1),n=r*N(-1,1);else{const t=r*N(-1,1),i=.3*r*N(-1,1);e=t*-We.sin+i*We.cos,n=t*We.cos+i*We.sin}const i=t*t*We.p.weight*N(.85,1.15)*b.stroke.weight,o=Math.max(.9,t)*We.alpha*N(.75,1.1);Me(Oe.x+e,Oe.y+n,i,o)}}(t*e)}}function Ze(){return Ge?qe()*Ge.pressure(Oe.plotted):qe()}function qe(){return"custom"===We.p.pressure.type?O(We.p.pressure.curve(Math.max(0,Math.min(1,.5+(Oe.plotted/Ue-.5+We.ct)*We.cs)))+We.cp+We.ck*(Oe.plotted/Ue-.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*Ue,a=(Oe.plotted<o?1.2*e:.8*e)*(Ue/2);return O(1/(1+Math.pow(Math.abs((Oe.plotted-o)/a),2*r)),0,1,n,i)}()}function Je(){const t=We.clipA*Oe.x+We.clipC*Oe.y+We.clipTX;if(t<We.clipMinX||t>We.clipMaxX)return!1;const e=We.clipB*Oe.x+We.clipD*Oe.y+We.clipTY;return e>=We.clipMinY&&e<=We.clipMaxY}function Qe(t,e=!0,r=We.alpha){const n=e?b.stroke.weight*We.p.scatter:0,i=e?n*N(-1,1):0,o=e?n*N(-1,1):0;Me(Oe.x+i,Oe.y+o,b.stroke.weight*We.p.weight*t,r*Math.max(.8,t)*N(.9,1.1))}function tr(t,e=We.alpha){const r=b.stroke.weight*We.p.scatter,n=r*N(-1,1),i=r*N(-1,1),o=We.p.weight*b.stroke.weight*t;let a=0;"random"===We.p.rotate?a=Y(0,360)*(Math.PI/180):"natural"===We.p.rotate&&(a=((Ge?-Ge.angle(Oe.plotted):-Ve)+Oe.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=$t*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=Ee(ye,u-1.42*c-1,f-1.42*c-1,u+1.42*c+1,f+1.42*c+1),pe++}(Oe.x+n,Oe.y+i,o,a,e*Math.max(.8,t)*N(.9,1.1))}function er(){if(Je()){let t=Ze(),e=We.alpha;if("marker"===We.p.type)for(let r=1;r<10;r++)Qe(t*r/10,!0,8*e);else if("custom"===We.p.type||"image"===We.p.type)for(let r=1;r<5;r++)tr(t*r/10,2*e)}}function rr(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.");ct();let i=Q(t,e,r,n);0!=i&&(He(t,e,i),je(tt(t,e,r,n),!1))}F(()=>{$e.length=0});const nr=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate"],ir=[["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 ir){let e={};for(let r=0;r<t[1].length;r++)e[nr[r]]=t[1][r];Fe(t[0],e)}Rt.prototype.draw=function(t=!1,e,r){let n=Ce();if(t&&Ye(t,e,r),n.isActive)for(let t of this.sides)rr(t[0].x,t[0].y,t[1].x,t[1].y);Le(n)},At.prototype.draw=function(t,e,r){Ce().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,n){ct(),He(e,r,t.length,t),je(n,!0)}(this,t,e,r))};const or={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=ke().createImage(n.naturalWidth,n.naturalHeight);r.drawingContext.drawImage(n,0,0),or.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 ar(){return{...b.hatch}}function sr(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=b.hatch;n.isActive=!0,n.dist=t,n.angle=q(e),n.options=r}function lr(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 cr(t){const e=b.hatch.dist,r=(b.hatch.angle%180+180)%180,n=b.hatch.options,i=Ce();b.hatch.hBrush&&Ye(...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 lr(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*N(-1,1),o+=s*e*N(-1,1),l+=s*e*N(-1,1),c+=s*e*N(-1,1)),rr(i,o,l,c),t>0&&n.continuous&&rr(a[t-1].x2,a[t-1].y2,i,o)}Le(i)}function hr(t,e,r){const n=2*Math.PI,i=w.ctx,o=r/2;i.moveTo(t+o,e),i.arc(t,e,o,0,n)}b.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},Rt.prototype.hatch=function(t=!1,e,r){let n=ar();t&&sr(t,e,r),n.isActive&&cr(this),function(t){b.hatch={...t}}(n)},At.prototype.hatch=function(t,e,r){ar().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 ur=()=>({...b.fill});function fr(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 mr(t,e="out"){b.fill.bleed_strength=U(t,0,1),b.fill.direction=e}function dr(t=.4,e=.4){b.fill.texture_strength=U(t,0,1),b.fill.border_strength=U(e,0,1)}let gr;const pr=[[],[]];function xr(){for(let t=0;t<512;t++)pr[0][t]=X(.5,.2),pr[1][t]=X(0,.02)}function yr(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}F(xr);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=J(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 gr.intersect(t.ray))yr(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const o=N(-.6,.6)*e,a=N(-.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.length-e,i=new Array(n),o=new Array(n),a=new Array(n);let s=0;for(let t=0;t<r;t++,s++)i[s]=this.v[t],o[s]=this.m[t],a[s]=this.dir[t];for(let t=r+e;t<this.v.length;t++,s++)i[s]=this.v[t],o[s]=this.m[t],a[s]=this.dir[t];return{v:i,m:o,dir:a}}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+N(0,.8*i)));const o=[],a=[],s=[],l=this.midP,c=gr.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)*N(.3,.6),y:l.y+(n.y-l.y)*N(.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(i),s=new Array(i),l=new Array(o),c=new Array(o),h="out"===b.fill.direction?-90:90;0===pr[0].length&&xr();const u=pr[0],f=u.length,m=pr[1],d=m.length;let g,p,x,y=0,_=0,v=999===t?N(.6,.8):b.fill.bleed_strength;for(let o=0;o<i;o++){const g=e[o],p=e[o+1<i?o+1:0],x=r[o],b=n[o];t<997&&(v=x);const w=(b?h:-h)+5*N(-1,1),R=j(w),A=K(w),E=p.x-g.x,M=p.y-g.y,S=R*E+A*M,P=R*M-A*E,T=u[~~(N(0,1)*f)]*N(.65,1.35)*v,k=x+m[~~(N(0,1)*d)];l[y]=x,c[y]=b,y++,a[_]=g.x+.5*E+S*T,s[_]=g.y+.5*M+P*T,l[y]=k,c[y]=b,y++,_++}const w=1024/b.fill.texture_strength;if(w&&y>w){const t=Math.ceil(y/w),r=Math.ceil(y/t);g=new Array(r),p=new Array(r),x=new Array(r);let n=0;for(let r=0;r<y;r+=t,n++)g[n]=r%2==0?e[r>>1]:{x:a[r>>1],y:s[r>>1]},p[n]=l[r],x[n]=c[r]}else{g=new Array(y);for(let t=0;t<y;t++)g[t]=t%2==0?e[t>>1]:{x:a[t>>1],y:s[t>>1]};l.length=y,c.length=y,p=l,x=c}return new _r(g,p,this.midP,x,!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*it(),o*ot(),o*at(),o*st(),o*(rt()+e/2),o*(nt()+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=N(.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,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(),n=r.a,i=r.b,o=r.c,a=r.d,s=r.e,l=r.f;let c=Infinity,h=Infinity,u=-Infinity,f=-Infinity;e.beginPath();const m=t[0];let d=n*m.x+o*m.y+s,g=i*m.x+a*m.y+l;c=u=d,h=f=g,e.moveTo(m.x,m.y);for(let r=1;r<t.length;r++){const m=t[r];d=n*m.x+o*m.y+s,g=i*m.x+a*m.y+l,c=Math.min(c,d),h=Math.min(h,g),u=Math.max(u,d),f=Math.max(f,g),e.lineTo(m.x,m.y)}e.closePath();const p=function(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}(e,r);w.markDirtyRect(w.mask,{minX:c-p,minY:h-p,maxX:u+p,maxY:f+p})}(this.v),w.ctx.fill(),w.ctx.stroke()}erase(t,e){w.ctx.save();const r=~~(N(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=.04*o,s=.35*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+X(0,n),r=c+X(0,i),o=N(a,s);w.ctx.beginPath(),hr(e,r,o),t%5!=0&&w.ctx.fill()}w.ctx.globalCompositeOperation="source-over",w.ctx.restore()}}Rt.prototype.fill=function(t=!1,e,r,n,i,o){let a=ur();t&&(fr(t,e),mr(r,o),dr(n,i)),a.isActive&&(ct(),function(t){if(!b.fill.isActive||!b.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");gr=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)*N(.85,1.4)*n),o=Y(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(b.fill.color,O(b.fill.opacity,0,255,0,1,!0),b.fill.texture_strength)}(this)),(t=>{b.fill={...t}})(a)},At.prototype.fill=function(t,e,r){ur().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,.6,!0)),this.pol.fill())};const br=[];"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),ct(),br.push({fill:{...b.fill},stroke:{...b.stroke},hatch:{...b.hatch},field:{...b.field}})},e.pop=function(){i.call(this),function(){const t=br.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=>{C=k(t);for(const t of L)t()})(t)},e.noiseSeed=function(t){a.call(this,t),(t=>{D=T(k(t))})(t)}}),t.Plot=At,t.Polygon=Rt,t.Position=ht,t.add=Fe,t.addField=vt,t.arc=function(t,e,r,n,i){const o=q(n),a=((q(i)-o)%360+360)%360;if(0===a)return;const s=new At("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*j(o),f=e-r*K(o);s.draw(u,f,1)},t.beginShape=kt,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Pt=[e,r],St=new At(t)},t.box=function(){return[...Pe.keys()]},t.circle=function(t,e,r,n=!1){const i=new At("curve"),o=Math.PI*r,a=N(0,360),s=n?()=>1+.2*n*N():()=>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*Y(-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*K(a),c=e-r*j(-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:ze(t),inverse:e}},t.endShape=Ct,t.endStroke=function(t,e){if(!St)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");St.endPlot(t,e),St.draw(Pt[0],Pt[1],1),St=!1},t.field=bt,t.fill=fr,t.fillBleed=mr,t.fillTexture=dr,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.");ct(),He(t,e,r),je(Z(n),!1)},t.hatch=sr,t.hatchArray=cr,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=rr,t.listFields=function(){return ct(),Array.from(pt.keys())},t.load=p,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(){b.stroke.clipWindow=null},t.noField=function(){ct(),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=De,t.polygon=function(t){new Rt(t).show()},t.rect=function(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),kt(0),It(t,e),It(t+r,e),It(t+r,e+n),It(t,e+n),Ct(!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=pt.get(b.field.current);e.field=_t(e,t)},t.scaleBrushes=function(t){for(const{param:e}of Pe.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.set=Ye,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].");Lt(t,e).draw()},t.stroke=Ne,t.strokeWeight=Be,t.vertex=It,t.wRand=z,t.wiggle=function(t=1){bt("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.mapdiff --git a/dist/p5.brush.js.map b/dist/p5.brush.js.mapindex 73dad96..2df621f 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/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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2D,GAAc0kB,EAAc9vB,EACnD,iBM1CO,SAAsB0K,GAC3B,IAAK,MAAMsR,MAAEA,KAAWpS,GAAK6b,SACvBzJ,IACFA,EAAM7C,QAAUzO,EAChBsR,EAAM3B,SAAW3P,EACjBsR,EAAMyE,SAAW/V,EAGvB,oBHQO,SAAgBqlB,EAAejhB,EAAa,IACjD,IAAKihB,GAAiBA,EAAcx5B,OAAS,EAC3C,MAAM,IAAI+C,MACR,+EAGIgW,GAAcygB,EAAejhB,GACnCpW,MACJ,+DHmFO,SAAgBxC,EAAI,GACzBuR,GAAM,QACN5N,EAAM4N,MAAMqC,OAAS5T,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/fill/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\nlet FillMaskUploadCanvas = null;\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 * 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 (buffer.renderer._pInst !== getSketchRenderer()) {\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 = () => Renderer?._renderer?.activeFramebuffer?.() ?? null;\n\nconst clearTarget = (target) => {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n target.draw(() => Renderer.clear());\n return;\n }\n\n const ctx = target.drawingContext;\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, target.width, target.height);\n ctx.restore();\n};\n\nconst uploadFillMaskToMirror = (mask, dirtyRect = null) => {\n const target = Renderer.fillMaskFramebuffer;\n const gl = Renderer.drawingContext;\n const uploadRect = normalizeDirtyRect(dirtyRect) ?? getFullDirtyRect();\n const uploadWidth = uploadRect.maxX - uploadRect.minX;\n const uploadHeight = uploadRect.maxY - uploadRect.minY;\n\n if (\n !FillMaskUploadCanvas ||\n FillMaskUploadCanvas.width !== uploadWidth ||\n FillMaskUploadCanvas.height !== uploadHeight\n ) {\n FillMaskUploadCanvas = new OffscreenCanvas(uploadWidth, uploadHeight);\n FillMaskUploadCanvas.drawingContext = FillMaskUploadCanvas.getContext(\"2d\");\n }\n\n const uploadContext = FillMaskUploadCanvas.drawingContext;\n uploadContext.clearRect(0, 0, uploadWidth, uploadHeight);\n uploadContext.drawImage(\n mask,\n uploadRect.minX,\n uploadRect.minY,\n uploadWidth,\n uploadHeight,\n 0,\n 0,\n uploadWidth,\n uploadHeight,\n );\n\n clearTarget(target);\n gl.bindTexture(gl.TEXTURE_2D, target.colorTexture);\n gl.texSubImage2D(\n gl.TEXTURE_2D,\n 0,\n uploadRect.minX,\n uploadRect.minY,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n FillMaskUploadCanvas,\n );\n\n return target;\n};\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, flipY = true) => {\n const normalized = normalizeDirtyRect(rect);\n if (!normalized) return null;\n\n const { height } = getTargetPixelSize();\n return {\n x: normalized.minX,\n y: flipY ? height - normalized.maxY : normalized.minY,\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 */\nconst withScissor = (gl, rect, draw, flipY = true) => {\n const box = toScissorBox(rect, flipY);\n if (!box) {\n draw();\n return;\n }\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\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 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 clearTarget(target);\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-mask dirty rects are still less predictable when the destination\n // is itself a framebuffer, so keep that path conservative.\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 // Section: Setup and load shaders\n // =============================================================================\n /**\n * Ensures the mask buffers and blend shader exist for the current renderer.\n */\n load() {\n Density = Renderer.pixelDensity();\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n const needsBuffers =\n !Renderer.mask ||\n !Renderer.glMask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight;\n const needsBlendSourceFramebuffer =\n !Renderer.blendSourceFramebuffer ||\n Renderer.blendSourceFramebuffer.width !== Cwidth ||\n Renderer.blendSourceFramebuffer.height !== Cheight ||\n (typeof Renderer.blendSourceFramebuffer.pixelDensity === \"function\" &&\n Renderer.blendSourceFramebuffer.pixelDensity() !== Density);\n const needsFillMaskFramebuffer =\n !Renderer.fillMaskFramebuffer ||\n Renderer.fillMaskFramebuffer.width !== Cwidth ||\n Renderer.fillMaskFramebuffer.height !== Cheight ||\n (typeof Renderer.fillMaskFramebuffer.pixelDensity === \"function\" &&\n Renderer.fillMaskFramebuffer.pixelDensity() !== Density);\n if (!Renderer.loaded || needsBuffers) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n // Keep one 2D mask for fill/hatch work and one framebuffer-backed mask\n // for brush stamps so the brush path stays in the main renderer context.\n Renderer.mask = new OffscreenCanvas(maskWidth, maskHeight);\n Renderer.mask.drawingContext = Renderer.mask.getContext(\"2d\");\n Renderer.glMask = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n Renderer.loaded = true;\n\n Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);\n }\n\n if (needsBlendSourceFramebuffer) {\n if (Renderer.blendSourceFramebuffer?.remove) {\n Renderer.blendSourceFramebuffer.remove();\n }\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 if (needsFillMaskFramebuffer) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = Renderer.createFramebuffer({\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n clearTarget(Renderer.fillMaskFramebuffer);\n }\n\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.ctx.imageSmoothingEnabled = false;\n\n this.glMask.dirtyRect ??= null;\n this.glMask.isDrawn ??= false;\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 // Reset the brush mask at the start of each blend cycle.\n clearTarget(this.glMask);\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\n const dirtyRect = this.getCompositeRect(mask, isBrushMask);\n if (!dirtyRect) {\n this.clearMask(mask);\n return;\n }\n\n const gl = Renderer.drawingContext;\n const shader = Renderer.shaderProgram;\n const activeFramebuffer = getActiveFramebuffer();\n const source = blitToBlendSourceFramebuffer(activeFramebuffer ?? Renderer, dirtyRect);\n const targetIsFramebuffer = !!activeFramebuffer;\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 Renderer.push();\n Renderer.translate(0, 0);\n Renderer.shader(shader);\n\n shader.setUniform(\"u_source\", source);\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n if (isBrushMask) {\n shader.setUniform(\"u_mask\", mask);\n } else {\n shader.setUniform(\"u_mask\", uploadFillMaskToMirror(mask, dirtyRect));\n }\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 }, !targetIsFramebuffer);\n\n Renderer.pop();\n Renderer.resetShader();\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n this.clearMask(mask);\n },\n};\n\n/**\n * Copies the current pixels of a renderer or framebuffer into the reusable\n * blend source framebuffer.\n * @param {p5|p5.Graphics|p5.Framebuffer} sourceTarget - Source to copy from.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} [dirtyRect=null] - Optional copy region.\n * @returns {p5.Framebuffer} Blend source framebuffer after the blit.\n */\nconst blitToBlendSourceFramebuffer = (sourceTarget, dirtyRect = null) => {\n const sourceFramebuffer = Renderer.blendSourceFramebuffer;\n const gl = Renderer.drawingContext;\n const sourceIsFramebuffer = isFramebufferTarget(sourceTarget);\n const { width, height } = getTargetPixelSize();\n const sourceBox = dirtyRect ? toScissorBox(dirtyRect) : null;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n\n (sourceIsFramebuffer ? sourceTarget.renderer : Renderer._renderer)?.flushDraw?.();\n\n if (sourceIsFramebuffer) {\n sourceFramebuffer.draw(() => {\n withScissor(Renderer.drawingContext, dirtyRect, () => {\n Renderer.clear();\n Renderer.push();\n Renderer.imageMode(Renderer.CENTER);\n Renderer.image(sourceTarget, 0, 0, Cwidth, Cheight);\n Renderer.pop();\n }, false);\n });\n return sourceFramebuffer;\n }\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, sourceFramebuffer.framebuffer);\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.blitFramebuffer(\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n sourceBox?.x ?? 0,\n sourceBox?.y ?? 0,\n sourceBox ? sourceBox.x + sourceBox.width : width,\n sourceBox ? sourceBox.y + sourceBox.height : height,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST,\n );\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n\n return sourceFramebuffer;\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), 20);\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 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 resetMaskShaderTracking() {\n const renderer = Mix.glMask?.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 rendererMask = Renderer?.glMask;\n if (!rendererMask) return null;\n brushMaskTarget = rendererMask;\n brushMaskTarget.dirtyRect ??= null;\n brushMaskTarget.isDrawn ??= false;\n Mix.glMask = brushMaskTarget;\n return brushMaskTarget;\n}\n\nfunction getProjectionMatrix() {\n return framebufferProjMatrix;\n}\n\nfunction beginMaskTarget() {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = hadDepthTest;\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n prevMaskTarget = Renderer._renderer.activeFramebuffer?.() ?? null;\n if (prevMaskTarget?._beforeEnd) prevMaskTarget._beforeEnd();\n gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(Mix.glMask));\n gl.viewport(\n 0,\n 0,\n Mix.glMask.width * Mix.glMask.density,\n Mix.glMask.height * Mix.glMask.density,\n );\n}\n\nfunction endMaskTarget() {\n if (beginMaskTarget._hadDepthTest) gl.enable(gl.DEPTH_TEST);\n beginMaskTarget._hadDepthTest = false;\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 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 \"../core/color.js\";\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 // Cache the current 2D transform once so the hot loop can stay numeric and\n // avoid repeated property reads while we build bounds.\n const a = matrix.a;\n const b = matrix.b;\n const c = matrix.c;\n const d = matrix.d;\n const e = matrix.e;\n const f = matrix.f;\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n\n ctx.beginPath();\n\n // Seed both the path and the transformed bounds from the first vertex so the\n // loop below only needs to append line segments.\n const first = vertices[0];\n let tx = a * first.x + c * first.y + e;\n let ty = b * first.x + d * first.y + f;\n minX = maxX = tx;\n minY = maxY = ty;\n\n ctx.moveTo(first.x, first.y);\n\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i];\n\n // Track the transformed bounds in canvas space while we build the path so\n // dirty-rect bookkeeping does not need a second pass over the vertices.\n tx = a * v.x + c * v.y + e;\n ty = b * v.x + d * v.y + f;\n minX = Math.min(minX, tx);\n minY = Math.min(minY, ty);\n maxX = Math.max(maxX, tx);\n maxY = Math.max(maxY, ty);\n\n ctx.lineTo(v.x, v.y);\n }\n\n ctx.closePath();\n\n // Expand by stroke width so the later composite pass copies enough pixels\n // even when the polygon border extends outside the raw vertex bounds.\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 radius = d / 2;\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 \"./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 // Copy only the kept ranges instead of cloning the full arrays and splicing.\n const keep = this.v.length - n;\n const v = new Array(keep);\n const m = new Array(keep);\n const dir = new Array(keep);\n let dst = 0;\n\n for (let i = 0; i < s; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\n }\n\n for (let i = s + n; i < this.v.length; i++, dst++) {\n v[dst] = this.v[i];\n m[dst] = this.m[i];\n dir[dst] = this.dir[i];\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 insertedX = new Array(len);\n const insertedY = new Array(len);\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 insertedIdx = 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\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 const d = gPool[~~(rr(0, 1) * gPoolLen)] * rr(0.65, 1.35) * mod;\n const nextMod = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];\n\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n\n insertedX[insertedIdx] = cv.x + sideX * 0.5 + dirX * d;\n insertedY[insertedIdx] = cv.y + sideY * 0.5 + dirY * d;\n newMods[idx] = nextMod;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n }\n\n let fv,\n fm,\n fd;\n const growCap = GROW_MAX_VERTS / State.fill.texture_strength;\n if (growCap && idx > growCap) {\n const step = Math.ceil(idx / growCap);\n const kept = Math.ceil(idx / step);\n fv = new Array(kept);\n fm = new Array(kept);\n fd = new Array(kept);\n let dst = 0;\n for (let j = 0; j < idx; j += step, dst++) {\n fv[dst] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n fm[dst] = newMods[j];\n fd[dst] = newDirs[j];\n }\n } else {\n fv = new Array(idx);\n for (let j = 0; j < idx; j++) {\n fv[j] =\n j % 2 === 0\n ? tr_v[j >> 1]\n : { x: insertedX[j >> 1], y: insertedY[j >> 1] };\n }\n newMods.length = idx;\n newDirs.length = idx;\n fm = newMods;\n fd = newDirs;\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) {\n pol = pol.grow();\n }\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) {\n const grown = p.grow(999).grow(997);\n grown.layer(i, size, int, color);\n }\n const sparseLayer = sparse.grow(999).flipDirs().grow(997);\n sparseLayer.layer(i, size, int * texture, color);\n if (i % 2 === 0) {\n const darkerLayer = pol.grow(darker).grow(999);\n darkerLayer.layer(i, size, int * 2, color);\n }\n\n if (i % 8 === 0 || i === numLayers - 1) {\n if (texture !== 0) {\n pol.erase(texture * 3, intensity);\n }\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\n Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;\n\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.04 * minSize;\n const maxSizeFactor = 0.35 * 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 radius = rr(minSizeFactor, maxSizeFactor);\n\n Mix.ctx.beginPath();\n circle(x, y, radius);\n if (i % 5 !== 0) {\n Mix.ctx.fill();\n }\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.60, 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","FillMaskUploadCanvas","isFramebufferTarget","target","begin","end","renderer","_pInst","getSketchRenderer","_isInstanced","window","self","p5","instance","getActiveFramebuffer","_renderer","activeFramebuffer","clearTarget","draw","clear","ctx","drawingContext","save","setTransform","clearRect","width","height","restore","getTargetPixelSize","Math","max","round","normalizeDirtyRect","rect","minX","floor","min","maxX","minY","maxY","ceil","getFullDirtyRect","toScissorBox","flipY","normalized","x","y","withScissor","gl","box","enable","SCISSOR_TEST","scissor","disable","load","buffer","Error","resolveTarget","webglVersion","_isReady","loaded","Mix","isCanvasReady","State","isMixReady","isBlending","cachedColor","Object","markDirtyRect","a","b","dirtyRect","isDrawn","clearMask","getCompositeRect","isBrushMask","padding","expandDirtyRect","pixelDensity","maskWidth","maskHeight","needsBuffers","mask","glMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","needsFillMaskFramebuffer","fillMaskFramebuffer","remove","OffscreenCanvas","getContext","createFramebuffer","density","antialias","depth","stencil","shaderProgram","createShader","this","imageSmoothingEnabled","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","source","blitToBlendSourceFramebuffer","targetIsFramebuffer","hadDepthTest","getParameter","DEPTH_TEST","push","translate","setUniform","uploadRect","uploadWidth","uploadHeight","uploadContext","drawImage","bindTexture","TEXTURE_2D","colorTexture","texSubImage2D","RGBA","UNSIGNED_BYTE","uploadFillMaskToMirror","fill","noStroke","pop","resetShader","sourceTarget","sourceFramebuffer","sourceIsFramebuffer","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","flushDraw","imageMode","CENTER","image","bindFramebuffer","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","framebuffer","clearColor","COLOR_BUFFER_BIT","blitFramebuffer","NEAREST","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","angleMode","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","uModelMatrix","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","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","shaderSource","compileShader","attachShader","linkProgram","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","resetMaskShaderTracking","_curShader","_cachedBlendMode","_isBlending","activeTexture","TEXTURE0","blendEquation","FUNC_ADD","blendFunc","ONE","ONE_MINUS_SRC_ALPHA","getProjectionMatrix","beginMaskTarget","isEnabled","_hadDepthTest","_beforeEnd","FRAMEBUFFER","_framebufferToBind","viewport","endMaskTarget","_beforeBegin","_origViewport","_applyStencilTestIfClipping","accumulateDirtyRect","currentRect","circle","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","tex","createTexture","texImage2D","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","flush","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","createGraphics","background","noSmooth","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","rendererMask","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","onerror","crossOrigin","HatchState","rand","continuous","gradient","scanlineHatch","polygon","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","createHatch","polygons","hBrush","values","segs","poly","arc","_dist","_angle","_options","HatchSetState","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","center","isFirst","sx","sy","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","keep","dst","ratio","L","indices","sv","sm","sd","crossings","ay","by","flipDirs","grow","tr_v","tr_m","tr_dir","outLen","insertedX","insertedY","newMods","newDirs","bleedDirDeg","gPool","gPoolLen","g2Pool","g2PoolLen","fv","fm","fd","insertedIdx","mod","cv","nv","mi","di","rotDeg","sideX","sideY","dirX","dirY","nextMod","growCap","kept","intensity","texture","int","switchingToFill","strokeStyle","_getRed","_getGreen","_getBlue","lineCap","darker","sparse","pols","layer","numLayers","erase","lineWidth","fillStyle","matrix","getTransform","beginPath","first","lineTo","closePath","strokePadding","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,EAE5CC,EAAuB,KAW3B,MAAMC,EAAuBC,KACzBA,GACsB,mBAAjBA,EAAOC,OACQ,mBAAfD,EAAOE,OACZF,EAAOG,YACPH,EAAOG,SAASC,OAMdC,EAAoB,IACxBC,EAAeX,EAAWY,OAAOC,KAAKC,GAAGC,SAoDrCC,EAAuB,IAAMf,GAAUgB,WAAWC,uBAAyB,KAE3EC,EAAed,IACnB,IAAKA,EAAQ,OAEb,GAAID,EAAoBC,GAEtB,YADAA,EAAOe,KAAK,IAAMnB,EAASoB,SAI7B,MAAMC,EAAMjB,EAAOkB,eACnBD,EAAIE,OACJF,EAAIG,aAAa,EAAG,EAAG,EAAG,EAAG,EAAG,GAChCH,EAAII,UAAU,EAAG,EAAGrB,EAAOsB,MAAOtB,EAAOuB,QACzCN,EAAIO,WA0DAC,EAAqB,KAAA,CACzBH,MAAOI,KAAKC,IAAI,EAAGD,KAAKE,MAAMnC,EAASI,IACvC0B,OAAQG,KAAKC,IAAI,EAAGD,KAAKE,MAAMlC,EAAUG,M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AMsP,MAAMsC,OAAStR,CACvB","x_google_ignoreList":[1,2]}\ No newline at end of filediff --git a/package.json b/package.jsonindex 4ac330b..4b60667 100644--- a/package.json+++ b/package.json@@ -40,9 +40,10 @@"vitest": "^2.0.0"},"peerDependencies": {- "p5": "^2.1.1"+ "p5": "^2.2"},"dependencies": {+ "earcut": "^3.0.2","esm-seedrandom": "^3.0.5","simplex-noise": "^4.0.3"}diff --git a/src/core/color.js b/src/core/color.jsindex 850d178..8b84b07 100644--- a/src/core/color.js+++ b/src/core/color.js@@ -12,52 +12,7 @@ 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);- }-};+let FillMaskUploadCanvas = null;// =============================================================================// Section: Target Resolution@@ -82,14 +37,6 @@ const isFramebufferTarget = (target) =>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.@@ -116,7 +63,7 @@ const resolveTarget = (buffer = false) => {}if (isFramebufferTarget(buffer)) {- if (!isSupportedFramebufferTarget(buffer)) {+ if (buffer.renderer._pInst !== getSketchRenderer()) {throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch",);@@ -140,12 +87,67 @@ const resolveTarget = (buffer = false) => {* Returns the currently bound sketch framebuffer when drawing into one.* @returns {p5.Framebuffer|null} Active framebuffer or null.*/-const getActiveFramebuffer = () =>- Renderer &&- Renderer._renderer &&- typeof Renderer._renderer.activeFramebuffer === "function"- ? Renderer._renderer.activeFramebuffer()- : null;+const getActiveFramebuffer = () => Renderer?._renderer?.activeFramebuffer?.() ?? null;++const clearTarget = (target) => {+ if (!target) return;++ if (isFramebufferTarget(target)) {+ target.draw(() => Renderer.clear());+ return;+ }++ const ctx = target.drawingContext;+ ctx.save();+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.clearRect(0, 0, target.width, target.height);+ ctx.restore();+};++const uploadFillMaskToMirror = (mask, dirtyRect = null) => {+ const target = Renderer.fillMaskFramebuffer;+ const gl = Renderer.drawingContext;+ const uploadRect = normalizeDirtyRect(dirtyRect) ?? getFullDirtyRect();+ const uploadWidth = uploadRect.maxX - uploadRect.minX;+ const uploadHeight = uploadRect.maxY - uploadRect.minY;++ if (+ !FillMaskUploadCanvas ||+ FillMaskUploadCanvas.width !== uploadWidth ||+ FillMaskUploadCanvas.height !== uploadHeight+ ) {+ FillMaskUploadCanvas = new OffscreenCanvas(uploadWidth, uploadHeight);+ FillMaskUploadCanvas.drawingContext = FillMaskUploadCanvas.getContext("2d");+ }++ const uploadContext = FillMaskUploadCanvas.drawingContext;+ uploadContext.clearRect(0, 0, uploadWidth, uploadHeight);+ uploadContext.drawImage(+ mask,+ uploadRect.minX,+ uploadRect.minY,+ uploadWidth,+ uploadHeight,+ 0,+ 0,+ uploadWidth,+ uploadHeight,+ );++ clearTarget(target);+ gl.bindTexture(gl.TEXTURE_2D, target.colorTexture);+ gl.texSubImage2D(+ gl.TEXTURE_2D,+ 0,+ uploadRect.minX,+ uploadRect.minY,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ FillMaskUploadCanvas,+ );++ return target;+};// =============================================================================// Section: Dirty Rect Utilities@@ -232,16 +234,14 @@ const getFullDirtyRect = () => {* @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 toScissorBox = (rect, flipY = true) => {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,- y: height - normalized.maxY,+ y: flipY ? height - normalized.maxY : normalized.minY,width: normalized.maxX - normalized.minX,height: normalized.maxY - normalized.minY,};@@ -252,11 +252,13 @@ const toScissorBox = (rect) => {* @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 withScissor = (gl, rect, draw, flipY = true) => {+ const box = toScissorBox(rect, flipY);+ if (!box) {+ draw();+ return;+ }// Scissor is never nested in this module, so we can set/clear it directly// without saving previous GL state.@@ -268,8 +270,6 @@ const withScissor = (gl, rect, draw) => {} finally {gl.disable(gl.SCISSOR_TEST);}-- return true;};// =============================================================================@@ -285,8 +285,6 @@ export const load = (buffer = false) => {const target = resolveTarget(buffer);Renderer = target.renderer;- // Check if Rendrer is webgl and throw error if it's not-if (Renderer.webglVersion !== "webgl2") {throw new Error("p5.brush requires a WEBGL canvas");}@@ -367,7 +365,7 @@ export const Mix = {clearMask(target) {if (!target) return;- target.clear();+ clearTarget(target);target.isDrawn = false;target.dirtyRect = null;},@@ -382,9 +380,8 @@ export const Mix = {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.+ // Brush-mask dirty rects are still less predictable when the destination+ // is itself a framebuffer, so keep that path conservative.if (isBrushMask && getActiveFramebuffer()) return getFullDirtyRect();return normalizeDirtyRect(expandDirtyRect(@@ -394,54 +391,6 @@ 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;-- // 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,- density: Density,- antialias: false,- depth: false,- stencil: false,- });- }-- Renderer.blendSourceFramebuffer.draw(() => {- withScissor(Renderer.drawingContext, dirtyRect, () => {- Renderer.clear();- Renderer.push();- if (typeof Renderer.imageMode === "function") {- Renderer.imageMode(- Renderer.CENTER ?? Renderer._renderer?._pInst?.CENTER,- );- }- Renderer.image(activeFramebuffer, 0, 0, Cwidth, Cheight);- Renderer.pop();- });- });- return Renderer.blendSourceFramebuffer;- },-// =============================================================================// Section: Setup and load shaders// =============================================================================@@ -449,54 +398,85 @@ export const Mix = {* 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;+ Density = Renderer.pixelDensity();+ const maskWidth = Math.max(1, Math.round(Cwidth * Density));+ const maskHeight = Math.max(1, Math.round(Cheight * Density));const needsBuffers =!Renderer.mask ||!Renderer.glMask ||- Renderer.mask.width !== Cwidth ||- Renderer.mask.height !== Cheight ||+ Renderer.mask.width !== maskWidth ||+ Renderer.mask.height !== maskHeight ||Renderer.glMask.width !== Cwidth ||Renderer.glMask.height !== Cheight;-- Density = Renderer.pixelDensity();- const p2dMode = graphicsFactory.P2D ?? Renderer.P2D;- const webglMode = graphicsFactory.WEBGL ?? Renderer.WEBGL;-+ const needsBlendSourceFramebuffer =+ !Renderer.blendSourceFramebuffer ||+ Renderer.blendSourceFramebuffer.width !== Cwidth ||+ Renderer.blendSourceFramebuffer.height !== Cheight ||+ (typeof Renderer.blendSourceFramebuffer.pixelDensity === "function" &&+ Renderer.blendSourceFramebuffer.pixelDensity() !== Density);+ const needsFillMaskFramebuffer =+ !Renderer.fillMaskFramebuffer ||+ Renderer.fillMaskFramebuffer.width !== Cwidth ||+ Renderer.fillMaskFramebuffer.height !== Cheight ||+ (typeof Renderer.fillMaskFramebuffer.pixelDensity === "function" &&+ Renderer.fillMaskFramebuffer.pixelDensity() !== Density);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,- Cheight,- webglMode,- );+ // Keep one 2D mask for fill/hatch work and one framebuffer-backed mask+ // for brush stamps so the brush path stays in the main renderer context.+ Renderer.mask = new OffscreenCanvas(maskWidth, maskHeight);+ Renderer.mask.drawingContext = Renderer.mask.getContext("2d");+ Renderer.glMask = Renderer.createFramebuffer({+ width: Cwidth,+ height: Cheight,+ density: Density,+ antialias: false,+ depth: false,+ stencil: false,+ });Renderer.loaded = true;+Renderer.shaderProgram ??= Renderer.createShader(vertSrc, fragSrc);}+ if (needsBlendSourceFramebuffer) {+ if (Renderer.blendSourceFramebuffer?.remove) {+ Renderer.blendSourceFramebuffer.remove();+ }+ Renderer.blendSourceFramebuffer = Renderer.createFramebuffer({+ width: Cwidth,+ height: Cheight,+ density: Density,+ antialias: false,+ depth: false,+ stencil: false,+ });+ }++ if (needsFillMaskFramebuffer) {+ if (Renderer.fillMaskFramebuffer?.remove) {+ Renderer.fillMaskFramebuffer.remove();+ }+ Renderer.fillMaskFramebuffer = Renderer.createFramebuffer({+ width: Cwidth,+ height: Cheight,+ density: Density,+ antialias: false,+ depth: false,+ stencil: false,+ });+ clearTarget(Renderer.fillMaskFramebuffer);+ }+this.mask = Renderer.mask;this.glMask = Renderer.glMask;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.ctx.imageSmoothingEnabled = 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;},// =============================================================================@@ -525,9 +505,8 @@ export const Mix = {if (!this.isBlending && nextColor) {this.isBlending = true;this.cachedColor = nextColor;- // Force p5 to bind its internal render target for glMask before the- // first raw GL brush draw of the blend cycle.- this.glMask.clear();+ // Reset the brush mask at the start of each blend cycle.+ clearTarget(this.glMask);}if (_isLast || colorChanged) {@@ -550,63 +529,101 @@ export const Mix = {*/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 = profileComposite(- `${profilePrefix}.getCompositeRect`,- () => this.getCompositeRect(mask, isBrushMask),- );- if (!dirtyRect) {- profileComposite(`${profilePrefix}.clearMask`, () => this.clearMask(mask));- return;- }-- 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);- // 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);+ const dirtyRect = this.getCompositeRect(mask, isBrushMask);+ if (!dirtyRect) {+ this.clearMask(mask);+ return;+ }- const drawShaderPass = () => {- Renderer.push();- Renderer.translate(0, 0);- Renderer.shader(shader);+ const gl = Renderer.drawingContext;+ const shader = Renderer.shaderProgram;+ const activeFramebuffer = getActiveFramebuffer();+ const source = blitToBlendSourceFramebuffer(activeFramebuffer ?? Renderer, dirtyRect);+ const targetIsFramebuffer = !!activeFramebuffer;+ const hadDepthTest = gl.getParameter(gl.DEPTH_TEST);++ // 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);++ Renderer.push();+ Renderer.translate(0, 0);+ Renderer.shader(shader);++ shader.setUniform("u_source", source);+ shader.setUniform("u_targetIsFramebuffer", targetIsFramebuffer);+ shader.setUniform("u_isBrush", isBrushMask);+ if (isBrushMask) {+ shader.setUniform("u_mask", mask);+ } else {+ shader.setUniform("u_mask", uploadFillMaskToMirror(mask, dirtyRect));+ }+ 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);+ }, !targetIsFramebuffer);++ Renderer.pop();+ Renderer.resetShader();+ if (hadDepthTest) gl.enable(gl.DEPTH_TEST);+ 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);+/**+ * Copies the current pixels of a renderer or framebuffer into the reusable+ * blend source framebuffer.+ * @param {p5|p5.Graphics|p5.Framebuffer} sourceTarget - Source to copy from.+ * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} [dirtyRect=null] - Optional copy region.+ * @returns {p5.Framebuffer} Blend source framebuffer after the blit.+ */+const blitToBlendSourceFramebuffer = (sourceTarget, dirtyRect = null) => {+ const sourceFramebuffer = Renderer.blendSourceFramebuffer;+ const gl = Renderer.drawingContext;+ const sourceIsFramebuffer = isFramebufferTarget(sourceTarget);+ const { width, height } = getTargetPixelSize();+ const sourceBox = dirtyRect ? toScissorBox(dirtyRect) : null;+ const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);+ const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);- withScissor(gl, dirtyRect, () => {- Renderer.fill(0, 0, 0, 0);- Renderer.noStroke();- Renderer.rect(-Cwidth / 2, -Cheight / 2, Cwidth, Cheight);- });+ (sourceIsFramebuffer ? sourceTarget.renderer : Renderer._renderer)?.flushDraw?.();+ if (sourceIsFramebuffer) {+ sourceFramebuffer.draw(() => {+ withScissor(Renderer.drawingContext, dirtyRect, () => {+ Renderer.clear();+ Renderer.push();+ Renderer.imageMode(Renderer.CENTER);+ Renderer.image(sourceTarget, 0, 0, Cwidth, Cheight);Renderer.pop();- };-- profileComposite(`${profilePrefix}.shaderPass`, drawShaderPass);-- Renderer.resetShader();- if (hadDepthTest) gl.enable(gl.DEPTH_TEST);- profileComposite(`${profilePrefix}.clearMask`, () => this.clearMask(mask));+ }, false);});- },+ return sourceFramebuffer;+ }++ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, sourceFramebuffer.framebuffer);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.blitFramebuffer(+ sourceBox?.x ?? 0,+ sourceBox?.y ?? 0,+ sourceBox ? sourceBox.x + sourceBox.width : width,+ sourceBox ? sourceBox.y + sourceBox.height : height,+ sourceBox?.x ?? 0,+ sourceBox?.y ?? 0,+ sourceBox ? sourceBox.x + sourceBox.width : width,+ sourceBox ? sourceBox.y + sourceBox.height : height,+ gl.COLOR_BUFFER_BIT,+ gl.NEAREST,+ );++ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);++ return sourceFramebuffer;};diff --git a/src/core/gl/shader.frag b/src/core/gl/shader.fragindex 745d169..42f246f 100644--- a/src/core/gl/shader.frag+++ b/src/core/gl/shader.frag@@ -3,6 +3,7 @@precision highp float;uniform bool u_isBrush;+uniform bool u_targetIsFramebuffer;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;@@ -202,10 +203,11 @@ 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);+ vec2 sourceUV = vec2(uv.x, 1.0 - uv.y);+ vec2 maskUV = u_targetIsFramebuffer ? vec2(uv.x, 1.0 - uv.y) : uv;- vec4 source = texture(u_source, uv1);- vec4 maskColor = texture(u_mask, uv1);+ vec4 source = texture(u_source, sourceUV);+ vec4 maskColor = texture(u_mask, maskUV);if (maskColor.a == 0.0) {outColor = source;@@ -228,7 +230,7 @@ void main(void) {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;+ vec2 neighborUV = maskUV + 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))));diff --git a/src/core/gl/shader.vert b/src/core/gl/shader.vertindex d8a2e0a..48e9fd0 100644--- a/src/core/gl/shader.vert+++ b/src/core/gl/shader.vert@@ -1,12 +1,10 @@#version 300 es-uniform 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);-}\ No newline at end of file+ gl_Position = vec4(v.x, -v.y, 0, 1);+}diff --git a/src/core/mask.js b/src/core/mask.jsindex dece51f..fd47370 100644--- a/src/core/mask.js+++ b/src/core/mask.js@@ -1,11 +1,6 @@import { Mix } from "./color.js";-function transformPoint(matrix, x, y) {- return {- x: matrix.a * x + matrix.c * y + matrix.e,- y: matrix.b * x + matrix.d * y + matrix.f,- };-}+const ctx = Mix.ctx;function strokePadding(ctx, matrix) {const lineWidth = ctx.lineWidth || 0;@@ -27,26 +22,51 @@ function strokePadding(ctx, matrix) {* @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.*/export function drawPolygon(vertices) {- const ctx = Mix.ctx;const matrix = ctx.getTransform();+ // Cache the current 2D transform once so the hot loop can stay numeric and+ // avoid repeated property reads while we build bounds.+ const a = matrix.a;+ const b = matrix.b;+ const c = matrix.c;+ const d = matrix.d;+ const e = matrix.e;+ const f = matrix.f;let minX = Infinity,minY = Infinity,maxX = -Infinity,maxY = -Infinity;ctx.beginPath();- vertices.forEach((v, i) => {- const point = transformPoint(matrix, v.x, v.y);- minX = Math.min(minX, point.x);- minY = Math.min(minY, point.y);- maxX = Math.max(maxX, point.x);- maxY = Math.max(maxY, point.y);-- if (i === 0) ctx.moveTo(v.x, v.y);- else ctx.lineTo(v.x, v.y);- });++ // Seed both the path and the transformed bounds from the first vertex so the+ // loop below only needs to append line segments.+ const first = vertices[0];+ let tx = a * first.x + c * first.y + e;+ let ty = b * first.x + d * first.y + f;+ minX = maxX = tx;+ minY = maxY = ty;++ ctx.moveTo(first.x, first.y);++ for (let i = 1; i < vertices.length; i++) {+ const v = vertices[i];++ // Track the transformed bounds in canvas space while we build the path so+ // dirty-rect bookkeeping does not need a second pass over the vertices.+ tx = a * v.x + c * v.y + e;+ ty = b * v.x + d * v.y + f;+ minX = Math.min(minX, tx);+ minY = Math.min(minY, ty);+ maxX = Math.max(maxX, tx);+ maxY = Math.max(maxY, ty);++ ctx.lineTo(v.x, v.y);+ }+ctx.closePath();+ // Expand by stroke width so the later composite pass copies enough pixels+ // even when the polygon border extends outside the raw vertex bounds.const padding = strokePadding(ctx, matrix);Mix.markDirtyRect(Mix.mask, {minX: minX - padding,@@ -56,29 +76,16 @@ export function drawPolygon(vertices) {});}++const PI2 = Math.PI * 2;+/*** Draws a circle to the mask.* @param {number} x - X-coordinate of the circle's center.* @param {number} y - Y-coordinate of the circle's center.* @param {number} d - Diameter of the circle.*/-export function circle(x, y, d) {- const PI2 = Math.PI * 2;- const ctx = Mix.ctx;- const matrix = ctx.getTransform();- const radius = d / 2;- const center = transformPoint(matrix, x, y);- const rx = radius * Math.hypot(matrix.a, matrix.c);- const ry = radius * Math.hypot(matrix.b, matrix.d);- const padding = strokePadding(ctx, matrix);-- Mix.markDirtyRect(Mix.mask, {- minX: center.x - rx - padding,- minY: center.y - ry - padding,- maxX: center.x + rx + padding,- maxY: center.y + ry + padding,- });-+export function circle(x, y, radius) {ctx.moveTo(x + radius, y);ctx.arc(x, y, radius, 0, PI2);}diff --git a/src/core/plot.js b/src/core/plot.jsindex 62934e8..d32052d 100644--- a/src/core/plot.js+++ b/src/core/plot.js@@ -144,7 +144,7 @@ export class Plot {pos.plotTo(this, step, step);const idx = this.calcIndex(pos.plotted);pside += step;- const maxSize = Math.max(this.segments[idx] * _side * rr(0.7, 1.3), 10);+ const maxSize = Math.max(this.segments[idx] * _side * rr(0.7, 1.3), 20);if ((pside >= maxSize || idx >= prevIdx) && pos.x) {vertices.push([pos.x - Cwidth / 2, pos.y - Cheight / 2]);pside = 0;diff --git a/src/fill/fill.js b/src/fill/fill.jsindex 8164441..be4e37b 100644--- a/src/fill/fill.js+++ b/src/fill/fill.js@@ -20,7 +20,7 @@ import {Cheight,Density,} from "../core/color.js";-import { drawPolygon, circle } from "../core/mask.js";+import { drawPolygon, circle } from "./mask.js";import {constrain,weightedRand,@@ -281,20 +281,31 @@ class FillPoly {trim(f = 1) {// Fast path for common caseif (f >= 1 || f < 0 || this.v.length <= 8) {- return { v: [...this.v], m: [...this.m], dir: [...this.dir] };+ return { v: this.v, m: this.m, dir: this.dir };}// Trim from middle for balanceconst n = ~~((1 - f) * this.v.length);const s = ~~(this.v.length / 2 - n / 2);- // Clone and splice- const v = [...this.v],- m = [...this.m],- dir = [...this.dir];- v.splice(s, n);- m.splice(s, n);- dir.splice(s, n);+ // Copy only the kept ranges instead of cloning the full arrays and splicing.+ const keep = this.v.length - n;+ const v = new Array(keep);+ const m = new Array(keep);+ const dir = new Array(keep);+ let dst = 0;++ for (let i = 0; i < s; i++, dst++) {+ v[dst] = this.v[i];+ m[dst] = this.m[i];+ dir[dst] = this.dir[i];+ }++ for (let i = s + n; i < this.v.length; i++, dst++) {+ v[dst] = this.v[i];+ m[dst] = this.m[i];+ dir[dst] = this.dir[i];+ }return { v, m, dir };}@@ -362,7 +373,8 @@ class FillPoly {const len = tr_v.length;const outLen = len * 2;- const newVerts = new Array(outLen);+ const insertedX = new Array(len);+ const insertedY = new Array(len);const newMods = new Array(outLen);const newDirs = new Array(outLen);const bleedDirDeg = State.fill.direction === "out" ? -90 : 90;@@ -374,6 +386,7 @@ class FillPoly {g2PoolLen = g2Pool.length;let idx = 0;+ let insertedIdx = 0;let mod = f === 999 ? rr(0.6, 0.8) : State.fill.bleed_strength;for (let i = 0; i < len; i++) {@@ -387,46 +400,59 @@ class FillPoly {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;+ const nextMod = mi + g2Pool[~~(rr(0, 1) * g2PoolLen)];- 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)];+ insertedX[insertedIdx] = cv.x + sideX * 0.5 + dirX * d;+ insertedY[insertedIdx] = cv.y + sideY * 0.5 + dirY * d;+ newMods[idx] = nextMod;newDirs[idx] = di;idx++;+ insertedIdx++;}- let fv = newVerts,- fm = newMods,- fd = newDirs;+ let fv,+ fm,+ fd;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]);+ const kept = Math.ceil(idx / step);+ fv = new Array(kept);+ fm = new Array(kept);+ fd = new Array(kept);+ let dst = 0;+ for (let j = 0; j < idx; j += step, dst++) {+ fv[dst] =+ j % 2 === 0+ ? tr_v[j >> 1]+ : { x: insertedX[j >> 1], y: insertedY[j >> 1] };+ fm[dst] = newMods[j];+ fd[dst] = newDirs[j];}} else {- fv.length = idx;- fm.length = idx;- fd.length = idx;+ fv = new Array(idx);+ for (let j = 0; j < idx; j++) {+ fv[j] =+ j % 2 === 0+ ? tr_v[j >> 1]+ : { x: insertedX[j >> 1], y: insertedY[j >> 1] };+ }+ newMods.length = idx;+ newDirs.length = idx;+ fm = newMods;+ fd = newDirs;}-return new FillPoly(fv, fm, this.midP, fd, false, this.sizeX, this.sizeY);}@@ -468,7 +494,9 @@ class FillPoly {let pols;for (let i = 0; i < numLayers; i++) {- if (i % 4 === 0) pol = pol.grow();+ if (i % 4 === 0) {+ pol = pol.grow();+ }if (i % 2 === 0) {pols = [@@ -478,18 +506,21 @@ class FillPoly {];}- 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 * texture, color);+ for (const p of pols) {+ const grown = p.grow(999).grow(997);+ grown.layer(i, size, int, color);+ }+ const sparseLayer = sparse.grow(999).flipDirs().grow(997);+ sparseLayer.layer(i, size, int * texture, color);if (i % 2 === 0) {- pol.grow(darker).grow(999).layer(i, size, int * 2, color);+ const darkerLayer = pol.grow(darker).grow(999);+ darkerLayer.layer(i, size, int * 2, color);}if (i % 8 === 0 || i === numLayers - 1) {- if (texture !== 0) pol.erase(texture * 3, intensity);+ if (texture !== 0) {+ pol.erase(texture * 3, intensity);+ }Mix.blend(color, true, false, true);}}@@ -503,7 +534,9 @@ class FillPoly {*/layer(i, size, int, color) {Mix.ctx.lineWidth = map(i, 0, 24, size / 25, size / 30, true);+Mix.ctx.fillStyle = `rgb(${color._getRed()} ${color._getGreen()} ${color._getBlue()} / ${int}%)`;+drawPolygon(this.v);Mix.ctx.fill();Mix.ctx.stroke();@@ -522,8 +555,8 @@ class FillPoly {const halfSizeY = this.sizeY / 1.3;const minSize =Math.min(this.sizeX, this.sizeY) * (1.4 - State.fill.bleed_strength);- const minSizeFactor = 0.05 * minSize;- const maxSizeFactor = 0.4 * minSize;+ const minSizeFactor = 0.04 * minSize;+ const maxSizeFactor = 0.35 * minSize;const { x: midX, y: midY } = this.midP;Mix.ctx.globalCompositeOperation = "destination-out";@@ -536,11 +569,13 @@ class FillPoly {for (let i = 0; i < numCircles; i++) {const x = midX + gaussian(0, halfSizeX);const y = midY + gaussian(0, halfSizeY);- const size = rr(minSizeFactor, maxSizeFactor);+ const radius = rr(minSizeFactor, maxSizeFactor);Mix.ctx.beginPath();- circle(x, y, size);- if (i % 5 !== 0) Mix.ctx.fill();+ circle(x, y, radius);+ if (i % 5 !== 0) {+ Mix.ctx.fill();+ }}Mix.ctx.globalCompositeOperation = "source-over";@@ -595,7 +630,7 @@ Plot.prototype.fill = function (x, y, scale) {x,y,scale,- map(State.fill.bleed_strength, 0, 0.6, 0.3, 0.45, true),+ map(State.fill.bleed_strength, 0, 0.6, 0.3, 0.60, true),);this.pol.fill();}diff --git a/src/fill/mask.js b/src/fill/mask.jsnew file mode 100644index 0000000..d3da076--- /dev/null+++ b/src/fill/mask.js@@ -0,0 +1,91 @@+import { Mix } from "../core/color.js";++function strokePadding(ctx, matrix) {+ const lineWidth = ctx.lineWidth || 0;+ if (lineWidth <= 0) return 1;++ return (+ 1 ++ (lineWidth * Math.max(Math.hypot(matrix.a, matrix.c), Math.hypot(matrix.b, matrix.d))) /+ 2+ );+}++// =============================================================================+// Section: Draw shapes to Mask Buffers+// =============================================================================++/**+ * Draws a polygon to the mask using the provided vertices.+ * @param {Array<{x: number, y: number}>} vertices - Array of vertex coordinates.+ */+export function drawPolygon(vertices) {+ const ctx = Mix.ctx;+ const matrix = ctx.getTransform();+ // Cache the current 2D transform once so the hot loop can stay numeric and+ // avoid repeated property reads while we build bounds.+ const a = matrix.a;+ const b = matrix.b;+ const c = matrix.c;+ const d = matrix.d;+ const e = matrix.e;+ const f = matrix.f;+ let minX = Infinity,+ minY = Infinity,+ maxX = -Infinity,+ maxY = -Infinity;++ ctx.beginPath();++ // Seed both the path and the transformed bounds from the first vertex so the+ // loop below only needs to append line segments.+ const first = vertices[0];+ let tx = a * first.x + c * first.y + e;+ let ty = b * first.x + d * first.y + f;+ minX = maxX = tx;+ minY = maxY = ty;++ ctx.moveTo(first.x, first.y);++ for (let i = 1; i < vertices.length; i++) {+ const v = vertices[i];++ // Track the transformed bounds in canvas space while we build the path so+ // dirty-rect bookkeeping does not need a second pass over the vertices.+ tx = a * v.x + c * v.y + e;+ ty = b * v.x + d * v.y + f;+ minX = Math.min(minX, tx);+ minY = Math.min(minY, ty);+ maxX = Math.max(maxX, tx);+ maxY = Math.max(maxY, ty);++ ctx.lineTo(v.x, v.y);+ }++ ctx.closePath();++ // Expand by stroke width so the later composite pass copies enough pixels+ // even when the polygon border extends outside the raw vertex bounds.+ const padding = strokePadding(ctx, matrix);+ Mix.markDirtyRect(Mix.mask, {+ minX: minX - padding,+ minY: minY - padding,+ maxX: maxX + padding,+ maxY: maxY + padding,+ });+}++/**+ * Draws a circle to the mask.+ * @param {number} x - X-coordinate of the circle's center.+ * @param {number} y - Y-coordinate of the circle's center.+ * @param {number} d - Diameter of the circle.+ */+export function circle(x, y, d) {+ const PI2 = Math.PI * 2;+ const ctx = Mix.ctx;+ const radius = d / 2;++ ctx.moveTo(x + radius, y);+ ctx.arc(x, y, radius, 0, PI2);+}diff --git a/src/index.js b/src/index.jsindex 1163391..9f4feaf 100644--- a/src/index.js+++ b/src/index.js@@ -118,12 +118,7 @@ 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 registrationimport { Mix } from "./core/color.js";diff --git a/src/stroke/gl_draw.js b/src/stroke/gl_draw.jsindex 3b641f4..9196e78 100644--- a/src/stroke/gl_draw.js+++ b/src/stroke/gl_draw.js@@ -30,7 +30,6 @@ import imgFragSrc from "./image.frag";// Module statelet isLoaded = false,gl,- projMatrix,framebufferProjMatrix,vao,buf,@@ -102,18 +101,8 @@ 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;+ const renderer = Mix.glMask?.renderer;if (!renderer) return;renderer._curShader = null;renderer._cachedBlendMode = null;@@ -131,78 +120,37 @@ function getFramebufferHandle(target) {}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;+ const rendererMask = Renderer?.glMask;+ if (!rendererMask) return null;+ brushMaskTarget = rendererMask;+ brushMaskTarget.dirtyRect ??= null;+ brushMaskTarget.isDrawn ??= false;Mix.glMask = brushMaskTarget;return brushMaskTarget;}function getProjectionMatrix() {- return isFramebufferMask(Mix.glMask) ? framebufferProjMatrix : projMatrix;+ return framebufferProjMatrix;}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);+ prevMaskTarget = Renderer._renderer.activeFramebuffer?.() ?? null;+ if (prevMaskTarget?._beforeEnd) prevMaskTarget._beforeEnd();+ gl.bindFramebuffer(gl.FRAMEBUFFER, getFramebufferHandle(Mix.glMask));+ gl.viewport(+ 0,+ 0,+ Mix.glMask.width * Mix.glMask.density,+ Mix.glMask.height * Mix.glMask.density,+ );}function endMaskTarget() {if (beginMaskTarget._hadDepthTest) gl.enable(gl.DEPTH_TEST);beginMaskTarget._hadDepthTest = false;- if (!isFramebufferMask(Mix.glMask)) return;if (prevMaskTarget?._beforeBegin) {prevMaskTarget._beforeBegin();} else {@@ -238,24 +186,6 @@ export function isReady() {needsContextRefresh || loadedWidth !== Cwidth || loadedHeight !== Cheight;if (needsProjectionRefresh) {- projMatrix = new Float32Array([- 2 / Cwidth,- 0,- 0,- 0,- 0,- -2 / Cheight,- 0,- 0,- 0,- 0,- 1,- 0,- -1,- 1,- 0,- 1,- ]);framebufferProjMatrix = new Float32Array([2 / Cwidth,0,diff --git a/test/canvas_upload_benchmark.html b/test/canvas_upload_benchmark.htmldeleted file mode 100644index 718ccb8..0000000--- a/test/canvas_upload_benchmark.html+++ /dev/null@@ -1,414 +0,0 @@-<!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/offscreen_target_test.js b/test/offscreen_target_test.jsindex fa88ae4..4d8efdf 100644--- a/test/offscreen_target_test.js+++ b/test/offscreen_target_test.js@@ -68,6 +68,27 @@ function renderBrushSceneLocal(w, h) {brush.circle(w * 0.74, h * 0.64, Math.min(w, h) * 0.23)}+function renderNativeMarkerLocal(surface, w, h, centeredCoords = true) {+ surface.push()+ if (centeredCoords) {+ surface.translate(-w / 2, -h / 2)+ }+ surface.noStroke()+ surface.fill(BLUE)+ const cx = w * 0.14+ const cy = h * 0.16+ const size = Math.min(w, h) * 0.08+ surface.triangle(+ cx,+ cy - size,+ cx - size * 0.8,+ cy + size * 0.7,+ cx + size * 0.8,+ cy + size * 0.7,+ )+ surface.pop()+}+function renderSceneOnSurface(surface, x, y, w, h) {surface.push()surface.translate(x, y)@@ -126,6 +147,7 @@ function runGraphicsTest() {pg.pixelDensity(targetDensity)pg.angleMode(DEGREES)paintTargetBackground(pg, PANEL_W, TARGET_H)+ renderNativeMarkerLocal(pg, PANEL_W, TARGET_H, true)brush.load(pg)renderSceneOnSurface(pg, -PANEL_W / 2, -TARGET_H / 2, PANEL_W, TARGET_H)@@ -164,6 +186,7 @@ function runMainFramebufferTest() {fb.draw(() => {background(...TARGET_BG)+ renderNativeMarkerLocal(window.self.p5.instance, PANEL_W, TARGET_H, true)brush.load(fb)renderSceneOnSurface(window.self.p5.instance, -PANEL_W / 2, -TARGET_H / 2, PANEL_W, TARGET_H)@@ -287,6 +310,7 @@ function drawReferencePanel(x, y, w, h) {stroke(222, 214, 201)strokeWeight(1)rect(10, 10, w - 20, TARGET_H - 20, 16)+ renderNativeMarkerLocal(window.self.p5.instance, w, TARGET_H, false)renderBrushSceneLocal(w, TARGET_H)pop()}@@ -376,4 +400,4 @@ function draw() {}image(labelBuf, 0, 0)-}\ No newline at end of file+}diff --git a/test/transform_test.html b/test/transform_test.htmlindex d73ee95..b970963 100644--- a/test/transform_test.html+++ b/test/transform_test.html@@ -62,12 +62,15 @@const BLUE = "#1a3a6a";const RED = "#c0392b";const OLIVE = "#4a6a1a";+ const SEED = 12345;// ----------------------------------------------------------------// p5 sketch// ----------------------------------------------------------------function setup() {createCanvas(CW, CH, WEBGL);+ randomSeed(SEED);+ noiseSeed(SEED);brush.load();brush.scaleBrushes(2);noLoop();