Skip to content

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

Better tests

acamposuribe6cb5a2d2d072
diff --git a/dist/brush.esm.js b/dist/brush.esm.js
index 9892871..d858fe8 100644
--- a/dist/brush.esm.js
+++ b/dist/brush.esm.js
@@ -1,2 +1,2 @@
-const t={a:1,b:0,c:0,d:1,x:0,y:0};let e,r,n,i,a=()=>!1,o=t=>t,s=()=>{throw new Error("No runtime color adapter registered.")},c=()=>t,l={load:()=>{throw new Error("No target runtime adapter registered.")},syncDensity:()=>i,isCanvasReady:()=>{throw new Error("No target runtime adapter registered.")},instance:t=>{},activateInstance:t=>{},deactivateInstance:()=>{},getActiveFramebuffer:()=>null,isFramebufferTarget:()=>!1};function u(t){"Cwidth"in t&&(e=t.Cwidth),"Cheight"in t&&(r=t.Cheight),"Instance"in t&&t.Instance,"Renderer"in t&&(n=t.Renderer),"Density"in t&&(i=t.Density)}const h=()=>l.isCanvasReady(),f=t=>l.instance(t),m=()=>l.getActiveFramebuffer(),d=t=>l.isFramebufferTarget(t),x=(t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null,g=(t,e,r=!1)=>{const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,e):(()=>{const r=document.createElement("canvas");return r.width=t,r.height=e,r})();return n.drawingContext=n.getContext("2d",r?{willReadFrequently:!0}:void 0),n};let p={clearTarget:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendShaderProgram:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendSourceFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},createFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},runBlendShaderPass:()=>{throw new Error("No compositor runtime adapter registered.")},blitSourceToFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")}};const y=(...t)=>p.createFramebuffer(...t);let _=null,v=null;const b=t=>{((...t)=>{p.clearTarget(...t)})(n,t,d)},R=()=>({width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(r*i))}),w=t=>{if(!t)return null;const{width:e,height:r}=R();return((t,e,r)=>{if(!t)return null;const 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}})(t,e,r)},E=()=>{const{width:t,height:e}=R();return((t,e)=>({minX:0,minY:0,maxX:t,maxY:e}))(t,e)},A=(t,e=!0)=>{const r=w(t);if(!r)return null;const{height:n}=R();return{x:r.minX,y:e?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},M=(t,e,r,n=!0)=>{const i=A(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()},T={},S=()=>{n?.loaded||(h(),P.load())},P={isBlending:!1,cachedColor:null,markDirtyRect(t,e){const r=w(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){if(!t)return;const e=t===this.glMask?_:v;e?.clearMask?.(t,b)},getCompositeRect(t,e){const r=e?_:v;return r?.getCompositeRect?.(t,m,E,x,w)},load(){l.syncDensity();const t=!n.blendSourceFramebuffer||n.blendSourceFramebuffer.width!==e||n.blendSourceFramebuffer.height!==r||"function"==typeof n.blendSourceFramebuffer.pixelDensity&&n.blendSourceFramebuffer.pixelDensity()!==i;((...t)=>{p.ensureBlendShaderProgram(...t)})(n,"#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.);}"),this.glMask=_?.ensureResources?.(n,e,r,i);const a=v?.ensureResources?.(n,e,r,i,b)??{mask:null,ctx:null};t&&(n.blendSourceFramebuffer=((...t)=>p.ensureBlendSourceFramebuffer(...t))(n,n.blendSourceFramebuffer,e,r,i)),this.mask=a.mask,this.ctx=a.ctx},blend(t=!1,e=!1){S();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,this.clearMask(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,this.cachedColor=null))},applyShader(t,i){if(!t?.isDrawn)return;const a=this.getCompositeRect(t,i);if(!a)return void this.clearMask(t);n.drawingContext;const o=n.shaderProgram,s=m(),c=((...t)=>p.blitSourceToFramebuffer(...t))({renderer:n,sourceTarget:s??n,sourceFramebuffer:n.blendSourceFramebuffer,dirtyRect:a,isFramebufferTarget:d,Cwidth:e,Cheight:r,getTargetPixelSize:R,toScissorBox:A,withScissor:M}),l=!!s,u=(i?_:v).getShaderMask(n,t,a,w,E,b);((...t)=>{p.runBlendShaderPass(...t)})({renderer:n,shader:o,source:c,mask:u,color:this.cachedColor,isBrushMask:i,Cwidth:e,Cheight:r,dirtyRect:a,targetIsFramebuffer:l,withScissor:M}),this.clearMask(t)}},C=()=>{S(),P.blend(!1,!0),P.clearMask(P.glMask),P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null},F=(t=!1)=>{((t=!1)=>{l.load(t)})(t),n.loaded&&P.load()},k=Math.sqrt(3),I=.5*(k-1),L=(3-k)/6,D=t=>0|Math.floor(t),N=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 B(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=>N[t%12*2]),n=new Float64Array(e).map(t=>N[t%12*2+1]);return function(t,i){let a=0,o=0,s=0;const c=(t+i)*I,l=D(t+c),u=D(i+c),h=(l+u)*L,f=t-(l-h),m=i-(u-h);let d,x;f>m?(d=1,x=0):(d=0,x=1);const g=f-d+L,p=m-x+L,y=f-1+2*L,_=m-1+2*L,v=255&l,b=255&u;let R=.5-f*f-m*m;if(R>=0){const t=v+e[b];R*=R,a=R*R*(r[t]*f+n[t]*m)}let w=.5-g*g-p*p;if(w>=0){const t=v+d+e[b+x];w*=w,o=w*w*(r[t]*g+n[t]*p)}let E=.5-y*y-_*_;if(E>=0){const t=v+1+e[b+1];E*=E,s=E*E*(r[t]*y+n[t]*_)}return 70*(a+o+s)}}function U(t,e){let r=new O(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class O{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 Y=U(Math.random()),z=U(Math.random());const X=[],G=t=>X.push(t),Z=t=>{Y=U(t),z=U(`${t}:2`);for(const t of X)t()};let V=B(U(Math.random())),$=B(U(Math.random()));const H=t=>{V=B(U(t)),$=B(U(`${t}:2`))},W=(t=0,e=1)=>t+Y()*(e-t),q=(t=0,e=1)=>t+z()*(e-t),j=t=>t[~~(Y()*t.length)],K=(t,e)=>~~W(t,e),J=(t,e)=>~~q(t,e),Q=(t=0,e=1)=>{const r=1-Y(),n=Y();return Math.sqrt(-2*Math.log(r))*ct(360*n)*e+t},tt=t=>{let e=0;const r=[];for(const n in t)e+=t[n],r.push({key:n,cumulative:e});const n=Y()*e;for(const{key:t,cumulative:e}of r)if(n<e)return isNaN(t)?t:parseInt(t)},et=(t,e,r,n,i,a=!1)=>{let o=n+(t-e)/(r-e)*(i-n);return a?n<i?rt(o,n,i):rt(o,i,n):o},rt=(t,e,r)=>Math.max(Math.min(t,r),e),nt=t=>(t%=360)<0?t+360:t,it=1440,at=2*Math.PI/it,ot=new Float32Array(it).fill(NaN),st=new Float32Array(it).fill(NaN),ct=t=>{const e=~~(4*nt(t));let r=ot[e];return isNaN(r)&&(r=Math.cos(e*at),ot[e]=r),r},lt=t=>{const e=~~(4*nt(t));let r=st[e];return isNaN(r)&&(r=Math.sin(e*at),st[e]=r),r},ut=(t,e=!1)=>{if(e||a()){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},ht=(t,e=!1)=>e||a()?180*t/Math.PI:t,ft=(t,e,r,n,i)=>{let a=ct(i),o=lt(i);return{x:a*(r-t)+o*(n-e)+t,y:a*(n-e)-o*(r-t)+e}},mt=(t,e,r,n)=>Math.hypot(r-t,n-e),dt=(t,e,r,n)=>ut(Math.atan2(-(n-e),r-t),!0),xt=(t,e,r,n,i=!1)=>{let a=t.x,o=t.y,s=e.x,c=e.y,l=r.x,u=r.y,h=n.x,f=n.y;if(a===s&&o===c||l===h&&u===f)return!1;let m=s-a,d=c-o,x=h-l,g=f-u,p=g*m-x*d;if(0===p)return!1;let y=(x*(o-u)-g*(a-l))/p,_=(m*(o-u)-d*(a-l))/p;return!(!i&&(_<0||_>1))&&{x:a+y*m,y:o+y*d}};let gt=!1;function pt(){gt||(S(),_t=.01*e,vt=-.5*e,bt=-.5*r,Rt=Math.round(2*e/_t),wt=Math.round(2*r/_t),Ft("hand",(t,e)=>{const r=q(.2,.8),n=J(5,10);return Lt(e,(e,i)=>.5*n*lt(r*i*e+J(15,25))*.2*ct(t)+$(e,i)*n*.7)}),Ft("curved",(t,e)=>{let r=J(-10,10);return J(0,100)%2==0&&(r*=-1),Lt(e,(e,n)=>3*et($(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),Ft("zigzag",(t,e)=>{let r=J(-30,-15)+Math.abs(44*lt(t));J(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t<Rt;t++){for(let r=0;r<wt;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),Ft("waves",(t,e)=>{const r=J(10,15)+5*lt(t),n=J(3,6)+3*ct(t),i=J(20,35);return Lt(e,(t,e)=>lt(r*t)*i*ct(e*n)+J(-3,3))}),Ft("seabed",(t,e)=>{const r=q(.4,.8),n=J(18,26);return Lt(e,(e,i)=>1.1*n*lt(r*i*e+J(15,20))*ct(t))}),Ft("spiral",(t,e)=>{const r=J(5,10),n=2*J(0,2)-1,i=J(65,80),a=Array.from({length:r},()=>({x:q(.1,.9)*Rt,y:q(.1,.9)*wt}));return Lt(e,(t,e)=>{let r=0,o=0;for(const s of a){const a=t-s.x,c=e-s.y,l=1/(a*a+c*c+1),u=Math.atan2(c,a)*(180/Math.PI),h=n*(u+i)*Math.PI/180;r+=l*Math.cos(h),o+=l*Math.sin(h)}return Math.atan2(o,r)*(180/Math.PI)})}),Ft("columns",(t,e)=>{const r=J(3,8),n=J(25,45);return Lt(e,(t,e)=>lt(t*r)*n)}),gt=!0)}class yt{constructor(t,e){pt();const r=c();this.mx=r.x,this.my=r.y,this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=Math.round((t+this.mx-vt)/_t),this.rowIdx=Math.round((e+this.my-bt)/_t)}reset(){this.plotted=0}isIn(){return T.field.isActive?yt.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,n=r,i=this.x+this.mx,a=this.y+this.my;return i>=-.3*t&&i<=1.3*t&&a>=-.3*n&&a<=1.3*n}angle(t=!1){return T.field.isActive&&(t||this.isIn())?Et.get(T.field.current).field[this.colIdx][this.rowIdx]*T.field.wiggle:0}moveTo(t,e,r=1){this.movePos(ht(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())return void(this.plotted+=r/i);const a=e/r,o=T.field.isActive,s=!!n;for(let e=0;e<a;e++){const e=(o?this.angle(!0):0)-(s?t.angle(this.plotted):t);this.update(this.x+r*ct(e),this.y+r*lt(e)),this.plotted+=r/i}}static getRowIndex(t,e=1){const r=t+c().y-bt;return Math.round(r/_t/e)}static getColIndex(t,e=1){const r=t+c().x-vt;return Math.round(r/_t/e)}static isIn(t,e){return t>=0&&e>=0&&t<Rt&&e<wt}}T.field={isActive:!1,current:null,wiggle:1};let _t,vt,bt,Rt,wt,Et=new Map;const At=new Set(["degrees","radians"]);function Mt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!At.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function Tt(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]=ht(t[e][r],!0);return t}(t.gen(e,new Array(Rt).fill(null).map(()=>new Float32Array(wt))),t.angleMode)}function St(t=0){if(!T.field.isActive||!T.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=Et.get(T.field.current);e.field=Tt(e,t)}function Pt(t){if(T.field.wiggle||(T.field.wiggle=1),pt(),!Et.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(Et.keys()).join(", ")}.`);T.field.isActive=!0,T.field.current=t;const e=Et.get(t);e.field||(e.field=Tt(e,0))}function Ct(){pt(),T.field.isActive=!1}function Ft(t,e,r={}){Et.set(t,{gen:e,field:null,angleMode:Mt(r)})}function kt(){return pt(),Array.from(Et.keys())}function It(t=1){Pt("hand"),T.field.wiggle=t}function Lt(t,e){for(let r=0;r<Rt;r++)for(let n=0;n<wt;n++)t[r][n]=e(r,n);return t}const Dt=[],Nt=(t,e,r)=>Math.max(e,Math.min(t,r)),Bt="degrees",Ut="radians";let Ot=null,Yt=Bt;const zt=[];let Xt={a:1,b:0,c:0,d:1,x:0,y:0};function Gt(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,x:t.a*e.x+t.c*e.y+t.x,y:t.b*e.x+t.d*e.y+t.y}}class Zt{constructor(t,e,r){if(t?._array)return this.r=Math.round(255*t._array[0]),this.g=Math.round(255*t._array[1]),this.b=Math.round(255*t._array[2]),this.hex=this.rgbToHex(this.r,this.g,this.b),this._array=[...t._array],void(this.gl=this._array);if("string"==typeof t){this.hex=this.standardize(t);const e=this.hexToRgb(this.hex);this.r=e.r,this.g=e.g,this.b=e.b}else this.r=Nt(t??0,0,255),this.g=Nt(e??t??0,0,255),this.b=Nt(r??t??0,0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);this._array=[this.r/255,this.g/255,this.b/255,1],this.gl=this._array}rgbToHex(t,e,r){return`#${(1<<24|t<<16|e<<8|r).toString(16).slice(1)}`}hexToRgb(t){t=t.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(t,e,r,n)=>e+e+r+r+n+n);const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(!e)throw new Error(`Invalid color value "${t}".`);return{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}}standardize(t){const e=function(){if(Ot)return Ot;if("undefined"!=typeof document)return Ot=document.createElement("canvas").getContext("2d"),Ot;if("undefined"!=typeof OffscreenCanvas)return Ot=new OffscreenCanvas(1,1).getContext("2d"),Ot;throw new Error("Standalone color parsing requires CanvasRenderingContext2D support.")}();return e.fillStyle=t,e.fillStyle}_getRed(){return this.r}_getGreen(){return this.g}_getBlue(){return this.b}}function Vt(t){if(t!==Bt&&t!==Ut)throw new Error(`Invalid angle mode "${t}". Use "degrees" or "radians".`);Yt=t}function $t(){return Yt}function Ht(){pt(),Dt.push({fill:{...T.fill},wash:T.wash?{...T.wash}:null,stroke:{...T.stroke},hatch:{...T.hatch},mass:T.mass?{...T.mass}:null,field:{...T.field}}),zt.push({...Xt})}function Wt(){0!==zt.length&&(Xt=zt.pop(),function(){const t=Dt.pop();t&&(T.stroke={...t.stroke},T.field={...t.field},T.hatch={...t.hatch},T.fill={...t.fill},t.wash&&(T.wash={...t.wash}),t.mass?T.mass={...t.mass}:T.mass&&(T.mass={...T.mass,isActive:!1,brush:null,color:null,options:{}}))}())}function qt(t,e){Xt=Gt(Xt,{a:1,b:0,c:0,d:1,x:t,y:e})}function jt(t){const e=Yt===Ut?t:t*Math.PI/180,r=Math.cos(e),n=Math.sin(e);Xt=Gt(Xt,{a:r,b:n,c:-n,d:r,x:0,y:0})}function Kt(t,e=t){Xt=Gt(Xt,{a:t,b:0,c:0,d:e,x:0,y:0})}function Jt(){var t;(t={usesRadians:()=>"radians"===Yt,fromDegrees:t=>"radians"===Yt?t*Math.PI/180:t,createColor:(...t)=>1===t.length&&t[0]?._array?t[0]:new Zt(...t),getAffineMatrix:()=>Xt}).usesRadians&&(a=t.usesRadians),t.fromDegrees&&(o=t.fromDegrees),t.createColor&&(s=t.createColor),t.getAffineMatrix&&(c=t.getAffineMatrix)}function Qt(){C()}function te(...t){h(),P.glMask&&P.clearMask(P.glMask),P.mask&&P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null;const e=n.drawingContext,r=0===t.length?[1,1,1,0]:[...s(...t)._array.slice(0,3),1];e.bindFramebuffer(e.FRAMEBUFFER,null),e.disable(e.SCISSOR_TEST),e.clearColor(r[0],r[1],r[2],r[3]),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}let ee,re,ne,ie,ae=null,oe=!1,se=1,ce=0,le=0;function ue(t,e,r,n){ae=t,ce=e,le=r,se=n;const i=function(t,e,r,n){const i=function(t){return t.getContext("webgl2",{premultipliedAlpha:!0})??t.getContext("webgl2")}(t);if(!i)throw new Error("brush.load(target) requires a canvas with a WebGL2 context.");return{canvas:t,drawingContext:i,width:e,height:r,pixelDensity:()=>n}}(t,e,r,n);u({Renderer:i,Cwidth:e,Cheight:r,Density:n}),oe=!0}function he(t,e,r={}){if("undefined"==typeof document)throw new Error("brush.createCanvas() requires a browser document.");const n=Math.max(1,Math.round(t)),i=Math.max(1,Math.round(e)),a=Math.max(1,Number(r.pixelDensity)||1),o=document.createElement("canvas");if(o.width=Math.max(1,Math.round(n*a)),o.height=Math.max(1,Math.round(i*a)),o.style.width=`${n}px`,o.style.height=`${i}px`,r.id&&(o.id=r.id),r.parent){const t="string"==typeof r.parent?document.querySelector(r.parent):r.parent;if(!t)throw new Error(`Could not find parent "${r.parent}" for brush.createCanvas().`);t.appendChild(o)}return ue(o,n,i,a),o}class fe{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=xt(t.point1,t.point2,e,n);i&&r.push(i)}return this._intersectionCache[e]=r,r}show(){T.wash&&this.wash(),T.fill&&this.fill(),T.mass&&this.mass(),T.hatch&&this.hatch(),T.stroke&&this.draw()}}class me{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:ut(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:ut(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=ut(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)),et(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,a){pt();const o=a<0?4:1,s=[],c=Math.round(this.length/o),l=new yt(t+e/2,n+r/2);let u=0,h=0;for(let t=0;t<c;t++){l.plotTo(this,o,o);const t=this.calcIndex(l.plotted);u+=o,(u>=(a<=0?8:Math.max(this.segments[t]*a*q(.7,1.3),20))||t>=h)&&l.x&&(s.push([l.x-e/2,l.y-r/2]),u=0,t>=h&&h++)}return new fe(s)}show(t,e,r=1){T.wash&&this.wash(t,e,r),T.fill&&this.fill(t,e,r),T.mass&&this.mass(t,e,r),T.hatch&&this.hatch(t,e,r),T.stroke&&this.draw(t,e,r)}}function de(t){new fe(t).show()}function xe(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),_e(0),ve(t,e),ve(t+r,e),ve(t+r,e+n),ve(t,e+n),be(!0)}function ge(t,e,r,n=!1){const i=new me("curve"),a=Math.PI*r,o=q(0,360),s=n?()=>1+.2*n*q():()=>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*J(-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 c=t-r*lt(o),l=e-r*ct(-o);i.show(c,l,1)}function pe(t,e,r,n,i){const a=ht(n),o=((ht(i)-a)%360+360)%360;if(0===o)return;const s=new me("curve"),c=Math.max(1,Math.ceil(o/90)),l=o/c,u=Math.PI*r*l/180;for(let t=0;t<c;t++)s.addSegment(a+t*l+90,u,1,!0);s.endPlot(a+o+90,1,!0);const h=t+r*ct(a),f=e-r*lt(a);s.draw(h,f,1)}class ye{constructor(){this.isClosed=!1,this.curvature=re,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){Me(this.vert,this.curvature,this.isClosed).show()}}function _e(t=0){re=rt(t,0,1),ee=new ye}function ve(t,e,r=1){if(!ee)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");ee.vertex(t,e,r)}function be(t=!1){if(!ee)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(ee.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(ee.vertex(...ee.vert[0]),ee.isClosed=!0),ee.show(),ee=!1}function Re(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);ie=[e,r],ne=new me(t)}function we(t,e,r){if(!ne)throw new Error("move() called without beginStroke(). Call beginStroke() first.");ne.addSegment(t,e,r)}function Ee(t,e){if(!ne)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");ne.endPlot(t,e),ne.draw(ie[0],ie[1],1),ne=!1}function Ae(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");Me(t,e).draw()}function Me(t,e=.5,r=!1){const n=new me(0===e?"segments":"curve"),i=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let a,o,s,c=0;for(let l=0;l<t.length-1;l++)if(e>0&&l<t.length-2){const u=t[l],h=t[l+1],f=t[l+2],m=mt(u[0],u[1],h[0],h[1]),d=mt(h[0],h[1],f[0],f[1]),x=dt(u[0],u[1],h[0],h[1]),g=dt(h[0],h[1],f[0],f[1]),p=e*Math.min(m,d,.5*Math.min(m,d)),y=Math.max(m,d),_=m-p,v=d-p;if(Math.floor(x)===Math.floor(g)){const e=r&&0===l?0:m-c,i=r?0===l?0:d-s:d;n.addSegment(x,e,u[2],!0),l===t.length-3&&n.addSegment(g,i,h[2],!0),c=0,0===l&&(a=m,s=p,o=t[1],c=0)}else{const e={x:h[0]-p*ct(-x),y:h[1]-p*lt(-x)},f={x:e.x+y*ct(90-x),y:e.y+y*lt(90-x)},m={x:h[0]+p*ct(-g),y:h[1]+p*lt(-g)},d={x:m.x+y*ct(90-g),y:m.y+y*lt(90-g)},b=xt(e,f,m,d,!0),R=mt(e.x,e.y,b.x,b.y),w=mt(e.x,e.y,m.x,m.y)/2,E=i*R*(2*Math.asin(w/R)*(180/Math.PI))/360,A=r&&0===l?0:_-c,M=l===t.length-3?r?a-p:v:0;n.addSegment(x,A,u[2],!0),n.addSegment(x,isNaN(E)?0:E,u[2],!0),n.addSegment(g,M,h[2],!0),c=p,0===l&&(a=_,s=p,o=[e.x,e.y])}l===t.length-3&&n.endPlot(g,h[2],!0)}else if(0===e){const e=t[l],r=t[l+1],i=mt(e[0],e[1],r[0],r[1]),a=dt(e[0],e[1],r[0],r[1]);n.addSegment(a,i,r[2],!0),l===t.length-2&&n.endPlot(a,1,!0)}n.origin=r&&0!==e?o:t[0]}return n}let Te={createTipSurface:()=>{throw new Error("No stroke runtime adapter registered.")},loadImageTip:()=>{throw new Error("No stroke runtime adapter registered.")}},Se=!1;const Pe=(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 Ce={beginDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},endDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},resetDirectShaderTracking:()=>{}};const Fe=(t,e)=>Ce.resetDirectShaderTracking(t,e);let ke,Ie,Le,De,Ne,Be=!1,Ue=0,Oe=0,Ye=null;const ze={},Xe={};let Ge=1,Ze=0,Ve=0,$e=1,He=0,We=0,qe=0,je=0,Ke=1,Je=1,Qe=new Float32Array(8192),tr=0,er=2048,rr=32768,nr=null,ir=null,ar=null,or=null,sr=null;const cr={},lr={};let ur=0,hr=new Float32Array(1280),fr=0,mr=256,dr=null;const xr=new Map,gr=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function pr(){return Ie}function yr(){return((t,e,r)=>Ce.beginDirectMaskDraw(t,e,r))(n,ke,P.glMask)}function _r(t){((t,e,r)=>{Ce.endDirectMaskDraw(t,e,r)})(n,ke,t)}function vr(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 br(t,e,r,n){if(tr>=er){er*=2;const t=new Float32Array(4*er);t.set(Qe),Qe=t}const i=t-qe,a=e-je,o=4*tr,s=Ge*i+Ve*a+He+qe,c=Ze*i+$e*a+We+je,l=Je*r*Ke/2;Qe[o]=s,Qe[o+1]=c,Qe[o+2]=l,Qe[o+3]=n/255;const u=s*Je,h=c*Je;nr=vr(nr,u-l-1,h-l-1,u+l+1,h+l+1),tr++}function Rr(t,e){if(0===fr)return;P.glMask.isDrawn=!0;const r=yr();let i=xr.get(e);i||(i=ke.createTexture(),ke.bindTexture(ke.TEXTURE_2D,i),ke.texImage2D(ke.TEXTURE_2D,0,ke.RGBA,ke.RGBA,ke.UNSIGNED_BYTE,t.canvas),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_MIN_FILTER,ke.LINEAR),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_MAG_FILTER,ke.LINEAR),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_WRAP_S,ke.CLAMP_TO_EDGE),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_WRAP_T,ke.CLAMP_TO_EDGE),xr.set(e,i)),ke.useProgram(ir),ke.enable(ke.BLEND),ke.blendFunc(ke.ONE_MINUS_DST_ALPHA,ke.ONE),ke.activeTexture(ke.TEXTURE0),ke.bindTexture(ke.TEXTURE_2D,i),ke.uniform1i(lr.u_tex,0);const a=T.stroke.color._array;ke.uniform4f(lr.u_color,...a),ke.uniformMatrix4fv(lr.u_proj,!1,pr()),ke.bindVertexArray(ar),ke.bindBuffer(ke.ARRAY_BUFFER,sr);const o=5*fr*4,s=hr.subarray(0,5*fr);o>ur?(ke.bufferData(ke.ARRAY_BUFFER,hr,ke.DYNAMIC_DRAW),ur=hr.byteLength):ke.bufferSubData(ke.ARRAY_BUFFER,0,s),ke.drawArraysInstanced(ke.TRIANGLE_STRIP,0,4,fr),ke.flush(),ke.bindVertexArray(null),ke.bindTexture(ke.TEXTURE_2D,null),_r(r),dr&&(P.markDirtyRect(P.glMask,dr),dr=null),fr=0,Fe(n,ke)}Se||(_={ensureResources:function(t,e,r,n){return function(t,e,r,n){return!t.glMask||t.glMask.width!==e||t.glMask.height!==r||"function"==typeof t.glMask.pixelDensity&&t.glMask.pixelDensity()!==n}(t,e,r,n)&&(t.glMask?.remove&&t.glMask.remove(),t.glMask=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1})),t.glMask.dirtyRect??=null,t.glMask.isDrawn??=!1,t.glMask},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?e()?r():i(n(t.dirtyRect,2)):r():null},getShaderMask:function(t,e){return e}},Se=!0),T.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let wr=new Map;const Er={offset:.08,scale:.08,warp:.06,tilt:.06};function Ar(){return{...T.stroke}}function Mr(t){T.stroke={...t}}function Tr(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0===e.markerTip&&(e.markerTip=!0),void 0===e.noise&&(e.noise=.3),e.noise=Math.max(0,Math.min(1,e.noise)),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:{...Er}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...Er,...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,c,l]=[(e-i)/o,(r-i)/o,(n-i)/o];return{type:"custom",min_max:[i,a],variation:{...Er},curve:t=>t<.5?s+(c-s)*t*2:c+(l-c)*(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=xr.get(t);e&&ke&&ke.deleteTexture(e),xr.delete(t)}(r);const n=Te.createTipSurface(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(),rn.imageToWhite(n),rn.tips.set(r,n),e.tipKey=r,void wr.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 rn.add(e.image.src),wr.set(t,{param:e,colors:[],buffers:[]}),rn.load()}wr.set(t,{param:e,colors:[],buffers:[]})}function Sr(){return[...wr.keys()]}function Pr(t){return wr.get(t)?.param??null}function Cr(t){for(const{param:e}of wr.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function Fr(t){if(!wr.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...wr.keys()].join(", ")}.`);T.stroke.type=t}function kr(t,e,r){h(),T.stroke.color=s(...arguments),T.stroke.isActive=!0}function Ir(t){T.stroke.weight=t}function Lr(t,e,r=1){Fr(t),kr(e),Ir(r)}function Dr(){T.stroke.isActive=!1}function Nr(t){return h(),t}function Br(){}let Ur,Or,Yr,zr;const Xr={};function Gr(t,n,a,o=!1){!function(){const t=c();Ge=t.a,Ze=t.b,Ve=t.c,$e=t.d,He=t.x,We=t.y,qe=e/2,je=r/2,Ke=Math.sqrt(Ge*Ge+Ze*Ze),Je=i}(),Ur=new yt(t+e/2,n+r/2),Or=a,Yr=o,Yr&&Yr.calcIndex(0)}const Zr=[];function Vr(t,i){i||(zr=t),function(){Xr.seed=999999*W();const{param:t}=wr.get(T.stroke.type)??{};if(!t)return;Xr.p=t;const{pressure:i}=t;if(Xr.a="custom"!==i.type?W(-1,1):0,Xr.b="custom"!==i.type?W(1,1.5):0,"custom"!==i.type)Xr.cp=W(3,3.5),Xr.ct=0,Xr.cs=1,Xr.ck=0;else{const t=i.variation??Er;Xr.cp=W(-t.offset,t.offset),Xr.ct=W(-t.warp,t.warp),Xr.cs=W(1-t.scale,1+t.scale),Xr.ck=W(-t.tilt,t.tilt)}[Xr.min,Xr.max]=i.min_max,Xr.noiseoffset=.05*Xr.p.noise,Yr||(Xr.cos=ct(zr),Xr.sin=lt(zr)),function(){S(),function(){const t=n?.glMask;t&&(Ye=t,Ye.dirtyRect??=null,Ye.isDrawn??=!1,P.glMask=Ye)}();const t=n.drawingContext,i=!Be||ke!==t;(i||Ue!==e||Oe!==r)&&(Ie=new Float32Array([2/e,0,0,0,0,2/r,0,0,0,0,1,0,-1,-1,0,1]),Ue=e,Oe=r),i&&(ke=t,Ne=Pe(ke,"#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);}"),ke.useProgram(Ne),ke.enable(ke.BLEND),ke.blendFunc(ke.ONE_MINUS_DST_ALPHA,ke.ONE),["a_position","a_radius","a_alpha"].forEach(t=>ze[t]=ke.getAttribLocation(Ne,t)),["u_matrix","u_color"].forEach(t=>Xe[t]=ke.getUniformLocation(Ne,t)),Le=ke.createVertexArray(),ke.bindVertexArray(Le),De=ke.createBuffer(),ke.bindBuffer(ke.ARRAY_BUFFER,De),ke.bufferData(ke.ARRAY_BUFFER,Qe.byteLength,ke.DYNAMIC_DRAW),rr=Qe.byteLength,ke.enableVertexAttribArray(ze.a_position),ke.vertexAttribPointer(ze.a_position,2,ke.FLOAT,!1,16,0),ke.enableVertexAttribArray(ze.a_radius),ke.vertexAttribPointer(ze.a_radius,1,ke.FLOAT,!1,16,8),ke.enableVertexAttribArray(ze.a_alpha),ke.vertexAttribPointer(ze.a_alpha,1,ke.FLOAT,!1,16,12),ke.bindVertexArray(null),xr.clear(),ir=Pe(ke,"#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=>cr[t]=ke.getAttribLocation(ir,t)),["u_proj","u_color","u_tex"].forEach(t=>lr[t]=ke.getUniformLocation(ir,t)),ar=ke.createVertexArray(),ke.bindVertexArray(ar),or=ke.createBuffer(),ke.bindBuffer(ke.ARRAY_BUFFER,or),ke.bufferData(ke.ARRAY_BUFFER,gr,ke.STATIC_DRAW),ke.enableVertexAttribArray(cr.a_corner),ke.vertexAttribPointer(cr.a_corner,2,ke.FLOAT,!1,0,0),sr=ke.createBuffer(),ke.bindBuffer(ke.ARRAY_BUFFER,sr),ke.bufferData(ke.ARRAY_BUFFER,hr.byteLength,ke.DYNAMIC_DRAW),ur=hr.byteLength,ke.enableVertexAttribArray(cr.a_pos),ke.vertexAttribPointer(cr.a_pos,2,ke.FLOAT,!1,20,0),ke.vertexAttribDivisor(cr.a_pos,1),ke.enableVertexAttribArray(cr.a_size),ke.vertexAttribPointer(cr.a_size,1,ke.FLOAT,!1,20,8),ke.vertexAttribDivisor(cr.a_size,1),ke.enableVertexAttribArray(cr.a_angle),ke.vertexAttribPointer(cr.a_angle,1,ke.FLOAT,!1,20,12),ke.vertexAttribDivisor(cr.a_angle,1),ke.enableVertexAttribArray(cr.a_alpha),ke.vertexAttribPointer(cr.a_alpha,1,ke.FLOAT,!1,20,16),ke.vertexAttribDivisor(cr.a_alpha,1),ke.bindVertexArray(null),Be=!0)}();const a=!0!==P.isBrush;P.isBrush=!0,a&&(P.justChanged=!0),P.blend(T.stroke.color),Xr.alpha=["default","spray"].includes(Xr.p.type)?Xr.p.opacity:Xr.p.opacity/Math.min(T.stroke.weight,1.3),Kr()}();const a=function(){const{param:t}=wr.get(T.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(Or*(i?t:1)/a);Xr.pressureCount=10,Xr.cachedPressure=void 0,Xr.lineNoiseCount=5,Xr.cachedLineNoise=void 0;for(let e=0;e<o;e++)Zr.length<2*o&&Zr.push(Q()),$r(),i?Ur.plotTo(Yr,a,a,t,e<10):Ur._moveToDegrees(t,a,a);!function(){Kr(),function(){if(0===tr)return;P.glMask.isDrawn=!0;const t=yr(),e=T.stroke.color._array;ke.useProgram(Ne),ke.enable(ke.BLEND),ke.blendFunc(ke.ONE_MINUS_DST_ALPHA,ke.ONE),ke.bindVertexArray(Le),ke.bindBuffer(ke.ARRAY_BUFFER,De);const r=16*tr,i=Qe.subarray(0,4*tr);r>rr?(ke.bufferData(ke.ARRAY_BUFFER,Qe,ke.DYNAMIC_DRAW),rr=Qe.byteLength):ke.bufferSubData(ke.ARRAY_BUFFER,0,i),ke.uniform4f(Xe.u_color,...e),ke.uniformMatrix4fv(Xe.u_matrix,!1,pr()),ke.drawArrays(ke.POINTS,0,tr),ke.flush(),ke.bindVertexArray(null),_r(t),nr&&(P.markDirtyRect(P.glMask,nr),nr=null),tr=0,Fe(n,ke)}();const t=Xr.p?.type;"image"===t?Rr(rn.tips.get(Xr.p.image.src),Xr.p.image.src):"custom"===t&&Rr(rn.tips.get(Xr.p.tipKey),Xr.p.tipKey)}()}function $r(){const t=Hr(),e=((Xr.lineNoiseCount>=10||void 0===Xr.cachedLineNoise)&&(Xr.cachedLineNoise=et(V(Xr.seed+.01*Ur.plotted,0),-1,1,1-Xr.noiseoffset,1+Xr.noiseoffset),Xr.lineNoiseCount=0),Xr.lineNoiseCount++,Xr.cachedLineNoise);if(!(e>W(1,1.02)&&W(0,1)<.7))switch(Xr.p.type){case"spray":!function(t){const e=T.stroke.weight*Xr.p.scatter*t+T.stroke.weight*j(Zr)*Xr.p.scatter/3,r=Xr.p.weight*W(.9,1.1),n=Math.ceil(Xr.p.grain/t);for(let t=0;t<n;t++){const t=W(.9,1.1),n=t*e*W(-1,1),i=W(-1,1),a=Math.sqrt((t*e)**2-n**2);br(Ur.x+n,Ur.y+i*a,r,Xr.alpha)}}(t*e);break;case"marker":qr(t*e);break;case"custom":case"image":jr(t*e);break;default:!function(t,e=1){const r=(e=et(e,0,1,.9,1.05))*T.stroke.weight*Xr.p.scatter*(Xr.p.sharpness+(1-Xr.p.sharpness)*j(Zr)/t);if(W(0,Xr.p.grain*t)>.4){let e,n;if(Yr){const t=Yr.angle(Ur.plotted),i=ct(t),a=lt(t),o=r*W(-1,1),s=.3*r*W(-1,1);e=o*a+s*i,n=o*i-s*a}else{const t=r*W(-1,1),i=.3*r*W(-1,1);e=t*Xr.sin+i*Xr.cos,n=t*Xr.cos-i*Xr.sin}const i=t*t*Xr.p.weight*W(.85,1.15)*T.stroke.weight,a=Math.max(.9,t)*Xr.alpha*W(.75,1.1);br(Ur.x+e,Ur.y+n,i,a)}}(t*e)}}function Hr(){return(Xr.pressureCount>=10||void 0===Xr.cachedPressure)&&(Xr.cachedPressure=Yr?Wr()*Yr.pressure(Ur.plotted):Wr(),Xr.pressureCount=0),Xr.pressureCount++,Xr.cachedPressure}function Wr(){return"custom"===Xr.p.pressure.type?et(Xr.p.pressure.curve(Math.max(0,Math.min(1,.5+(Ur.plotted/Or-.5+Xr.ct)*Xr.cs)))+Xr.cp+Xr.ck*(Ur.plotted/Or-.5),0,1,Xr.min,Xr.max,!0):function(t=.5+Xr.p.pressure.curve[0]*Xr.a,e=1-Xr.p.pressure.curve[1]*Xr.b,r=Xr.cp,n=Xr.min,i=Xr.max){const a=t*Or,o=(Ur.plotted<a?1.2*e:.8*e)*(Or/2);return et(1/(1+Math.pow(Math.abs((Ur.plotted-a)/o),2*r)),0,1,n,i)}()}function qr(t,e=!0,r=Xr.alpha){const n=e?T.stroke.weight*Xr.p.scatter:0,i=e?n*W(-1,1):0,a=e?n*W(-1,1):0;br(Ur.x+i,Ur.y+a,T.stroke.weight*Xr.p.weight*t,r*Math.max(.8,t)*W(.9,1.1))}function jr(t,e=Xr.alpha){const r=T.stroke.weight*Xr.p.scatter,n=r*W(-1,1),i=r*W(-1,1),a=Xr.p.weight*T.stroke.weight*t,o=function(){const t=Math.max(1,Xr.max??1),e=T.stroke.weight*Xr.p.scatter,r=T.stroke.weight*Xr.p.weight*t;return Math.max(8,1.5*e+.75*r)}();let s=0;"random"===Xr.p.rotate?s=K(0,360)*(Math.PI/180):"natural"===Xr.p.rotate&&(s=((Yr?-Yr.angle(Ur.plotted):-zr)+Ur.angle())*(Math.PI/180)),function(t,e,r,n,i,a=0){if(fr>=mr){mr*=2;const t=new Float32Array(5*mr);t.set(hr),hr=t}const o=t-qe,s=e-je,c=Ge*o+Ve*s+He+qe,l=Ze*o+$e*s+We+je,u=Je*r*Ke/2,h=Je*a*Ke,f=5*fr;hr[f]=c,hr[f+1]=l,hr[f+2]=u,hr[f+3]=n,hr[f+4]=i/255;const m=c*Je,d=l*Je,x=1.42*u+h;dr=vr(dr,m-x-1,d-x-1,m+x+1,d+x+1),fr++}(Ur.x+n,Ur.y+i,a,s,e*Math.max(.8,t)*W(.9,1.1),o)}function Kr(){if(!1===Xr.p.markerTip)return;let t=Hr(),e=Xr.alpha;if("marker"===Xr.p.type)for(let r=1;r<10;r++)qr(t*r/10,!0,8*e);else if("custom"===Xr.p.type||"image"===Xr.p.type)for(let r=1;r<5;r++)jr(t*r/10,2*e)}function Jr(t,e,r,n){if(!T.stroke.isActive||!T.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");pt();let i=mt(t,e,r,n);0!=i&&(Gr(t,e,i),Vr(dt(t,e,r,n),!1))}function Qr(t,e,r,n){if(!T.stroke.isActive||!T.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");pt(),Gr(t,e,r),Vr(ut(n),!1)}G(()=>{Zr.length=0});const tn=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],en=[["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]}]],["pastel",[2.05/3,13.4/3,.91,28,35,.085/3,{mode:"gaussian",curve:[.4,.05],min_max:[1.09,.93]},"default",void 0,"natural",!0,1]],["crayon",[.3,5.45/3,.75,250,159,.23/3,[1.1,.9],"default",void 0,"natural",!0,1]],["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 en){let e={};for(let r=0;r<t[1].length;r++)e[tn[r]]=t[1][r];Tr(t[0],e)}fe.prototype.draw=function(t=!1,e,r){let n=Ar();if(t&&Lr(t,e,r),n.isActive)for(let t of this.sides)Jr(t[0].x,t[0].y,t[1].x,t[1].y);Mr(n)},me.prototype.draw=function(t,e,r){Ar().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,n){pt(),Gr(e,r,t.length,t),Vr(n,!0)}(this,t,e,r))};const rn={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=>((t,e)=>Te.loadImageTip(t,e))(t,rn.imageToWhite).then(e=>{this.tips.set(t,e)})))}};function nn(){return{...T.hatch}}function an(t){T.hatch={...t}}function on(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=T.hatch;n.isActive=!0,n.dist=t,n.angle=ht(e),n.options=r}function sn(t,e="black",r=1){T.hatch.hBrush={brush:t,color:e,weight:r}}function cn(){T.hatch.isActive=!1,T.hatch.hBrush=!1}function ln(t,e,r,n){const i=e*Math.PI/180,a=Math.cos(i),o=Math.sin(i),s=Math.cos(-i),c=Math.sin(-i),l=t.a,u=l.length,h=new Array(u);let f=Infinity,m=-Infinity;for(let t=0;t<u;t++){const e=l[t][0],r=l[t][1],n=[e*a-r*o,e*o+r*a];h[t]=n,n[1]<f&&(f=n[1]),n[1]>m&&(m=n[1])}const d=[];for(let t=0;t<u;t++){const e=h[t],r=h[(t+1)%u];e[1]!==r[1]&&d.push(e,r)}const x=d.length,g=[];let p=f+.5*r,y=r;for(;p<m;){const t=[];for(let e=0;e<x;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)g.push({scanY:p,x1:t[e]*s-p*c,y1:t[e]*c+p*s,x2:t[e+1]*s-p*c,y2:t[e+1]*c+p*s});p+=y,y*=n}return g}function un(t){const{dist:e,options:r,segs:n}=function(t){const e=T.hatch.dist,r=(T.hatch.angle%180+180)%180,n=T.hatch.options,i=function(t,e,r,n){Array.isArray(t)||(t=[t]);const i=[];for(const a of t)for(const t of ln(a,r,e,n))i.push(t);return i.sort((t,e)=>t.scanY===e.scanY?t.x1-e.x1:t.scanY-e.scanY),i}(t,e,r,n.gradient?et(n.gradient,0,1,1,1.1,!0):1);return{dist:e,options:n,segs:i}}(t),i=r.rand||0,a=[];for(let t=0;t<n.length;t++){const o=n[t];let s=o.x1,c=o.y1,l=o.x2,u=o.y2;i&&(s+=2*i*e*W(-1,1),c+=2*i*e*W(-1,1),l+=2*i*e*W(-1,1),u+=2*i*e*W(-1,1));const h=r.continuous&&t%2==1?{x1:l,y1:u,x2:s,y2:c,scanY:o.scanY,isConnector:!1}:{x1:s,y1:c,x2:l,y2:u,scanY:o.scanY,isConnector:!1};if(a.push(h),t>0&&r.continuous){const t=a[a.length-2];a.push({x1:t.x2,y1:t.y2,x2:h.x1,y2:h.y1,scanY:o.scanY,isConnector:!0})}}return a}function hn(t){!function(t,e){const r=un(t);!function(){const t=Ar();T.hatch.hBrush&&Lr(...Object.values(T.hatch.hBrush)),(()=>{for(let t=0;t<r.length;t++){const n=r[t];e(n.x1,n.y1,n.x2,n.y2,t,r)}})(),Mr(t)}()}(t,(t,e,r,n)=>{Jr(t,e,r,n)})}function fn(t,e,r={}){T.mass.brush=t,T.mass.color=e,T.mass.options=r,T.mass.isActive=!0}function mn(){T.mass.isActive=!1,T.mass.brush=null,T.mass.color=null,T.mass.options={}}function dn(t,e,r){return new fe(t.vertices.map(t=>[t.x+e,t.y+r]))}function xn(t,e,r,n,i){const a=(e+n)/2,o=(r+i)/2,s=n-e,c=i-r,l=Math.hypot(s,c);if(!l)return null;const u=-c/l,h=s/l,f=(t.x-a)*u+(t.y-o)*h;return{x:a+u*f,y:o+h*f}}function gn(t,e,r,n,i,a,o){let s=dt(t,e,r,n),c=dt(t,e,i,a);return((c-s)%360+360)%360>180&&([s,c]=[c,s]),[o(s),o(c)]}function pn(t){const e=q(.35,.65),r=t.x1+(t.x2-t.x1)*e,n=t.y1+(t.y2-t.y1)*e,i=t.x2-t.x1,a=t.y2-t.y1,o=Math.hypot(i,a)||1,s=q(.04,.1)*o,c=i/o*s*.5,l=a/o*s*.5;return[{x1:t.x1,y1:t.y1,x2:r-c,y2:n-l},{x1:r+c,y1:n+l,x2:t.x2,y2:t.y2}]}function yn(t,e,r){const n=function(t,e){const r=function(t){const e=t?.a??[];let r=Infinity,n=Infinity,i=-Infinity,a=-Infinity;for(const[t,o]of e)t<r&&(r=t),o<n&&(n=o),t>i&&(i=t),o>a&&(a=o);return{minX:r,minY:n,maxX:i,maxY:a,cx:(r+i)/2,cy:(n+a)/2,size:Math.hypot(i-r,a-n)}}(t),n=r.size*q(.6,1.4),[i,a]=e;return{x:r.cx+i*n,y:r.cy+a*n}}(t,e);for(const e of un(t)){const t=!e.isConnector&&q()<.35?pn(e):[e];for(const e of t){const t=xn(n,e.x1,e.y1,e.x2,e.y2);if(!t)continue;const i=mt(t.x,t.y,e.x1,e.y1);if(!i)continue;const[a,o]=gn(t.x,t.y,e.x1,e.y1,e.x2,e.y2,r);pe(t.x,t.y,i,a,o)}}}function _n(t,e,r,n,i,a){on(e,r,n),yn(t,i,a)}function vn(t,e,r,n){const i=function(t,e,r,n){const i=!1===e,a=Pr(T.mass.brush)?.scatter??0,o=i?t:t.genPol(e,r,n,.15),s=Math.min(2*a,5),c=[[q(-s,s),q(-s,s)],[q(-s,s),q(-s,s)]];return[o,dn(o,c[0][0],c[0][1]),dn(o,c[1][0],c[1][1])]}(t,e,r,n),s=nn(),c=Ar(),l={...T.field},u=T.mass.options?.precision??.5,h=T.mass.options?.strength??1,f=T.mass.options?.gradient??.1,m=T.mass.options?.outline??!1,d=Pr(T.mass.brush)?.scatter??0,x=1.6*q(.65*d,.85*d)-.4*f,g=q(-90,90),p=((g+90)%180+180)%180-90>=0?q()<.5?[1,1]:[-1,-1]:q()<.5?[-1,1]:[1,-1],y=a()?t=>t*Math.PI/180:t=>t;Lr(T.mass.brush,T.mass.color,1),It(2-u),m&&i[0].draw(),_n(i[0],.9*x,o(g),{gradient:f,rand:2-2*u,continuous:!0},p,y),h>.33&&_n(i[1],x,o(g+20*q(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),h>.66&&_n(i[2],.8*x,o(g+15*q(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),Mr(c),an(s),T.field={...l}}function bn(t,e,r){const n=2*Math.PI,i=P.ctx,a=r/2;i.moveTo(t+a,e),i.arc(t,e,a,0,n)}T.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},fe.prototype.hatch=function(t=!1,e,r){let n=nn();t&&on(t,e,r),T.hatch.isActive&&hn(this),an(n)},me.prototype.hatch=function(t,e,r){nn().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.3),this.pol.hatch())},T.mass={isActive:!1,brush:null,color:null,options:{}},fe.prototype.mass=function(){T.mass?.isActive&&vn(this,!1)},me.prototype.mass=function(t,e,r){T.mass?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),vn(this,t,e,r))};let Rn=null,wn=!1;wn||(v={ensureResources:function(t,e,r,n,i){const a=Math.max(1,Math.round(e*n)),o=Math.max(1,Math.round(r*n));return function(t,e,r){return!t.mask||t.mask.width!==e||t.mask.height!==r}(t,a,o)&&(t.mask=g(a,o)),function(t,e,r,n){return!t.fillMaskFramebuffer||t.fillMaskFramebuffer.width!==e||t.fillMaskFramebuffer.height!==r||"function"==typeof t.fillMaskFramebuffer.pixelDensity&&t.fillMaskFramebuffer.pixelDensity()!==n}(t,e,r,n)&&(t.fillMaskFramebuffer?.remove&&t.fillMaskFramebuffer.remove(),t.fillMaskFramebuffer=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1}),i(t.fillMaskFramebuffer)),t.mask.dirtyRect??=null,t.mask.isDrawn??=!1,t.mask.drawingContext.imageSmoothingEnabled=!1,{mask:t.mask,ctx:t.mask.drawingContext}},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?i(n(t.dirtyRect,4)):r():null},getShaderMask:function(t,e,r,n,i,a){const o=t.fillMaskFramebuffer,s=t.drawingContext,c=n(r)??i(),l=c.maxX-c.minX,u=c.maxY-c.minY;Rn&&Rn.width===l&&Rn.height===u||(Rn=g(l,u));const h=Rn.drawingContext;return h.clearRect(0,0,l,u),h.drawImage(e,c.minX,c.minY,l,u,0,0,l,u),a(o),s.bindTexture(s.TEXTURE_2D,o.colorTexture),s.texSubImage2D(s.TEXTURE_2D,0,c.minX,c.minY,s.RGBA,s.UNSIGNED_BYTE,Rn),o}},wn=!0),T.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const En=()=>({...T.fill});function An(t,e,r,n){T.fill.opacity=(arguments.length<4?e:n)||150,T.fill.color=arguments.length<3?s(t):s(t,e,r),T.fill.isActive=!0}function Mn(t,e="out"){T.fill.bleed_strength=rt(t,0,1),T.fill.direction=e}function Tn(t=.4,e=.4){T.fill.texture_strength=rt(t,0,1),T.fill.border_strength=rt(e,0,1)}function Sn(){T.fill.isActive=!1}let Pn;const Cn=[[],[]];function Fn(){for(let t=0;t<512;t++)Cn[0][t]=Q(.5,.2),Cn[1][t]=Q(0,.02)}function kn(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}G(Fn);class In{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 c=t[a],l=t[(a+1)%t.length],u={x:l.x-c.x,y:l.y-c.y},h=ft(0,0,u.x,u.y,90),f={x:c.x+u.x/2,y:c.y+u.y/2};i.push({v1:c,v2:l,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=e,this.sizeY=n,this.dir=Array(t.length),i.forEach((t,e)=>{let r=0;for(const e of Pn.intersect(t.ray))kn(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const a=W(-.6,.6)*e,o=W(-.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];const c=r,l=r+e,u=this.v[(c-1+this.v.length)%this.v.length],h=this.v[l%this.v.length],f=h.x-u.x,m=h.y-u.y;for(let t=0;t<2;t++){const e=W(.25,.75),n={x:u.x+f*e,y:u.y+m*e},s=r+t;i.splice(s,0,n),a.splice(s,0,W(.4,.7)),o.splice(s,0,this.dir[c%this.dir.length])}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+W(0,.8*i)));const a=[],o=[],s=[],c=this.midP,l=Pn.sides;for(const t of n){const r=t%e;let n=this.v[r],i=0;for(const[t,e]of l){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:c.x+(n.x-c.x)*W(.3,.6),y:c.y+(n.y-c.y)*W(.3,.6)}),a.push(n),o.push(this.m[r]),s.push(!this.dir[r])}return new In(a,o,this.midP,s,!1,this.sizeX,this.sizeY)}flipDirs(){return new In(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),c=new Array(a),l=new Array(a),u="out"===T.fill.direction?-90:90;0===Cn[0].length&&Fn();const h=Cn[0],f=h.length,m=Cn[1],d=m.length;let x,g,p,y=0,_=0,v=999===t?W(.6,.8):T.fill.bleed_strength;for(let a=0;a<i;a++){const x=e[a],g=e[a+1<i?a+1:0],p=r[a],b=n[a];if(t<997&&(v=p),v<.05){c[y]=p,l[y]=b,y++,o[_]=(x.x+g.x)/2,s[_]=(x.y+g.y)/2,c[y]=p,l[y]=b,y++,_++;continue}const R=(b?u:-u)+5*W(-1,1),w=ct(R),E=lt(R),A=g.x-x.x,M=g.y-x.y,T=w*A+E*M,S=w*M-E*A,P=h[~~(W(0,1)*f)]*W(.65,1.35)*v,C=p+m[~~(W(0,1)*d)];c[y]=p,l[y]=b,y++,o[_]=x.x+.5*A+T*P,s[_]=x.y+.5*M+S*P,c[y]=C,l[y]=b,y++,_++}const b=2024*Math.max(.1,2*T.fill.bleed_strength);if(b&&y>b){const t=Math.ceil(y/b),r=Math.ceil(y/t);x=new Array(r),g=new Array(r),p=new Array(r);let n=0;for(let r=0;r<y;r+=t,n++)x[n]=r%2==0?e[r>>1]:{x:o[r>>1],y:s[r>>1]},g[n]=c[r],p[n]=l[r]}else{x=new Array(y);for(let t=0;t<y;t++)x[t]=t%2==0?e[t>>1]:{x:o[t>>1],y:s[t>>1]};c.length=y,l.length=y,g=c,p=l}return new In(x,g,this.midP,p,!1,this.sizeX,this.sizeY)}fill(t,n,a){const o=3*a,s=2*n*(1+a/2),l=!1!==P.isBrush;P.isBrush=!1,l&&(P.justChanged=!0),P.blend(t);const u=c();P.ctx.save(),P.ctx.setTransform(i*u.a,i*u.b,i*u.c,i*u.d,i*(u.x+e/2),i*(u.y+r/2)),P.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*T.fill.border_strength})`,P.ctx.lineCap="round";const h=Math.max(this.sizeX,this.sizeY),f=W(.15,.7);let m=this.grow();const d=this.scatter(.1).grow().scatter(.75).flipDirs();let x;for(let e=0;e<20;e++){e%4==0&&(m=m.grow()),e%2==0&&(x=[m.grow(1-.0125*e),m.grow(.7-.0125*e),m.grow(.4-.0125*e)]);for(const r of x)r.grow(999).grow(997).layer(e,h,s,t);d.grow(999).flipDirs().grow(997).layer(e,h,s*o,t),e%2==0&&m.grow(f).grow(999).layer(e,h,2*s,t),e%8!=0&&19!==e||(0!==o&&m.erase(3*o,n),P.blend(t,!0))}P.ctx.restore()}layer(t,e,r,n){P.ctx.lineWidth=et(t,0,24,e/25,e/30,!0),P.ctx.fillStyle=`rgb(${n._getRed()} ${n._getGreen()} ${n._getBlue()} / ${r}%)`,function(t){const e=P.ctx,r=e.getTransform(),n=r.a,i=r.b,a=r.c,o=r.d,s=r.e,c=r.f;let l=Infinity,u=Infinity,h=-Infinity,f=-Infinity;e.beginPath();const m=t[0];let d=n*m.x+a*m.y+s,x=i*m.x+o*m.y+c;l=h=d,u=f=x,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,x=i*m.x+o*m.y+c,l=Math.min(l,d),u=Math.min(u,x),h=Math.max(h,d),f=Math.max(f,x),e.lineTo(m.x,m.y)}e.closePath();const g=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);P.markDirtyRect(P.mask,{minX:l-g,minY:u-g,maxX:h+g,maxY:f+g})}(this.v),P.ctx.fill(),P.ctx.stroke()}erase(t,e){P.ctx.save();const r=~~(W(80,110)*et(t,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,a=1.3*Math.min(this.sizeX,this.sizeY),o=.03*a,s=.45*a,{x:c,y:l}=this.midP;P.ctx.globalCompositeOperation="destination-out";const u=(5-et(e,80,100,.3,.7,!0))*t/255;P.ctx.fillStyle=`rgb(255 0 0 / ${u})`,P.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=c+Q(0,n),r=l+Q(0,i),a=W(o,s);P.ctx.beginPath(),bn(e,r,a),t%5!=0&&P.ctx.fill()}P.ctx.globalCompositeOperation="source-over",P.ctx.restore()}}function Ln(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!Zn(n,n.next)&&0!==Gn(n.prev,n,n.next))n=n.next;else{if(Kn(n),n=e=n.prev,n===n.next)break;r=!0}}while(r||n!==e);return e}function Dn(t,e,r,n,i,a,o){if(!t)return;!o&&a&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=Yn(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let a=null;for(e=0;i;){e++;let o=i,s=0;for(let t=0;t<r&&(s++,o=o.nextZ,o);t++);let c=r;for(;s>0||c>0&&o;)0!==s&&(0===c||!o||i.z<=o.z)?(n=i,i=i.nextZ,s--):(n=o,o=o.nextZ,c--),a?a.nextZ=n:t=n,n.prevZ=a,a=n;i=o}a.nextZ=null,r*=2}while(e>1)}(i)}(t,n,i,a);let s=t;for(;t.prev!==t.next;){const c=t.prev,l=t.next;if(a?Bn(t,n,i,a):Nn(t))e.push(c.i,t.i,l.i),Kn(t),t=l.next,s=l.next;else if((t=l)===s){o?1===o?Dn(t=Un(Ln(t),e),e,r,n,i,a,2):2===o&&On(t,e,r,n,i,a):Dn(Ln(t),e,r,n,i,a,1);break}}}function Nn(t){const e=t.prev,r=t,n=t.next;if(Gn(e,r,n)>=0)return!1;const i=e.x,a=r.x,o=n.x,s=e.y,c=r.y,l=n.y,u=Math.min(i,a,o),h=Math.min(s,c,l),f=Math.max(i,a,o),m=Math.max(s,c,l);let d=n.next;for(;d!==e;){if(d.x>=u&&d.x<=f&&d.y>=h&&d.y<=m&&zn(i,s,a,c,o,l,d.x,d.y)&&Gn(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function Bn(t,e,r,n){const i=t.prev,a=t,o=t.next;if(Gn(i,a,o)>=0)return!1;const s=i.x,c=a.x,l=o.x,u=i.y,h=a.y,f=o.y,m=Math.min(s,c,l),d=Math.min(u,h,f),x=Math.max(s,c,l),g=Math.max(u,h,f),p=Yn(m,d,e,r,n),y=Yn(x,g,e,r,n);let _=t.prevZ,v=t.nextZ;for(;_&&_.z>=p&&v&&v.z<=y;){if(_.x>=m&&_.x<=x&&_.y>=d&&_.y<=g&&_!==i&&_!==o&&zn(s,u,c,h,l,f,_.x,_.y)&&Gn(_.prev,_,_.next)>=0)return!1;if(_=_.prevZ,v.x>=m&&v.x<=x&&v.y>=d&&v.y<=g&&v!==i&&v!==o&&zn(s,u,c,h,l,f,v.x,v.y)&&Gn(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;_&&_.z>=p;){if(_.x>=m&&_.x<=x&&_.y>=d&&_.y<=g&&_!==i&&_!==o&&zn(s,u,c,h,l,f,_.x,_.y)&&Gn(_.prev,_,_.next)>=0)return!1;_=_.prevZ}for(;v&&v.z<=y;){if(v.x>=m&&v.x<=x&&v.y>=d&&v.y<=g&&v!==i&&v!==o&&zn(s,u,c,h,l,f,v.x,v.y)&&Gn(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function Un(t,e){let r=t;do{const n=r.prev,i=r.next.next;!Zn(n,i)&&Vn(n,r,r.next,i)&&Wn(n,i)&&Wn(i,n)&&(e.push(n.i,r.i,i.i),Kn(r),Kn(r.next),r=t=i),r=r.next}while(r!==t);return Ln(r)}function On(t,e,r,n,i,a){let o=t;do{let t=o.next.next;for(;t!==o.prev;){if(o.i!==t.i&&Xn(o,t)){let s=qn(o,t);return o=Ln(o,o.next),s=Ln(s,s.next),Dn(o,e,r,n,i,a,0),void Dn(s,e,r,n,i,a,0)}t=t.next}o=o.next}while(o!==t)}function Yn(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function zn(t,e,r,n,i,a,o,s){return!(t===o&&e===s)&&function(t,e,r,n,i,a,o,s){return(i-o)*(e-s)>=(t-o)*(a-s)&&(t-o)*(n-s)>=(r-o)*(e-s)&&(r-o)*(a-s)>=(i-o)*(n-s)}(t,e,r,n,i,a,o,s)}function Xn(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&Vn(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&(Wn(t,e)&&Wn(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)&&(Gn(t.prev,t,e.prev)||Gn(t,e.prev,e))||Zn(t,e)&&Gn(t.prev,t,t.next)>0&&Gn(e.prev,e,e.next)>0)}function Gn(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Zn(t,e){return t.x===e.x&&t.y===e.y}function Vn(t,e,r,n){const i=Hn(Gn(t,e,r)),a=Hn(Gn(t,e,n)),o=Hn(Gn(r,n,t)),s=Hn(Gn(r,n,e));return i!==a&&o!==s||!(0!==i||!$n(t,r,e))||!(0!==a||!$n(t,n,e))||!(0!==o||!$n(r,t,n))||!(0!==s||!$n(r,e,n))}function $n(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function Hn(t){return t>0?1:t<0?-1:0}function Wn(t,e){return Gn(t.prev,t,t.next)<0?Gn(t,e,t.next)>=0&&Gn(t,t.prev,e)>=0:Gn(t,e,t.prev)<0||Gn(t,t.next,e)<0}function qn(t,e){const r=Jn(t.i,t.x,t.y),n=Jn(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function jn(t,e,r,n){const i=Jn(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Kn(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function Jn(t,e,r){return{i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}fe.prototype.fill=function(t=!1,e,r,n,i,a){let o=En();t&&(An(t,e),Mn(r,a),Tn(n,i)),o.isActive&&(pt(),function(t){if(!T.fill.isActive||!T.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Pn=t;const e=[...t.vertices],r=~~(.25*e.length*tt({1:5,2:10,3:60})),n=T.fill.bleed_strength,i=e.map((t,e)=>(e>r?1:.3)*W(.85,1.4)*n),a=K(0,e.length),o=[...e.slice(a),...e.slice(0,a)],s=function(t){if(0===t.length)return{x:0,y:0};if(t.length<8){const e=t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0});return{x:e.x/t.length,y:e.y/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 In(o,i,s,[],!0).fill(T.fill.color,et(T.fill.opacity,0,255,0,1,!0),T.fill.texture_strength)}(this)),(t=>{T.fill={...t}})(o)},me.prototype.fill=function(t,e,r){En().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,T.fill.bleed_strength<.06?0:et(T.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let Qn=null,ti=null,ei=null,ri=null,ni=null,ii=0,ai=0,oi=0;const si={},ci={};function li(t,e,r,n){h(),T.wash.opacity=(arguments.length<4?e:n)??150,T.wash.color=arguments.length<3?s(t):s(t,e,r),T.wash.isActive=!0}function ui(){T.wash.isActive=!1}function hi(t,e){const r=c();return[r.a*t+r.c*e+r.x+ii/2,r.b*t+r.d*e+r.y+ai/2]}function fi(t,e,r){const n=e.isEnabled(e.DEPTH_TEST);return n&&e.disable(e.DEPTH_TEST),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.viewport(0,0,r.width*r.density,r.height*r.density),{hadDepthTest:n}}function mi(t,n,a){a?.hadDepthTest&&n.enable(n.DEPTH_TEST),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,Math.max(1,Math.round(e*i)),Math.max(1,Math.round(r*i)))}function di(t,e){e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA)}function xi(t,e,r){if(!e)return;if(r(e)){const r=t.drawingContext,n=r.getParameter(r.FRAMEBUFFER_BINDING),i=r.getParameter(r.VIEWPORT);return r.bindFramebuffer(r.FRAMEBUFFER,e.framebuffer),r.viewport(0,0,e.width*e.density,e.height*e.density),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.bindFramebuffer(r.FRAMEBUFFER,n),void r.viewport(i[0],i[1],i[2],i[3])}const n=e.drawingContext;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,e.width,e.height),n.restore()}function gi(t,e,r){return t.shaderProgram??=function(t,e,r){const n=Pe(t,e,r),i=new Map;return{program:n,setUniform(e,r){const a=(e=>(i.has(e)||i.set(e,t.getUniformLocation(n,e)),i.get(e)))(e);a&&("boolean"!=typeof r?"number"!=typeof r?Array.isArray(r)&&(3===r.length?t.uniform3f(a,r[0],r[1],r[2]):4===r.length&&t.uniform4f(a,r[0],r[1],r[2],r[3])):t.uniform1f(a,r):t.uniform1i(a,r?1:0))}}}(t.drawingContext,e,r),t.shaderProgram}function pi(t,e){const r=t.drawingContext,n=e.density??1,i=r.createFramebuffer(),a=Math.max(1,e.width),o=Math.max(1,e.height),s=Math.max(1,Math.round(a*n)),c=Math.max(1,Math.round(o*n)),l=function(t,e,r){const n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,r,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindTexture(t.TEXTURE_2D,null),n}(r,s,c);return r.bindFramebuffer(r.FRAMEBUFFER,i),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,l,0),r.bindFramebuffer(r.FRAMEBUFFER,null),{__brushFramebuffer:!0,framebuffer:i,colorTexture:l,width:a,height:o,density:n,pixelDensity:()=>n,remove(){r.deleteFramebuffer(i),r.deleteTexture(l)}}}function yi(t,e,r,n,i){return e?.remove?.(),pi(t,{width:r,height:n,density:i})}function _i({renderer:t,shader:e,source:r,mask:n,color:i,isBrushMask:a,dirtyRect:o,targetIsFramebuffer:s,withScissor:c}){const l=t.drawingContext,u=l.isEnabled(l.DEPTH_TEST),h=l.getParameter(l.FRAMEBUFFER_BINDING),f=l.getParameter(l.CURRENT_PROGRAM),m=l.getParameter(l.VERTEX_ARRAY_BINDING),d=l.createVertexArray();l.bindVertexArray(d),l.useProgram(e.program),l.disable(l.DEPTH_TEST),l.enable(l.BLEND),l.blendEquation(l.FUNC_ADD),l.blendFunc(l.ONE,l.ONE_MINUS_SRC_ALPHA),l.activeTexture(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,r.colorTexture),l.uniform1i(l.getUniformLocation(e.program,"u_source"),0),l.activeTexture(l.TEXTURE1),l.bindTexture(l.TEXTURE_2D,n.colorTexture),l.uniform1i(l.getUniformLocation(e.program,"u_mask"),1),e.setUniform("u_targetIsFramebuffer",s),e.setUniform("u_isBrush",a),l.uniform3f(l.getUniformLocation(e.program,"u_color"),i[0],i[1],i[2]),l.bindFramebuffer(l.FRAMEBUFFER,null),c(l,o,()=>{l.drawArrays(l.TRIANGLES,0,3)},!s),l.bindTexture(l.TEXTURE_2D,null),l.activeTexture(l.TEXTURE0),l.bindVertexArray(m),l.useProgram(f),l.bindFramebuffer(l.FRAMEBUFFER,h),u&&l.enable(l.DEPTH_TEST),l.deleteVertexArray(d)}function vi(t){return function({renderer:t,sourceFramebuffer:e,dirtyRect:r,getTargetPixelSize:n,toScissorBox:i}){const a=t.drawingContext,{width:o,height:s}=n(),c=r?i(r):null,l=a.getParameter(a.READ_FRAMEBUFFER_BINDING),u=a.getParameter(a.DRAW_FRAMEBUFFER_BINDING);return a.bindFramebuffer(a.READ_FRAMEBUFFER,null),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,e.framebuffer),a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT),a.blitFramebuffer(c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,a.COLOR_BUFFER_BIT,a.NEAREST),a.bindFramebuffer(a.READ_FRAMEBUFFER,l),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,u),e}(t)}function bi(t){if("number"==typeof t){const e=Math.max(0,Math.min(255,t));return`rgb(${e} ${e} ${e})`}return t??"black"}function Ri(t){const e=((t,e=!1)=>(t.drawingContext??=t.getContext("2d",e?{willReadFrequently:!0}:void 0),t.drawingContext))(t,!0),r={canvas:t,drawingContext:e,width:t.width,height:t.height,pixels:null,_fillStyle:"#ffffff",_strokeStyle:"transparent",_lineWidth:1,pixelDensity:()=>1,background(r){e.save(),e.setTransform(1,0,0,1,0,0),e.fillStyle=bi(r),e.fillRect(0,0,t.width,t.height),e.restore()},noSmooth(){e.imageSmoothingEnabled=!1},push(){e.save()},pop(){e.restore()},translate(t,r){e.translate(t,r)},scale(t,r=t){e.scale(t,r)},rotate(t){e.rotate(t)},noStroke(){r._strokeStyle="transparent"},stroke(t){r._strokeStyle=bi(t)},noFill(){r._fillStyle="transparent"},fill(t){r._fillStyle=bi(t)},strokeWeight(t){r._lineWidth=t},rect(t,n,i,a){e.beginPath(),e.rect(t,n,i,a),r._paint()},circle(t,n,i){e.beginPath(),e.arc(t,n,i/2,0,2*Math.PI),r._paint()},ellipse(t,n,i,a){e.beginPath(),e.ellipse(t,n,i/2,a/2,0,0,2*Math.PI),r._paint()},line(t,n,i,a){e.beginPath(),e.moveTo(t,n),e.lineTo(i,a),e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke()},beginShape(){e.beginPath(),r._shapeStarted=!1},vertex(t,n){r._shapeStarted?e.lineTo(t,n):(e.moveTo(t,n),r._shapeStarted=!0)},endShape(t=!1){t&&e.closePath(),r._paint()},loadPixels(){r.pixels=e.getImageData(0,0,t.width,t.height).data},updatePixels(){const n=e.getImageData(0,0,t.width,t.height);n.data.set(r.pixels),e.putImageData(n,0,0)},_paint(){"transparent"!==r._fillStyle&&(e.fillStyle=r._fillStyle,e.fill()),"transparent"!==r._strokeStyle&&(e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke())}};return r}function wi(t,e){return Ri(g(t,e,!0))}function Ei(t,e){return new Promise((r,n)=>{const i=globalThis.Image;if(!i)return void n(new Error("Standalone image brush loading requires Image support."));const a=new i;a.onload=()=>{const t=Ri(g(a.naturalWidth,a.naturalHeight,!0));t.drawingContext.drawImage(a,0,0),e(t),r(t)},a.onerror=()=>n(new Error(`Failed to load image tip: ${t}`)),a.crossOrigin="anonymous",a.src=t})}var Ai;T.wash={color:null,opacity:150,isActive:!1},fe.prototype.wash=function(t=!1,i){const a={...T.wash};!1!==t&&li(t,i),T.wash.isActive&&function(t){if(!T.wash?.isActive||!T.wash.color||t.vertices.length<3)return;C(),function(){const t=n.drawingContext;ni&&!(ii!==e||ai!==r)||(ii=e,ai=r,ni=new Float32Array([2/ii,0,0,0,0,-2/ai,0,0,0,0,1,0,-1,1,0,1])),Qn===t&&ti&&ei&&ri||(Qn=t,ti=Pe(Qn,"#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}","#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}"),si.a_position=Qn.getAttribLocation(ti,"a_position"),ci.u_matrix=Qn.getUniformLocation(ti,"u_matrix"),ci.u_color=Qn.getUniformLocation(ti,"u_color"),ei=Qn.createVertexArray(),Qn.bindVertexArray(ei),ri=Qn.createBuffer(),Qn.bindBuffer(Qn.ARRAY_BUFFER,ri),Qn.bufferData(Qn.ARRAY_BUFFER,0,Qn.DYNAMIC_DRAW),oi=0,Qn.enableVertexAttribArray(si.a_position),Qn.vertexAttribPointer(si.a_position,2,Qn.FLOAT,!1,8,0),Qn.bindVertexArray(null),Qn.bindBuffer(Qn.ARRAY_BUFFER,null))}();const{triangles:i,vertexCount:a}=function(t){const e=new Float32Array(2*t.vertices.length);for(let r=0;r<t.vertices.length;r++){const n=t.vertices[r];e[2*r]=n.x,e[2*r+1]=n.y}const r=function(t,e,r=2){const n=t.length;let i=function(t,e,r,n){let i;if(1==function(t,e,r,n){let i=0;for(let e=0,a=r-n;e<r;e+=n)i+=(t[a]-t[e])*(t[e+1]+t[a+1]),a=e;return i}(t,0,r,n)>0)for(let e=0;e<r;e+=n)i=jn(e/n|0,t[e],t[e+1],i);else for(let e=r-n;e>=0;e-=n)i=jn(e/n|0,t[e],t[e+1],i);return i&&Zn(i,i.next)&&(Kn(i),i=i.next),i}(t,0,n,r);const a=[];if(!i||i.next===i.prev)return a;let o,s,c;if(t.length>80*r){o=t[0],s=t[1];let e=o,i=s;for(let a=r;a<n;a+=r){const r=t[a],n=t[a+1];r<o&&(o=r),n<s&&(s=n),r>e&&(e=r),n>i&&(i=n)}c=Math.max(e-o,i-s),c=0!==c?32767/c:0}return Dn(i,a,r,o,s,c,0),a}(e),n=new Float32Array(2*r.length);for(let t=0;t<r.length;t++){const i=r[t],[a,o]=hi(e[2*i],e[2*i+1]);n[2*t]=a,n[2*t+1]=o}return{triangles:n,vertexCount:r.length}}(t),o=i.byteLength;Qn.useProgram(ti),Qn.enable(Qn.BLEND),Qn.blendEquation(Qn.FUNC_ADD),Qn.blendFunc(Qn.ONE,Qn.ONE_MINUS_SRC_ALPHA),Qn.bindVertexArray(ei),Qn.bindBuffer(Qn.ARRAY_BUFFER,ri),o>oi?(Qn.bufferData(Qn.ARRAY_BUFFER,i,Qn.DYNAMIC_DRAW),oi=o):Qn.bufferSubData(Qn.ARRAY_BUFFER,0,i);const s=T.wash.color._array;Qn.uniformMatrix4fv(ci.u_matrix,!1,ni),Qn.uniform4f(ci.u_color,s[0],s[1],s[2],T.wash.opacity/255),Qn.drawArrays(Qn.TRIANGLES,0,a),Qn.bindVertexArray(null),Qn.bindBuffer(Qn.ARRAY_BUFFER,null),Fe(n,Qn)}(this),T.wash={...a}},me.prototype.wash=function(t,e,r){T.wash?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,0,-1),this.pol.wash())},Ai={load:function(t=ae){if(!function(t){return function(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement}(t)||function(t){return"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas}(t)}(t))throw new Error("Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.");ue(t,t.width,t.height,1)},syncDensity:function(){return u({Cwidth:ce,Cheight:le,Density:se}),se},isCanvasReady:function(){if(!oe)throw new Error("No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.")},instance:function(){},activateInstance:function(){},deactivateInstance:function(){},getActiveFramebuffer:function(){return null},isFramebufferTarget:function(){return!0===arguments[0]?.__brushFramebuffer}},l={...l,...Ai},Jt(),function(){var t;t={beginDirectMaskDraw:fi,endDirectMaskDraw:mi,resetDirectShaderTracking:di},Ce={...Ce,...t}}(),function(){var t;t={clearTarget:xi,ensureBlendShaderProgram:gi,ensureBlendSourceFramebuffer:yi,createFramebuffer:pi,runBlendShaderPass:_i,blitSourceToFramebuffer:vi},p={...p,...t}}(),function(){var t;t={createTipSurface:wi,loadImageTip:Ei},Te={...Te,...t}}();export{Zt as Color,Bt as DEGREES,me as Plot,fe as Polygon,yt as Position,Ut as RADIANS,Tr as add,Ft as addField,Vt as angleMode,pe as arc,_e as beginShape,Re as beginStroke,Sr as box,ge as circle,te as clear,Nr as clip,he as createCanvas,be as endShape,Ee as endStroke,Pt as field,An as fill,Mn as fillBleed,Tn as fillTexture,Qr as flowLine,$t as getAngleMode,on as hatch,hn as hatchArray,sn as hatchStyle,Jt as initStandaloneRuntime,f as instance,Jr as line,kt as listFields,F as load,fn as mass,we as move,Br as noClip,Ct as noField,Sn as noFill,cn as noHatch,mn as noMass,Dr as noStroke,ui as noWash,H as noiseSeed,Fr as pick,de as polygon,Wt as pop,Ht as push,xe as rect,St as refreshField,Qt as render,jt as rotate,Kt as scale,Cr as scaleBrushes,Z as seed,Lr as set,Ae as spline,kr as stroke,Ir as strokeWeight,qt as translate,ve as vertex,tt as wRand,li as wash,It as wiggle};
+const t={a:1,b:0,c:0,d:1,x:0,y:0};let e,r,n,i,a=()=>!1,o=t=>t,s=()=>{throw new Error("No runtime color adapter registered.")},c=()=>t,l={load:()=>{throw new Error("No target runtime adapter registered.")},syncDensity:()=>i,isCanvasReady:()=>{throw new Error("No target runtime adapter registered.")},instance:t=>{},activateInstance:t=>{},deactivateInstance:()=>{},getActiveFramebuffer:()=>null,isFramebufferTarget:()=>!1};function u(t){"Cwidth"in t&&(e=t.Cwidth),"Cheight"in t&&(r=t.Cheight),"Instance"in t&&t.Instance,"Renderer"in t&&(n=t.Renderer),"Density"in t&&(i=t.Density)}const h=()=>l.isCanvasReady(),f=t=>l.instance(t),m=()=>l.getActiveFramebuffer(),d=t=>l.isFramebufferTarget(t),x=(t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null,g=(t,e,r=!1)=>{const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,e):(()=>{const r=document.createElement("canvas");return r.width=t,r.height=e,r})();return n.drawingContext=n.getContext("2d",r?{willReadFrequently:!0}:void 0),n};let p={clearTarget:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendShaderProgram:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendSourceFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},createFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},runBlendShaderPass:()=>{throw new Error("No compositor runtime adapter registered.")},blitSourceToFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")}};const y=(...t)=>p.createFramebuffer(...t);let b=null,_=null;const v=t=>{((...t)=>{p.clearTarget(...t)})(n,t,d)},R=()=>({width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(r*i))}),w=t=>{if(!t)return null;const{width:e,height:r}=R();return((t,e,r)=>{if(!t)return null;const 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}})(t,e,r)},E=()=>{const{width:t,height:e}=R();return((t,e)=>({minX:0,minY:0,maxX:t,maxY:e}))(t,e)},A=(t,e=!0)=>{const r=w(t);if(!r)return null;const{height:n}=R();return{x:r.minX,y:e?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},M=(t,e,r,n=!0)=>{const i=A(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()},T={},S=()=>{n?.loaded||(h(),P.load())},P={isBlending:!1,cachedColor:null,markDirtyRect(t,e){const r=w(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){if(!t)return;const e=t===this.glMask?b:_;e?.clearMask?.(t,v)},getCompositeRect(t,e){const r=e?b:_;return r?.getCompositeRect?.(t,m,E,x,w)},load(){l.syncDensity();const t=!n.blendSourceFramebuffer||n.blendSourceFramebuffer.width!==e||n.blendSourceFramebuffer.height!==r||"function"==typeof n.blendSourceFramebuffer.pixelDensity&&n.blendSourceFramebuffer.pixelDensity()!==i;((...t)=>{p.ensureBlendShaderProgram(...t)})(n,"#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.);}"),this.glMask=b?.ensureResources?.(n,e,r,i);const a=_?.ensureResources?.(n,e,r,i,v)??{mask:null,ctx:null};t&&(n.blendSourceFramebuffer=((...t)=>p.ensureBlendSourceFramebuffer(...t))(n,n.blendSourceFramebuffer,e,r,i)),this.mask=a.mask,this.ctx=a.ctx},blend(t=!1,e=!1){S();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,this.clearMask(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,this.cachedColor=null))},applyShader(t,i){if(!t?.isDrawn)return;const a=this.getCompositeRect(t,i);if(!a)return void this.clearMask(t);n.drawingContext;const o=n.shaderProgram,s=m(),c=((...t)=>p.blitSourceToFramebuffer(...t))({renderer:n,sourceTarget:s??n,sourceFramebuffer:n.blendSourceFramebuffer,dirtyRect:a,isFramebufferTarget:d,Cwidth:e,Cheight:r,getTargetPixelSize:R,toScissorBox:A,withScissor:M}),l=!!s,u=(i?b:_).getShaderMask(n,t,a,w,E,v);((...t)=>{p.runBlendShaderPass(...t)})({renderer:n,shader:o,source:c,mask:u,color:this.cachedColor,isBrushMask:i,Cwidth:e,Cheight:r,dirtyRect:a,targetIsFramebuffer:l,withScissor:M}),this.clearMask(t)}},C=()=>{S(),P.blend(!1,!0),P.clearMask(P.glMask),P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null},F=(t=!1)=>{((t=!1)=>{l.load(t)})(t),n.loaded&&P.load()},k=Math.sqrt(3),I=.5*(k-1),L=(3-k)/6,D=t=>0|Math.floor(t),N=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 B(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=>N[t%12*2]),n=new Float64Array(e).map(t=>N[t%12*2+1]);return function(t,i){let a=0,o=0,s=0;const c=(t+i)*I,l=D(t+c),u=D(i+c),h=(l+u)*L,f=t-(l-h),m=i-(u-h);let d,x;f>m?(d=1,x=0):(d=0,x=1);const g=f-d+L,p=m-x+L,y=f-1+2*L,b=m-1+2*L,_=255&l,v=255&u;let R=.5-f*f-m*m;if(R>=0){const t=_+e[v];R*=R,a=R*R*(r[t]*f+n[t]*m)}let w=.5-g*g-p*p;if(w>=0){const t=_+d+e[v+x];w*=w,o=w*w*(r[t]*g+n[t]*p)}let E=.5-y*y-b*b;if(E>=0){const t=_+1+e[v+1];E*=E,s=E*E*(r[t]*y+n[t]*b)}return 70*(a+o+s)}}function U(t,e){let r=new O(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class O{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 Y=U(Math.random()),z=U(Math.random());const X=[],G=t=>X.push(t),Z=t=>{Y=U(t),z=U(`${t}:2`);for(const t of X)t()};let V=B(U(Math.random())),$=B(U(Math.random()));const H=t=>{V=B(U(t)),$=B(U(`${t}:2`))},W=(t=0,e=1)=>t+Y()*(e-t),q=(t=0,e=1)=>t+z()*(e-t),j=t=>t[~~(Y()*t.length)],K=(t,e)=>~~W(t,e),J=(t,e)=>~~q(t,e),Q=(t=0,e=1)=>{const r=1-Y(),n=Y();return Math.sqrt(-2*Math.log(r))*ct(360*n)*e+t},tt=t=>{let e=0;const r=[];for(const n in t)e+=t[n],r.push({key:n,cumulative:e});const n=Y()*e;for(const{key:t,cumulative:e}of r)if(n<e)return isNaN(t)?t:parseInt(t)},et=(t,e,r,n,i,a=!1)=>{let o=n+(t-e)/(r-e)*(i-n);return a?n<i?rt(o,n,i):rt(o,i,n):o},rt=(t,e,r)=>Math.max(Math.min(t,r),e),nt=t=>(t%=360)<0?t+360:t,it=1440,at=2*Math.PI/it,ot=new Float32Array(it).fill(NaN),st=new Float32Array(it).fill(NaN),ct=t=>{const e=~~(4*nt(t));let r=ot[e];return isNaN(r)&&(r=Math.cos(e*at),ot[e]=r),r},lt=t=>{const e=~~(4*nt(t));let r=st[e];return isNaN(r)&&(r=Math.sin(e*at),st[e]=r),r},ut=(t,e=!1)=>{if(e||a()){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},ht=(t,e=!1)=>e||a()?180*t/Math.PI:t,ft=(t,e,r,n,i)=>{let a=ct(i),o=lt(i);return{x:a*(r-t)+o*(n-e)+t,y:a*(n-e)-o*(r-t)+e}},mt=(t,e,r,n)=>Math.hypot(r-t,n-e),dt=(t,e,r,n)=>ut(Math.atan2(-(n-e),r-t),!0),xt=(t,e,r,n,i=!1)=>{let a=t.x,o=t.y,s=e.x,c=e.y,l=r.x,u=r.y,h=n.x,f=n.y;if(a===s&&o===c||l===h&&u===f)return!1;let m=s-a,d=c-o,x=h-l,g=f-u,p=g*m-x*d;if(0===p)return!1;let y=(x*(o-u)-g*(a-l))/p,b=(m*(o-u)-d*(a-l))/p;return!(!i&&(b<0||b>1))&&{x:a+y*m,y:o+y*d}};let gt=!1;function pt(){gt||(S(),bt=.01*e,_t=-.5*e,vt=-.5*r,Rt=Math.round(2*e/bt),wt=Math.round(2*r/bt),Ft("hand",(t,e)=>{const r=q(.2,.8),n=J(5,10);return Lt(e,(e,i)=>.5*n*lt(r*i*e+J(15,25))*.2*ct(t)+$(e,i)*n*.7)}),Ft("curved",(t,e)=>{let r=J(-10,10);return J(0,100)%2==0&&(r*=-1),Lt(e,(e,n)=>3*et($(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),Ft("zigzag",(t,e)=>{let r=J(-30,-15)+Math.abs(44*lt(t));J(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t<Rt;t++){for(let r=0;r<wt;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),Ft("waves",(t,e)=>{const r=J(10,15)+5*lt(t),n=J(3,6)+3*ct(t),i=J(20,35);return Lt(e,(t,e)=>lt(r*t)*i*ct(e*n)+J(-3,3))}),Ft("seabed",(t,e)=>{const r=q(.4,.8),n=J(18,26);return Lt(e,(e,i)=>1.1*n*lt(r*i*e+J(15,20))*ct(t))}),Ft("spiral",(t,e)=>{const r=J(5,10),n=2*J(0,2)-1,i=J(65,80),a=Array.from({length:r},()=>({x:q(.1,.9)*Rt,y:q(.1,.9)*wt}));return Lt(e,(t,e)=>{let r=0,o=0;for(const s of a){const a=t-s.x,c=e-s.y,l=1/(a*a+c*c+1),u=Math.atan2(c,a)*(180/Math.PI),h=n*(u+i)*Math.PI/180;r+=l*Math.cos(h),o+=l*Math.sin(h)}return Math.atan2(o,r)*(180/Math.PI)})}),Ft("columns",(t,e)=>{const r=J(3,8),n=J(25,45);return Lt(e,(t,e)=>lt(t*r)*n)}),gt=!0)}class yt{constructor(t,e){pt();const r=c();this.mx=r.x,this.my=r.y,this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=Math.round((t+this.mx-_t)/bt),this.rowIdx=Math.round((e+this.my-vt)/bt)}reset(){this.plotted=0}isIn(){return T.field.isActive?yt.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=e,n=r,i=this.x+this.mx,a=this.y+this.my;return i>=-.3*t&&i<=1.3*t&&a>=-.3*n&&a<=1.3*n}angle(t=!1){return T.field.isActive&&(t||this.isIn())?Et.get(T.field.current).field[this.colIdx][this.rowIdx]*T.field.wiggle:0}moveTo(t,e,r=1){this.movePos(ht(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())return void(this.plotted+=r/i);const a=e/r,o=T.field.isActive,s=!!n;for(let e=0;e<a;e++){const e=(o?this.angle(!0):0)-(s?t.angle(this.plotted):t);this.update(this.x+r*ct(e),this.y+r*lt(e)),this.plotted+=r/i}}static getRowIndex(t,e=1){const r=t+c().y-vt;return Math.round(r/bt/e)}static getColIndex(t,e=1){const r=t+c().x-_t;return Math.round(r/bt/e)}static isIn(t,e){return t>=0&&e>=0&&t<Rt&&e<wt}}T.field={isActive:!1,current:null,wiggle:1};let bt,_t,vt,Rt,wt,Et=new Map;const At=new Set(["degrees","radians"]);function Mt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!At.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function Tt(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]=ht(t[e][r],!0);return t}(t.gen(e,new Array(Rt).fill(null).map(()=>new Float32Array(wt))),t.angleMode)}function St(t=0){if(!T.field.isActive||!T.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=Et.get(T.field.current);e.field=Tt(e,t)}function Pt(t){if(T.field.wiggle||(T.field.wiggle=1),pt(),!Et.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(Et.keys()).join(", ")}.`);T.field.isActive=!0,T.field.current=t;const e=Et.get(t);e.field||(e.field=Tt(e,0))}function Ct(){pt(),T.field.isActive=!1}function Ft(t,e,r={}){Et.set(t,{gen:e,field:null,angleMode:Mt(r)})}function kt(){return pt(),Array.from(Et.keys())}function It(t=1){Pt("hand"),T.field.wiggle=t}function Lt(t,e){for(let r=0;r<Rt;r++)for(let n=0;n<wt;n++)t[r][n]=e(r,n);return t}const Dt=[],Nt=(t,e,r)=>Math.max(e,Math.min(t,r)),Bt="degrees",Ut="radians";let Ot=null,Yt=Bt;const zt=[];let Xt={a:1,b:0,c:0,d:1,x:0,y:0};function Gt(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,x:t.a*e.x+t.c*e.y+t.x,y:t.b*e.x+t.d*e.y+t.y}}class Zt{constructor(t,e,r){if(t?._array)return this.r=Math.round(255*t._array[0]),this.g=Math.round(255*t._array[1]),this.b=Math.round(255*t._array[2]),this.hex=this.rgbToHex(this.r,this.g,this.b),this._array=[...t._array],void(this.gl=this._array);if("string"==typeof t){const e=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)$/i.exec(t);if(e){this.r=Nt(parseInt(e[1]),0,255),this.g=Nt(parseInt(e[2]),0,255),this.b=Nt(parseInt(e[3]),0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);const t=void 0!==e[4]?Nt(parseFloat(e[4]),0,1):1;return this._array=[this.r/255,this.g/255,this.b/255,t],void(this.gl=this._array)}this.hex=this.standardize(t);const r=this.hexToRgb(this.hex);this.r=r.r,this.g=r.g,this.b=r.b}else this.r=Nt(t??0,0,255),this.g=Nt(e??t??0,0,255),this.b=Nt(r??t??0,0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);this._array=[this.r/255,this.g/255,this.b/255,1],this.gl=this._array}rgbToHex(t,e,r){return`#${(1<<24|t<<16|e<<8|r).toString(16).slice(1)}`}hexToRgb(t){t=t.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(t,e,r,n)=>e+e+r+r+n+n);const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(!e)throw new Error(`Invalid color value "${t}".`);return{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}}standardize(t){const e=function(){if(Ot)return Ot;if("undefined"!=typeof document)return Ot=document.createElement("canvas").getContext("2d"),Ot;if("undefined"!=typeof OffscreenCanvas)return Ot=new OffscreenCanvas(1,1).getContext("2d"),Ot;throw new Error("Standalone color parsing requires CanvasRenderingContext2D support.")}();return e.fillStyle=t,e.fillStyle}_getRed(){return this.r}_getGreen(){return this.g}_getBlue(){return this.b}}function Vt(t){if(t!==Bt&&t!==Ut)throw new Error(`Invalid angle mode "${t}". Use "degrees" or "radians".`);Yt=t}function $t(){return Yt}function Ht(){pt(),Dt.push({fill:{...T.fill},wash:T.wash?{...T.wash}:null,stroke:{...T.stroke},hatch:{...T.hatch},mass:T.mass?{...T.mass}:null,field:{...T.field}}),zt.push({...Xt})}function Wt(){0!==zt.length&&(Xt=zt.pop(),function(){const t=Dt.pop();t&&(T.stroke={...t.stroke},T.field={...t.field},T.hatch={...t.hatch},T.fill={...t.fill},t.wash&&(T.wash={...t.wash}),t.mass?T.mass={...t.mass}:T.mass&&(T.mass={...T.mass,isActive:!1,brush:null,color:null,options:{}}))}())}function qt(t,e){Xt=Gt(Xt,{a:1,b:0,c:0,d:1,x:t,y:e})}function jt(t){const e=Yt===Ut?t:t*Math.PI/180,r=Math.cos(e),n=Math.sin(e);Xt=Gt(Xt,{a:r,b:n,c:-n,d:r,x:0,y:0})}function Kt(t,e=t){Xt=Gt(Xt,{a:t,b:0,c:0,d:e,x:0,y:0})}function Jt(){var t;(t={usesRadians:()=>"radians"===Yt,fromDegrees:t=>"radians"===Yt?t*Math.PI/180:t,createColor:(...t)=>1===t.length&&t[0]?._array?t[0]:new Zt(...t),getAffineMatrix:()=>Xt}).usesRadians&&(a=t.usesRadians),t.fromDegrees&&(o=t.fromDegrees),t.createColor&&(s=t.createColor),t.getAffineMatrix&&(c=t.getAffineMatrix)}function Qt(){C()}function te(...t){h(),P.glMask&&P.clearMask(P.glMask),P.mask&&P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null;const e=n.drawingContext,r=0===t.length?[1,1,1,0]:[...s(...t)._array.slice(0,3),1];e.bindFramebuffer(e.FRAMEBUFFER,null),e.disable(e.SCISSOR_TEST),e.clearColor(r[0],r[1],r[2],r[3]),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}let ee,re,ne,ie,ae=null,oe=!1,se=1,ce=0,le=0;function ue(t,e,r,n){ae=t,ce=e,le=r,se=n;const i=function(t,e,r,n){const i=function(t){return t.getContext("webgl2",{premultipliedAlpha:!0})??t.getContext("webgl2")}(t);if(!i)throw new Error("brush.load(target) requires a canvas with a WebGL2 context.");return{canvas:t,drawingContext:i,width:e,height:r,pixelDensity:()=>n}}(t,e,r,n);u({Renderer:i,Cwidth:e,Cheight:r,Density:n}),oe=!0}function he(t,e,r={}){if("undefined"==typeof document)throw new Error("brush.createCanvas() requires a browser document.");const n=Math.max(1,Math.round(t)),i=Math.max(1,Math.round(e)),a=Math.max(1,Number(r.pixelDensity)||1),o=document.createElement("canvas");if(o.width=Math.max(1,Math.round(n*a)),o.height=Math.max(1,Math.round(i*a)),o.style.width=`${n}px`,o.style.height=`${i}px`,r.id&&(o.id=r.id),r.parent){const t="string"==typeof r.parent?document.querySelector(r.parent):r.parent;if(!t)throw new Error(`Could not find parent "${r.parent}" for brush.createCanvas().`);t.appendChild(o)}return ue(o,n,i,a),o}class fe{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=xt(t.point1,t.point2,e,n);i&&r.push(i)}return this._intersectionCache[e]=r,r}show(){T.wash&&this.wash(),T.fill&&this.fill(),T.mass&&this.mass(),T.hatch&&this.hatch(),T.stroke&&this.draw()}}class me{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:ut(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:ut(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=ut(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)),et(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,a){pt();const o=a<0?4:1,s=[],c=Math.round(this.length/o),l=new yt(t+e/2,n+r/2);let u=0,h=0;for(let t=0;t<c;t++){l.plotTo(this,o,o);const t=this.calcIndex(l.plotted);u+=o,(u>=(a<=0?8:Math.max(this.segments[t]*a*q(.7,1.3),20))||t>=h)&&l.x&&(s.push([l.x-e/2,l.y-r/2]),u=0,t>=h&&h++)}return new fe(s)}show(t,e,r=1){T.wash&&this.wash(t,e,r),T.fill&&this.fill(t,e,r),T.mass&&this.mass(t,e,r),T.hatch&&this.hatch(t,e,r),T.stroke&&this.draw(t,e,r)}}function de(t){new fe(t).show()}function xe(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),be(0),_e(t,e),_e(t+r,e),_e(t+r,e+n),_e(t,e+n),ve(!0)}function ge(t,e,r,n=!1){const i=new me("curve"),a=Math.PI*r,o=q(0,360),s=n?()=>1+.2*n*q():()=>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*J(-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 c=t-r*lt(o),l=e-r*ct(-o);i.show(c,l,1)}function pe(t,e,r,n,i){const a=ht(n),o=((ht(i)-a)%360+360)%360;if(0===o)return;const s=new me("curve"),c=Math.max(1,Math.ceil(o/90)),l=o/c,u=Math.PI*r*l/180;for(let t=0;t<c;t++)s.addSegment(a+t*l+90,u,1,!0);s.endPlot(a+o+90,1,!0);const h=t+r*ct(a),f=e-r*lt(a);s.draw(h,f,1)}class ye{constructor(){this.isClosed=!1,this.curvature=re,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){Me(this.vert,this.curvature,this.isClosed).show()}}function be(t=0){re=rt(t,0,1),ee=new ye}function _e(t,e,r=1){if(!ee)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");ee.vertex(t,e,r)}function ve(t=!1){if(!ee)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(ee.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(ee.vertex(...ee.vert[0]),ee.isClosed=!0),ee.show(),ee=!1}function Re(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);ie=[e,r],ne=new me(t)}function we(t,e,r){if(!ne)throw new Error("move() called without beginStroke(). Call beginStroke() first.");ne.addSegment(t,e,r)}function Ee(t,e){if(!ne)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");ne.endPlot(t,e),ne.draw(ie[0],ie[1],1),ne=!1}function Ae(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");Me(t,e).draw()}function Me(t,e=.5,r=!1){const n=new me(0===e?"segments":"curve"),i=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let a,o,s,c=0;for(let l=0;l<t.length-1;l++)if(e>0&&l<t.length-2){const u=t[l],h=t[l+1],f=t[l+2],m=mt(u[0],u[1],h[0],h[1]),d=mt(h[0],h[1],f[0],f[1]),x=dt(u[0],u[1],h[0],h[1]),g=dt(h[0],h[1],f[0],f[1]),p=e*Math.min(m,d,.5*Math.min(m,d)),y=Math.max(m,d),b=m-p,_=d-p;if(Math.floor(x)===Math.floor(g)){const e=r&&0===l?0:m-c,i=r?0===l?0:d-s:d;n.addSegment(x,e,u[2],!0),l===t.length-3&&n.addSegment(g,i,h[2],!0),c=0,0===l&&(a=m,s=p,o=t[1],c=0)}else{const e={x:h[0]-p*ct(-x),y:h[1]-p*lt(-x)},f={x:e.x+y*ct(90-x),y:e.y+y*lt(90-x)},m={x:h[0]+p*ct(-g),y:h[1]+p*lt(-g)},d={x:m.x+y*ct(90-g),y:m.y+y*lt(90-g)},v=xt(e,f,m,d,!0),R=mt(e.x,e.y,v.x,v.y),w=mt(e.x,e.y,m.x,m.y)/2,E=i*R*(2*Math.asin(w/R)*(180/Math.PI))/360,A=r&&0===l?0:b-c,M=l===t.length-3?r?a-p:_:0;n.addSegment(x,A,u[2],!0),n.addSegment(x,isNaN(E)?0:E,u[2],!0),n.addSegment(g,M,h[2],!0),c=p,0===l&&(a=b,s=p,o=[e.x,e.y])}l===t.length-3&&n.endPlot(g,h[2],!0)}else if(0===e){const e=t[l],r=t[l+1],i=mt(e[0],e[1],r[0],r[1]),a=dt(e[0],e[1],r[0],r[1]);n.addSegment(a,i,r[2],!0),l===t.length-2&&n.endPlot(a,1,!0)}n.origin=r&&0!==e?o:t[0]}return n}let Te={createTipSurface:()=>{throw new Error("No stroke runtime adapter registered.")},loadImageTip:()=>{throw new Error("No stroke runtime adapter registered.")}},Se=!1;const Pe=(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 Ce={beginDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},endDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},resetDirectShaderTracking:()=>{}};const Fe=(t,e)=>Ce.resetDirectShaderTracking(t,e);let ke,Ie,Le,De,Ne,Be=!1,Ue=0,Oe=0,Ye=null;const ze={},Xe={};let Ge=1,Ze=0,Ve=0,$e=1,He=0,We=0,qe=0,je=0,Ke=1,Je=1,Qe=new Float32Array(8192),tr=0,er=2048,rr=32768,nr=null,ir=null,ar=null,or=null,sr=null;const cr={},lr={};let ur=0,hr=new Float32Array(1280),fr=0,mr=256,dr=null;const xr=new Map,gr=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function pr(){return Ie}function yr(){return((t,e,r)=>Ce.beginDirectMaskDraw(t,e,r))(n,ke,P.glMask)}function br(t){((t,e,r)=>{Ce.endDirectMaskDraw(t,e,r)})(n,ke,t)}function _r(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 vr(t,e,r,n){if(tr>=er){er*=2;const t=new Float32Array(4*er);t.set(Qe),Qe=t}const i=t-qe,a=e-je,o=4*tr,s=Ge*i+Ve*a+He+qe,c=Ze*i+$e*a+We+je,l=Je*r*Ke/2;Qe[o]=s,Qe[o+1]=c,Qe[o+2]=l,Qe[o+3]=n/255;const u=s*Je,h=c*Je;nr=_r(nr,u-l-1,h-l-1,u+l+1,h+l+1),tr++}function Rr(t,e){if(0===fr)return;P.glMask.isDrawn=!0;const r=yr();let i=xr.get(e);i||(i=ke.createTexture(),ke.bindTexture(ke.TEXTURE_2D,i),ke.texImage2D(ke.TEXTURE_2D,0,ke.RGBA,ke.RGBA,ke.UNSIGNED_BYTE,t.canvas),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_MIN_FILTER,ke.LINEAR),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_MAG_FILTER,ke.LINEAR),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_WRAP_S,ke.CLAMP_TO_EDGE),ke.texParameteri(ke.TEXTURE_2D,ke.TEXTURE_WRAP_T,ke.CLAMP_TO_EDGE),xr.set(e,i)),ke.useProgram(ir),ke.enable(ke.BLEND),ke.blendFunc(ke.ONE_MINUS_DST_ALPHA,ke.ONE),ke.activeTexture(ke.TEXTURE0),ke.bindTexture(ke.TEXTURE_2D,i),ke.uniform1i(lr.u_tex,0);const a=T.stroke.color._array;ke.uniform4f(lr.u_color,...a),ke.uniformMatrix4fv(lr.u_proj,!1,pr()),ke.bindVertexArray(ar),ke.bindBuffer(ke.ARRAY_BUFFER,sr);const o=5*fr*4,s=hr.subarray(0,5*fr);o>ur?(ke.bufferData(ke.ARRAY_BUFFER,hr,ke.DYNAMIC_DRAW),ur=hr.byteLength):ke.bufferSubData(ke.ARRAY_BUFFER,0,s),ke.drawArraysInstanced(ke.TRIANGLE_STRIP,0,4,fr),ke.flush(),ke.bindVertexArray(null),ke.bindTexture(ke.TEXTURE_2D,null),br(r),dr&&(P.markDirtyRect(P.glMask,dr),dr=null),fr=0,Fe(n,ke)}Se||(b={ensureResources:function(t,e,r,n){return function(t,e,r,n){return!t.glMask||t.glMask.width!==e||t.glMask.height!==r||"function"==typeof t.glMask.pixelDensity&&t.glMask.pixelDensity()!==n}(t,e,r,n)&&(t.glMask?.remove&&t.glMask.remove(),t.glMask=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1})),t.glMask.dirtyRect??=null,t.glMask.isDrawn??=!1,t.glMask},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?e()?r():i(n(t.dirtyRect,2)):r():null},getShaderMask:function(t,e){return e}},Se=!0),T.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let wr=new Map;const Er={offset:.08,scale:.08,warp:.06,tilt:.06};function Ar(){return{...T.stroke}}function Mr(t){T.stroke={...t}}function Tr(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0===e.markerTip&&(e.markerTip=!0),void 0===e.noise&&(e.noise=.3),e.noise=Math.max(0,Math.min(1,e.noise)),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:{...Er}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...Er,...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,c,l]=[(e-i)/o,(r-i)/o,(n-i)/o];return{type:"custom",min_max:[i,a],variation:{...Er},curve:t=>t<.5?s+(c-s)*t*2:c+(l-c)*(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=xr.get(t);e&&ke&&ke.deleteTexture(e),xr.delete(t)}(r);const n=Te.createTipSurface(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(),rn.imageToWhite(n),rn.tips.set(r,n),e.tipKey=r,void wr.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 rn.add(e.image.src),wr.set(t,{param:e,colors:[],buffers:[]}),rn.load()}wr.set(t,{param:e,colors:[],buffers:[]})}function Sr(){return[...wr.keys()]}function Pr(t){return wr.get(t)?.param??null}function Cr(t){for(const{param:e}of wr.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)}function Fr(t){if(!wr.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...wr.keys()].join(", ")}.`);T.stroke.type=t}function kr(t,e,r){h(),T.stroke.color=s(...arguments),T.stroke.isActive=!0}function Ir(t){T.stroke.weight=t}function Lr(t,e,r=1){Fr(t),kr(e),Ir(r)}function Dr(){T.stroke.isActive=!1}function Nr(t){return h(),t}function Br(){}let Ur,Or,Yr,zr;const Xr={};function Gr(t,n,a,o=!1){!function(){const t=c();Ge=t.a,Ze=t.b,Ve=t.c,$e=t.d,He=t.x,We=t.y,qe=e/2,je=r/2,Ke=Math.sqrt(Ge*Ge+Ze*Ze),Je=i}(),Ur=new yt(t+e/2,n+r/2),Or=a,Yr=o,Yr&&Yr.calcIndex(0)}const Zr=[];function Vr(t,i){i||(zr=t),function(){Xr.seed=999999*W();const{param:t}=wr.get(T.stroke.type)??{};if(!t)return;Xr.p=t;const{pressure:i}=t;if(Xr.a="custom"!==i.type?W(-1,1):0,Xr.b="custom"!==i.type?W(1,1.5):0,"custom"!==i.type)Xr.cp=W(3,3.5),Xr.ct=0,Xr.cs=1,Xr.ck=0;else{const t=i.variation??Er;Xr.cp=W(-t.offset,t.offset),Xr.ct=W(-t.warp,t.warp),Xr.cs=W(1-t.scale,1+t.scale),Xr.ck=W(-t.tilt,t.tilt)}[Xr.min,Xr.max]=i.min_max,Xr.noiseoffset=.05*Xr.p.noise,Yr||(Xr.cos=ct(zr),Xr.sin=lt(zr)),function(){S(),function(){const t=n?.glMask;t&&(Ye=t,Ye.dirtyRect??=null,Ye.isDrawn??=!1,P.glMask=Ye)}();const t=n.drawingContext,i=!Be||ke!==t;(i||Ue!==e||Oe!==r)&&(Ie=new Float32Array([2/e,0,0,0,0,2/r,0,0,0,0,1,0,-1,-1,0,1]),Ue=e,Oe=r),i&&(ke=t,Ne=Pe(ke,"#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);}"),ke.useProgram(Ne),ke.enable(ke.BLEND),ke.blendFunc(ke.ONE_MINUS_DST_ALPHA,ke.ONE),["a_position","a_radius","a_alpha"].forEach(t=>ze[t]=ke.getAttribLocation(Ne,t)),["u_matrix","u_color"].forEach(t=>Xe[t]=ke.getUniformLocation(Ne,t)),Le=ke.createVertexArray(),ke.bindVertexArray(Le),De=ke.createBuffer(),ke.bindBuffer(ke.ARRAY_BUFFER,De),ke.bufferData(ke.ARRAY_BUFFER,Qe.byteLength,ke.DYNAMIC_DRAW),rr=Qe.byteLength,ke.enableVertexAttribArray(ze.a_position),ke.vertexAttribPointer(ze.a_position,2,ke.FLOAT,!1,16,0),ke.enableVertexAttribArray(ze.a_radius),ke.vertexAttribPointer(ze.a_radius,1,ke.FLOAT,!1,16,8),ke.enableVertexAttribArray(ze.a_alpha),ke.vertexAttribPointer(ze.a_alpha,1,ke.FLOAT,!1,16,12),ke.bindVertexArray(null),xr.clear(),ir=Pe(ke,"#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=>cr[t]=ke.getAttribLocation(ir,t)),["u_proj","u_color","u_tex"].forEach(t=>lr[t]=ke.getUniformLocation(ir,t)),ar=ke.createVertexArray(),ke.bindVertexArray(ar),or=ke.createBuffer(),ke.bindBuffer(ke.ARRAY_BUFFER,or),ke.bufferData(ke.ARRAY_BUFFER,gr,ke.STATIC_DRAW),ke.enableVertexAttribArray(cr.a_corner),ke.vertexAttribPointer(cr.a_corner,2,ke.FLOAT,!1,0,0),sr=ke.createBuffer(),ke.bindBuffer(ke.ARRAY_BUFFER,sr),ke.bufferData(ke.ARRAY_BUFFER,hr.byteLength,ke.DYNAMIC_DRAW),ur=hr.byteLength,ke.enableVertexAttribArray(cr.a_pos),ke.vertexAttribPointer(cr.a_pos,2,ke.FLOAT,!1,20,0),ke.vertexAttribDivisor(cr.a_pos,1),ke.enableVertexAttribArray(cr.a_size),ke.vertexAttribPointer(cr.a_size,1,ke.FLOAT,!1,20,8),ke.vertexAttribDivisor(cr.a_size,1),ke.enableVertexAttribArray(cr.a_angle),ke.vertexAttribPointer(cr.a_angle,1,ke.FLOAT,!1,20,12),ke.vertexAttribDivisor(cr.a_angle,1),ke.enableVertexAttribArray(cr.a_alpha),ke.vertexAttribPointer(cr.a_alpha,1,ke.FLOAT,!1,20,16),ke.vertexAttribDivisor(cr.a_alpha,1),ke.bindVertexArray(null),Be=!0)}();const a=!0!==P.isBrush;P.isBrush=!0,a&&(P.justChanged=!0),P.blend(T.stroke.color),Xr.alpha=["default","spray"].includes(Xr.p.type)?Xr.p.opacity:Xr.p.opacity/Math.min(T.stroke.weight,1.3),Kr()}();const a=function(){const{param:t}=wr.get(T.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(Or*(i?t:1)/a);Xr.pressureCount=10,Xr.cachedPressure=void 0,Xr.lineNoiseCount=5,Xr.cachedLineNoise=void 0;for(let e=0;e<o;e++)Zr.length<2*o&&Zr.push(Q()),$r(),i?Ur.plotTo(Yr,a,a,t,e<10):Ur._moveToDegrees(t,a,a);!function(){Kr(),function(){if(0===tr)return;P.glMask.isDrawn=!0;const t=yr(),e=T.stroke.color._array;ke.useProgram(Ne),ke.enable(ke.BLEND),ke.blendFunc(ke.ONE_MINUS_DST_ALPHA,ke.ONE),ke.bindVertexArray(Le),ke.bindBuffer(ke.ARRAY_BUFFER,De);const r=16*tr,i=Qe.subarray(0,4*tr);r>rr?(ke.bufferData(ke.ARRAY_BUFFER,Qe,ke.DYNAMIC_DRAW),rr=Qe.byteLength):ke.bufferSubData(ke.ARRAY_BUFFER,0,i),ke.uniform4f(Xe.u_color,...e),ke.uniformMatrix4fv(Xe.u_matrix,!1,pr()),ke.drawArrays(ke.POINTS,0,tr),ke.flush(),ke.bindVertexArray(null),br(t),nr&&(P.markDirtyRect(P.glMask,nr),nr=null),tr=0,Fe(n,ke)}();const t=Xr.p?.type;"image"===t?Rr(rn.tips.get(Xr.p.image.src),Xr.p.image.src):"custom"===t&&Rr(rn.tips.get(Xr.p.tipKey),Xr.p.tipKey)}()}function $r(){const t=Hr(),e=((Xr.lineNoiseCount>=10||void 0===Xr.cachedLineNoise)&&(Xr.cachedLineNoise=et(V(Xr.seed+.01*Ur.plotted,0),-1,1,1-Xr.noiseoffset,1+Xr.noiseoffset),Xr.lineNoiseCount=0),Xr.lineNoiseCount++,Xr.cachedLineNoise);if(!(e>W(1,1.02)&&W(0,1)<.7))switch(Xr.p.type){case"spray":!function(t){const e=T.stroke.weight*Xr.p.scatter*t+T.stroke.weight*j(Zr)*Xr.p.scatter/3,r=Xr.p.weight*W(.9,1.1),n=Math.ceil(Xr.p.grain/t);for(let t=0;t<n;t++){const t=W(.9,1.1),n=t*e*W(-1,1),i=W(-1,1),a=Math.sqrt((t*e)**2-n**2);vr(Ur.x+n,Ur.y+i*a,r,Xr.alpha)}}(t*e);break;case"marker":qr(t*e);break;case"custom":case"image":jr(t*e);break;default:!function(t,e=1){const r=(e=et(e,0,1,.9,1.05))*T.stroke.weight*Xr.p.scatter*(Xr.p.sharpness+(1-Xr.p.sharpness)*j(Zr)/t);if(W(0,Xr.p.grain*t)>.4){let e,n;if(Yr){const t=Yr.angle(Ur.plotted),i=ct(t),a=lt(t),o=r*W(-1,1),s=.3*r*W(-1,1);e=o*a+s*i,n=o*i-s*a}else{const t=r*W(-1,1),i=.3*r*W(-1,1);e=t*Xr.sin+i*Xr.cos,n=t*Xr.cos-i*Xr.sin}const i=t*t*Xr.p.weight*W(.85,1.15)*T.stroke.weight,a=Math.max(.9,t)*Xr.alpha*W(.75,1.1);vr(Ur.x+e,Ur.y+n,i,a)}}(t*e)}}function Hr(){return(Xr.pressureCount>=10||void 0===Xr.cachedPressure)&&(Xr.cachedPressure=Yr?Wr()*Yr.pressure(Ur.plotted):Wr(),Xr.pressureCount=0),Xr.pressureCount++,Xr.cachedPressure}function Wr(){return"custom"===Xr.p.pressure.type?et(Xr.p.pressure.curve(Math.max(0,Math.min(1,.5+(Ur.plotted/Or-.5+Xr.ct)*Xr.cs)))+Xr.cp+Xr.ck*(Ur.plotted/Or-.5),0,1,Xr.min,Xr.max,!0):function(t=.5+Xr.p.pressure.curve[0]*Xr.a,e=1-Xr.p.pressure.curve[1]*Xr.b,r=Xr.cp,n=Xr.min,i=Xr.max){const a=t*Or,o=(Ur.plotted<a?1.2*e:.8*e)*(Or/2);return et(1/(1+Math.pow(Math.abs((Ur.plotted-a)/o),2*r)),0,1,n,i)}()}function qr(t,e=!0,r=Xr.alpha){const n=e?T.stroke.weight*Xr.p.scatter:0,i=e?n*W(-1,1):0,a=e?n*W(-1,1):0;vr(Ur.x+i,Ur.y+a,T.stroke.weight*Xr.p.weight*t,r*Math.max(.8,t)*W(.9,1.1))}function jr(t,e=Xr.alpha){const r=T.stroke.weight*Xr.p.scatter,n=r*W(-1,1),i=r*W(-1,1),a=Xr.p.weight*T.stroke.weight*t,o=function(){const t=Math.max(1,Xr.max??1),e=T.stroke.weight*Xr.p.scatter,r=T.stroke.weight*Xr.p.weight*t;return Math.max(8,1.5*e+.75*r)}();let s=0;"random"===Xr.p.rotate?s=K(0,360)*(Math.PI/180):"natural"===Xr.p.rotate&&(s=((Yr?-Yr.angle(Ur.plotted):-zr)+Ur.angle())*(Math.PI/180)),function(t,e,r,n,i,a=0){if(fr>=mr){mr*=2;const t=new Float32Array(5*mr);t.set(hr),hr=t}const o=t-qe,s=e-je,c=Ge*o+Ve*s+He+qe,l=Ze*o+$e*s+We+je,u=Je*r*Ke/2,h=Je*a*Ke,f=5*fr;hr[f]=c,hr[f+1]=l,hr[f+2]=u,hr[f+3]=n,hr[f+4]=i/255;const m=c*Je,d=l*Je,x=1.42*u+h;dr=_r(dr,m-x-1,d-x-1,m+x+1,d+x+1),fr++}(Ur.x+n,Ur.y+i,a,s,e*Math.max(.8,t)*W(.9,1.1),o)}function Kr(){if(!1===Xr.p.markerTip)return;let t=Hr(),e=Xr.alpha;if("marker"===Xr.p.type)for(let r=1;r<10;r++)qr(t*r/10,!0,8*e);else if("custom"===Xr.p.type||"image"===Xr.p.type)for(let r=1;r<5;r++)jr(t*r/10,2*e)}function Jr(t,e,r,n){if(!T.stroke.isActive||!T.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");pt();let i=mt(t,e,r,n);0!=i&&(Gr(t,e,i),Vr(dt(t,e,r,n),!1))}function Qr(t,e,r,n){if(!T.stroke.isActive||!T.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");pt(),Gr(t,e,r),Vr(ut(n),!1)}G(()=>{Zr.length=0});const tn=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],en=[["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]}]],["pastel",[2.05/3,13.4/3,.91,28,35,.085/3,{mode:"gaussian",curve:[.4,.05],min_max:[1.09,.93]},"default",void 0,"natural",!0,1]],["crayon",[.3,5.45/3,.75,250,159,.23/3,[1.1,.9],"default",void 0,"natural",!0,1]],["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 en){let e={};for(let r=0;r<t[1].length;r++)e[tn[r]]=t[1][r];Tr(t[0],e)}fe.prototype.draw=function(t=!1,e,r){let n=Ar();if(t&&Lr(t,e,r),n.isActive)for(let t of this.sides)Jr(t[0].x,t[0].y,t[1].x,t[1].y);Mr(n)},me.prototype.draw=function(t,e,r){Ar().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,n){pt(),Gr(e,r,t.length,t),Vr(n,!0)}(this,t,e,r))};const rn={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=>((t,e)=>Te.loadImageTip(t,e))(t,rn.imageToWhite).then(e=>{this.tips.set(t,e)})))}};function nn(){return{...T.hatch}}function an(t){T.hatch={...t}}function on(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=T.hatch;n.isActive=!0,n.dist=t,n.angle=ht(e),n.options=r}function sn(t,e="black",r=1){T.hatch.hBrush={brush:t,color:e,weight:r}}function cn(){T.hatch.isActive=!1,T.hatch.hBrush=!1}function ln(t,e,r,n){const i=e*Math.PI/180,a=Math.cos(i),o=Math.sin(i),s=Math.cos(-i),c=Math.sin(-i),l=t.a,u=l.length,h=new Array(u);let f=Infinity,m=-Infinity;for(let t=0;t<u;t++){const e=l[t][0],r=l[t][1],n=[e*a-r*o,e*o+r*a];h[t]=n,n[1]<f&&(f=n[1]),n[1]>m&&(m=n[1])}const d=[];for(let t=0;t<u;t++){const e=h[t],r=h[(t+1)%u];e[1]!==r[1]&&d.push(e,r)}const x=d.length,g=[];let p=f+.5*r,y=r;for(;p<m;){const t=[];for(let e=0;e<x;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)g.push({scanY:p,x1:t[e]*s-p*c,y1:t[e]*c+p*s,x2:t[e+1]*s-p*c,y2:t[e+1]*c+p*s});p+=y,y*=n}return g}function un(t){const{dist:e,options:r,segs:n}=function(t){const e=T.hatch.dist,r=(T.hatch.angle%180+180)%180,n=T.hatch.options,i=function(t,e,r,n){Array.isArray(t)||(t=[t]);const i=[];for(const a of t)for(const t of ln(a,r,e,n))i.push(t);return i.sort((t,e)=>t.scanY===e.scanY?t.x1-e.x1:t.scanY-e.scanY),i}(t,e,r,n.gradient?et(n.gradient,0,1,1,1.1,!0):1);return{dist:e,options:n,segs:i}}(t),i=r.rand||0,a=[];for(let t=0;t<n.length;t++){const o=n[t];let s=o.x1,c=o.y1,l=o.x2,u=o.y2;i&&(s+=2*i*e*W(-1,1),c+=2*i*e*W(-1,1),l+=2*i*e*W(-1,1),u+=2*i*e*W(-1,1));const h=r.continuous&&t%2==1?{x1:l,y1:u,x2:s,y2:c,scanY:o.scanY,isConnector:!1}:{x1:s,y1:c,x2:l,y2:u,scanY:o.scanY,isConnector:!1};if(a.push(h),t>0&&r.continuous){const t=a[a.length-2];a.push({x1:t.x2,y1:t.y2,x2:h.x1,y2:h.y1,scanY:o.scanY,isConnector:!0})}}return a}function hn(t){!function(t,e){const r=un(t);!function(){const t=Ar();T.hatch.hBrush&&Lr(...Object.values(T.hatch.hBrush)),(()=>{for(let t=0;t<r.length;t++){const n=r[t];e(n.x1,n.y1,n.x2,n.y2,t,r)}})(),Mr(t)}()}(t,(t,e,r,n)=>{Jr(t,e,r,n)})}function fn(t,e,r={}){T.mass.brush=t,T.mass.color=e,T.mass.options=r,T.mass.isActive=!0}function mn(){T.mass.isActive=!1,T.mass.brush=null,T.mass.color=null,T.mass.options={}}function dn(t,e,r){return new fe(t.vertices.map(t=>[t.x+e,t.y+r]))}function xn(t,e,r,n,i){const a=(e+n)/2,o=(r+i)/2,s=n-e,c=i-r,l=Math.hypot(s,c);if(!l)return null;const u=-c/l,h=s/l,f=(t.x-a)*u+(t.y-o)*h;return{x:a+u*f,y:o+h*f}}function gn(t,e,r,n,i,a,o){let s=dt(t,e,r,n),c=dt(t,e,i,a);return((c-s)%360+360)%360>180&&([s,c]=[c,s]),[o(s),o(c)]}function pn(t){const e=q(.35,.65),r=t.x1+(t.x2-t.x1)*e,n=t.y1+(t.y2-t.y1)*e,i=t.x2-t.x1,a=t.y2-t.y1,o=Math.hypot(i,a)||1,s=q(.04,.1)*o,c=i/o*s*.5,l=a/o*s*.5;return[{x1:t.x1,y1:t.y1,x2:r-c,y2:n-l},{x1:r+c,y1:n+l,x2:t.x2,y2:t.y2}]}function yn(t,e,r){const n=function(t,e){const r=function(t){const e=t?.a??[];let r=Infinity,n=Infinity,i=-Infinity,a=-Infinity;for(const[t,o]of e)t<r&&(r=t),o<n&&(n=o),t>i&&(i=t),o>a&&(a=o);return{minX:r,minY:n,maxX:i,maxY:a,cx:(r+i)/2,cy:(n+a)/2,size:Math.hypot(i-r,a-n)}}(t),n=r.size*q(.6,1.4),[i,a]=e;return{x:r.cx+i*n,y:r.cy+a*n}}(t,e);for(const e of un(t)){const t=!e.isConnector&&q()<.35?pn(e):[e];for(const e of t){const t=xn(n,e.x1,e.y1,e.x2,e.y2);if(!t)continue;const i=mt(t.x,t.y,e.x1,e.y1);if(!i)continue;const[a,o]=gn(t.x,t.y,e.x1,e.y1,e.x2,e.y2,r);pe(t.x,t.y,i,a,o)}}}function bn(t,e,r,n,i,a){on(e,r,n),yn(t,i,a)}function _n(t,e,r,n){const i=function(t,e,r,n){const i=!1===e,a=Pr(T.mass.brush)?.scatter??0,o=i?t:t.genPol(e,r,n,.15),s=Math.min(2*a,5),c=[[q(-s,s),q(-s,s)],[q(-s,s),q(-s,s)]];return[o,dn(o,c[0][0],c[0][1]),dn(o,c[1][0],c[1][1])]}(t,e,r,n),s=nn(),c=Ar(),l={...T.field},u=T.mass.options?.precision??.5,h=T.mass.options?.strength??1,f=T.mass.options?.gradient??.1,m=T.mass.options?.outline??!1,d=Pr(T.mass.brush)?.scatter??0,x=1.6*q(.65*d,.85*d)-.4*f,g=q(-90,90),p=((g+90)%180+180)%180-90>=0?q()<.5?[1,1]:[-1,-1]:q()<.5?[-1,1]:[1,-1],y=a()?t=>t*Math.PI/180:t=>t;Lr(T.mass.brush,T.mass.color,1),It(2-u),m&&i[0].draw(),bn(i[0],.9*x,o(g),{gradient:f,rand:2-2*u,continuous:!0},p,y),h>.33&&bn(i[1],x,o(g+20*q(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),h>.66&&bn(i[2],.8*x,o(g+15*q(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),Mr(c),an(s),T.field={...l}}function vn(t,e,r){const n=2*Math.PI,i=P.ctx,a=r/2;i.moveTo(t+a,e),i.arc(t,e,a,0,n)}T.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},fe.prototype.hatch=function(t=!1,e,r){let n=nn();t&&on(t,e,r),T.hatch.isActive&&hn(this),an(n)},me.prototype.hatch=function(t,e,r){nn().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.3),this.pol.hatch())},T.mass={isActive:!1,brush:null,color:null,options:{}},fe.prototype.mass=function(){T.mass?.isActive&&_n(this,!1)},me.prototype.mass=function(t,e,r){T.mass?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),_n(this,t,e,r))};let Rn=null,wn=!1;wn||(_={ensureResources:function(t,e,r,n,i){const a=Math.max(1,Math.round(e*n)),o=Math.max(1,Math.round(r*n));return function(t,e,r){return!t.mask||t.mask.width!==e||t.mask.height!==r}(t,a,o)&&(t.mask=g(a,o)),function(t,e,r,n){return!t.fillMaskFramebuffer||t.fillMaskFramebuffer.width!==e||t.fillMaskFramebuffer.height!==r||"function"==typeof t.fillMaskFramebuffer.pixelDensity&&t.fillMaskFramebuffer.pixelDensity()!==n}(t,e,r,n)&&(t.fillMaskFramebuffer?.remove&&t.fillMaskFramebuffer.remove(),t.fillMaskFramebuffer=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1}),i(t.fillMaskFramebuffer)),t.mask.dirtyRect??=null,t.mask.isDrawn??=!1,t.mask.drawingContext.imageSmoothingEnabled=!1,{mask:t.mask,ctx:t.mask.drawingContext}},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?i(n(t.dirtyRect,4)):r():null},getShaderMask:function(t,e,r,n,i,a){const o=t.fillMaskFramebuffer,s=t.drawingContext,c=n(r)??i(),l=c.maxX-c.minX,u=c.maxY-c.minY;Rn&&Rn.width===l&&Rn.height===u||(Rn=g(l,u));const h=Rn.drawingContext;return h.clearRect(0,0,l,u),h.drawImage(e,c.minX,c.minY,l,u,0,0,l,u),a(o),s.bindTexture(s.TEXTURE_2D,o.colorTexture),s.texSubImage2D(s.TEXTURE_2D,0,c.minX,c.minY,s.RGBA,s.UNSIGNED_BYTE,Rn),o}},wn=!0),T.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const En=()=>({...T.fill});function An(t,e,r,n){T.fill.opacity=(arguments.length<4?e:n)||150,T.fill.color=arguments.length<3?s(t):s(t,e,r),T.fill.isActive=!0}function Mn(t,e="out"){T.fill.bleed_strength=rt(t,0,1),T.fill.direction=e}function Tn(t=.4,e=.4){T.fill.texture_strength=rt(t,0,1),T.fill.border_strength=rt(e,0,1)}function Sn(){T.fill.isActive=!1}let Pn;const Cn=[[],[]];function Fn(){for(let t=0;t<512;t++)Cn[0][t]=Q(.5,.2),Cn[1][t]=Q(0,.02)}function kn(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}G(Fn);class In{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 c=t[a],l=t[(a+1)%t.length],u={x:l.x-c.x,y:l.y-c.y},h=ft(0,0,u.x,u.y,90),f={x:c.x+u.x/2,y:c.y+u.y/2};i.push({v1:c,v2:l,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=e,this.sizeY=n,this.dir=Array(t.length),i.forEach((t,e)=>{let r=0;for(const e of Pn.intersect(t.ray))kn(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const a=W(-.6,.6)*e,o=W(-.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];const c=r,l=r+e,u=this.v[(c-1+this.v.length)%this.v.length],h=this.v[l%this.v.length],f=h.x-u.x,m=h.y-u.y;for(let t=0;t<2;t++){const e=W(.25,.75),n={x:u.x+f*e,y:u.y+m*e},s=r+t;i.splice(s,0,n),a.splice(s,0,W(.4,.7)),o.splice(s,0,this.dir[c%this.dir.length])}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+W(0,.8*i)));const a=[],o=[],s=[],c=this.midP,l=Pn.sides;for(const t of n){const r=t%e;let n=this.v[r],i=0;for(const[t,e]of l){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:c.x+(n.x-c.x)*W(.3,.6),y:c.y+(n.y-c.y)*W(.3,.6)}),a.push(n),o.push(this.m[r]),s.push(!this.dir[r])}return new In(a,o,this.midP,s,!1,this.sizeX,this.sizeY)}flipDirs(){return new In(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),c=new Array(a),l=new Array(a),u="out"===T.fill.direction?-90:90;0===Cn[0].length&&Fn();const h=Cn[0],f=h.length,m=Cn[1],d=m.length;let x,g,p,y=0,b=0,_=999===t?W(.6,.8):T.fill.bleed_strength;for(let a=0;a<i;a++){const x=e[a],g=e[a+1<i?a+1:0],p=r[a],v=n[a];if(t<997&&(_=p),_<.05){c[y]=p,l[y]=v,y++,o[b]=(x.x+g.x)/2,s[b]=(x.y+g.y)/2,c[y]=p,l[y]=v,y++,b++;continue}const R=(v?u:-u)+5*W(-1,1),w=ct(R),E=lt(R),A=g.x-x.x,M=g.y-x.y,T=w*A+E*M,S=w*M-E*A,P=h[~~(W(0,1)*f)]*W(.65,1.35)*_,C=p+m[~~(W(0,1)*d)];c[y]=p,l[y]=v,y++,o[b]=x.x+.5*A+T*P,s[b]=x.y+.5*M+S*P,c[y]=C,l[y]=v,y++,b++}const v=2024*Math.max(.1,2*T.fill.bleed_strength);if(v&&y>v){const t=Math.ceil(y/v),r=Math.ceil(y/t);x=new Array(r),g=new Array(r),p=new Array(r);let n=0;for(let r=0;r<y;r+=t,n++)x[n]=r%2==0?e[r>>1]:{x:o[r>>1],y:s[r>>1]},g[n]=c[r],p[n]=l[r]}else{x=new Array(y);for(let t=0;t<y;t++)x[t]=t%2==0?e[t>>1]:{x:o[t>>1],y:s[t>>1]};c.length=y,l.length=y,g=c,p=l}return new In(x,g,this.midP,p,!1,this.sizeX,this.sizeY)}fill(t,n,a){const o=3*a,s=2*n*(1+a/2),l=!1!==P.isBrush;P.isBrush=!1,l&&(P.justChanged=!0),P.blend(t);const u=c();P.ctx.save(),P.ctx.setTransform(i*u.a,i*u.b,i*u.c,i*u.d,i*(u.x+e/2),i*(u.y+r/2)),P.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*T.fill.border_strength})`,P.ctx.lineCap="round";const h=Math.max(this.sizeX,this.sizeY),f=W(.15,.7);let m=this.grow();const d=this.scatter(.1).grow().scatter(.75).flipDirs();let x;for(let e=0;e<20;e++){e%4==0&&(m=m.grow()),e%2==0&&(x=[m.grow(1-.0125*e),m.grow(.7-.0125*e),m.grow(.4-.0125*e)]);for(const r of x)r.grow(999).grow(997).layer(e,h,s,t);d.grow(999).flipDirs().grow(997).layer(e,h,s*o,t),e%2==0&&m.grow(f).grow(999).layer(e,h,2*s,t),e%8!=0&&19!==e||(0!==o&&m.erase(3*o,n),P.blend(t,!0))}P.ctx.restore()}layer(t,e,r,n){P.ctx.lineWidth=et(t,0,24,e/25,e/30,!0),P.ctx.fillStyle=`rgb(${n._getRed()} ${n._getGreen()} ${n._getBlue()} / ${r}%)`,function(t){const e=P.ctx,r=e.getTransform(),n=r.a,i=r.b,a=r.c,o=r.d,s=r.e,c=r.f;let l=Infinity,u=Infinity,h=-Infinity,f=-Infinity;e.beginPath();const m=t[0];let d=n*m.x+a*m.y+s,x=i*m.x+o*m.y+c;l=h=d,u=f=x,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,x=i*m.x+o*m.y+c,l=Math.min(l,d),u=Math.min(u,x),h=Math.max(h,d),f=Math.max(f,x),e.lineTo(m.x,m.y)}e.closePath();const g=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);P.markDirtyRect(P.mask,{minX:l-g,minY:u-g,maxX:h+g,maxY:f+g})}(this.v),P.ctx.fill(),P.ctx.stroke()}erase(t,e){P.ctx.save();const r=~~(W(80,110)*et(t,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,a=1.3*Math.min(this.sizeX,this.sizeY),o=.03*a,s=.45*a,{x:c,y:l}=this.midP;P.ctx.globalCompositeOperation="destination-out";const u=(5-et(e,80,100,.3,.7,!0))*t/255;P.ctx.fillStyle=`rgb(255 0 0 / ${u})`,P.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=c+Q(0,n),r=l+Q(0,i),a=W(o,s);P.ctx.beginPath(),vn(e,r,a),t%5!=0&&P.ctx.fill()}P.ctx.globalCompositeOperation="source-over",P.ctx.restore()}}function Ln(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!Zn(n,n.next)&&0!==Gn(n.prev,n,n.next))n=n.next;else{if(Kn(n),n=e=n.prev,n===n.next)break;r=!0}}while(r||n!==e);return e}function Dn(t,e,r,n,i,a,o){if(!t)return;!o&&a&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=Yn(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let a=null;for(e=0;i;){e++;let o=i,s=0;for(let t=0;t<r&&(s++,o=o.nextZ,o);t++);let c=r;for(;s>0||c>0&&o;)0!==s&&(0===c||!o||i.z<=o.z)?(n=i,i=i.nextZ,s--):(n=o,o=o.nextZ,c--),a?a.nextZ=n:t=n,n.prevZ=a,a=n;i=o}a.nextZ=null,r*=2}while(e>1)}(i)}(t,n,i,a);let s=t;for(;t.prev!==t.next;){const c=t.prev,l=t.next;if(a?Bn(t,n,i,a):Nn(t))e.push(c.i,t.i,l.i),Kn(t),t=l.next,s=l.next;else if((t=l)===s){o?1===o?Dn(t=Un(Ln(t),e),e,r,n,i,a,2):2===o&&On(t,e,r,n,i,a):Dn(Ln(t),e,r,n,i,a,1);break}}}function Nn(t){const e=t.prev,r=t,n=t.next;if(Gn(e,r,n)>=0)return!1;const i=e.x,a=r.x,o=n.x,s=e.y,c=r.y,l=n.y,u=Math.min(i,a,o),h=Math.min(s,c,l),f=Math.max(i,a,o),m=Math.max(s,c,l);let d=n.next;for(;d!==e;){if(d.x>=u&&d.x<=f&&d.y>=h&&d.y<=m&&zn(i,s,a,c,o,l,d.x,d.y)&&Gn(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function Bn(t,e,r,n){const i=t.prev,a=t,o=t.next;if(Gn(i,a,o)>=0)return!1;const s=i.x,c=a.x,l=o.x,u=i.y,h=a.y,f=o.y,m=Math.min(s,c,l),d=Math.min(u,h,f),x=Math.max(s,c,l),g=Math.max(u,h,f),p=Yn(m,d,e,r,n),y=Yn(x,g,e,r,n);let b=t.prevZ,_=t.nextZ;for(;b&&b.z>=p&&_&&_.z<=y;){if(b.x>=m&&b.x<=x&&b.y>=d&&b.y<=g&&b!==i&&b!==o&&zn(s,u,c,h,l,f,b.x,b.y)&&Gn(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,_.x>=m&&_.x<=x&&_.y>=d&&_.y<=g&&_!==i&&_!==o&&zn(s,u,c,h,l,f,_.x,_.y)&&Gn(_.prev,_,_.next)>=0)return!1;_=_.nextZ}for(;b&&b.z>=p;){if(b.x>=m&&b.x<=x&&b.y>=d&&b.y<=g&&b!==i&&b!==o&&zn(s,u,c,h,l,f,b.x,b.y)&&Gn(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;_&&_.z<=y;){if(_.x>=m&&_.x<=x&&_.y>=d&&_.y<=g&&_!==i&&_!==o&&zn(s,u,c,h,l,f,_.x,_.y)&&Gn(_.prev,_,_.next)>=0)return!1;_=_.nextZ}return!0}function Un(t,e){let r=t;do{const n=r.prev,i=r.next.next;!Zn(n,i)&&Vn(n,r,r.next,i)&&Wn(n,i)&&Wn(i,n)&&(e.push(n.i,r.i,i.i),Kn(r),Kn(r.next),r=t=i),r=r.next}while(r!==t);return Ln(r)}function On(t,e,r,n,i,a){let o=t;do{let t=o.next.next;for(;t!==o.prev;){if(o.i!==t.i&&Xn(o,t)){let s=qn(o,t);return o=Ln(o,o.next),s=Ln(s,s.next),Dn(o,e,r,n,i,a,0),void Dn(s,e,r,n,i,a,0)}t=t.next}o=o.next}while(o!==t)}function Yn(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function zn(t,e,r,n,i,a,o,s){return!(t===o&&e===s)&&function(t,e,r,n,i,a,o,s){return(i-o)*(e-s)>=(t-o)*(a-s)&&(t-o)*(n-s)>=(r-o)*(e-s)&&(r-o)*(a-s)>=(i-o)*(n-s)}(t,e,r,n,i,a,o,s)}function Xn(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&Vn(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&(Wn(t,e)&&Wn(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)&&(Gn(t.prev,t,e.prev)||Gn(t,e.prev,e))||Zn(t,e)&&Gn(t.prev,t,t.next)>0&&Gn(e.prev,e,e.next)>0)}function Gn(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Zn(t,e){return t.x===e.x&&t.y===e.y}function Vn(t,e,r,n){const i=Hn(Gn(t,e,r)),a=Hn(Gn(t,e,n)),o=Hn(Gn(r,n,t)),s=Hn(Gn(r,n,e));return i!==a&&o!==s||!(0!==i||!$n(t,r,e))||!(0!==a||!$n(t,n,e))||!(0!==o||!$n(r,t,n))||!(0!==s||!$n(r,e,n))}function $n(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function Hn(t){return t>0?1:t<0?-1:0}function Wn(t,e){return Gn(t.prev,t,t.next)<0?Gn(t,e,t.next)>=0&&Gn(t,t.prev,e)>=0:Gn(t,e,t.prev)<0||Gn(t,t.next,e)<0}function qn(t,e){const r=Jn(t.i,t.x,t.y),n=Jn(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function jn(t,e,r,n){const i=Jn(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Kn(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function Jn(t,e,r){return{i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}fe.prototype.fill=function(t=!1,e,r,n,i,a){let o=En();t&&(An(t,e),Mn(r,a),Tn(n,i)),o.isActive&&(pt(),function(t){if(!T.fill.isActive||!T.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Pn=t;const e=[...t.vertices],r=~~(.25*e.length*tt({1:5,2:10,3:60})),n=T.fill.bleed_strength,i=e.map((t,e)=>(e>r?1:.3)*W(.85,1.4)*n),a=K(0,e.length),o=[...e.slice(a),...e.slice(0,a)],s=function(t){if(0===t.length)return{x:0,y:0};if(t.length<8){const e=t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0});return{x:e.x/t.length,y:e.y/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 In(o,i,s,[],!0).fill(T.fill.color,et(T.fill.opacity,0,255,0,1,!0),T.fill.texture_strength)}(this)),(t=>{T.fill={...t}})(o)},me.prototype.fill=function(t,e,r){En().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,T.fill.bleed_strength<.06?0:et(T.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let Qn=null,ti=null,ei=null,ri=null,ni=null,ii=0,ai=0,oi=0;const si={},ci={};function li(t,e,r,n){h(),T.wash.opacity=(arguments.length<4?e:n)??150,T.wash.color=arguments.length<3?s(t):s(t,e,r),T.wash.isActive=!0}function ui(){T.wash.isActive=!1}function hi(t,e){const r=c();return[r.a*t+r.c*e+r.x+ii/2,r.b*t+r.d*e+r.y+ai/2]}function fi(t,e,r){const n=e.isEnabled(e.DEPTH_TEST);return n&&e.disable(e.DEPTH_TEST),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.viewport(0,0,r.width*r.density,r.height*r.density),{hadDepthTest:n}}function mi(t,n,a){a?.hadDepthTest&&n.enable(n.DEPTH_TEST),n.bindFramebuffer(n.FRAMEBUFFER,null),n.viewport(0,0,Math.max(1,Math.round(e*i)),Math.max(1,Math.round(r*i)))}function di(t,e){e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA)}function xi(t,e,r){if(!e)return;if(r(e)){const r=t.drawingContext,n=r.getParameter(r.FRAMEBUFFER_BINDING),i=r.getParameter(r.VIEWPORT);return r.bindFramebuffer(r.FRAMEBUFFER,e.framebuffer),r.viewport(0,0,e.width*e.density,e.height*e.density),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.bindFramebuffer(r.FRAMEBUFFER,n),void r.viewport(i[0],i[1],i[2],i[3])}const n=e.drawingContext;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,e.width,e.height),n.restore()}function gi(t,e,r){return t.shaderProgram??=function(t,e,r){const n=Pe(t,e,r),i=new Map;return{program:n,setUniform(e,r){const a=(e=>(i.has(e)||i.set(e,t.getUniformLocation(n,e)),i.get(e)))(e);a&&("boolean"!=typeof r?"number"!=typeof r?Array.isArray(r)&&(3===r.length?t.uniform3f(a,r[0],r[1],r[2]):4===r.length&&t.uniform4f(a,r[0],r[1],r[2],r[3])):t.uniform1f(a,r):t.uniform1i(a,r?1:0))}}}(t.drawingContext,e,r),t.shaderProgram}function pi(t,e){const r=t.drawingContext,n=e.density??1,i=r.createFramebuffer(),a=Math.max(1,e.width),o=Math.max(1,e.height),s=Math.max(1,Math.round(a*n)),c=Math.max(1,Math.round(o*n)),l=function(t,e,r){const n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,r,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindTexture(t.TEXTURE_2D,null),n}(r,s,c);return r.bindFramebuffer(r.FRAMEBUFFER,i),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,l,0),r.bindFramebuffer(r.FRAMEBUFFER,null),{__brushFramebuffer:!0,framebuffer:i,colorTexture:l,width:a,height:o,density:n,pixelDensity:()=>n,remove(){r.deleteFramebuffer(i),r.deleteTexture(l)}}}function yi(t,e,r,n,i){return e?.remove?.(),pi(t,{width:r,height:n,density:i})}function bi({renderer:t,shader:e,source:r,mask:n,color:i,isBrushMask:a,dirtyRect:o,targetIsFramebuffer:s,withScissor:c}){const l=t.drawingContext,u=l.isEnabled(l.DEPTH_TEST),h=l.getParameter(l.FRAMEBUFFER_BINDING),f=l.getParameter(l.CURRENT_PROGRAM),m=l.getParameter(l.VERTEX_ARRAY_BINDING),d=l.createVertexArray();l.bindVertexArray(d),l.useProgram(e.program),l.disable(l.DEPTH_TEST),l.enable(l.BLEND),l.blendEquation(l.FUNC_ADD),l.blendFunc(l.ONE,l.ONE_MINUS_SRC_ALPHA),l.activeTexture(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,r.colorTexture),l.uniform1i(l.getUniformLocation(e.program,"u_source"),0),l.activeTexture(l.TEXTURE1),l.bindTexture(l.TEXTURE_2D,n.colorTexture),l.uniform1i(l.getUniformLocation(e.program,"u_mask"),1),e.setUniform("u_targetIsFramebuffer",s),e.setUniform("u_isBrush",a),l.uniform3f(l.getUniformLocation(e.program,"u_color"),i[0],i[1],i[2]),l.bindFramebuffer(l.FRAMEBUFFER,null),c(l,o,()=>{l.drawArrays(l.TRIANGLES,0,3)},!s),l.bindTexture(l.TEXTURE_2D,null),l.activeTexture(l.TEXTURE0),l.bindVertexArray(m),l.useProgram(f),l.bindFramebuffer(l.FRAMEBUFFER,h),u&&l.enable(l.DEPTH_TEST),l.deleteVertexArray(d)}function _i(t){return function({renderer:t,sourceFramebuffer:e,dirtyRect:r,getTargetPixelSize:n,toScissorBox:i}){const a=t.drawingContext,{width:o,height:s}=n(),c=r?i(r):null,l=a.getParameter(a.READ_FRAMEBUFFER_BINDING),u=a.getParameter(a.DRAW_FRAMEBUFFER_BINDING);return a.bindFramebuffer(a.READ_FRAMEBUFFER,null),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,e.framebuffer),a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT),a.blitFramebuffer(c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,a.COLOR_BUFFER_BIT,a.NEAREST),a.bindFramebuffer(a.READ_FRAMEBUFFER,l),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,u),e}(t)}function vi(t){if("number"==typeof t){const e=Math.max(0,Math.min(255,t));return`rgb(${e} ${e} ${e})`}return t??"black"}function Ri(t){const e=((t,e=!1)=>(t.drawingContext??=t.getContext("2d",e?{willReadFrequently:!0}:void 0),t.drawingContext))(t,!0),r={canvas:t,drawingContext:e,width:t.width,height:t.height,pixels:null,_fillStyle:"#ffffff",_strokeStyle:"transparent",_lineWidth:1,pixelDensity:()=>1,background(r){e.save(),e.setTransform(1,0,0,1,0,0),e.fillStyle=vi(r),e.fillRect(0,0,t.width,t.height),e.restore()},noSmooth(){e.imageSmoothingEnabled=!1},push(){e.save()},pop(){e.restore()},translate(t,r){e.translate(t,r)},scale(t,r=t){e.scale(t,r)},rotate(t){e.rotate(t)},noStroke(){r._strokeStyle="transparent"},stroke(t){r._strokeStyle=vi(t)},noFill(){r._fillStyle="transparent"},fill(t){r._fillStyle=vi(t)},strokeWeight(t){r._lineWidth=t},rect(t,n,i,a){e.beginPath(),e.rect(t,n,i,a),r._paint()},circle(t,n,i){e.beginPath(),e.arc(t,n,i/2,0,2*Math.PI),r._paint()},ellipse(t,n,i,a){e.beginPath(),e.ellipse(t,n,i/2,a/2,0,0,2*Math.PI),r._paint()},line(t,n,i,a){e.beginPath(),e.moveTo(t,n),e.lineTo(i,a),e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke()},beginShape(){e.beginPath(),r._shapeStarted=!1},vertex(t,n){r._shapeStarted?e.lineTo(t,n):(e.moveTo(t,n),r._shapeStarted=!0)},endShape(t=!1){t&&e.closePath(),r._paint()},loadPixels(){r.pixels=e.getImageData(0,0,t.width,t.height).data},updatePixels(){const n=e.getImageData(0,0,t.width,t.height);n.data.set(r.pixels),e.putImageData(n,0,0)},_paint(){"transparent"!==r._fillStyle&&(e.fillStyle=r._fillStyle,e.fill()),"transparent"!==r._strokeStyle&&(e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke())}};return r}function wi(t,e){return Ri(g(t,e,!0))}function Ei(t,e){return new Promise((r,n)=>{const i=globalThis.Image;if(!i)return void n(new Error("Standalone image brush loading requires Image support."));const a=new i;a.onload=()=>{const t=Ri(g(a.naturalWidth,a.naturalHeight,!0));t.drawingContext.drawImage(a,0,0),e(t),r(t)},a.onerror=()=>n(new Error(`Failed to load image tip: ${t}`)),a.crossOrigin="anonymous",a.src=t})}var Ai;T.wash={color:null,opacity:150,isActive:!1},fe.prototype.wash=function(t=!1,i){const a={...T.wash};!1!==t&&li(t,i),T.wash.isActive&&function(t){if(!T.wash?.isActive||!T.wash.color||t.vertices.length<3)return;C(),function(){const t=n.drawingContext;ni&&!(ii!==e||ai!==r)||(ii=e,ai=r,ni=new Float32Array([2/ii,0,0,0,0,-2/ai,0,0,0,0,1,0,-1,1,0,1])),Qn===t&&ti&&ei&&ri||(Qn=t,ti=Pe(Qn,"#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}","#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}"),si.a_position=Qn.getAttribLocation(ti,"a_position"),ci.u_matrix=Qn.getUniformLocation(ti,"u_matrix"),ci.u_color=Qn.getUniformLocation(ti,"u_color"),ei=Qn.createVertexArray(),Qn.bindVertexArray(ei),ri=Qn.createBuffer(),Qn.bindBuffer(Qn.ARRAY_BUFFER,ri),Qn.bufferData(Qn.ARRAY_BUFFER,0,Qn.DYNAMIC_DRAW),oi=0,Qn.enableVertexAttribArray(si.a_position),Qn.vertexAttribPointer(si.a_position,2,Qn.FLOAT,!1,8,0),Qn.bindVertexArray(null),Qn.bindBuffer(Qn.ARRAY_BUFFER,null))}();const{triangles:i,vertexCount:a}=function(t){const e=new Float32Array(2*t.vertices.length);for(let r=0;r<t.vertices.length;r++){const n=t.vertices[r];e[2*r]=n.x,e[2*r+1]=n.y}const r=function(t,e,r=2){const n=t.length;let i=function(t,e,r,n){let i;if(1==function(t,e,r,n){let i=0;for(let e=0,a=r-n;e<r;e+=n)i+=(t[a]-t[e])*(t[e+1]+t[a+1]),a=e;return i}(t,0,r,n)>0)for(let e=0;e<r;e+=n)i=jn(e/n|0,t[e],t[e+1],i);else for(let e=r-n;e>=0;e-=n)i=jn(e/n|0,t[e],t[e+1],i);return i&&Zn(i,i.next)&&(Kn(i),i=i.next),i}(t,0,n,r);const a=[];if(!i||i.next===i.prev)return a;let o,s,c;if(t.length>80*r){o=t[0],s=t[1];let e=o,i=s;for(let a=r;a<n;a+=r){const r=t[a],n=t[a+1];r<o&&(o=r),n<s&&(s=n),r>e&&(e=r),n>i&&(i=n)}c=Math.max(e-o,i-s),c=0!==c?32767/c:0}return Dn(i,a,r,o,s,c,0),a}(e),n=new Float32Array(2*r.length);for(let t=0;t<r.length;t++){const i=r[t],[a,o]=hi(e[2*i],e[2*i+1]);n[2*t]=a,n[2*t+1]=o}return{triangles:n,vertexCount:r.length}}(t),o=i.byteLength;Qn.useProgram(ti),Qn.enable(Qn.BLEND),Qn.blendEquation(Qn.FUNC_ADD),Qn.blendFunc(Qn.ONE,Qn.ONE_MINUS_SRC_ALPHA),Qn.bindVertexArray(ei),Qn.bindBuffer(Qn.ARRAY_BUFFER,ri),o>oi?(Qn.bufferData(Qn.ARRAY_BUFFER,i,Qn.DYNAMIC_DRAW),oi=o):Qn.bufferSubData(Qn.ARRAY_BUFFER,0,i);const s=T.wash.color._array;Qn.uniformMatrix4fv(ci.u_matrix,!1,ni),Qn.uniform4f(ci.u_color,s[0],s[1],s[2],T.wash.opacity/255),Qn.drawArrays(Qn.TRIANGLES,0,a),Qn.bindVertexArray(null),Qn.bindBuffer(Qn.ARRAY_BUFFER,null),Fe(n,Qn)}(this),T.wash={...a}},me.prototype.wash=function(t,e,r){T.wash?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,0,-1),this.pol.wash())},Ai={load:function(t=ae){if(!function(t){return function(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement}(t)||function(t){return"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas}(t)}(t))throw new Error("Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.");ue(t,t.width,t.height,1)},syncDensity:function(){return u({Cwidth:ce,Cheight:le,Density:se}),se},isCanvasReady:function(){if(!oe)throw new Error("No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.")},instance:function(){},activateInstance:function(){},deactivateInstance:function(){},getActiveFramebuffer:function(){return null},isFramebufferTarget:function(){return!0===arguments[0]?.__brushFramebuffer}},l={...l,...Ai},Jt(),function(){var t;t={beginDirectMaskDraw:fi,endDirectMaskDraw:mi,resetDirectShaderTracking:di},Ce={...Ce,...t}}(),function(){var t;t={clearTarget:xi,ensureBlendShaderProgram:gi,ensureBlendSourceFramebuffer:yi,createFramebuffer:pi,runBlendShaderPass:bi,blitSourceToFramebuffer:_i},p={...p,...t}}(),function(){var t;t={createTipSurface:wi,loadImageTip:Ei},Te={...Te,...t}}();export{Zt as Color,Bt as DEGREES,me as Plot,fe as Polygon,yt as Position,Ut as RADIANS,Tr as add,Ft as addField,Vt as angleMode,pe as arc,be as beginShape,Re as beginStroke,Sr as box,ge as circle,te as clear,Nr as clip,he as createCanvas,ve as endShape,Ee as endStroke,Pt as field,An as fill,Mn as fillBleed,Tn as fillTexture,Qr as flowLine,$t as getAngleMode,on as hatch,hn as hatchArray,sn as hatchStyle,Jt as initStandaloneRuntime,f as instance,Jr as line,kt as listFields,F as load,fn as mass,we as move,Br as noClip,Ct as noField,Sn as noFill,cn as noHatch,mn as noMass,Dr as noStroke,ui as noWash,H as noiseSeed,Fr as pick,de as polygon,Wt as pop,Ht as push,xe as rect,St as refreshField,Qt as render,jt as rotate,Kt as scale,Cr as scaleBrushes,Z as seed,Lr as set,Ae as spline,kr as stroke,Ir as strokeWeight,qt as translate,_e as vertex,tt as wRand,li as wash,It as wiggle};
//# sourceMappingURL=brush.esm.js.map
diff --git a/dist/brush.esm.js.map b/dist/brush.esm.js.map
index e2e24c0..babe991 100644
--- a/dist/brush.esm.js.map
+++ b/dist/brush.esm.js.map
@@ -1 +1 @@
-{"version":3,"file":"brush.esm.js","sources":["../src/core/runtime.js","../src/core/target.js","../src/core/dirty_rect.js","../src/core/compositor_runtime.js","../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/save.js","../src/adapters/standalone/runtime.js","../src/adapters/standalone/frame.js","../src/adapters/standalone/target.js","../src/core/primitives.js","../src/core/polygon.js","../src/core/plot.js","../src/stroke/runtime.js","../src/stroke/composite.js","../src/core/gl/utils.js","../src/core/renderer_runtime.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/hatch/mass.js","../src/fill/mask.js","../src/fill/composite.js","../src/fill/fill.js","../node_modules/earcut/src/earcut.js","../src/fill/wash.js","../src/adapters/standalone/renderer.js","../src/adapters/standalone/compositor.js","../src/adapters/standalone/stroke.js","../src/index.standalone.js"],"sourcesContent":["// =============================================================================\n// Runtime Hooks\n// =============================================================================\n\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nexport let usesRadians = () => false;\nexport let fromDegrees = (angle) => angle;\nexport let createColor = () => {\n throw new Error(\"No runtime color adapter registered.\");\n};\nexport let getAffineMatrix = () => identityMatrix;\n\n/**\n * Registers or updates host-runtime hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setRuntime(hooks) {\n if (hooks.usesRadians) usesRadians = hooks.usesRadians;\n if (hooks.fromDegrees) fromDegrees = hooks.fromDegrees;\n if (hooks.createColor) createColor = hooks.createColor;\n if (hooks.getAffineMatrix) getAffineMatrix = hooks.getAffineMatrix;\n}\n","// =============================================================================\n// Target Runtime Hooks\n// =============================================================================\n\n/**\n * Shared target state exposed to core modules.\n *\n * Host adapters are expected to keep these bindings updated with the currently\n * active drawing target. The exact object type is adapter-defined, but core code\n * assumes the active renderer exposes:\n * - `drawingContext`: the active WebGL context\n * - target dimensions through `Cwidth` / `Cheight`\n * - pixel density through `Density`\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\n\nlet targetRuntime = {\n load: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n syncDensity: () => Density,\n isCanvasReady: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n instance: (inst) => {\n Instance = inst;\n },\n activateInstance: (inst) => {\n Instance = inst;\n },\n deactivateInstance: () => {},\n getActiveFramebuffer: () => null,\n isFramebufferTarget: () => false,\n};\n\n/**\n * Updates the shared target state consumed by core modules.\n *\n * @param {object} state\n */\nexport function setTargetState(state) {\n if (\"Cwidth\" in state) Cwidth = state.Cwidth;\n if (\"Cheight\" in state) Cheight = state.Cheight;\n if (\"Instance\" in state) Instance = state.Instance;\n if (\"Renderer\" in state) Renderer = state.Renderer;\n if (\"Density\" in state) Density = state.Density;\n}\n\n/**\n * Registers or updates host target hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setTargetRuntime(hooks) {\n targetRuntime = { ...targetRuntime, ...hooks };\n}\n\nexport const load = (buffer = false) => targetRuntime.load(buffer);\nexport const syncDensity = () => targetRuntime.syncDensity();\nexport const isCanvasReady = () => targetRuntime.isCanvasReady();\nexport const instance = (inst) => targetRuntime.instance(inst);\nexport const activateInstance = (inst) => targetRuntime.activateInstance(inst);\nexport const deactivateInstance = () => targetRuntime.deactivateInstance();\nexport const getActiveFramebuffer = () => targetRuntime.getActiveFramebuffer();\nexport const isFramebufferTarget = (target) =>\n targetRuntime.isFramebufferTarget(target);\n","// =============================================================================\n// Module: Dirty Rect Utilities\n// =============================================================================\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n *\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 */\nexport const 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 explicit target bounds.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nexport const normalizeDirtyRect = (rect, width, height) => {\n if (!rect) return null;\n\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 *\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 */\nexport const 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 target bounds.\n *\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nexport const getFullDirtyRect = (width, height) => ({\n minX: 0,\n minY: 0,\n maxX: width,\n maxY: height,\n});\n","// =============================================================================\n// Compositor Runtime Hooks\n// =============================================================================\n\n/**\n * Shared compositor helpers and host hooks.\n *\n * The shared code in this module assumes framebuffer-like targets expose:\n * - `framebuffer`: native WebGL framebuffer handle\n * - optional lifecycle methods supplied by the host adapter\n *\n * Higher-level core modules also attach their own bookkeeping fields onto the\n * active renderer and mask targets, such as:\n * - `shaderProgram`\n * - `blendSourceFramebuffer`\n * - `glMask`\n * - `fillMaskFramebuffer`\n * - `mask`\n *\n * These are library-level contract fields, not host-specific internals.\n */\n\nexport const create2DCanvas = (width, height, willReadFrequently = false) => {\n const canvas =\n typeof OffscreenCanvas !== \"undefined\"\n ? new OffscreenCanvas(width, height)\n : (() => {\n const element = document.createElement(\"canvas\");\n element.width = width;\n element.height = height;\n return element;\n })();\n canvas.drawingContext = canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas;\n};\n\nexport const get2DContext = (canvas, willReadFrequently = false) => {\n canvas.drawingContext ??= canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas.drawingContext;\n};\n\nexport function blitDefaultFramebufferSource({\n renderer,\n sourceFramebuffer,\n dirtyRect,\n getTargetPixelSize,\n toScissorBox,\n}) {\n const gl = renderer.drawingContext;\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 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\nlet compositorRuntime = {\n clearTarget: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendShaderProgram: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendSourceFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n createFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n runBlendShaderPass: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n blitSourceToFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host compositor hooks used by core compositing code.\n *\n * @param {object} hooks\n */\nexport function setCompositorRuntime(hooks) {\n compositorRuntime = { ...compositorRuntime, ...hooks };\n}\n\nexport const clearTarget = (...args) => compositorRuntime.clearTarget(...args);\nexport const ensureBlendShaderProgram = (...args) =>\n compositorRuntime.ensureBlendShaderProgram(...args);\nexport const ensureBlendSourceFramebuffer = (...args) =>\n compositorRuntime.ensureBlendSourceFramebuffer(...args);\nexport const createFramebuffer = (...args) =>\n compositorRuntime.createFramebuffer(...args);\nexport const runBlendShaderPass = (...args) =>\n compositorRuntime.runBlendShaderPass(...args);\nexport const blitSourceToFramebuffer = (...args) =>\n compositorRuntime.blitSourceToFramebuffer(...args);\n","import {\n Cwidth,\n Cheight,\n Renderer,\n Density,\n load as loadTarget,\n isCanvasReady,\n syncDensity,\n getActiveFramebuffer,\n isFramebufferTarget,\n} from \"./target.js\";\nimport {\n expandDirtyRect,\n normalizeDirtyRect as clampDirtyRect,\n unionDirtyRect,\n getFullDirtyRect as getFullRect,\n} from \"./dirty_rect.js\";\nimport {\n clearTarget as clearRenderTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n} from \"./compositor_runtime.js\";\n\nimport 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\nlet strokeComposite = null;\nlet fillComposite = null;\n\nexport const registerStrokeComposite = (composite) => {\n strokeComposite = composite;\n};\n\nexport const registerFillComposite = (composite) => {\n fillComposite = composite;\n};\n\nconst clearTarget = (target) => {\n clearRenderTarget(Renderer, target, isFramebufferTarget);\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\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\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n const { width, height } = getTargetPixelSize();\n return clampDirtyRect(rect, width, height);\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 getFullRect(width, 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 * 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/**\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: null,\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 const composite = target === this.glMask ? strokeComposite : fillComposite;\n composite?.clearMask?.(target, clearTarget);\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 GL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n const composite = isBrushMask ? strokeComposite : fillComposite;\n return composite?.getCompositeRect?.(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\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 syncDensity();\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 ensureBlendShaderProgram(Renderer, vertSrc, fragSrc);\n\n this.glMask = strokeComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n );\n const fillResources = fillComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n ) ?? {\n mask: null,\n ctx: null,\n };\n\n if (needsBlendSourceFramebuffer) {\n Renderer.blendSourceFramebuffer = ensureBlendSourceFramebuffer(\n Renderer,\n Renderer.blendSourceFramebuffer,\n Cwidth,\n Cheight,\n Density,\n );\n }\n\n this.mask = fillResources.mask;\n this.ctx = fillResources.ctx;\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 // 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 fully at the start of each blend cycle so stale\n // dirty-rect bookkeeping cannot leak an old stroke into the next color.\n this.clearMask(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) {\n this.isBlending = false;\n this.cachedColor = null;\n \n }\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 GL 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 = blitSourceToFramebuffer({\n renderer: Renderer,\n sourceTarget: activeFramebuffer ?? Renderer,\n sourceFramebuffer: Renderer.blendSourceFramebuffer,\n dirtyRect,\n isFramebufferTarget,\n Cwidth,\n Cheight,\n getTargetPixelSize,\n toScissorBox,\n withScissor,\n });\n const targetIsFramebuffer = !!activeFramebuffer;\n const composite = isBrushMask ? strokeComposite : fillComposite;\n const shaderMask = composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n );\n\n runBlendShaderPass({\n renderer: Renderer,\n shader,\n source,\n mask: shaderMask,\n color: this.cachedColor,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n });\n this.clearMask(mask);\n },\n};\n\n/**\n * Flushes any pending stroke/fill mask work into the current target and resets\n * the shared compositor back to its initial idle state.\n */\nexport const flushActiveComposite = () => {\n isMixReady();\n Mix.blend(false, true);\n Mix.clearMask(Mix.glMask);\n Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n};\n\n/**\n * Loads and initializes the drawing target, then refreshes compositing\n * resources if the renderer was already active.\n *\n * @param {object|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\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 { usesRadians as runtimeUsesRadians } from \"./runtime.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());\nlet rng2 = 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 rng2 = prng_alea(`${s}:2`);\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()));\nexport let noise2 = 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 noise2 = createNoise2D(prng_alea(`${s}:2`));\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);\nexport const rr2 = (e = 0, r = 1) => e + rng2() * (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);\nexport const randInt2 = (e, r) => ~~rr2(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 if (isRad || runtimeUsesRadians()) {\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 || runtimeUsesRadians()\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 { Cwidth, Cheight } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\nimport { getAffineMatrix } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Matrix transformations\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 const m = getAffineMatrix();\n this.mx = m.x;\n this.my = m.y;\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 = Math.round((x + this.mx - left_x) / resolution);\n this.rowIdx = Math.round((y + this.my - top_y) / resolution);\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 + this.mx;\n const y = this.y + this.my;\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(skipCheck = false) {\n if (!State.field.isActive) return 0;\n return (skipCheck || this.isIn())\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 runtime angle units.\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 const steps = _length / _step;\n const fieldActive = State.field.isActive;\n const usePlot = !!_scale;\n for (let i = 0; i < steps; i++) {\n const angle =\n (fieldActive ? this.angle(true) : 0) - (usePlot ? _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 + getAffineMatrix().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 + getAffineMatrix().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 = rr2(0.2, 0.8),\n ba = randInt2(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt2(15, 25));\n return 0.2 * angle * cos(t) + noise2(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt2(-10, 10);\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise2(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 = randInt2(-30, -15) + Math.abs(44 * sin(t));\n if (randInt2(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 = randInt2(10, 15) + 5 * sin(t),\n cr = randInt2(3, 6) + 3 * cos(t),\n ba = randInt2(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt2(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr2(0.4, 0.8),\n ba = randInt2(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt2(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt2(5, 10);\n const dir = randInt2(0, 2) * 2 - 1;\n const offset = randInt2(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr2(0.1, 0.9) * num_columns,\n y: rr2(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 = randInt2(3, 8),\n amp = randInt2(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\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 wash: State.wash ? { ...State.wash } : null,\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n mass: State.mass ? { ...State.mass } : null,\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 if (saved.wash) State.wash = { ...saved.wash };\n if (saved.mass) {\n State.mass = { ...saved.mass };\n } else if (State.mass) {\n State.mass = {\n ...State.mass,\n isActive: false,\n brush: null,\n color: null,\n options: {},\n };\n }\n}\n","// =============================================================================\n// Adapter: Standalone Runtime Hooks\n// =============================================================================\n\nimport { setRuntime } from \"../../core/runtime.js\";\nimport { push as pushState, pop as popState } from \"../../core/save.js\";\n\nconst clamp = (value, min, max) => Math.max(min, Math.min(value, max));\n\nexport const DEGREES = \"degrees\";\nexport const RADIANS = \"radians\";\n\nlet colorContext = null;\nlet currentAngleMode = DEGREES;\nconst transformStack = [];\nlet currentTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nfunction getColorContext() {\n if (colorContext) return colorContext;\n\n if (typeof document !== \"undefined\") {\n colorContext = document.createElement(\"canvas\").getContext(\"2d\");\n return colorContext;\n }\n\n if (typeof OffscreenCanvas !== \"undefined\") {\n colorContext = new OffscreenCanvas(1, 1).getContext(\"2d\");\n return colorContext;\n }\n\n throw new Error(\"Standalone color parsing requires CanvasRenderingContext2D support.\");\n}\n\nfunction multiplyTransform(left, right) {\n return {\n a: left.a * right.a + left.c * right.b,\n b: left.b * right.a + left.d * right.b,\n c: left.a * right.c + left.c * right.d,\n d: left.b * right.c + left.d * right.d,\n x: left.a * right.x + left.c * right.y + left.x,\n y: left.b * right.x + left.d * right.y + left.y,\n };\n}\n\n/**\n * Runtime-native color object compatible with the expectations of core modules.\n */\nexport class Color {\n constructor(r, g, b) {\n if (r?._array) {\n this.r = Math.round(r._array[0] * 255);\n this.g = Math.round(r._array[1] * 255);\n this.b = Math.round(r._array[2] * 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n this._array = [...r._array];\n this.gl = this._array;\n return;\n }\n\n if (typeof r === \"string\") {\n this.hex = this.standardize(r);\n const rgb = this.hexToRgb(this.hex);\n this.r = rgb.r;\n this.g = rgb.g;\n this.b = rgb.b;\n } else {\n this.r = clamp(r ?? 0, 0, 255);\n this.g = clamp(g ?? r ?? 0, 0, 255);\n this.b = clamp(b ?? r ?? 0, 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n }\n\n this._array = [this.r / 255, this.g / 255, this.b / 255, 1];\n this.gl = this._array;\n }\n\n rgbToHex(r, g, b) {\n return `#${((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1)}`;\n }\n\n hexToRgb(hex) {\n hex = hex.replace(\n /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i,\n (_match, red, green, blue) => red + red + green + green + blue + blue,\n );\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n if (!result) {\n throw new Error(`Invalid color value \"${hex}\".`);\n }\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n };\n }\n\n standardize(value) {\n const ctx = getColorContext();\n ctx.fillStyle = value;\n return ctx.fillStyle;\n }\n\n _getRed() {\n return this.r;\n }\n\n _getGreen() {\n return this.g;\n }\n\n _getBlue() {\n return this.b;\n }\n}\n\n/**\n * Sets the active standalone angle mode.\n *\n * @param {\"degrees\"|\"radians\"} mode\n */\nexport function angleMode(mode) {\n if (mode !== DEGREES && mode !== RADIANS) {\n throw new Error(`Invalid angle mode \"${mode}\". Use \"degrees\" or \"radians\".`);\n }\n currentAngleMode = mode;\n}\n\n/**\n * Returns the current standalone angle mode.\n *\n * @returns {\"degrees\"|\"radians\"}\n */\nexport function getAngleMode() {\n return currentAngleMode;\n}\n\n/**\n * Pushes the current standalone transform onto the stack.\n */\nexport function push() {\n pushState();\n transformStack.push({ ...currentTransform });\n}\n\n/**\n * Pops the last standalone transform from the stack.\n */\nexport function pop() {\n if (transformStack.length === 0) return;\n currentTransform = transformStack.pop();\n popState();\n}\n\n/**\n * Applies a translation to the current standalone transform.\n *\n * @param {number} x\n * @param {number} y\n */\nexport function translate(x, y) {\n currentTransform = multiplyTransform(currentTransform, {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x,\n y,\n });\n}\n\n/**\n * Applies a rotation to the current standalone transform.\n *\n * @param {number} angle\n */\nexport function rotate(angle) {\n const theta =\n currentAngleMode === RADIANS ? angle : (angle * Math.PI) / 180;\n const cosTheta = Math.cos(theta);\n const sinTheta = Math.sin(theta);\n currentTransform = multiplyTransform(currentTransform, {\n a: cosTheta,\n b: sinTheta,\n c: -sinTheta,\n d: cosTheta,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Applies a scale to the current standalone transform.\n *\n * @param {number} x\n * @param {number} [y=x]\n */\nexport function scale(x, y = x) {\n currentTransform = multiplyTransform(currentTransform, {\n a: x,\n b: 0,\n c: 0,\n d: y,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Installs the standalone runtime hooks used by core modules.\n */\nexport function initStandaloneRuntime() {\n setRuntime({\n usesRadians: () => currentAngleMode === \"radians\",\n fromDegrees: (angle) =>\n currentAngleMode === \"radians\" ? (angle * Math.PI) / 180 : angle,\n createColor: (...args) => {\n if (args.length === 1 && args[0]?._array) return args[0];\n return new Color(...args);\n },\n getAffineMatrix: () => currentTransform,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Frame Helpers\n// =============================================================================\n\nimport { Renderer, isCanvasReady } from \"../../core/target.js\";\nimport { Mix, flushActiveComposite } from \"../../core/color.js\";\nimport { createColor } from \"../../core/runtime.js\";\n\nfunction resetCompositeState() {\n if (Mix.glMask) Mix.clearMask(Mix.glMask);\n if (Mix.mask) Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n}\n\n/**\n * Flushes any pending stroke/fill compositing into the active standalone target.\n *\n * Standalone users should call this at the end of a drawing pass or frame.\n */\nexport function render() {\n flushActiveComposite();\n}\n\n/**\n * Clears the active standalone target.\n *\n * With no arguments, clears to transparent white.\n * With a color, clears to that color at full opacity.\n *\n * @param {...*} args\n */\nexport function clear(...args) {\n isCanvasReady();\n resetCompositeState();\n\n const gl = Renderer.drawingContext;\n const color =\n args.length === 0\n ? [1, 1, 1, 0]\n : [...createColor(...args)._array.slice(0, 3), 1];\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.disable(gl.SCISSOR_TEST);\n gl.clearColor(color[0], color[1], color[2], color[3]);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n}\n","// =============================================================================\n// Adapter: Standalone Target Hooks\n// =============================================================================\n\nimport {\n setTargetRuntime,\n setTargetState,\n} from \"../../core/target.js\";\n\nlet activeTarget = null;\nlet isLoaded = false;\nlet activeDensity = 1;\nlet activeWidth = 0;\nlet activeHeight = 0;\n\nfunction isCanvasTarget(target) {\n return (\n typeof HTMLCanvasElement !== \"undefined\" &&\n target instanceof HTMLCanvasElement\n );\n}\n\nfunction isOffscreenCanvasTarget(target) {\n return (\n typeof OffscreenCanvas !== \"undefined\" &&\n target instanceof OffscreenCanvas\n );\n}\n\nfunction isSupportedTarget(target) {\n return isCanvasTarget(target) || isOffscreenCanvasTarget(target);\n}\n\nfunction getTargetContext(target) {\n return (\n target.getContext(\"webgl2\", { premultipliedAlpha: true }) ??\n target.getContext(\"webgl2\")\n );\n}\n\nfunction createRenderer(target, width, height, density) {\n const drawingContext = getTargetContext(target);\n if (!drawingContext) {\n throw new Error(\"brush.load(target) requires a canvas with a WebGL2 context.\");\n }\n\n return {\n canvas: target,\n drawingContext,\n width,\n height,\n pixelDensity: () => density,\n };\n}\n\nfunction applyLoadedTarget(target, width, height, density) {\n activeTarget = target;\n activeWidth = width;\n activeHeight = height;\n activeDensity = density;\n\n const renderer = createRenderer(target, width, height, density);\n setTargetState({\n Renderer: renderer,\n Cwidth: width,\n Cheight: height,\n Density: density,\n });\n isLoaded = true;\n}\n\n/**\n * Loads a standalone draw target from a DOM canvas or OffscreenCanvas.\n *\n * @param {HTMLCanvasElement|OffscreenCanvas} target\n */\nexport function load(target = activeTarget) {\n if (!isSupportedTarget(target)) {\n throw new Error(\n \"Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.\",\n );\n }\n\n applyLoadedTarget(target, target.width, target.height, 1);\n}\n\n/**\n * Creates a standalone DOM canvas, configures its backing resolution according\n * to the provided pixel density, appends it optionally to the DOM, and loads it\n * as the active brush target.\n *\n * @param {number} width Logical canvas width.\n * @param {number} height Logical canvas height.\n * @param {{pixelDensity?: number, parent?: string|Element|null, id?: string}} [options]\n * @returns {HTMLCanvasElement}\n */\nexport function createCanvas(width, height, options = {}) {\n if (typeof document === \"undefined\") {\n throw new Error(\"brush.createCanvas() requires a browser document.\");\n }\n\n const logicalWidth = Math.max(1, Math.round(width));\n const logicalHeight = Math.max(1, Math.round(height));\n const density = Math.max(1, Number(options.pixelDensity) || 1);\n const canvas = document.createElement(\"canvas\");\n\n canvas.width = Math.max(1, Math.round(logicalWidth * density));\n canvas.height = Math.max(1, Math.round(logicalHeight * density));\n canvas.style.width = `${logicalWidth}px`;\n canvas.style.height = `${logicalHeight}px`;\n if (options.id) canvas.id = options.id;\n\n if (options.parent) {\n const parent =\n typeof options.parent === \"string\"\n ? document.querySelector(options.parent)\n : options.parent;\n if (!parent) {\n throw new Error(`Could not find parent \"${options.parent}\" for brush.createCanvas().`);\n }\n parent.appendChild(canvas);\n }\n\n applyLoadedTarget(canvas, logicalWidth, logicalHeight, density);\n return canvas;\n}\n\n/**\n * Refreshes the standalone target density.\n *\n * Standalone targets currently use a fixed density of 1.\n *\n * @returns {number}\n */\nexport function syncDensity() {\n setTargetState({\n Cwidth: activeWidth,\n Cheight: activeHeight,\n Density: activeDensity,\n });\n return activeDensity;\n}\n\n/**\n * Ensures a standalone target has been loaded.\n */\nexport function isCanvasReady() {\n if (!isLoaded) {\n throw new Error(\n \"No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.\",\n );\n }\n}\n\n/**\n * Standalone build does not use p5 instance switching, so these are no-ops.\n */\nexport function instance() {}\nexport function activateInstance() {}\nexport function deactivateInstance() {}\n\n/**\n * Standalone build does not yet support framebuffer targets.\n *\n * @returns {null}\n */\nexport function getActiveFramebuffer() {\n return null;\n}\n\n/**\n * Returns whether the given target behaves like a framebuffer target.\n *\n * Standalone targets currently only accept canvases and offscreen canvases.\n *\n * @returns {boolean}\n */\nexport function isFramebufferTarget() {\n return arguments[0]?.__brushFramebuffer === true;\n}\n\nexport function initStandaloneTargetRuntime() {\n setTargetRuntime({\n load,\n syncDensity,\n isCanvasReady,\n instance,\n activateInstance,\n deactivateInstance,\n getActiveFramebuffer,\n isFramebufferTarget,\n });\n}\n","import {\n rr2,\n randInt2,\n sin,\n cos,\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 * Polygons ignore fields and won't be good for fills and masses\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 = rr2(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr2() : () => 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 * randInt2(-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 runtime angle units.\n * @param {number} end - End angle in the current runtime angle units.\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","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.wash) this.wash();\n if (State.fill) this.fill();\n if (State.mass) this.mass();\n if (State.hatch) this.hatch();\n if (State.stroke) this.draw();\n }\n}","import { Cwidth, Cheight } from \"./target.js\";\nimport { State } from \"./color.js\";\nimport { toDegrees, map, rr2 } 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 = _side < 0 ? 4 : 1;\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 let maxSize = _side <= 0 ? 8 : Math.max(this.segments[idx] * _side * rr2(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.wash) this.wash(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n if (State.mass) this.mass(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.stroke) this.draw(x, y, scale);\n }\n}\n","// =============================================================================\n// Stroke Runtime Hooks\n// =============================================================================\n\nlet strokeRuntime = {\n createTipSurface: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n loadImageTip: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host stroke hooks used by brush-tip loading code.\n *\n * @param {object} hooks\n */\nexport function setStrokeRuntime(hooks) {\n strokeRuntime = { ...strokeRuntime, ...hooks };\n}\n\nexport const createTipSurface = (width, height) =>\n strokeRuntime.createTipSurface(width, height);\nexport const loadImageTip = (src, imageToWhite) =>\n strokeRuntime.loadImageTip(src, imageToWhite);\n","import * as Color from \"../core/color.js\";\nimport { createFramebuffer } from \"../core/compositor_runtime.js\";\n\nlet isStrokeCompositeRegistered = false;\nconst DIRTY_BRUSH_PADDING = 2;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the current stroke mask framebuffer must be recreated.\n * This happens when the renderer has no mask yet, or when the canvas size or\n * pixel density changed since the last allocation.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the stroke mask must be rebuilt.\n */\nfunction needsStrokeMask(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.glMask ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight ||\n (typeof Renderer.glMask.pixelDensity === \"function\" &&\n Renderer.glMask.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures the stroke compositor owns a framebuffer-backed mask with the current\n * canvas dimensions. Stroke stamps are rendered into this mask in WebGL before\n * being blended into the main target.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {object} The framebuffer used as stroke mask.\n */\nexport function ensureStrokeCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n) {\n if (needsStrokeMask(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n Renderer.glMask = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n Renderer.glMask.dirtyRect ??= null;\n Renderer.glMask.isDrawn ??= false;\n return Renderer.glMask;\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current stroke mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearStrokeMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the rect that should be composited from the stroke mask into the\n * main canvas. Stroke bounds are normally tight dirty rects, but when drawing\n * into an active framebuffer we keep the result conservative and composite the\n * full target.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} getActiveFramebuffer - Returns the currently bound framebuffer.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {number} padding - Extra brush padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getStrokeCompositeRect(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n if (getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_BRUSH_PADDING),\n );\n}\n\n/**\n * Returns the resource that should be bound to the blend shader's `u_mask`\n * uniform for stroke compositing.\n *\n * @param {object} _Renderer - Active host renderer.\n * @param {object} mask - Stroke mask framebuffer.\n * @returns {object} Stroke mask framebuffer.\n */\nexport function getStrokeShaderMask(_Renderer, mask) {\n return mask;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the stroke compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initStrokeComposite() {\n if (isStrokeCompositeRegistered) return;\n Color.registerStrokeComposite?.({\n ensureResources: ensureStrokeCompositeResources,\n clearMask: clearStrokeMask,\n getCompositeRect: getStrokeCompositeRect,\n getShaderMask: getStrokeShaderMask,\n });\n isStrokeCompositeRegistered = true;\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// Renderer Runtime Hooks\n// =============================================================================\n\n/**\n * Direct-render hooks used by modules that issue raw WebGL commands.\n *\n * These hooks are intentionally narrow:\n * - begin drawing into an offscreen GL mask target\n * - restore the previous draw target afterward\n * - reset any host-side shader/program bookkeeping after direct GL usage\n */\n\nlet rendererRuntime = {\n beginDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n endDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n resetDirectShaderTracking: () => {},\n};\n\n/**\n * Registers or updates host renderer hooks used by direct WebGL drawing paths.\n *\n * @param {object} hooks\n */\nexport function setRendererRuntime(hooks) {\n rendererRuntime = { ...rendererRuntime, ...hooks };\n}\n\nexport const beginDirectMaskDraw = (renderer, gl, target) =>\n rendererRuntime.beginDirectMaskDraw(renderer, gl, target);\nexport const endDirectMaskDraw = (renderer, gl, state) =>\n rendererRuntime.endDirectMaskDraw(renderer, gl, state);\nexport const resetDirectShaderTracking = (renderer, gl) =>\n rendererRuntime.resetDirectShaderTracking(renderer, gl);\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 { Cwidth, Cheight, Density, Renderer } from \"../core/target.js\";\nimport {\n Mix,\n isMixReady,\n State,\n} from \"../core/color.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport {\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking,\n} from \"../core/renderer_runtime.js\";\nimport { getAffineMatrix } from \"../core/runtime.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;\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 runtime affine transform. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n const m = getAffineMatrix();\n _ma = m.a;\n _mb = m.b;\n _mc = m.c;\n _md = m.d;\n _mx = m.x;\n _my = m.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 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 return beginDirectMaskDraw(Renderer, gl, Mix.glMask);\n}\n\nfunction endMaskTarget(state) {\n endDirectMaskDraw(Renderer, gl, state);\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 * the current runtime transform 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 * @param {number} [extraPadding=0] - Conservative extra padding in user units.\n */\nexport function stampImage(x, y, size, angle, alpha, extraPadding = 0) {\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 const extraRadius = _density * extraPadding * _scale;\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 const boundsRadius = halfSize * 1.42 + extraRadius;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - boundsRadius - 1,\n dScreenY - boundsRadius - 1,\n dScreenX + boundsRadius + 1,\n dScreenY + boundsRadius + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {object} p5img - The preprocessed brush-tip image/canvas (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 const targetState = beginMaskTarget();\n\n // Lazy-create the WebGL texture from the tip 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(targetState);\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let the host adapter know we changed the active program.\n resetDirectShaderTracking(Renderer, gl);\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 const targetState = beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader in case host drawing 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(targetState);\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 host shader tracking.\n // Reset it so the host is forced to re-activate its own shader next time\n // it draws — otherwise it may skip gl.useProgram() and set uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetDirectShaderTracking(Renderer, gl);\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\n// Core imports\nimport { Cwidth, Cheight, Renderer, isCanvasReady } from \"../core/target.js\";\nimport {\n Mix,\n State,\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 cos,\n sin\n} from \"../core/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { createTipSurface, loadImageTip } from \"./runtime.js\";\n\n// Internal module imports\nimport { initStrokeComposite } from \"./composite.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\n\ninitStrokeComposite(); // Register the stroke composite system for offscreen mask rendering and compositing.\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 type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\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 if (params.markerTip === undefined) params.markerTip = true;\n if (params.noise === undefined) params.noise = 0.3;\n params.noise = Math.max(0, Math.min(1, params.noise));\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 g = createTipSurface(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\nexport function getBrushParams(brushName) {\n return list.get(brushName)?.param ?? null;\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 = createColor(...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\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current runtime 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 return region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n return;\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 _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 current.pressureCount = 10;\n current.cachedPressure = undefined;\n current.lineNoiseCount = 5;\n current.cachedLineNoise = undefined;\n\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n if (isPlot) {\n _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n );\n } else {\n _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\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.05 * current.p.noise;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n current.cos = cos(_dir);\n current.sin = sin(_dir);\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 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 pressure = calculatePressure();\n const lineNoise = calculateLineNoise();\n\n if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;\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 if (current.pressureCount >= 10 || current.cachedPressure === undefined) {\n current.cachedPressure = _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n current.pressureCount = 0;\n }\n current.pressureCount++;\n return current.cachedPressure;\n}\n\nfunction calculateLineNoise() {\n if (current.lineNoiseCount >= 10 || current.cachedLineNoise === undefined) {\n current.cachedLineNoise = map(\n noise(current.seed + _position.plotted * 0.01, 0),\n -1,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n current.lineNoiseCount = 0;\n }\n current.lineNoiseCount++;\n return current.cachedLineNoise;\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 * 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\nfunction getImageTipOverscan() {\n const maxPressure = Math.max(1, current.max ?? 1);\n const scatterReach = State.stroke.weight * current.p.scatter;\n const tipReach = State.stroke.weight * current.p.weight * maxPressure;\n\n // Custom/image tips can extend beyond their nominal square because the tip\n // drawing itself may be large and because high scatter creates sparse large\n // stamps near the edge. Keep culling/dirty tracking conservative.\n return Math.max(8, scatterReach * 1.5 + tipReach * 0.75);\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 const overscan = getImageTipOverscan();\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(\n _position.x + rx,\n _position.y + ry,\n size,\n angle,\n alpha * Math.max(0.8, pressure) * rr(0.9, 1.1),\n overscan,\n );\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\n let dx, dy;\n if (_plot) {\n const plotAngle = _plot.angle(_position.plotted);\n const plotCos = cos(plotAngle);\n const plotSin = sin(plotAngle);\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * plotSin + along * plotCos;\n dy = perp * plotCos - along * plotSin;\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 (current.p.markerTip === false) return;\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// 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 runtime angle units.\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 \"markerTip\",\n \"noise\",\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 \"pastel\",\n [\n 2.05 / 3,\n 13.4 / 3,\n 0.91,\n 28,\n 35,\n 0.085 / 3,\n { mode: \"gaussian\", curve: [0.4, 0.05], min_max: [1.09, 0.93] },\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"crayon\",\n [\n 0.9 / 3,\n 5.45 / 3,\n 0.75,\n 250,\n 159,\n 0.23 / 3,\n [1.1, 0.9],\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\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 active host image pipeline.\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 host image object 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 loadImageTip(src, T.imageToWhite).then((p5img) => {\n this.tips.set(src, p5img);\n }),\n ),\n );\n },\n};\n","import { 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// Module: Classic Hatch\n// =============================================================================\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\n/**\n * Returns a shallow snapshot of the current hatch modifier state.\n *\n * @returns {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}}\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Restores hatch modifier state from a previously captured snapshot.\n *\n * @param {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}} state\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Activates classic scanline hatching for subsequent shapes.\n *\n * @param {number} [dist=5] Distance between scanlines.\n * @param {number} [angle=45] Hatch angle in the current runtime angle units.\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [options]\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Overrides the brush, color, and weight used specifically for hatch strokes.\n *\n * @param {string} brush\n * @param {string|object} [color=\"black\"]\n * @param {number} [weight=1]\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Deactivates hatching and clears any hatch-specific brush override.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Generation\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for one polygon by rotating it into scanline space,\n * intersecting horizontal scanlines against its edges, and rotating the\n * resulting segments back into canvas space.\n *\n * @param {Polygon} polygon\n * @param {number} angle Hatch angle in degrees.\n * @param {number} dist Base scanline spacing.\n * @param {number} gradient Multiplicative spacing growth per scanline.\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad),\n sinA = Math.sin(rad);\n const cosB = Math.cos(-rad),\n sinB = Math.sin(-rad);\n\n const verts = polygon.a,\n n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity,\n maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0],\n 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],\n 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,\n step = dist;\n while (Y < maxY) {\n const cx = [];\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1],\n y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(\n edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0])\n );\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n scanY: Y,\n x1: cx[i] * cosB - Y * sinB,\n y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB,\n y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n/**\n * Collects and orders hatch segments for one polygon or a polygon list.\n *\n * Segments are sorted in scanline traversal order so downstream rendering can\n * optionally connect them into a continuous serpentine path.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {number} dist\n * @param {number} angle\n * @param {number} gradient\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction getHatchSegments(polygons, dist, angle, gradient) {\n if (!Array.isArray(polygons)) polygons = [polygons];\n const segs = [];\n for (const poly of polygons) {\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n }\n segs.sort((a, b) => (a.scanY === b.scanY ? a.x1 - b.x1 : a.scanY - b.scanY));\n return segs;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Runs hatch drawing with the temporary hatch-specific brush style if one is active,\n * then restores the outer stroke state.\n *\n * @param {() => void} drawFn\n */\nfunction withHatchStyle(drawFn) {\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n drawFn();\n BrushSetState(save);\n}\n\n/**\n * Resolves the active hatch parameters and precomputes the ordered scanline segments.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{dist:number, options:Object, segs:Object[]}}\n */\nfunction getActiveHatchConfig(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n const segs = getHatchSegments(polygons, dist, angle, gradient);\n return { dist, options, segs };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Lines\n// ---------------------------------------------------------------------------\n\n/**\n * Expands ordered hatch segments into the actual line list that will be drawn.\n *\n * This includes endpoint jitter when `rand` is active and inserts the serpentine\n * connector lines when `continuous` is enabled.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{x1:number, y1:number, x2:number, y2:number, scanY:number, isConnector:boolean}[]}\n */\nexport function getHatchLines(polygons) {\n const { dist, options, segs } = getActiveHatchConfig(polygons);\n const r = options.rand || 0;\n const lines = [];\n\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 += 2 * r * dist * rr(-1, 1);\n y1 += 2 * r * dist * rr(-1, 1);\n x2 += 2 * r * dist * rr(-1, 1);\n y2 += 2 * r * dist * rr(-1, 1);\n }\n const reverse = options.continuous && j % 2 === 1;\n const line = reverse\n ? { x1: x2, y1: y2, x2: x1, y2: y1, scanY: s.scanY, isConnector: false }\n : { x1, y1, x2, y2, scanY: s.scanY, isConnector: false };\n lines.push(line);\n if (j > 0 && options.continuous) {\n const prev = lines[lines.length - 2];\n lines.push({\n x1: prev.x2,\n y1: prev.y2,\n x2: line.x1,\n y2: line.y1,\n scanY: s.scanY,\n isConnector: true,\n });\n }\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Iterates the generated hatch lines and delegates the actual rendering of each\n * segment to the provided callback.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {(x1:number, y1:number, x2:number, y2:number, index:number, segs:Object[]) => void} drawSegment\n */\nfunction renderHatchSegments(polygons, drawSegment) {\n const segs = getHatchLines(polygons);\n withHatchStyle(() => {\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n drawSegment(s.x1, s.y1, s.x2, s.y2, j, segs);\n }\n });\n}\n\n/**\n * Draws classic hatch lines over one polygon or an array of polygons.\n *\n * @param {Polygon|Polygon[]} polygons\n */\nexport function createHatch(polygons) {\n renderHatchSegments(polygons, (x1, y1, x2, y2) => {\n line(x1, y1, x2, y2);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies the currently active hatch modifier to a polygon, or temporarily\n * overrides hatch parameters for this call only.\n *\n * @param {number|false} [_dist=false]\n * @param {number} [_angle]\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [_options]\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (State.hatch.isActive) createHatch(this);\n HatchSetState(state);\n};\n\n/**\n * Converts the plot to a polygon and applies the currently active hatch modifier.\n *\n * @param {number} x\n * @param {number} y\n * @param {number} scale\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.3);\n this.pol.hatch();\n }\n};\n","// =============================================================================\n// Module: Mass\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { arc } from \"../core/primitives.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { rr2, dist, calcAngle } from \"../core/utils.js\";\nimport { fromDegrees, usesRadians } from \"../core/runtime.js\";\nimport { HatchState, HatchSetState, hatch, getHatchLines } from \"./hatch.js\";\nimport { BrushState, BrushSetState, getBrushParams, set } from \"../stroke/stroke.js\";\nimport { wiggle } from \"../core/flowfield.js\";\n\n// ---------------------------------------------------------------------------\n// Mass State\n// ---------------------------------------------------------------------------\n\nState.mass = {\n isActive: false,\n brush: null,\n color: null,\n options: {},\n};\n\n/**\n * Returns a shallow copy of the current mass state.\n * @returns {object}\n */\nexport function MassState() {\n return { ...State.mass };\n}\n\n/**\n * Restores a previously saved mass state.\n * @param {object} state\n */\nexport function MassSetState(state) {\n State.mass = { ...state };\n}\n\n/**\n * Enables massing mode with a brush, color, and optional configuration.\n *\n * @param {string} brush - Brush name to use for the mass pass.\n * @param {string|Color} color - Color to use for the mass pass.\n * @param {object} [options={}] - Massing options such as precision, strength, gradient, and outline.\n */\nexport function mass(brush, color, options = {}) {\n State.mass.brush = brush;\n State.mass.color = color;\n State.mass.options = options;\n State.mass.isActive = true;\n}\n\n/**\n * Disables massing mode for subsequent geometry.\n */\nexport function noMass() {\n State.mass.isActive = false;\n State.mass.brush = null;\n State.mass.color = null;\n State.mass.options = {};\n}\n\n// ---------------------------------------------------------------------------\n// Polygon Preparation\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a translated copy of a polygon.\n * Used to build the secondary mass layers from an existing base polygon.\n * @param {Polygon} polygon\n * @param {number} jitterX\n * @param {number} jitterY\n * @returns {Polygon}\n */\nfunction jitterPolygon(polygon, jitterX, jitterY) {\n return new Polygon(\n polygon.vertices.map((vertex) => [vertex.x + jitterX, vertex.y + jitterY]),\n );\n}\n\n/**\n * Builds the three polygons used for a mass pass.\n * Both polygon and plot inputs use one base polygon plus two translated copies,\n * so plot-based massing only needs a single `genPol(...)` call.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n * @returns {Polygon[]}\n */\nfunction getMassPolygons(shape, x, y, scale) {\n const isPolygon = x === false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const basePolygon = isPolygon ? shape : shape.genPol(x, y, scale, 0.15);\n const maxJitter = Math.min(scatter * 2, 5);\n const jitters = [\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n ];\n\n return [\n basePolygon,\n jitterPolygon(basePolygon, jitters[0][0], jitters[0][1]),\n jitterPolygon(basePolygon, jitters[1][0], jitters[1][1]),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Angle & Bounds Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts degree values into the current runtime angle units.\n * @param {number} angle\n * @returns {number}\n */\nfunction getAngleConverter() {\n return usesRadians()\n ? (angle) => (angle * Math.PI) / 180\n : (angle) => angle;\n}\n\n/**\n * Computes an axis-aligned bounding box for a polygon.\n * The diagonal is used as a size reference for pivot distance.\n * @param {Polygon} polygon\n * @returns {{minX:number,minY:number,maxX:number,maxY:number,cx:number,cy:number,size:number}}\n */\nfunction getPolygonBounds(polygon) {\n const points = polygon?.a ?? [];\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n for (const [x, y] of points) {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n return {\n minX,\n minY,\n maxX,\n maxY,\n cx: (minX + maxX) / 2,\n cy: (minY + maxY) / 2,\n size: Math.hypot(maxX - minX, maxY - minY),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pivot Geometry\n// ---------------------------------------------------------------------------\n\n/**\n * Chooses the diagonal corner family for a whole mass gesture.\n * Positive-angle hatching uses either bottom-right or top-left; negative-angle\n * hatching uses either bottom-left or top-right.\n * @param {number} angleDeg\n * @returns {[number, number]}\n */\nfunction getPivotBias(angleDeg) {\n const normalizedAngle = ((((angleDeg + 90) % 180) + 180) % 180) - 90;\n if (normalizedAngle >= 0) {\n return rr2() < 0.5 ? [1, 1] : [-1, -1];\n } else {\n return rr2() < 0.5 ? [-1, 1] : [1, -1];\n }\n}\n\n/**\n * Places the global pivot anchor outside the polygon, along the selected bias.\n * Distance varies per layer while the bias stays fixed for the whole mass.\n * @param {Polygon} polygon\n * @param {[number, number]} bias\n * @returns {{x:number,y:number}}\n */\nfunction getPivotAnchor(polygon, bias) {\n const bounds = getPolygonBounds(polygon);\n const offset = bounds.size * rr2(0.6, 1.4);\n const [sx, sy] = bias;\n return {\n x: bounds.cx + sx * offset,\n y: bounds.cy + sy * offset,\n };\n}\n\n/**\n * Projects the global pivot anchor onto the perpendicular bisector of a line.\n * This yields a valid circle center equidistant from both endpoints.\n * @param {{x:number,y:number}} anchor\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {{x:number,y:number}|null}\n */\nfunction projectAnchorToBisector(anchor, x1, y1, x2, y2) {\n const mx = (x1 + x2) / 2;\n const my = (y1 + y2) / 2;\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n if (!length) return null;\n const nx = -dy / length;\n const ny = dx / length;\n const offset = (anchor.x - mx) * nx + (anchor.y - my) * ny;\n return {\n x: mx + nx * offset,\n y: my + ny * offset,\n };\n}\n\n/**\n * Returns the shortest arc between two endpoints around a given center.\n * The returned angles are already converted into the current runtime angle units.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {[number, number]}\n */\nfunction getShortArcAngles(cx, cy, x1, y1, x2, y2, toAngleUnit) {\n let startDeg = calcAngle(cx, cy, x1, y1);\n let endDeg = calcAngle(cx, cy, x2, y2);\n const sweep = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweep > 180) [startDeg, endDeg] = [endDeg, startDeg];\n return [\n toAngleUnit(startDeg),\n toAngleUnit(endDeg),\n ];\n}\n\n/**\n * Splits a hatch line into two slightly separated segments so some gestures\n * read as interrupted rather than perfectly continuous.\n * @param {{x1:number,y1:number,x2:number,y2:number}} seg\n * @returns {Array<{x1:number,y1:number,x2:number,y2:number}>}\n */\nfunction splitSegment(seg) {\n const t = rr2(0.35, 0.65);\n const mx = seg.x1 + (seg.x2 - seg.x1) * t;\n const my = seg.y1 + (seg.y2 - seg.y1) * t;\n const dx = seg.x2 - seg.x1;\n const dy = seg.y2 - seg.y1;\n const length = Math.hypot(dx, dy) || 1;\n const gap = rr2(0.04, 0.1) * length;\n const gx = (dx / length) * gap * 0.5;\n const gy = (dy / length) * gap * 0.5;\n return [\n { x1: seg.x1, y1: seg.y1, x2: mx - gx, y2: my - gy },\n { x1: mx + gx, y1: my + gy, x2: seg.x2, y2: seg.y2 },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Mass Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Draws one polygon of the mass as a family of arcs derived from hatch lines.\n * The same pivot bias is used across layers, while each layer gets its own\n * anchor distance from the shape.\n * @param {Polygon} polygon\n * @param {[number, number]} pivotBias\n */\nfunction drawMassArcs(polygon, pivotBias, toAngleUnit) {\n const anchor = getPivotAnchor(polygon, pivotBias);\n for (const seg of getHatchLines(polygon)) {\n const parts = !seg.isConnector && rr2() < 0.35 ? splitSegment(seg) : [seg];\n for (const part of parts) {\n const center = projectAnchorToBisector(anchor, part.x1, part.y1, part.x2, part.y2);\n if (!center) continue;\n const radius = dist(center.x, center.y, part.x1, part.y1);\n if (!radius) continue;\n const [startAngle, endAngle] = getShortArcAngles(\n center.x,\n center.y,\n part.x1,\n part.y1,\n part.x2,\n part.y2,\n toAngleUnit,\n );\n arc(center.x, center.y, radius, startAngle, endAngle);\n }\n }\n}\n\n/**\n * Configures a hatch pass and immediately reinterprets the generated lines as arcs.\n * @param {Polygon} polygon\n * @param {number} dist\n * @param {number} angle\n * @param {object} options\n * @param {[number, number]} pivotBias\n */\nfunction drawMassPass(polygon, dist, angle, options, pivotBias, toAngleUnit) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias, toAngleUnit);\n}\n\n/**\n * Creates the built-in \"massing\" effect for a polygon or plot.\n * A mass is built from up to three jittered polygon layers, each hatched and\n * then redrawn as arc gestures around a shared pivot bias.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n */\nexport function createMass(shape, x, y, scale) {\n const pols = getMassPolygons(shape, x, y, scale);\n const hatchState = HatchState();\n const brushState = BrushState();\n const fieldState = { ...State.field };\n const precision = State.mass.options?.precision ?? 0.5;\n const strength = State.mass.options?.strength ?? 1;\n const gradient = State.mass.options?.gradient ?? 0.1;\n const outline = State.mass.options?.outline ?? false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const hatchDist = 1.6 * rr2(scatter * 0.65, scatter * 0.85) - 0.4 * gradient;\n const baseAngle = rr2(-90, 90);\n const pivotBias = getPivotBias(baseAngle);\n const toAngleUnit = getAngleConverter();\n\n set(State.mass.brush, State.mass.color, 1);\n wiggle(2 - precision);\n if (outline) pols[0].draw();\n\n drawMassPass(\n pols[0],\n hatchDist * 0.9,\n fromDegrees(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n fromDegrees(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n fromDegrees(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n BrushSetState(brushState);\n HatchSetState(hatchState);\n State.field = { ...fieldState };\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies massing to polygon geometry.\n */\nPolygon.prototype.mass = function () {\n if (State.mass?.isActive) {\n createMass(this, false);\n }\n};\n\n/**\n * Applies massing to plots by generating their polygon first.\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.mass = function (x, y, scale) {\n if (State.mass?.isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n createMass(this, x, y, scale);\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","import * as Color from \"../core/color.js\";\nimport {\n createFramebuffer,\n create2DCanvas,\n} from \"../core/compositor_runtime.js\";\n\n// Small staging canvas used to upload only the dirty fill sub-rect into the\n// framebuffer-backed mask mirror consumed by the blend shader.\nlet FillMaskUploadCanvas = null;\nlet isFillCompositeRegistered = false;\nconst DIRTY_FILL_PADDING = 4;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the CPU-side 2D fill mask must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} maskWidth - Mask width in physical pixels.\n * @param {number} maskHeight - Mask height in physical pixels.\n * @returns {boolean} True when the 2D fill mask needs reallocation.\n */\nfunction needsFillMaskCanvas(Renderer, maskWidth, maskHeight) {\n return (\n !Renderer.mask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight\n );\n}\n\n/**\n * Returns whether the framebuffer-backed fill mask mirror must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the fill mask framebuffer needs reallocation.\n */\nfunction needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density) {\n return (\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 );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures fill compositing resources exist for the active renderer.\n *\n * Fill draws first into a CPU-side 2D mask canvas. That mask is later uploaded,\n * dirty-rect by dirty-rect, into a framebuffer-backed mirror used by the final\n * blend shader pass.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {{mask: object, ctx: CanvasRenderingContext2D}} Fill mask resources.\n */\nexport function ensureFillCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n) {\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n\n if (needsFillMaskCanvas(Renderer, maskWidth, maskHeight)) {\n Renderer.mask = create2DCanvas(maskWidth, maskHeight);\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = createFramebuffer(Renderer, {\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 Renderer.mask.dirtyRect ??= null;\n Renderer.mask.isDrawn ??= false;\n Renderer.mask.drawingContext.imageSmoothingEnabled = false;\n return {\n mask: Renderer.mask,\n ctx: Renderer.mask.drawingContext,\n };\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current fill mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Fill mask canvas or framebuffer mirror.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearFillMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the fill dirty rect to composite into the main target. Fill bounds are\n * taken directly from the accumulated 2D mask dirty area plus a small padding.\n *\n * @param {object|null} target - Fill mask canvas.\n * @param {Function} _getActiveFramebuffer - Unused for fill masks.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getFillCompositeRect(\n target,\n _getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_FILL_PADDING),\n );\n}\n\n// =============================================================================\n// Section: Upload\n// =============================================================================\n/**\n * Uploads only the dirty portion of the CPU-side 2D fill mask into the\n * framebuffer-backed fill mask mirror used by the shader compositor.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {object} mask - CPU-side 2D fill mask canvas.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} dirtyRect - Dirty rect to upload.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {object} Framebuffer-backed fill mask mirror.\n */\nexport function getFillShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n) {\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 = create2DCanvas(uploadWidth, uploadHeight);\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 return target;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the fill compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initFillComposite() {\n if (isFillCompositeRegistered) return;\n Color.registerFillComposite?.({\n ensureResources: ensureFillCompositeResources,\n clearMask: clearFillMask,\n getCompositeRect: getFillCompositeRect,\n getShaderMask: getFillShaderMask,\n });\n isFillCompositeRegistered = true;\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\n// Core imports\nimport { Renderer, Cwidth, Cheight, Density } from \"../core/target.js\";\nimport {\n Mix,\n State,\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 } from \"../core/flowfield.js\";\nimport { createColor, getAffineMatrix } from \"../core/runtime.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// Internal module imports\nimport { initFillComposite } from \"./composite.js\";\n\ninitFillComposite(); // Register the fill composite with the core color module\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 = 2024;\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 = arguments.length < 3 ? createColor(a) : createColor(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 === 0) {\n return { x: 0, y: 0 };\n }\n\n if (pts.length < 8) {\n // Simple average for small polygons\n const sum = pts.reduce(\n (center, point) => ({ x: center.x + point.x, y: center.y + point.y }),\n { x: 0, y: 0 },\n );\n return { x: sum.x / pts.length, y: sum.y / 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\n // We want to add at least two vertices to divide the new edge that appears after trimming, at random distances along its path\n const trimStart = s;\n const trimEnd = s + n;\n const edgeStart = this.v[(trimStart - 1 + this.v.length) % this.v.length];\n const edgeEnd = this.v[trimEnd % this.v.length];\n const edgeVec = { x: edgeEnd.x - edgeStart.x, y: edgeEnd.y - edgeStart.y };\n \n // Insert two new vertices at random positions along the new edge\n const insertCount = 2;\n for (let i = 0; i < insertCount; i++) {\n const t = rr(0.25, 0.75); // Random position between 25% and 75% along the edge\n const newVertex = { x: edgeStart.x + edgeVec.x * t, y: edgeStart.y + edgeVec.y * t };\n const insertIdx = s + i;\n v.splice(insertIdx, 0, newVertex);\n m.splice(insertIdx, 0, rr(0.4, 0.7));\n dir.splice(insertIdx, 0, this.dir[trimStart % this.dir.length]);\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 // If mod is smaller than 0.02, skip growing math and just insert the middle vertex\n if (mod < 0.05) {\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedX[insertedIdx] = (cv.x + nv.x) / 2;\n insertedY[insertedIdx] = (cv.y + nv.y) / 2;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n continue;\n }\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 * Math.max(0.1, 2 * State.fill.bleed_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 const m = getAffineMatrix();\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * m.a,\n Density * m.b,\n Density * m.c,\n Density * m.d,\n Density * (m.x + Cwidth / 2),\n Density * (m.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);\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.3);\n const minSizeFactor = 0.03 * minSize;\n const maxSizeFactor = 0.45 * 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 State.fill.bleed_strength < 0.06\n ? 0\n : map(State.fill.bleed_strength, 0, 0.6, 0.2, 0.60, true),\n );\n this.pol.fill();\n }\n};\n","\nexport default function earcut(data, holeIndices, dim = 2) {\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let minX, minY, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = data[0];\n minY = data[1];\n let maxX = minX;\n let maxY = minY;\n\n for (let i = dim; i < outerLen; i += dim) {\n const x = data[i];\n const y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n let last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n } else {\n for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n let p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n let stop = ear;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n const prev = ear.prev;\n const next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n triangles.push(prev.i, ear.i, next.i); // cut off the triangle\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n let p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n // z-order range for the current triangle bbox;\n const minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n let p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles) {\n let p = start;\n do {\n const a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i, p.i, b.i);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n let a = start;\n do {\n let b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n let c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n const queue = [];\n\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n const list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareXYSlope);\n\n // process holes from left to right\n for (let i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareXYSlope(a, b) {\n let result = a.x - b.x;\n // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find\n // the bridge to the outer shell is always the point that they meet at.\n if (result === 0) {\n result = a.y - b.y;\n if (result === 0) {\n const aSlope = (a.next.y - a.y) / (a.next.x - a.x);\n const bSlope = (b.next.y - b.y) / (b.next.x - b.x);\n result = aSlope - bSlope;\n }\n }\n return result;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole(hole, outerNode) {\n const bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n const bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n // unless they intersect at a vertex, then choose the vertex\n if (equals(hole, p)) return p;\n do {\n if (equals(hole, p.next)) return p.next;\n else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n let p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n let numMerges;\n let inSize = 1;\n\n do {\n let p = list;\n let e;\n list = null;\n let tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n let q = p;\n let pSize = 0;\n for (let i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n let qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n let p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a point lies within a convex triangle but false if its equal to the first point of the triangle\nfunction pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {\n return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n let p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n const a2 = createNode(a.i, a.x, a.y),\n b2 = createNode(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n const p = createNode(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction createNode(i, x, y) {\n return {\n i, // vertex index in coordinates array\n x, y, // vertex coordinates\n prev: null, // previous and next vertex nodes in a polygon ring\n next: null,\n z: 0, // z-order curve value\n prevZ: null, // previous and next nodes in z-order\n nextZ: null,\n steiner: false // indicates whether this is a steiner point\n };\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nexport function deviation(data, holeIndices, dim, triangles) {\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n let trianglesArea = 0;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = triangles[i] * dim;\n const b = triangles[i + 1] * dim;\n const c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n}\n\nfunction signedArea(data, start, end, dim) {\n let sum = 0;\n for (let i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nexport function flatten(data) {\n const vertices = [];\n const holes = [];\n const dimensions = data[0][0].length;\n let holeIndex = 0;\n let prevLen = 0;\n\n for (const ring of data) {\n for (const p of ring) {\n for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n }\n if (prevLen) {\n holeIndex += prevLen;\n holes.push(holeIndex);\n }\n prevLen = ring.length;\n }\n return {vertices, holes, dimensions};\n}\n","// =============================================================================\n// Module: Wash\n// =============================================================================\n/**\n * Minimal stateful API for the `wash()` fill modifier.\n */\n\nimport earcut from \"earcut\";\nimport { Renderer, Cwidth, Cheight, isCanvasReady } from \"../core/target.js\";\nimport { State, flushActiveComposite } from \"../core/color.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { resetDirectShaderTracking } from \"../core/renderer_runtime.js\";\n\nlet gl = null;\nlet washProgram = null;\nlet washVao = null;\nlet washBuffer = null;\nlet washProjection = null;\nlet loadedWidth = 0;\nlet loadedHeight = 0;\nlet washGpuBufferSize = 0;\n\nconst WashAttr = {};\nconst WashUniform = {};\n\nconst washVertSrc = `#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}`;\n\nconst washFragSrc = `#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}`;\n\nState.wash = {\n color: null,\n opacity: 150,\n isActive: false,\n};\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Enables wash mode with a color and opacity.\n *\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 wash(a, b, c, d) {\n isCanvasReady();\n State.wash.opacity = (arguments.length < 4 ? b : d) ?? 150;\n State.wash.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.wash.isActive = true;\n}\n\n/**\n * Disables wash mode for subsequent drawing operations.\n */\nexport function noWash() {\n State.wash.isActive = false;\n}\n\n// =============================================================================\n// GL helpers\n// =============================================================================\n\n/**\n * Lazily creates the reusable program/buffer state for solid wash drawing and\n * refreshes the orthographic projection when the active target size changes.\n */\nfunction ensureWashReady() {\n const nextGl = Renderer.drawingContext;\n const sizeChanged = loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (!washProjection || sizeChanged) {\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n washProjection = new Float32Array([\n 2 / loadedWidth,\n 0,\n 0,\n 0,\n 0,\n -2 / loadedHeight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n }\n\n if (gl === nextGl && washProgram && washVao && washBuffer) return;\n\n gl = nextGl;\n washProgram = createProgram(gl, washVertSrc, washFragSrc);\n WashAttr.a_position = gl.getAttribLocation(washProgram, \"a_position\");\n WashUniform.u_matrix = gl.getUniformLocation(washProgram, \"u_matrix\");\n WashUniform.u_color = gl.getUniformLocation(washProgram, \"u_color\");\n\n washVao = gl.createVertexArray();\n gl.bindVertexArray(washVao);\n\n washBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, 0, gl.DYNAMIC_DRAW);\n washGpuBufferSize = 0;\n\n gl.enableVertexAttribArray(WashAttr.a_position);\n gl.vertexAttribPointer(WashAttr.a_position, 2, gl.FLOAT, false, 8, 0);\n\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n}\n\n/**\n * Applies the current runtime affine transform and converts the result into\n * the screen-space coordinates used by the direct GL wash pipeline.\n *\n * @param {number} x - The source x-coordinate in brush drawing space.\n * @param {number} y - The source y-coordinate in brush drawing space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n const m = getAffineMatrix();\n return [\n m.a * x + m.c * y + m.x + loadedWidth / 2,\n m.b * x + m.d * y + m.y + loadedHeight / 2,\n ];\n}\n\n/**\n * Triangulates a polygon in local space and returns the transformed triangle\n * vertex buffer ready for upload to the GPU.\n *\n * @param {Polygon} polygon - The polygon to triangulate.\n * @returns {{ triangles: Float32Array, vertexCount: number }} Screen-space\n * triangle vertices plus the number of vertices to draw.\n */\nfunction buildTriangleBuffer(polygon) {\n const flat = new Float32Array(polygon.vertices.length * 2);\n for (let i = 0; i < polygon.vertices.length; i++) {\n const vertex = polygon.vertices[i];\n flat[i * 2] = vertex.x;\n flat[i * 2 + 1] = vertex.y;\n }\n\n const indices = earcut(flat);\n const triangles = new Float32Array(indices.length * 2);\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n const [screenX, screenY] = transformVertexToScreen(flat[idx * 2], flat[idx * 2 + 1]);\n triangles[i * 2] = screenX;\n triangles[i * 2 + 1] = screenY;\n }\n\n return {\n triangles,\n vertexCount: indices.length,\n };\n}\n\n/**\n * Draws a triangulated solid wash directly to the current GL target.\n *\n * @param {Polygon} polygon - The polygon to fill with the current wash state.\n */\nfunction drawWashPolygon(polygon) {\n if (!State.wash?.isActive || !State.wash.color || polygon.vertices.length < 3) return;\n\n flushActiveComposite();\n ensureWashReady();\n const { triangles, vertexCount } = buildTriangleBuffer(polygon);\n const byteCount = triangles.byteLength;\n gl.useProgram(washProgram);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.bindVertexArray(washVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n if (byteCount > washGpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.DYNAMIC_DRAW);\n washGpuBufferSize = byteCount;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, triangles);\n }\n const color = State.wash.color._array;\n gl.uniformMatrix4fv(WashUniform.u_matrix, false, washProjection);\n gl.uniform4f(\n WashUniform.u_color,\n color[0],\n color[1],\n color[2],\n State.wash.opacity / 255,\n );\n\n gl.drawArrays(gl.TRIANGLES, 0, vertexCount);\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n resetDirectShaderTracking(Renderer, gl);\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct GL wash fill to the polygon using the current wash state.\n *\n * @param {Color|string|false} [_color] - Optional override color for this call.\n * @param {number} [_opacity] - Optional override opacity for this call.\n */\nPolygon.prototype.wash = function (_color = false, _opacity) {\n const state = { ...State.wash };\n if (_color !== false) wash(_color, _opacity);\n\n if (State.wash.isActive) {\n drawWashPolygon(this);\n }\n\n State.wash = { ...state };\n};\n\n/**\n * Applies wash to a plot by first generating the plot polygon, mirroring the\n * existing fill-path behavior, and then drawing that polygon with wash.\n *\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\nPlot.prototype.wash = function (x, y, scale) {\n if (!State.wash?.isActive) return;\n if (this.origin) {\n x = this.origin[0];\n y = this.origin[1];\n scale = 1;\n }\n this.pol = this.genPol(x, y, scale, 0, -1);\n this.pol.wash();\n};\n","// =============================================================================\n// Adapter: Standalone Renderer Hooks\n// =============================================================================\n\nimport { Cwidth, Cheight, Density } from \"../../core/target.js\";\nimport { setRendererRuntime } from \"../../core/renderer_runtime.js\";\n\nfunction beginDirectMaskDraw(_renderer, gl, target) {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n\n return { hadDepthTest };\n}\n\nfunction endDirectMaskDraw(renderer, gl, state) {\n if (state?.hadDepthTest) gl.enable(gl.DEPTH_TEST);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.viewport(\n 0,\n 0,\n Math.max(1, Math.round(Cwidth * Density)),\n Math.max(1, Math.round(Cheight * Density)),\n );\n}\n\nfunction resetStandaloneShaderTracking(_renderer, gl) {\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\nexport function initStandaloneRendererRuntime() {\n setRendererRuntime({\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking: resetStandaloneShaderTracking,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Compositor Hooks\n// =============================================================================\n\nimport { createProgram } from \"../../core/gl/utils.js\";\nimport {\n setCompositorRuntime,\n blitDefaultFramebufferSource,\n} from \"../../core/compositor_runtime.js\";\n\nfunction clearTarget(renderer, target, isFramebufferTarget) {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n const gl = renderer.drawingContext;\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousViewport = gl.getParameter(gl.VIEWPORT);\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\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 gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n gl.viewport(\n previousViewport[0],\n previousViewport[1],\n previousViewport[2],\n previousViewport[3],\n );\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\nfunction makeShader(gl, vertSrc, fragSrc) {\n const program = createProgram(gl, vertSrc, fragSrc);\n const uniformCache = new Map();\n\n const getUniformLocation = (name) => {\n if (!uniformCache.has(name)) {\n uniformCache.set(name, gl.getUniformLocation(program, name));\n }\n return uniformCache.get(name);\n };\n\n return {\n program,\n setUniform(name, value) {\n const location = getUniformLocation(name);\n if (!location) return;\n if (typeof value === \"boolean\") {\n gl.uniform1i(location, value ? 1 : 0);\n return;\n }\n if (typeof value === \"number\") {\n gl.uniform1f(location, value);\n return;\n }\n if (Array.isArray(value)) {\n if (value.length === 3) gl.uniform3f(location, value[0], value[1], value[2]);\n else if (value.length === 4) gl.uniform4f(location, value[0], value[1], value[2], value[3]);\n return;\n }\n },\n };\n}\n\nfunction ensureBlendShaderProgram(renderer, vertSrc, fragSrc) {\n renderer.shaderProgram ??= makeShader(renderer.drawingContext, vertSrc, fragSrc);\n return renderer.shaderProgram;\n}\n\nfunction createFramebufferTexture(gl, width, height) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n gl.RGBA,\n width,\n height,\n 0,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n null,\n );\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 gl.bindTexture(gl.TEXTURE_2D, null);\n return texture;\n}\n\nfunction createFramebuffer(renderer, options) {\n const gl = renderer.drawingContext;\n const density = options.density ?? 1;\n const framebuffer = gl.createFramebuffer();\n const width = Math.max(1, options.width);\n const height = Math.max(1, options.height);\n const pixelWidth = Math.max(1, Math.round(width * density));\n const pixelHeight = Math.max(1, Math.round(height * density));\n const colorTexture = createFramebufferTexture(gl, pixelWidth, pixelHeight);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER,\n gl.COLOR_ATTACHMENT0,\n gl.TEXTURE_2D,\n colorTexture,\n 0,\n );\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n\n return {\n __brushFramebuffer: true,\n framebuffer,\n colorTexture,\n width,\n height,\n density,\n pixelDensity: () => density,\n remove() {\n gl.deleteFramebuffer(framebuffer);\n gl.deleteTexture(colorTexture);\n },\n };\n}\n\nfunction ensureBlendSourceFramebuffer(\n renderer,\n currentFramebuffer,\n width,\n height,\n density,\n) {\n currentFramebuffer?.remove?.();\n return createFramebuffer(renderer, {\n width,\n height,\n density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n}\n\nfunction runBlendShaderPass({\n renderer,\n shader,\n source,\n mask,\n color,\n isBrushMask,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n}) {\n const gl = renderer.drawingContext;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousProgram = gl.getParameter(gl.CURRENT_PROGRAM);\n const previousVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);\n\n const quadVao = gl.createVertexArray();\n gl.bindVertexArray(quadVao);\n gl.useProgram(shader.program);\n gl.disable(gl.DEPTH_TEST);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, source.colorTexture);\n gl.uniform1i(gl.getUniformLocation(shader.program, \"u_source\"), 0);\n\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, mask.colorTexture);\n gl.uniform1i(gl.getUniformLocation(shader.program, \"u_mask\"), 1);\n\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n gl.uniform3f(\n gl.getUniformLocation(shader.program, \"u_color\"),\n color[0],\n color[1],\n color[2],\n );\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n withScissor(\n gl,\n dirtyRect,\n () => {\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n },\n !targetIsFramebuffer,\n );\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.activeTexture(gl.TEXTURE0);\n gl.bindVertexArray(previousVao);\n gl.useProgram(previousProgram);\n gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n gl.deleteVertexArray(quadVao);\n}\n\nfunction blitSourceToFramebuffer(args) {\n return blitDefaultFramebufferSource(args);\n}\n\nexport function initStandaloneCompositorRuntime() {\n setCompositorRuntime({\n clearTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n createFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Stroke Hooks\n// =============================================================================\n\nimport { create2DCanvas, get2DContext } from \"../../core/compositor_runtime.js\";\nimport { setStrokeRuntime } from \"../../stroke/runtime.js\";\n\nfunction cssColor(value) {\n if (typeof value === \"number\") {\n const c = Math.max(0, Math.min(255, value));\n return `rgb(${c} ${c} ${c})`;\n }\n return value ?? \"black\";\n}\n\nfunction buildTipSurface(canvas) {\n const ctx = get2DContext(canvas, true);\n const surface = {\n canvas,\n drawingContext: ctx,\n width: canvas.width,\n height: canvas.height,\n pixels: null,\n _fillStyle: \"#ffffff\",\n _strokeStyle: \"transparent\",\n _lineWidth: 1,\n\n pixelDensity() {\n return 1;\n },\n\n background(value) {\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.fillStyle = cssColor(value);\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n ctx.restore();\n },\n\n noSmooth() {\n ctx.imageSmoothingEnabled = false;\n },\n\n push() {\n ctx.save();\n },\n\n pop() {\n ctx.restore();\n },\n\n translate(x, y) {\n ctx.translate(x, y);\n },\n\n scale(x, y = x) {\n ctx.scale(x, y);\n },\n\n rotate(angle) {\n ctx.rotate(angle);\n },\n\n noStroke() {\n surface._strokeStyle = \"transparent\";\n },\n\n stroke(value) {\n surface._strokeStyle = cssColor(value);\n },\n\n noFill() {\n surface._fillStyle = \"transparent\";\n },\n\n fill(value) {\n surface._fillStyle = cssColor(value);\n },\n\n strokeWeight(value) {\n surface._lineWidth = value;\n },\n\n rect(x, y, w, h) {\n ctx.beginPath();\n ctx.rect(x, y, w, h);\n surface._paint();\n },\n\n circle(x, y, d) {\n ctx.beginPath();\n ctx.arc(x, y, d / 2, 0, Math.PI * 2);\n surface._paint();\n },\n\n ellipse(x, y, w, h) {\n ctx.beginPath();\n ctx.ellipse(x, y, w / 2, h / 2, 0, 0, Math.PI * 2);\n surface._paint();\n },\n\n line(x1, y1, x2, y2) {\n ctx.beginPath();\n ctx.moveTo(x1, y1);\n ctx.lineTo(x2, y2);\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n },\n\n beginShape() {\n ctx.beginPath();\n surface._shapeStarted = false;\n },\n\n vertex(x, y) {\n if (!surface._shapeStarted) {\n ctx.moveTo(x, y);\n surface._shapeStarted = true;\n } else {\n ctx.lineTo(x, y);\n }\n },\n\n endShape(close = false) {\n if (close) ctx.closePath();\n surface._paint();\n },\n\n loadPixels() {\n surface.pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;\n },\n\n updatePixels() {\n const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n imageData.data.set(surface.pixels);\n ctx.putImageData(imageData, 0, 0);\n },\n\n _paint() {\n if (surface._fillStyle !== \"transparent\") {\n ctx.fillStyle = surface._fillStyle;\n ctx.fill();\n }\n if (surface._strokeStyle !== \"transparent\") {\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n }\n },\n };\n\n return surface;\n}\n\nfunction createTipSurface(width, height) {\n return buildTipSurface(create2DCanvas(width, height, true));\n}\n\nfunction loadImageTip(src, imageToWhite) {\n return new Promise((resolve, reject) => {\n const NativeImage = globalThis.Image;\n if (!NativeImage) {\n reject(new Error(\"Standalone image brush loading requires Image support.\"));\n return;\n }\n\n const nativeImg = new NativeImage();\n nativeImg.onload = () => {\n const surface = buildTipSurface(\n create2DCanvas(nativeImg.naturalWidth, nativeImg.naturalHeight, true),\n );\n surface.drawingContext.drawImage(nativeImg, 0, 0);\n imageToWhite(surface);\n resolve(surface);\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\nexport function initStandaloneStrokeRuntime() {\n setStrokeRuntime({\n createTipSurface,\n loadImageTip,\n });\n}\n","/**\n * @fileoverview Standalone entry point for brush.\n */\n\nexport * from \"./adapters/standalone/runtime.js\";\nexport * from \"./adapters/standalone/frame.js\";\nexport { createCanvas } from \"./adapters/standalone/target.js\";\nexport * from \"./index.shared.js\";\n\nimport { initStandaloneTargetRuntime } from \"./adapters/standalone/target.js\";\nimport { initStandaloneRendererRuntime } from \"./adapters/standalone/renderer.js\";\nimport { initStandaloneCompositorRuntime } from \"./adapters/standalone/compositor.js\";\nimport { initStandaloneStrokeRuntime } from \"./adapters/standalone/stroke.js\";\nimport { initStandaloneRuntime } from \"./adapters/standalone/runtime.js\";\n\ninitStandaloneTargetRuntime();\ninitStandaloneRuntime();\ninitStandaloneRendererRuntime();\ninitStandaloneCompositorRuntime();\ninitStandaloneStrokeRuntime();\n"],"names":["identityMatrix","a","b","c","d","x","y","Cwidth","Cheight","Renderer","Density","usesRadians","fromDegrees","angle","createColor","Error","getAffineMatrix","targetRuntime","load","syncDensity","isCanvasReady","instance","inst","activateInstance","deactivateInstance","getActiveFramebuffer","isFramebufferTarget","setTargetState","state","Instance","target","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","create2DCanvas","width","height","willReadFrequently","canvas","OffscreenCanvas","element","document","createElement","drawingContext","getContext","undefined","compositorRuntime","clearTarget","ensureBlendShaderProgram","ensureBlendSourceFramebuffer","createFramebuffer","runBlendShaderPass","blitSourceToFramebuffer","args","strokeComposite","fillComposite","clearRenderTarget","getTargetPixelSize","Math","max","round","normalizeDirtyRect","floor","min","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","draw","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","this","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","pixelDensity","ensureResources","fillResources","mask","ctx","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","shaderProgram","activeFramebuffer","source","renderer","sourceTarget","sourceFramebuffer","targetIsFramebuffer","shaderMask","getShaderMask","color","flushActiveComposite","buffer","loadTarget","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","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","push","callback","noise","noise2","noiseSeed","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","withinBounds","constrain","low","high","nAngle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","sin","toDegrees","rad","isRad","runtimeUsesRadians","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","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","m","mx","my","update","plotted","colIdx","rowIdx","reset","isIn","isActive","isInCanvas","skipCheck","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","steps","fieldActive","usePlot","getRowIndex","y_offset","getColIndex","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","angleMode","has","generateField","entry","normalizeFieldAngles","gen","refreshField","currentField","keys","join","noField","name","funct","set","listFields","fn","_stateStack","clamp","DEGREES","RADIANS","colorContext","currentAngleMode","transformStack","currentTransform","multiplyTransform","left","right","Color","g","hex","rgbToHex","standardize","rgb","hexToRgb","toString","slice","replace","_match","red","green","blue","result","exec","getColorContext","fillStyle","_getRed","_getGreen","_getBlue","mode","getAngleMode","wash","stroke","hatch","mass","pop","saved","brush","popState","translate","theta","cosTheta","sinTheta","scale","initStandaloneRuntime","hooks","render","clear","bindFramebuffer","FRAMEBUFFER","clearColor","COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","_current","_curvature","_strokeArray","_strokeOrigin","activeTarget","activeDensity","activeWidth","activeHeight","applyLoadedTarget","density","premultipliedAlpha","getTargetContext","createRenderer","createCanvas","logicalWidth","logicalHeight","Number","style","id","parent","querySelector","appendChild","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","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","polygon","beginShape","vertex","endShape","circle","radius","arcLength","angleOffset","randomFactor","randomAngle","offsetX","offsetY","arc","startDeg","sweepDeg","segmentCount","segmentSweep","startX","startY","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","strokeRuntime","createTipSurface","loadImageTip","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","createShader","shaderSource","compileShader","attachShader","linkProgram","rendererRuntime","beginDirectMaskDraw","endDirectMaskDraw","resetDirectShaderTracking","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","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","getProjectionMatrix","beginMaskTarget","endMaskTarget","accumulateDirtyRect","currentRect","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","targetState","tex","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","activeTexture","TEXTURE0","uniform1i","u_tex","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","flush","needsStrokeMask","remove","antialias","depth","stencil","_Renderer","weight","opacity","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","add","params","includes","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","rest","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","background","noSmooth","noStroke","T","imageToWhite","tips","tipKey","param","colors","buffers","image","getBrushParams","brushName","scaleBrushes","values","spacing","pick","arguments","strokeWeight","clip","region","noClip","_position","initializeDrawingState","plot","snapshotMatrix","gaussians","angleScale","isPlot","cp","ct","cs","ck","noiseoffset","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","saveState","stepSize","totalSteps","pressureCount","cachedPressure","lineNoiseCount","cachedLineNoise","u_matrix","drawArrays","POINTS","glDraw","restoreState","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawImageTip","plotAngle","plotCos","plotSin","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","vibrate","rx","ry","size","overscan","maxPressure","scatterReach","tipReach","getImageTipOverscan","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","flowLine","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","then","HatchState","HatchSetState","rand","continuous","gradient","hatchStyle","hBrush","noHatch","scanlineHatch","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","scanY","getHatchLines","polygons","segs","poly","getHatchSegments","getActiveHatchConfig","lines","isConnector","prev","createHatch","drawSegment","save","Object","drawFn","withHatchStyle","renderHatchSegments","noMass","jitterPolygon","jitterX","jitterY","projectAnchorToBisector","anchor","nx","ny","getShortArcAngles","toAngleUnit","endDeg","splitSegment","seg","gap","gx","gy","drawMassArcs","pivotBias","bias","bounds","getPolygonBounds","sx","sy","getPivotAnchor","parts","part","center","startAngle","endAngle","drawMassPass","createMass","shape","pols","isPolygon","basePolygon","maxJitter","jitters","getMassPolygons","hatchState","brushState","fieldState","precision","strength","outline","hatchDist","baseAngle","_dist","_angle","_options","FillMaskUploadCanvas","isFillCompositeRegistered","maskWidth","maskHeight","needsFillMaskCanvas","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","clearRect","drawImage","colorTexture","texSubImage2D","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","noFill","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","keep","dst","trimStart","trimEnd","edgeStart","edgeEnd","edgeVec","newVertex","insertIdx","splice","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","setTransform","strokeStyle","lineCap","darker","sparse","layer","numLayers","erase","restore","lineWidth","matrix","getTransform","beginPath","first","tx","ty","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","filterPoints","again","steiner","equals","area","removeNode","earcutLinked","ear","triangles","dim","invSize","pass","z","zOrder","prevZ","nextZ","numMerges","inSize","tail","q","pSize","qSize","sortLinked","indexCurve","stop","isEarHashed","isEar","cureLocalIntersections","splitEarcut","ax","bx","pointInTriangleExceptFirst","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","pointInTriangle","intersectsPolygon","inside","middleInside","q1","q2","o1","sign","o2","o3","o4","onSegment","num","createNode","b2","an","bp","insertNode","last","_opacity","_bleed","fluid","modifiers","_","shift","shifted","pts","point","cross","_center","createFill","FillSetState","washProgram","washVao","washBuffer","washProjection","washGpuBufferSize","WashAttr","WashUniform","noWash","transformVertexToScreen","_renderer","hadDepthTest","isEnabled","DEPTH_TEST","framebuffer","viewport","resetStandaloneShaderTracking","blendEquation","FUNC_ADD","ONE_MINUS_SRC_ALPHA","previousFramebuffer","getParameter","FRAMEBUFFER_BINDING","previousViewport","VIEWPORT","vertSrc","fragSrc","uniformCache","setUniform","location","uniform3f","uniform1f","makeShader","pixelWidth","pixelHeight","createFramebufferTexture","framebufferTexture2D","COLOR_ATTACHMENT0","__brushFramebuffer","deleteFramebuffer","currentFramebuffer","previousProgram","CURRENT_PROGRAM","previousVao","VERTEX_ARRAY_BINDING","quadVao","TEXTURE1","TRIANGLES","deleteVertexArray","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","blitFramebuffer","NEAREST","blitDefaultFramebufferSource","cssColor","buildTipSurface","get2DContext","surface","_fillStyle","_strokeStyle","_lineWidth","fillRect","_paint","ellipse","_shapeStarted","getImageData","imageData","putImageData","resolve","reject","NativeImage","globalThis","Image","nativeImg","onload","naturalWidth","naturalHeight","onerror","crossOrigin","ensureWashReady","vertexCount","flat","holeIndices","outerLen","outerNode","signedArea","linkedList","earcut","buildTriangleBuffer","drawWashPolygon","HTMLCanvasElement","isCanvasTarget","isOffscreenCanvasTarget","isSupportedTarget","initStandaloneRendererRuntime","initStandaloneCompositorRuntime","initStandaloneStrokeRuntime"],"mappings":"AAIA,MAAMA,EAAiB,CACrBC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,GAGE,ICEIC,EAAQC,EAAmBC,EAAUC,EDFrCC,EAAc,KAAM,EACpBC,EAAeC,GAAUA,EACzBC,EAAc,KACvB,MAAM,IAAIC,MAAM,yCAEPC,EAAkB,IAAMhB,ECD/BiB,EAAgB,CAClBC,KAAM,KACJ,MAAM,IAAIH,MAAM,0CAElBI,YAAa,IAAMT,EACnBU,cAAe,KACb,MAAM,IAAIL,MAAM,0CAElB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+Z,GAAkBhZ,EAAQA,EAAOS,MAAOT,EAAOU,OAAQ,EACzD,EAoGIrB,YAlDG,WAML,OALAQ,EAAe,CACbpB,OAAQqa,GACRpa,QAASqa,GACTna,QAASia,KAEJA,EACT,EA4CIvZ,cAvCG,WACL,IAAK+P,GACH,MAAM,IAAIpQ,MACR,+EAGN,EAkCIM,SA7BG,WAAqB,EA8BxBE,iBA7BG,WAA6B,EA8BhCC,mBA7BG,WAA+B,EA8BlCC,qBAvBG,WACL,OAAO,IACT,EAsBIC,oBAbG,WACL,OAA4C,IAArC8qB,UAAU,IAAI+a,kBACvB,GX5HEtmC,EAAgB,IAAKA,KAAkB6Y,I+BvCzCD,KHmBO,WVPA,IAA4BC,IUQd,CACjBkJ,uBACAC,qBACAC,0BAA2B+iB,IVV7BljB,GAAkB,IAAKA,MAAoBjJ,EUY7C,CGxBAsxB,GFuMO,W3B3GA,IAA8BtxB,I2B4Gd,CACnB3W,eACAC,4BACAC,gCACAC,qBACAC,sBACAC,4B3BjHFN,EAAoB,IAAKA,KAAsB4W,E2BmHjD,CE/MAuxB,GDqKO,WfrKA,IAA0BvxB,IesKd,CACfoI,oBACAC,iBfvKFF,GAAgB,IAAKA,MAAkBnI,EeyKzC,CCzKAwxB","x_google_ignoreList":[5,6,27]}
\ No newline at end of file
+{"version":3,"file":"brush.esm.js","sources":["../src/core/runtime.js","../src/core/target.js","../src/core/dirty_rect.js","../src/core/compositor_runtime.js","../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/save.js","../src/adapters/standalone/runtime.js","../src/adapters/standalone/frame.js","../src/adapters/standalone/target.js","../src/core/primitives.js","../src/core/polygon.js","../src/core/plot.js","../src/stroke/runtime.js","../src/stroke/composite.js","../src/core/gl/utils.js","../src/core/renderer_runtime.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/hatch/mass.js","../src/fill/mask.js","../src/fill/composite.js","../src/fill/fill.js","../node_modules/earcut/src/earcut.js","../src/fill/wash.js","../src/adapters/standalone/renderer.js","../src/adapters/standalone/compositor.js","../src/adapters/standalone/stroke.js","../src/index.standalone.js"],"sourcesContent":["// =============================================================================\n// Runtime Hooks\n// =============================================================================\n\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nexport let usesRadians = () => false;\nexport let fromDegrees = (angle) => angle;\nexport let createColor = () => {\n throw new Error(\"No runtime color adapter registered.\");\n};\nexport let getAffineMatrix = () => identityMatrix;\n\n/**\n * Registers or updates host-runtime hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setRuntime(hooks) {\n if (hooks.usesRadians) usesRadians = hooks.usesRadians;\n if (hooks.fromDegrees) fromDegrees = hooks.fromDegrees;\n if (hooks.createColor) createColor = hooks.createColor;\n if (hooks.getAffineMatrix) getAffineMatrix = hooks.getAffineMatrix;\n}\n","// =============================================================================\n// Target Runtime Hooks\n// =============================================================================\n\n/**\n * Shared target state exposed to core modules.\n *\n * Host adapters are expected to keep these bindings updated with the currently\n * active drawing target. The exact object type is adapter-defined, but core code\n * assumes the active renderer exposes:\n * - `drawingContext`: the active WebGL context\n * - target dimensions through `Cwidth` / `Cheight`\n * - pixel density through `Density`\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\n\nlet targetRuntime = {\n load: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n syncDensity: () => Density,\n isCanvasReady: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n instance: (inst) => {\n Instance = inst;\n },\n activateInstance: (inst) => {\n Instance = inst;\n },\n deactivateInstance: () => {},\n getActiveFramebuffer: () => null,\n isFramebufferTarget: () => false,\n};\n\n/**\n * Updates the shared target state consumed by core modules.\n *\n * @param {object} state\n */\nexport function setTargetState(state) {\n if (\"Cwidth\" in state) Cwidth = state.Cwidth;\n if (\"Cheight\" in state) Cheight = state.Cheight;\n if (\"Instance\" in state) Instance = state.Instance;\n if (\"Renderer\" in state) Renderer = state.Renderer;\n if (\"Density\" in state) Density = state.Density;\n}\n\n/**\n * Registers or updates host target hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setTargetRuntime(hooks) {\n targetRuntime = { ...targetRuntime, ...hooks };\n}\n\nexport const load = (buffer = false) => targetRuntime.load(buffer);\nexport const syncDensity = () => targetRuntime.syncDensity();\nexport const isCanvasReady = () => targetRuntime.isCanvasReady();\nexport const instance = (inst) => targetRuntime.instance(inst);\nexport const activateInstance = (inst) => targetRuntime.activateInstance(inst);\nexport const deactivateInstance = () => targetRuntime.deactivateInstance();\nexport const getActiveFramebuffer = () => targetRuntime.getActiveFramebuffer();\nexport const isFramebufferTarget = (target) =>\n targetRuntime.isFramebufferTarget(target);\n","// =============================================================================\n// Module: Dirty Rect Utilities\n// =============================================================================\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n *\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 */\nexport const 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 explicit target bounds.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nexport const normalizeDirtyRect = (rect, width, height) => {\n if (!rect) return null;\n\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 *\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 */\nexport const 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 target bounds.\n *\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nexport const getFullDirtyRect = (width, height) => ({\n minX: 0,\n minY: 0,\n maxX: width,\n maxY: height,\n});\n","// =============================================================================\n// Compositor Runtime Hooks\n// =============================================================================\n\n/**\n * Shared compositor helpers and host hooks.\n *\n * The shared code in this module assumes framebuffer-like targets expose:\n * - `framebuffer`: native WebGL framebuffer handle\n * - optional lifecycle methods supplied by the host adapter\n *\n * Higher-level core modules also attach their own bookkeeping fields onto the\n * active renderer and mask targets, such as:\n * - `shaderProgram`\n * - `blendSourceFramebuffer`\n * - `glMask`\n * - `fillMaskFramebuffer`\n * - `mask`\n *\n * These are library-level contract fields, not host-specific internals.\n */\n\nexport const create2DCanvas = (width, height, willReadFrequently = false) => {\n const canvas =\n typeof OffscreenCanvas !== \"undefined\"\n ? new OffscreenCanvas(width, height)\n : (() => {\n const element = document.createElement(\"canvas\");\n element.width = width;\n element.height = height;\n return element;\n })();\n canvas.drawingContext = canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas;\n};\n\nexport const get2DContext = (canvas, willReadFrequently = false) => {\n canvas.drawingContext ??= canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas.drawingContext;\n};\n\nexport function blitDefaultFramebufferSource({\n renderer,\n sourceFramebuffer,\n dirtyRect,\n getTargetPixelSize,\n toScissorBox,\n}) {\n const gl = renderer.drawingContext;\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 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\nlet compositorRuntime = {\n clearTarget: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendShaderProgram: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendSourceFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n createFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n runBlendShaderPass: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n blitSourceToFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host compositor hooks used by core compositing code.\n *\n * @param {object} hooks\n */\nexport function setCompositorRuntime(hooks) {\n compositorRuntime = { ...compositorRuntime, ...hooks };\n}\n\nexport const clearTarget = (...args) => compositorRuntime.clearTarget(...args);\nexport const ensureBlendShaderProgram = (...args) =>\n compositorRuntime.ensureBlendShaderProgram(...args);\nexport const ensureBlendSourceFramebuffer = (...args) =>\n compositorRuntime.ensureBlendSourceFramebuffer(...args);\nexport const createFramebuffer = (...args) =>\n compositorRuntime.createFramebuffer(...args);\nexport const runBlendShaderPass = (...args) =>\n compositorRuntime.runBlendShaderPass(...args);\nexport const blitSourceToFramebuffer = (...args) =>\n compositorRuntime.blitSourceToFramebuffer(...args);\n","import {\n Cwidth,\n Cheight,\n Renderer,\n Density,\n load as loadTarget,\n isCanvasReady,\n syncDensity,\n getActiveFramebuffer,\n isFramebufferTarget,\n} from \"./target.js\";\nimport {\n expandDirtyRect,\n normalizeDirtyRect as clampDirtyRect,\n unionDirtyRect,\n getFullDirtyRect as getFullRect,\n} from \"./dirty_rect.js\";\nimport {\n clearTarget as clearRenderTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n} from \"./compositor_runtime.js\";\n\nimport 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\nlet strokeComposite = null;\nlet fillComposite = null;\n\nexport const registerStrokeComposite = (composite) => {\n strokeComposite = composite;\n};\n\nexport const registerFillComposite = (composite) => {\n fillComposite = composite;\n};\n\nconst clearTarget = (target) => {\n clearRenderTarget(Renderer, target, isFramebufferTarget);\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\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\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n const { width, height } = getTargetPixelSize();\n return clampDirtyRect(rect, width, height);\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 getFullRect(width, 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 * 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/**\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: null,\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 const composite = target === this.glMask ? strokeComposite : fillComposite;\n composite?.clearMask?.(target, clearTarget);\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 GL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n const composite = isBrushMask ? strokeComposite : fillComposite;\n return composite?.getCompositeRect?.(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\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 syncDensity();\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 ensureBlendShaderProgram(Renderer, vertSrc, fragSrc);\n\n this.glMask = strokeComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n );\n const fillResources = fillComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n ) ?? {\n mask: null,\n ctx: null,\n };\n\n if (needsBlendSourceFramebuffer) {\n Renderer.blendSourceFramebuffer = ensureBlendSourceFramebuffer(\n Renderer,\n Renderer.blendSourceFramebuffer,\n Cwidth,\n Cheight,\n Density,\n );\n }\n\n this.mask = fillResources.mask;\n this.ctx = fillResources.ctx;\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 // 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 fully at the start of each blend cycle so stale\n // dirty-rect bookkeeping cannot leak an old stroke into the next color.\n this.clearMask(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) {\n this.isBlending = false;\n this.cachedColor = null;\n \n }\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 GL 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 = blitSourceToFramebuffer({\n renderer: Renderer,\n sourceTarget: activeFramebuffer ?? Renderer,\n sourceFramebuffer: Renderer.blendSourceFramebuffer,\n dirtyRect,\n isFramebufferTarget,\n Cwidth,\n Cheight,\n getTargetPixelSize,\n toScissorBox,\n withScissor,\n });\n const targetIsFramebuffer = !!activeFramebuffer;\n const composite = isBrushMask ? strokeComposite : fillComposite;\n const shaderMask = composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n );\n\n runBlendShaderPass({\n renderer: Renderer,\n shader,\n source,\n mask: shaderMask,\n color: this.cachedColor,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n });\n this.clearMask(mask);\n },\n};\n\n/**\n * Flushes any pending stroke/fill mask work into the current target and resets\n * the shared compositor back to its initial idle state.\n */\nexport const flushActiveComposite = () => {\n isMixReady();\n Mix.blend(false, true);\n Mix.clearMask(Mix.glMask);\n Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n};\n\n/**\n * Loads and initializes the drawing target, then refreshes compositing\n * resources if the renderer was already active.\n *\n * @param {object|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\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 { usesRadians as runtimeUsesRadians } from \"./runtime.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());\nlet rng2 = 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 rng2 = prng_alea(`${s}:2`);\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()));\nexport let noise2 = 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 noise2 = createNoise2D(prng_alea(`${s}:2`));\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);\nexport const rr2 = (e = 0, r = 1) => e + rng2() * (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);\nexport const randInt2 = (e, r) => ~~rr2(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 if (isRad || runtimeUsesRadians()) {\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 || runtimeUsesRadians()\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 { Cwidth, Cheight } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\nimport { getAffineMatrix } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Matrix transformations\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 const m = getAffineMatrix();\n this.mx = m.x;\n this.my = m.y;\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 = Math.round((x + this.mx - left_x) / resolution);\n this.rowIdx = Math.round((y + this.my - top_y) / resolution);\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 + this.mx;\n const y = this.y + this.my;\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(skipCheck = false) {\n if (!State.field.isActive) return 0;\n return (skipCheck || this.isIn())\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 runtime angle units.\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 const steps = _length / _step;\n const fieldActive = State.field.isActive;\n const usePlot = !!_scale;\n for (let i = 0; i < steps; i++) {\n const angle =\n (fieldActive ? this.angle(true) : 0) - (usePlot ? _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 + getAffineMatrix().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 + getAffineMatrix().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 = rr2(0.2, 0.8),\n ba = randInt2(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt2(15, 25));\n return 0.2 * angle * cos(t) + noise2(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt2(-10, 10);\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise2(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 = randInt2(-30, -15) + Math.abs(44 * sin(t));\n if (randInt2(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 = randInt2(10, 15) + 5 * sin(t),\n cr = randInt2(3, 6) + 3 * cos(t),\n ba = randInt2(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt2(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr2(0.4, 0.8),\n ba = randInt2(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt2(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt2(5, 10);\n const dir = randInt2(0, 2) * 2 - 1;\n const offset = randInt2(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr2(0.1, 0.9) * num_columns,\n y: rr2(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 = randInt2(3, 8),\n amp = randInt2(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\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 wash: State.wash ? { ...State.wash } : null,\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n mass: State.mass ? { ...State.mass } : null,\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 if (saved.wash) State.wash = { ...saved.wash };\n if (saved.mass) {\n State.mass = { ...saved.mass };\n } else if (State.mass) {\n State.mass = {\n ...State.mass,\n isActive: false,\n brush: null,\n color: null,\n options: {},\n };\n }\n}\n","// =============================================================================\n// Adapter: Standalone Runtime Hooks\n// =============================================================================\n\nimport { setRuntime } from \"../../core/runtime.js\";\nimport { push as pushState, pop as popState } from \"../../core/save.js\";\n\nconst clamp = (value, min, max) => Math.max(min, Math.min(value, max));\n\nexport const DEGREES = \"degrees\";\nexport const RADIANS = \"radians\";\n\nlet colorContext = null;\nlet currentAngleMode = DEGREES;\nconst transformStack = [];\nlet currentTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nfunction getColorContext() {\n if (colorContext) return colorContext;\n\n if (typeof document !== \"undefined\") {\n colorContext = document.createElement(\"canvas\").getContext(\"2d\");\n return colorContext;\n }\n\n if (typeof OffscreenCanvas !== \"undefined\") {\n colorContext = new OffscreenCanvas(1, 1).getContext(\"2d\");\n return colorContext;\n }\n\n throw new Error(\"Standalone color parsing requires CanvasRenderingContext2D support.\");\n}\n\nfunction multiplyTransform(left, right) {\n return {\n a: left.a * right.a + left.c * right.b,\n b: left.b * right.a + left.d * right.b,\n c: left.a * right.c + left.c * right.d,\n d: left.b * right.c + left.d * right.d,\n x: left.a * right.x + left.c * right.y + left.x,\n y: left.b * right.x + left.d * right.y + left.y,\n };\n}\n\n/**\n * Runtime-native color object compatible with the expectations of core modules.\n */\nexport class Color {\n constructor(r, g, b) {\n if (r?._array) {\n this.r = Math.round(r._array[0] * 255);\n this.g = Math.round(r._array[1] * 255);\n this.b = Math.round(r._array[2] * 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n this._array = [...r._array];\n this.gl = this._array;\n return;\n }\n\n if (typeof r === \"string\") {\n const rgbaMatch = /^rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*([\\d.]+))?\\s*\\)$/i.exec(r);\n if (rgbaMatch) {\n this.r = clamp(parseInt(rgbaMatch[1]), 0, 255);\n this.g = clamp(parseInt(rgbaMatch[2]), 0, 255);\n this.b = clamp(parseInt(rgbaMatch[3]), 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n const alpha = rgbaMatch[4] !== undefined ? clamp(parseFloat(rgbaMatch[4]), 0, 1) : 1;\n this._array = [this.r / 255, this.g / 255, this.b / 255, alpha];\n this.gl = this._array;\n return;\n }\n this.hex = this.standardize(r);\n const rgb = this.hexToRgb(this.hex);\n this.r = rgb.r;\n this.g = rgb.g;\n this.b = rgb.b;\n } else {\n this.r = clamp(r ?? 0, 0, 255);\n this.g = clamp(g ?? r ?? 0, 0, 255);\n this.b = clamp(b ?? r ?? 0, 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n }\n\n this._array = [this.r / 255, this.g / 255, this.b / 255, 1];\n this.gl = this._array;\n }\n\n rgbToHex(r, g, b) {\n return `#${((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1)}`;\n }\n\n hexToRgb(hex) {\n hex = hex.replace(\n /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i,\n (_match, red, green, blue) => red + red + green + green + blue + blue,\n );\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n if (!result) {\n throw new Error(`Invalid color value \"${hex}\".`);\n }\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n };\n }\n\n standardize(value) {\n const ctx = getColorContext();\n ctx.fillStyle = value;\n return ctx.fillStyle;\n }\n\n _getRed() {\n return this.r;\n }\n\n _getGreen() {\n return this.g;\n }\n\n _getBlue() {\n return this.b;\n }\n}\n\n/**\n * Sets the active standalone angle mode.\n *\n * @param {\"degrees\"|\"radians\"} mode\n */\nexport function angleMode(mode) {\n if (mode !== DEGREES && mode !== RADIANS) {\n throw new Error(`Invalid angle mode \"${mode}\". Use \"degrees\" or \"radians\".`);\n }\n currentAngleMode = mode;\n}\n\n/**\n * Returns the current standalone angle mode.\n *\n * @returns {\"degrees\"|\"radians\"}\n */\nexport function getAngleMode() {\n return currentAngleMode;\n}\n\n/**\n * Pushes the current standalone transform onto the stack.\n */\nexport function push() {\n pushState();\n transformStack.push({ ...currentTransform });\n}\n\n/**\n * Pops the last standalone transform from the stack.\n */\nexport function pop() {\n if (transformStack.length === 0) return;\n currentTransform = transformStack.pop();\n popState();\n}\n\n/**\n * Applies a translation to the current standalone transform.\n *\n * @param {number} x\n * @param {number} y\n */\nexport function translate(x, y) {\n currentTransform = multiplyTransform(currentTransform, {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x,\n y,\n });\n}\n\n/**\n * Applies a rotation to the current standalone transform.\n *\n * @param {number} angle\n */\nexport function rotate(angle) {\n const theta =\n currentAngleMode === RADIANS ? angle : (angle * Math.PI) / 180;\n const cosTheta = Math.cos(theta);\n const sinTheta = Math.sin(theta);\n currentTransform = multiplyTransform(currentTransform, {\n a: cosTheta,\n b: sinTheta,\n c: -sinTheta,\n d: cosTheta,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Applies a scale to the current standalone transform.\n *\n * @param {number} x\n * @param {number} [y=x]\n */\nexport function scale(x, y = x) {\n currentTransform = multiplyTransform(currentTransform, {\n a: x,\n b: 0,\n c: 0,\n d: y,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Installs the standalone runtime hooks used by core modules.\n */\nexport function initStandaloneRuntime() {\n setRuntime({\n usesRadians: () => currentAngleMode === \"radians\",\n fromDegrees: (angle) =>\n currentAngleMode === \"radians\" ? (angle * Math.PI) / 180 : angle,\n createColor: (...args) => {\n if (args.length === 1 && args[0]?._array) return args[0];\n return new Color(...args);\n },\n getAffineMatrix: () => currentTransform,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Frame Helpers\n// =============================================================================\n\nimport { Renderer, isCanvasReady } from \"../../core/target.js\";\nimport { Mix, flushActiveComposite } from \"../../core/color.js\";\nimport { createColor } from \"../../core/runtime.js\";\n\nfunction resetCompositeState() {\n if (Mix.glMask) Mix.clearMask(Mix.glMask);\n if (Mix.mask) Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n}\n\n/**\n * Flushes any pending stroke/fill compositing into the active standalone target.\n *\n * Standalone users should call this at the end of a drawing pass or frame.\n */\nexport function render() {\n flushActiveComposite();\n}\n\n/**\n * Clears the active standalone target.\n *\n * With no arguments, clears to transparent white.\n * With a color, clears to that color at full opacity.\n *\n * @param {...*} args\n */\nexport function clear(...args) {\n isCanvasReady();\n resetCompositeState();\n\n const gl = Renderer.drawingContext;\n const color =\n args.length === 0\n ? [1, 1, 1, 0]\n : [...createColor(...args)._array.slice(0, 3), 1];\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.disable(gl.SCISSOR_TEST);\n gl.clearColor(color[0], color[1], color[2], color[3]);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n}\n","// =============================================================================\n// Adapter: Standalone Target Hooks\n// =============================================================================\n\nimport {\n setTargetRuntime,\n setTargetState,\n} from \"../../core/target.js\";\n\nlet activeTarget = null;\nlet isLoaded = false;\nlet activeDensity = 1;\nlet activeWidth = 0;\nlet activeHeight = 0;\n\nfunction isCanvasTarget(target) {\n return (\n typeof HTMLCanvasElement !== \"undefined\" &&\n target instanceof HTMLCanvasElement\n );\n}\n\nfunction isOffscreenCanvasTarget(target) {\n return (\n typeof OffscreenCanvas !== \"undefined\" &&\n target instanceof OffscreenCanvas\n );\n}\n\nfunction isSupportedTarget(target) {\n return isCanvasTarget(target) || isOffscreenCanvasTarget(target);\n}\n\nfunction getTargetContext(target) {\n return (\n target.getContext(\"webgl2\", { premultipliedAlpha: true }) ??\n target.getContext(\"webgl2\")\n );\n}\n\nfunction createRenderer(target, width, height, density) {\n const drawingContext = getTargetContext(target);\n if (!drawingContext) {\n throw new Error(\"brush.load(target) requires a canvas with a WebGL2 context.\");\n }\n\n return {\n canvas: target,\n drawingContext,\n width,\n height,\n pixelDensity: () => density,\n };\n}\n\nfunction applyLoadedTarget(target, width, height, density) {\n activeTarget = target;\n activeWidth = width;\n activeHeight = height;\n activeDensity = density;\n\n const renderer = createRenderer(target, width, height, density);\n setTargetState({\n Renderer: renderer,\n Cwidth: width,\n Cheight: height,\n Density: density,\n });\n isLoaded = true;\n}\n\n/**\n * Loads a standalone draw target from a DOM canvas or OffscreenCanvas.\n *\n * @param {HTMLCanvasElement|OffscreenCanvas} target\n */\nexport function load(target = activeTarget) {\n if (!isSupportedTarget(target)) {\n throw new Error(\n \"Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.\",\n );\n }\n\n applyLoadedTarget(target, target.width, target.height, 1);\n}\n\n/**\n * Creates a standalone DOM canvas, configures its backing resolution according\n * to the provided pixel density, appends it optionally to the DOM, and loads it\n * as the active brush target.\n *\n * @param {number} width Logical canvas width.\n * @param {number} height Logical canvas height.\n * @param {{pixelDensity?: number, parent?: string|Element|null, id?: string}} [options]\n * @returns {HTMLCanvasElement}\n */\nexport function createCanvas(width, height, options = {}) {\n if (typeof document === \"undefined\") {\n throw new Error(\"brush.createCanvas() requires a browser document.\");\n }\n\n const logicalWidth = Math.max(1, Math.round(width));\n const logicalHeight = Math.max(1, Math.round(height));\n const density = Math.max(1, Number(options.pixelDensity) || 1);\n const canvas = document.createElement(\"canvas\");\n\n canvas.width = Math.max(1, Math.round(logicalWidth * density));\n canvas.height = Math.max(1, Math.round(logicalHeight * density));\n canvas.style.width = `${logicalWidth}px`;\n canvas.style.height = `${logicalHeight}px`;\n if (options.id) canvas.id = options.id;\n\n if (options.parent) {\n const parent =\n typeof options.parent === \"string\"\n ? document.querySelector(options.parent)\n : options.parent;\n if (!parent) {\n throw new Error(`Could not find parent \"${options.parent}\" for brush.createCanvas().`);\n }\n parent.appendChild(canvas);\n }\n\n applyLoadedTarget(canvas, logicalWidth, logicalHeight, density);\n return canvas;\n}\n\n/**\n * Refreshes the standalone target density.\n *\n * Standalone targets currently use a fixed density of 1.\n *\n * @returns {number}\n */\nexport function syncDensity() {\n setTargetState({\n Cwidth: activeWidth,\n Cheight: activeHeight,\n Density: activeDensity,\n });\n return activeDensity;\n}\n\n/**\n * Ensures a standalone target has been loaded.\n */\nexport function isCanvasReady() {\n if (!isLoaded) {\n throw new Error(\n \"No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.\",\n );\n }\n}\n\n/**\n * Standalone build does not use p5 instance switching, so these are no-ops.\n */\nexport function instance() {}\nexport function activateInstance() {}\nexport function deactivateInstance() {}\n\n/**\n * Standalone build does not yet support framebuffer targets.\n *\n * @returns {null}\n */\nexport function getActiveFramebuffer() {\n return null;\n}\n\n/**\n * Returns whether the given target behaves like a framebuffer target.\n *\n * Standalone targets currently only accept canvases and offscreen canvases.\n *\n * @returns {boolean}\n */\nexport function isFramebufferTarget() {\n return arguments[0]?.__brushFramebuffer === true;\n}\n\nexport function initStandaloneTargetRuntime() {\n setTargetRuntime({\n load,\n syncDensity,\n isCanvasReady,\n instance,\n activateInstance,\n deactivateInstance,\n getActiveFramebuffer,\n isFramebufferTarget,\n });\n}\n","import {\n rr2,\n randInt2,\n sin,\n cos,\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 * Polygons ignore fields and won't be good for fills and masses\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 = rr2(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr2() : () => 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 * randInt2(-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 runtime angle units.\n * @param {number} end - End angle in the current runtime angle units.\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","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.wash) this.wash();\n if (State.fill) this.fill();\n if (State.mass) this.mass();\n if (State.hatch) this.hatch();\n if (State.stroke) this.draw();\n }\n}","import { Cwidth, Cheight } from \"./target.js\";\nimport { State } from \"./color.js\";\nimport { toDegrees, map, rr2 } 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 = _side < 0 ? 4 : 1;\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 let maxSize = _side <= 0 ? 8 : Math.max(this.segments[idx] * _side * rr2(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.wash) this.wash(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n if (State.mass) this.mass(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.stroke) this.draw(x, y, scale);\n }\n}\n","// =============================================================================\n// Stroke Runtime Hooks\n// =============================================================================\n\nlet strokeRuntime = {\n createTipSurface: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n loadImageTip: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host stroke hooks used by brush-tip loading code.\n *\n * @param {object} hooks\n */\nexport function setStrokeRuntime(hooks) {\n strokeRuntime = { ...strokeRuntime, ...hooks };\n}\n\nexport const createTipSurface = (width, height) =>\n strokeRuntime.createTipSurface(width, height);\nexport const loadImageTip = (src, imageToWhite) =>\n strokeRuntime.loadImageTip(src, imageToWhite);\n","import * as Color from \"../core/color.js\";\nimport { createFramebuffer } from \"../core/compositor_runtime.js\";\n\nlet isStrokeCompositeRegistered = false;\nconst DIRTY_BRUSH_PADDING = 2;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the current stroke mask framebuffer must be recreated.\n * This happens when the renderer has no mask yet, or when the canvas size or\n * pixel density changed since the last allocation.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the stroke mask must be rebuilt.\n */\nfunction needsStrokeMask(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.glMask ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight ||\n (typeof Renderer.glMask.pixelDensity === \"function\" &&\n Renderer.glMask.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures the stroke compositor owns a framebuffer-backed mask with the current\n * canvas dimensions. Stroke stamps are rendered into this mask in WebGL before\n * being blended into the main target.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {object} The framebuffer used as stroke mask.\n */\nexport function ensureStrokeCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n) {\n if (needsStrokeMask(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n Renderer.glMask = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n Renderer.glMask.dirtyRect ??= null;\n Renderer.glMask.isDrawn ??= false;\n return Renderer.glMask;\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current stroke mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearStrokeMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the rect that should be composited from the stroke mask into the\n * main canvas. Stroke bounds are normally tight dirty rects, but when drawing\n * into an active framebuffer we keep the result conservative and composite the\n * full target.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} getActiveFramebuffer - Returns the currently bound framebuffer.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {number} padding - Extra brush padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getStrokeCompositeRect(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n if (getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_BRUSH_PADDING),\n );\n}\n\n/**\n * Returns the resource that should be bound to the blend shader's `u_mask`\n * uniform for stroke compositing.\n *\n * @param {object} _Renderer - Active host renderer.\n * @param {object} mask - Stroke mask framebuffer.\n * @returns {object} Stroke mask framebuffer.\n */\nexport function getStrokeShaderMask(_Renderer, mask) {\n return mask;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the stroke compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initStrokeComposite() {\n if (isStrokeCompositeRegistered) return;\n Color.registerStrokeComposite?.({\n ensureResources: ensureStrokeCompositeResources,\n clearMask: clearStrokeMask,\n getCompositeRect: getStrokeCompositeRect,\n getShaderMask: getStrokeShaderMask,\n });\n isStrokeCompositeRegistered = true;\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// Renderer Runtime Hooks\n// =============================================================================\n\n/**\n * Direct-render hooks used by modules that issue raw WebGL commands.\n *\n * These hooks are intentionally narrow:\n * - begin drawing into an offscreen GL mask target\n * - restore the previous draw target afterward\n * - reset any host-side shader/program bookkeeping after direct GL usage\n */\n\nlet rendererRuntime = {\n beginDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n endDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n resetDirectShaderTracking: () => {},\n};\n\n/**\n * Registers or updates host renderer hooks used by direct WebGL drawing paths.\n *\n * @param {object} hooks\n */\nexport function setRendererRuntime(hooks) {\n rendererRuntime = { ...rendererRuntime, ...hooks };\n}\n\nexport const beginDirectMaskDraw = (renderer, gl, target) =>\n rendererRuntime.beginDirectMaskDraw(renderer, gl, target);\nexport const endDirectMaskDraw = (renderer, gl, state) =>\n rendererRuntime.endDirectMaskDraw(renderer, gl, state);\nexport const resetDirectShaderTracking = (renderer, gl) =>\n rendererRuntime.resetDirectShaderTracking(renderer, gl);\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 { Cwidth, Cheight, Density, Renderer } from \"../core/target.js\";\nimport {\n Mix,\n isMixReady,\n State,\n} from \"../core/color.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport {\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking,\n} from \"../core/renderer_runtime.js\";\nimport { getAffineMatrix } from \"../core/runtime.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;\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 runtime affine transform. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n const m = getAffineMatrix();\n _ma = m.a;\n _mb = m.b;\n _mc = m.c;\n _md = m.d;\n _mx = m.x;\n _my = m.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 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 return beginDirectMaskDraw(Renderer, gl, Mix.glMask);\n}\n\nfunction endMaskTarget(state) {\n endDirectMaskDraw(Renderer, gl, state);\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 * the current runtime transform 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 * @param {number} [extraPadding=0] - Conservative extra padding in user units.\n */\nexport function stampImage(x, y, size, angle, alpha, extraPadding = 0) {\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 const extraRadius = _density * extraPadding * _scale;\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 const boundsRadius = halfSize * 1.42 + extraRadius;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - boundsRadius - 1,\n dScreenY - boundsRadius - 1,\n dScreenX + boundsRadius + 1,\n dScreenY + boundsRadius + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {object} p5img - The preprocessed brush-tip image/canvas (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 const targetState = beginMaskTarget();\n\n // Lazy-create the WebGL texture from the tip 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(targetState);\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let the host adapter know we changed the active program.\n resetDirectShaderTracking(Renderer, gl);\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 const targetState = beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader in case host drawing 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(targetState);\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 host shader tracking.\n // Reset it so the host is forced to re-activate its own shader next time\n // it draws — otherwise it may skip gl.useProgram() and set uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetDirectShaderTracking(Renderer, gl);\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\n// Core imports\nimport { Cwidth, Cheight, Renderer, isCanvasReady } from \"../core/target.js\";\nimport {\n Mix,\n State,\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 cos,\n sin\n} from \"../core/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { createTipSurface, loadImageTip } from \"./runtime.js\";\n\n// Internal module imports\nimport { initStrokeComposite } from \"./composite.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\n\ninitStrokeComposite(); // Register the stroke composite system for offscreen mask rendering and compositing.\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 type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\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 if (params.markerTip === undefined) params.markerTip = true;\n if (params.noise === undefined) params.noise = 0.3;\n params.noise = Math.max(0, Math.min(1, params.noise));\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 g = createTipSurface(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\nexport function getBrushParams(brushName) {\n return list.get(brushName)?.param ?? null;\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 = createColor(...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\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current runtime 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 return region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n return;\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 _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 current.pressureCount = 10;\n current.cachedPressure = undefined;\n current.lineNoiseCount = 5;\n current.cachedLineNoise = undefined;\n\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n if (isPlot) {\n _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n );\n } else {\n _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\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.05 * current.p.noise;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n current.cos = cos(_dir);\n current.sin = sin(_dir);\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 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 pressure = calculatePressure();\n const lineNoise = calculateLineNoise();\n\n if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;\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 if (current.pressureCount >= 10 || current.cachedPressure === undefined) {\n current.cachedPressure = _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n current.pressureCount = 0;\n }\n current.pressureCount++;\n return current.cachedPressure;\n}\n\nfunction calculateLineNoise() {\n if (current.lineNoiseCount >= 10 || current.cachedLineNoise === undefined) {\n current.cachedLineNoise = map(\n noise(current.seed + _position.plotted * 0.01, 0),\n -1,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n current.lineNoiseCount = 0;\n }\n current.lineNoiseCount++;\n return current.cachedLineNoise;\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 * 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\nfunction getImageTipOverscan() {\n const maxPressure = Math.max(1, current.max ?? 1);\n const scatterReach = State.stroke.weight * current.p.scatter;\n const tipReach = State.stroke.weight * current.p.weight * maxPressure;\n\n // Custom/image tips can extend beyond their nominal square because the tip\n // drawing itself may be large and because high scatter creates sparse large\n // stamps near the edge. Keep culling/dirty tracking conservative.\n return Math.max(8, scatterReach * 1.5 + tipReach * 0.75);\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 const overscan = getImageTipOverscan();\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(\n _position.x + rx,\n _position.y + ry,\n size,\n angle,\n alpha * Math.max(0.8, pressure) * rr(0.9, 1.1),\n overscan,\n );\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\n let dx, dy;\n if (_plot) {\n const plotAngle = _plot.angle(_position.plotted);\n const plotCos = cos(plotAngle);\n const plotSin = sin(plotAngle);\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * plotSin + along * plotCos;\n dy = perp * plotCos - along * plotSin;\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 (current.p.markerTip === false) return;\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// 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 runtime angle units.\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 \"markerTip\",\n \"noise\",\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 \"pastel\",\n [\n 2.05 / 3,\n 13.4 / 3,\n 0.91,\n 28,\n 35,\n 0.085 / 3,\n { mode: \"gaussian\", curve: [0.4, 0.05], min_max: [1.09, 0.93] },\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"crayon\",\n [\n 0.9 / 3,\n 5.45 / 3,\n 0.75,\n 250,\n 159,\n 0.23 / 3,\n [1.1, 0.9],\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\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 active host image pipeline.\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 host image object 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 loadImageTip(src, T.imageToWhite).then((p5img) => {\n this.tips.set(src, p5img);\n }),\n ),\n );\n },\n};\n","import { 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// Module: Classic Hatch\n// =============================================================================\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\n/**\n * Returns a shallow snapshot of the current hatch modifier state.\n *\n * @returns {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}}\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Restores hatch modifier state from a previously captured snapshot.\n *\n * @param {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}} state\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Activates classic scanline hatching for subsequent shapes.\n *\n * @param {number} [dist=5] Distance between scanlines.\n * @param {number} [angle=45] Hatch angle in the current runtime angle units.\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [options]\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Overrides the brush, color, and weight used specifically for hatch strokes.\n *\n * @param {string} brush\n * @param {string|object} [color=\"black\"]\n * @param {number} [weight=1]\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Deactivates hatching and clears any hatch-specific brush override.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Generation\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for one polygon by rotating it into scanline space,\n * intersecting horizontal scanlines against its edges, and rotating the\n * resulting segments back into canvas space.\n *\n * @param {Polygon} polygon\n * @param {number} angle Hatch angle in degrees.\n * @param {number} dist Base scanline spacing.\n * @param {number} gradient Multiplicative spacing growth per scanline.\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad),\n sinA = Math.sin(rad);\n const cosB = Math.cos(-rad),\n sinB = Math.sin(-rad);\n\n const verts = polygon.a,\n n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity,\n maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0],\n 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],\n 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,\n step = dist;\n while (Y < maxY) {\n const cx = [];\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1],\n y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(\n edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0])\n );\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n scanY: Y,\n x1: cx[i] * cosB - Y * sinB,\n y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB,\n y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n/**\n * Collects and orders hatch segments for one polygon or a polygon list.\n *\n * Segments are sorted in scanline traversal order so downstream rendering can\n * optionally connect them into a continuous serpentine path.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {number} dist\n * @param {number} angle\n * @param {number} gradient\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction getHatchSegments(polygons, dist, angle, gradient) {\n if (!Array.isArray(polygons)) polygons = [polygons];\n const segs = [];\n for (const poly of polygons) {\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n }\n segs.sort((a, b) => (a.scanY === b.scanY ? a.x1 - b.x1 : a.scanY - b.scanY));\n return segs;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Runs hatch drawing with the temporary hatch-specific brush style if one is active,\n * then restores the outer stroke state.\n *\n * @param {() => void} drawFn\n */\nfunction withHatchStyle(drawFn) {\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n drawFn();\n BrushSetState(save);\n}\n\n/**\n * Resolves the active hatch parameters and precomputes the ordered scanline segments.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{dist:number, options:Object, segs:Object[]}}\n */\nfunction getActiveHatchConfig(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n const segs = getHatchSegments(polygons, dist, angle, gradient);\n return { dist, options, segs };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Lines\n// ---------------------------------------------------------------------------\n\n/**\n * Expands ordered hatch segments into the actual line list that will be drawn.\n *\n * This includes endpoint jitter when `rand` is active and inserts the serpentine\n * connector lines when `continuous` is enabled.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{x1:number, y1:number, x2:number, y2:number, scanY:number, isConnector:boolean}[]}\n */\nexport function getHatchLines(polygons) {\n const { dist, options, segs } = getActiveHatchConfig(polygons);\n const r = options.rand || 0;\n const lines = [];\n\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 += 2 * r * dist * rr(-1, 1);\n y1 += 2 * r * dist * rr(-1, 1);\n x2 += 2 * r * dist * rr(-1, 1);\n y2 += 2 * r * dist * rr(-1, 1);\n }\n const reverse = options.continuous && j % 2 === 1;\n const line = reverse\n ? { x1: x2, y1: y2, x2: x1, y2: y1, scanY: s.scanY, isConnector: false }\n : { x1, y1, x2, y2, scanY: s.scanY, isConnector: false };\n lines.push(line);\n if (j > 0 && options.continuous) {\n const prev = lines[lines.length - 2];\n lines.push({\n x1: prev.x2,\n y1: prev.y2,\n x2: line.x1,\n y2: line.y1,\n scanY: s.scanY,\n isConnector: true,\n });\n }\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Iterates the generated hatch lines and delegates the actual rendering of each\n * segment to the provided callback.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {(x1:number, y1:number, x2:number, y2:number, index:number, segs:Object[]) => void} drawSegment\n */\nfunction renderHatchSegments(polygons, drawSegment) {\n const segs = getHatchLines(polygons);\n withHatchStyle(() => {\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n drawSegment(s.x1, s.y1, s.x2, s.y2, j, segs);\n }\n });\n}\n\n/**\n * Draws classic hatch lines over one polygon or an array of polygons.\n *\n * @param {Polygon|Polygon[]} polygons\n */\nexport function createHatch(polygons) {\n renderHatchSegments(polygons, (x1, y1, x2, y2) => {\n line(x1, y1, x2, y2);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies the currently active hatch modifier to a polygon, or temporarily\n * overrides hatch parameters for this call only.\n *\n * @param {number|false} [_dist=false]\n * @param {number} [_angle]\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [_options]\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (State.hatch.isActive) createHatch(this);\n HatchSetState(state);\n};\n\n/**\n * Converts the plot to a polygon and applies the currently active hatch modifier.\n *\n * @param {number} x\n * @param {number} y\n * @param {number} scale\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.3);\n this.pol.hatch();\n }\n};\n","// =============================================================================\n// Module: Mass\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { arc } from \"../core/primitives.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { rr2, dist, calcAngle } from \"../core/utils.js\";\nimport { fromDegrees, usesRadians } from \"../core/runtime.js\";\nimport { HatchState, HatchSetState, hatch, getHatchLines } from \"./hatch.js\";\nimport { BrushState, BrushSetState, getBrushParams, set } from \"../stroke/stroke.js\";\nimport { wiggle } from \"../core/flowfield.js\";\n\n// ---------------------------------------------------------------------------\n// Mass State\n// ---------------------------------------------------------------------------\n\nState.mass = {\n isActive: false,\n brush: null,\n color: null,\n options: {},\n};\n\n/**\n * Returns a shallow copy of the current mass state.\n * @returns {object}\n */\nexport function MassState() {\n return { ...State.mass };\n}\n\n/**\n * Restores a previously saved mass state.\n * @param {object} state\n */\nexport function MassSetState(state) {\n State.mass = { ...state };\n}\n\n/**\n * Enables massing mode with a brush, color, and optional configuration.\n *\n * @param {string} brush - Brush name to use for the mass pass.\n * @param {string|Color} color - Color to use for the mass pass.\n * @param {object} [options={}] - Massing options such as precision, strength, gradient, and outline.\n */\nexport function mass(brush, color, options = {}) {\n State.mass.brush = brush;\n State.mass.color = color;\n State.mass.options = options;\n State.mass.isActive = true;\n}\n\n/**\n * Disables massing mode for subsequent geometry.\n */\nexport function noMass() {\n State.mass.isActive = false;\n State.mass.brush = null;\n State.mass.color = null;\n State.mass.options = {};\n}\n\n// ---------------------------------------------------------------------------\n// Polygon Preparation\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a translated copy of a polygon.\n * Used to build the secondary mass layers from an existing base polygon.\n * @param {Polygon} polygon\n * @param {number} jitterX\n * @param {number} jitterY\n * @returns {Polygon}\n */\nfunction jitterPolygon(polygon, jitterX, jitterY) {\n return new Polygon(\n polygon.vertices.map((vertex) => [vertex.x + jitterX, vertex.y + jitterY]),\n );\n}\n\n/**\n * Builds the three polygons used for a mass pass.\n * Both polygon and plot inputs use one base polygon plus two translated copies,\n * so plot-based massing only needs a single `genPol(...)` call.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n * @returns {Polygon[]}\n */\nfunction getMassPolygons(shape, x, y, scale) {\n const isPolygon = x === false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const basePolygon = isPolygon ? shape : shape.genPol(x, y, scale, 0.15);\n const maxJitter = Math.min(scatter * 2, 5);\n const jitters = [\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n ];\n\n return [\n basePolygon,\n jitterPolygon(basePolygon, jitters[0][0], jitters[0][1]),\n jitterPolygon(basePolygon, jitters[1][0], jitters[1][1]),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Angle & Bounds Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts degree values into the current runtime angle units.\n * @param {number} angle\n * @returns {number}\n */\nfunction getAngleConverter() {\n return usesRadians()\n ? (angle) => (angle * Math.PI) / 180\n : (angle) => angle;\n}\n\n/**\n * Computes an axis-aligned bounding box for a polygon.\n * The diagonal is used as a size reference for pivot distance.\n * @param {Polygon} polygon\n * @returns {{minX:number,minY:number,maxX:number,maxY:number,cx:number,cy:number,size:number}}\n */\nfunction getPolygonBounds(polygon) {\n const points = polygon?.a ?? [];\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n for (const [x, y] of points) {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n return {\n minX,\n minY,\n maxX,\n maxY,\n cx: (minX + maxX) / 2,\n cy: (minY + maxY) / 2,\n size: Math.hypot(maxX - minX, maxY - minY),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pivot Geometry\n// ---------------------------------------------------------------------------\n\n/**\n * Chooses the diagonal corner family for a whole mass gesture.\n * Positive-angle hatching uses either bottom-right or top-left; negative-angle\n * hatching uses either bottom-left or top-right.\n * @param {number} angleDeg\n * @returns {[number, number]}\n */\nfunction getPivotBias(angleDeg) {\n const normalizedAngle = ((((angleDeg + 90) % 180) + 180) % 180) - 90;\n if (normalizedAngle >= 0) {\n return rr2() < 0.5 ? [1, 1] : [-1, -1];\n } else {\n return rr2() < 0.5 ? [-1, 1] : [1, -1];\n }\n}\n\n/**\n * Places the global pivot anchor outside the polygon, along the selected bias.\n * Distance varies per layer while the bias stays fixed for the whole mass.\n * @param {Polygon} polygon\n * @param {[number, number]} bias\n * @returns {{x:number,y:number}}\n */\nfunction getPivotAnchor(polygon, bias) {\n const bounds = getPolygonBounds(polygon);\n const offset = bounds.size * rr2(0.6, 1.4);\n const [sx, sy] = bias;\n return {\n x: bounds.cx + sx * offset,\n y: bounds.cy + sy * offset,\n };\n}\n\n/**\n * Projects the global pivot anchor onto the perpendicular bisector of a line.\n * This yields a valid circle center equidistant from both endpoints.\n * @param {{x:number,y:number}} anchor\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {{x:number,y:number}|null}\n */\nfunction projectAnchorToBisector(anchor, x1, y1, x2, y2) {\n const mx = (x1 + x2) / 2;\n const my = (y1 + y2) / 2;\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n if (!length) return null;\n const nx = -dy / length;\n const ny = dx / length;\n const offset = (anchor.x - mx) * nx + (anchor.y - my) * ny;\n return {\n x: mx + nx * offset,\n y: my + ny * offset,\n };\n}\n\n/**\n * Returns the shortest arc between two endpoints around a given center.\n * The returned angles are already converted into the current runtime angle units.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {[number, number]}\n */\nfunction getShortArcAngles(cx, cy, x1, y1, x2, y2, toAngleUnit) {\n let startDeg = calcAngle(cx, cy, x1, y1);\n let endDeg = calcAngle(cx, cy, x2, y2);\n const sweep = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweep > 180) [startDeg, endDeg] = [endDeg, startDeg];\n return [\n toAngleUnit(startDeg),\n toAngleUnit(endDeg),\n ];\n}\n\n/**\n * Splits a hatch line into two slightly separated segments so some gestures\n * read as interrupted rather than perfectly continuous.\n * @param {{x1:number,y1:number,x2:number,y2:number}} seg\n * @returns {Array<{x1:number,y1:number,x2:number,y2:number}>}\n */\nfunction splitSegment(seg) {\n const t = rr2(0.35, 0.65);\n const mx = seg.x1 + (seg.x2 - seg.x1) * t;\n const my = seg.y1 + (seg.y2 - seg.y1) * t;\n const dx = seg.x2 - seg.x1;\n const dy = seg.y2 - seg.y1;\n const length = Math.hypot(dx, dy) || 1;\n const gap = rr2(0.04, 0.1) * length;\n const gx = (dx / length) * gap * 0.5;\n const gy = (dy / length) * gap * 0.5;\n return [\n { x1: seg.x1, y1: seg.y1, x2: mx - gx, y2: my - gy },\n { x1: mx + gx, y1: my + gy, x2: seg.x2, y2: seg.y2 },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Mass Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Draws one polygon of the mass as a family of arcs derived from hatch lines.\n * The same pivot bias is used across layers, while each layer gets its own\n * anchor distance from the shape.\n * @param {Polygon} polygon\n * @param {[number, number]} pivotBias\n */\nfunction drawMassArcs(polygon, pivotBias, toAngleUnit) {\n const anchor = getPivotAnchor(polygon, pivotBias);\n for (const seg of getHatchLines(polygon)) {\n const parts = !seg.isConnector && rr2() < 0.35 ? splitSegment(seg) : [seg];\n for (const part of parts) {\n const center = projectAnchorToBisector(anchor, part.x1, part.y1, part.x2, part.y2);\n if (!center) continue;\n const radius = dist(center.x, center.y, part.x1, part.y1);\n if (!radius) continue;\n const [startAngle, endAngle] = getShortArcAngles(\n center.x,\n center.y,\n part.x1,\n part.y1,\n part.x2,\n part.y2,\n toAngleUnit,\n );\n arc(center.x, center.y, radius, startAngle, endAngle);\n }\n }\n}\n\n/**\n * Configures a hatch pass and immediately reinterprets the generated lines as arcs.\n * @param {Polygon} polygon\n * @param {number} dist\n * @param {number} angle\n * @param {object} options\n * @param {[number, number]} pivotBias\n */\nfunction drawMassPass(polygon, dist, angle, options, pivotBias, toAngleUnit) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias, toAngleUnit);\n}\n\n/**\n * Creates the built-in \"massing\" effect for a polygon or plot.\n * A mass is built from up to three jittered polygon layers, each hatched and\n * then redrawn as arc gestures around a shared pivot bias.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n */\nexport function createMass(shape, x, y, scale) {\n const pols = getMassPolygons(shape, x, y, scale);\n const hatchState = HatchState();\n const brushState = BrushState();\n const fieldState = { ...State.field };\n const precision = State.mass.options?.precision ?? 0.5;\n const strength = State.mass.options?.strength ?? 1;\n const gradient = State.mass.options?.gradient ?? 0.1;\n const outline = State.mass.options?.outline ?? false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const hatchDist = 1.6 * rr2(scatter * 0.65, scatter * 0.85) - 0.4 * gradient;\n const baseAngle = rr2(-90, 90);\n const pivotBias = getPivotBias(baseAngle);\n const toAngleUnit = getAngleConverter();\n\n set(State.mass.brush, State.mass.color, 1);\n wiggle(2 - precision);\n if (outline) pols[0].draw();\n\n drawMassPass(\n pols[0],\n hatchDist * 0.9,\n fromDegrees(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n fromDegrees(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n fromDegrees(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n BrushSetState(brushState);\n HatchSetState(hatchState);\n State.field = { ...fieldState };\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies massing to polygon geometry.\n */\nPolygon.prototype.mass = function () {\n if (State.mass?.isActive) {\n createMass(this, false);\n }\n};\n\n/**\n * Applies massing to plots by generating their polygon first.\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.mass = function (x, y, scale) {\n if (State.mass?.isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n createMass(this, x, y, scale);\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","import * as Color from \"../core/color.js\";\nimport {\n createFramebuffer,\n create2DCanvas,\n} from \"../core/compositor_runtime.js\";\n\n// Small staging canvas used to upload only the dirty fill sub-rect into the\n// framebuffer-backed mask mirror consumed by the blend shader.\nlet FillMaskUploadCanvas = null;\nlet isFillCompositeRegistered = false;\nconst DIRTY_FILL_PADDING = 4;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the CPU-side 2D fill mask must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} maskWidth - Mask width in physical pixels.\n * @param {number} maskHeight - Mask height in physical pixels.\n * @returns {boolean} True when the 2D fill mask needs reallocation.\n */\nfunction needsFillMaskCanvas(Renderer, maskWidth, maskHeight) {\n return (\n !Renderer.mask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight\n );\n}\n\n/**\n * Returns whether the framebuffer-backed fill mask mirror must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the fill mask framebuffer needs reallocation.\n */\nfunction needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density) {\n return (\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 );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures fill compositing resources exist for the active renderer.\n *\n * Fill draws first into a CPU-side 2D mask canvas. That mask is later uploaded,\n * dirty-rect by dirty-rect, into a framebuffer-backed mirror used by the final\n * blend shader pass.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {{mask: object, ctx: CanvasRenderingContext2D}} Fill mask resources.\n */\nexport function ensureFillCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n) {\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n\n if (needsFillMaskCanvas(Renderer, maskWidth, maskHeight)) {\n Renderer.mask = create2DCanvas(maskWidth, maskHeight);\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = createFramebuffer(Renderer, {\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 Renderer.mask.dirtyRect ??= null;\n Renderer.mask.isDrawn ??= false;\n Renderer.mask.drawingContext.imageSmoothingEnabled = false;\n return {\n mask: Renderer.mask,\n ctx: Renderer.mask.drawingContext,\n };\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current fill mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Fill mask canvas or framebuffer mirror.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearFillMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the fill dirty rect to composite into the main target. Fill bounds are\n * taken directly from the accumulated 2D mask dirty area plus a small padding.\n *\n * @param {object|null} target - Fill mask canvas.\n * @param {Function} _getActiveFramebuffer - Unused for fill masks.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getFillCompositeRect(\n target,\n _getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_FILL_PADDING),\n );\n}\n\n// =============================================================================\n// Section: Upload\n// =============================================================================\n/**\n * Uploads only the dirty portion of the CPU-side 2D fill mask into the\n * framebuffer-backed fill mask mirror used by the shader compositor.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {object} mask - CPU-side 2D fill mask canvas.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} dirtyRect - Dirty rect to upload.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {object} Framebuffer-backed fill mask mirror.\n */\nexport function getFillShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n) {\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 = create2DCanvas(uploadWidth, uploadHeight);\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 return target;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the fill compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initFillComposite() {\n if (isFillCompositeRegistered) return;\n Color.registerFillComposite?.({\n ensureResources: ensureFillCompositeResources,\n clearMask: clearFillMask,\n getCompositeRect: getFillCompositeRect,\n getShaderMask: getFillShaderMask,\n });\n isFillCompositeRegistered = true;\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\n// Core imports\nimport { Renderer, Cwidth, Cheight, Density } from \"../core/target.js\";\nimport {\n Mix,\n State,\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 } from \"../core/flowfield.js\";\nimport { createColor, getAffineMatrix } from \"../core/runtime.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// Internal module imports\nimport { initFillComposite } from \"./composite.js\";\n\ninitFillComposite(); // Register the fill composite with the core color module\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 = 2024;\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 = arguments.length < 3 ? createColor(a) : createColor(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 === 0) {\n return { x: 0, y: 0 };\n }\n\n if (pts.length < 8) {\n // Simple average for small polygons\n const sum = pts.reduce(\n (center, point) => ({ x: center.x + point.x, y: center.y + point.y }),\n { x: 0, y: 0 },\n );\n return { x: sum.x / pts.length, y: sum.y / 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\n // We want to add at least two vertices to divide the new edge that appears after trimming, at random distances along its path\n const trimStart = s;\n const trimEnd = s + n;\n const edgeStart = this.v[(trimStart - 1 + this.v.length) % this.v.length];\n const edgeEnd = this.v[trimEnd % this.v.length];\n const edgeVec = { x: edgeEnd.x - edgeStart.x, y: edgeEnd.y - edgeStart.y };\n \n // Insert two new vertices at random positions along the new edge\n const insertCount = 2;\n for (let i = 0; i < insertCount; i++) {\n const t = rr(0.25, 0.75); // Random position between 25% and 75% along the edge\n const newVertex = { x: edgeStart.x + edgeVec.x * t, y: edgeStart.y + edgeVec.y * t };\n const insertIdx = s + i;\n v.splice(insertIdx, 0, newVertex);\n m.splice(insertIdx, 0, rr(0.4, 0.7));\n dir.splice(insertIdx, 0, this.dir[trimStart % this.dir.length]);\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 // If mod is smaller than 0.02, skip growing math and just insert the middle vertex\n if (mod < 0.05) {\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedX[insertedIdx] = (cv.x + nv.x) / 2;\n insertedY[insertedIdx] = (cv.y + nv.y) / 2;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n continue;\n }\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 * Math.max(0.1, 2 * State.fill.bleed_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 const m = getAffineMatrix();\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * m.a,\n Density * m.b,\n Density * m.c,\n Density * m.d,\n Density * (m.x + Cwidth / 2),\n Density * (m.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);\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.3);\n const minSizeFactor = 0.03 * minSize;\n const maxSizeFactor = 0.45 * 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 State.fill.bleed_strength < 0.06\n ? 0\n : map(State.fill.bleed_strength, 0, 0.6, 0.2, 0.60, true),\n );\n this.pol.fill();\n }\n};\n","\nexport default function earcut(data, holeIndices, dim = 2) {\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let minX, minY, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = data[0];\n minY = data[1];\n let maxX = minX;\n let maxY = minY;\n\n for (let i = dim; i < outerLen; i += dim) {\n const x = data[i];\n const y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n let last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n } else {\n for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n let p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n let stop = ear;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n const prev = ear.prev;\n const next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n triangles.push(prev.i, ear.i, next.i); // cut off the triangle\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n let p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n // z-order range for the current triangle bbox;\n const minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n let p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles) {\n let p = start;\n do {\n const a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i, p.i, b.i);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n let a = start;\n do {\n let b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n let c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n const queue = [];\n\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n const list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareXYSlope);\n\n // process holes from left to right\n for (let i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareXYSlope(a, b) {\n let result = a.x - b.x;\n // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find\n // the bridge to the outer shell is always the point that they meet at.\n if (result === 0) {\n result = a.y - b.y;\n if (result === 0) {\n const aSlope = (a.next.y - a.y) / (a.next.x - a.x);\n const bSlope = (b.next.y - b.y) / (b.next.x - b.x);\n result = aSlope - bSlope;\n }\n }\n return result;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole(hole, outerNode) {\n const bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n const bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n // unless they intersect at a vertex, then choose the vertex\n if (equals(hole, p)) return p;\n do {\n if (equals(hole, p.next)) return p.next;\n else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n let p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n let numMerges;\n let inSize = 1;\n\n do {\n let p = list;\n let e;\n list = null;\n let tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n let q = p;\n let pSize = 0;\n for (let i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n let qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n let p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a point lies within a convex triangle but false if its equal to the first point of the triangle\nfunction pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {\n return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n let p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n const a2 = createNode(a.i, a.x, a.y),\n b2 = createNode(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n const p = createNode(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction createNode(i, x, y) {\n return {\n i, // vertex index in coordinates array\n x, y, // vertex coordinates\n prev: null, // previous and next vertex nodes in a polygon ring\n next: null,\n z: 0, // z-order curve value\n prevZ: null, // previous and next nodes in z-order\n nextZ: null,\n steiner: false // indicates whether this is a steiner point\n };\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nexport function deviation(data, holeIndices, dim, triangles) {\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n let trianglesArea = 0;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = triangles[i] * dim;\n const b = triangles[i + 1] * dim;\n const c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n}\n\nfunction signedArea(data, start, end, dim) {\n let sum = 0;\n for (let i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nexport function flatten(data) {\n const vertices = [];\n const holes = [];\n const dimensions = data[0][0].length;\n let holeIndex = 0;\n let prevLen = 0;\n\n for (const ring of data) {\n for (const p of ring) {\n for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n }\n if (prevLen) {\n holeIndex += prevLen;\n holes.push(holeIndex);\n }\n prevLen = ring.length;\n }\n return {vertices, holes, dimensions};\n}\n","// =============================================================================\n// Module: Wash\n// =============================================================================\n/**\n * Minimal stateful API for the `wash()` fill modifier.\n */\n\nimport earcut from \"earcut\";\nimport { Renderer, Cwidth, Cheight, isCanvasReady } from \"../core/target.js\";\nimport { State, flushActiveComposite } from \"../core/color.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { resetDirectShaderTracking } from \"../core/renderer_runtime.js\";\n\nlet gl = null;\nlet washProgram = null;\nlet washVao = null;\nlet washBuffer = null;\nlet washProjection = null;\nlet loadedWidth = 0;\nlet loadedHeight = 0;\nlet washGpuBufferSize = 0;\n\nconst WashAttr = {};\nconst WashUniform = {};\n\nconst washVertSrc = `#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}`;\n\nconst washFragSrc = `#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}`;\n\nState.wash = {\n color: null,\n opacity: 150,\n isActive: false,\n};\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Enables wash mode with a color and opacity.\n *\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 wash(a, b, c, d) {\n isCanvasReady();\n State.wash.opacity = (arguments.length < 4 ? b : d) ?? 150;\n State.wash.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.wash.isActive = true;\n}\n\n/**\n * Disables wash mode for subsequent drawing operations.\n */\nexport function noWash() {\n State.wash.isActive = false;\n}\n\n// =============================================================================\n// GL helpers\n// =============================================================================\n\n/**\n * Lazily creates the reusable program/buffer state for solid wash drawing and\n * refreshes the orthographic projection when the active target size changes.\n */\nfunction ensureWashReady() {\n const nextGl = Renderer.drawingContext;\n const sizeChanged = loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (!washProjection || sizeChanged) {\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n washProjection = new Float32Array([\n 2 / loadedWidth,\n 0,\n 0,\n 0,\n 0,\n -2 / loadedHeight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n }\n\n if (gl === nextGl && washProgram && washVao && washBuffer) return;\n\n gl = nextGl;\n washProgram = createProgram(gl, washVertSrc, washFragSrc);\n WashAttr.a_position = gl.getAttribLocation(washProgram, \"a_position\");\n WashUniform.u_matrix = gl.getUniformLocation(washProgram, \"u_matrix\");\n WashUniform.u_color = gl.getUniformLocation(washProgram, \"u_color\");\n\n washVao = gl.createVertexArray();\n gl.bindVertexArray(washVao);\n\n washBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, 0, gl.DYNAMIC_DRAW);\n washGpuBufferSize = 0;\n\n gl.enableVertexAttribArray(WashAttr.a_position);\n gl.vertexAttribPointer(WashAttr.a_position, 2, gl.FLOAT, false, 8, 0);\n\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n}\n\n/**\n * Applies the current runtime affine transform and converts the result into\n * the screen-space coordinates used by the direct GL wash pipeline.\n *\n * @param {number} x - The source x-coordinate in brush drawing space.\n * @param {number} y - The source y-coordinate in brush drawing space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n const m = getAffineMatrix();\n return [\n m.a * x + m.c * y + m.x + loadedWidth / 2,\n m.b * x + m.d * y + m.y + loadedHeight / 2,\n ];\n}\n\n/**\n * Triangulates a polygon in local space and returns the transformed triangle\n * vertex buffer ready for upload to the GPU.\n *\n * @param {Polygon} polygon - The polygon to triangulate.\n * @returns {{ triangles: Float32Array, vertexCount: number }} Screen-space\n * triangle vertices plus the number of vertices to draw.\n */\nfunction buildTriangleBuffer(polygon) {\n const flat = new Float32Array(polygon.vertices.length * 2);\n for (let i = 0; i < polygon.vertices.length; i++) {\n const vertex = polygon.vertices[i];\n flat[i * 2] = vertex.x;\n flat[i * 2 + 1] = vertex.y;\n }\n\n const indices = earcut(flat);\n const triangles = new Float32Array(indices.length * 2);\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n const [screenX, screenY] = transformVertexToScreen(flat[idx * 2], flat[idx * 2 + 1]);\n triangles[i * 2] = screenX;\n triangles[i * 2 + 1] = screenY;\n }\n\n return {\n triangles,\n vertexCount: indices.length,\n };\n}\n\n/**\n * Draws a triangulated solid wash directly to the current GL target.\n *\n * @param {Polygon} polygon - The polygon to fill with the current wash state.\n */\nfunction drawWashPolygon(polygon) {\n if (!State.wash?.isActive || !State.wash.color || polygon.vertices.length < 3) return;\n\n flushActiveComposite();\n ensureWashReady();\n const { triangles, vertexCount } = buildTriangleBuffer(polygon);\n const byteCount = triangles.byteLength;\n gl.useProgram(washProgram);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.bindVertexArray(washVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n if (byteCount > washGpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.DYNAMIC_DRAW);\n washGpuBufferSize = byteCount;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, triangles);\n }\n const color = State.wash.color._array;\n gl.uniformMatrix4fv(WashUniform.u_matrix, false, washProjection);\n gl.uniform4f(\n WashUniform.u_color,\n color[0],\n color[1],\n color[2],\n State.wash.opacity / 255,\n );\n\n gl.drawArrays(gl.TRIANGLES, 0, vertexCount);\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n resetDirectShaderTracking(Renderer, gl);\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct GL wash fill to the polygon using the current wash state.\n *\n * @param {Color|string|false} [_color] - Optional override color for this call.\n * @param {number} [_opacity] - Optional override opacity for this call.\n */\nPolygon.prototype.wash = function (_color = false, _opacity) {\n const state = { ...State.wash };\n if (_color !== false) wash(_color, _opacity);\n\n if (State.wash.isActive) {\n drawWashPolygon(this);\n }\n\n State.wash = { ...state };\n};\n\n/**\n * Applies wash to a plot by first generating the plot polygon, mirroring the\n * existing fill-path behavior, and then drawing that polygon with wash.\n *\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\nPlot.prototype.wash = function (x, y, scale) {\n if (!State.wash?.isActive) return;\n if (this.origin) {\n x = this.origin[0];\n y = this.origin[1];\n scale = 1;\n }\n this.pol = this.genPol(x, y, scale, 0, -1);\n this.pol.wash();\n};\n","// =============================================================================\n// Adapter: Standalone Renderer Hooks\n// =============================================================================\n\nimport { Cwidth, Cheight, Density } from \"../../core/target.js\";\nimport { setRendererRuntime } from \"../../core/renderer_runtime.js\";\n\nfunction beginDirectMaskDraw(_renderer, gl, target) {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n\n return { hadDepthTest };\n}\n\nfunction endDirectMaskDraw(renderer, gl, state) {\n if (state?.hadDepthTest) gl.enable(gl.DEPTH_TEST);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.viewport(\n 0,\n 0,\n Math.max(1, Math.round(Cwidth * Density)),\n Math.max(1, Math.round(Cheight * Density)),\n );\n}\n\nfunction resetStandaloneShaderTracking(_renderer, gl) {\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\nexport function initStandaloneRendererRuntime() {\n setRendererRuntime({\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking: resetStandaloneShaderTracking,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Compositor Hooks\n// =============================================================================\n\nimport { createProgram } from \"../../core/gl/utils.js\";\nimport {\n setCompositorRuntime,\n blitDefaultFramebufferSource,\n} from \"../../core/compositor_runtime.js\";\n\nfunction clearTarget(renderer, target, isFramebufferTarget) {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n const gl = renderer.drawingContext;\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousViewport = gl.getParameter(gl.VIEWPORT);\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\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 gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n gl.viewport(\n previousViewport[0],\n previousViewport[1],\n previousViewport[2],\n previousViewport[3],\n );\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\nfunction makeShader(gl, vertSrc, fragSrc) {\n const program = createProgram(gl, vertSrc, fragSrc);\n const uniformCache = new Map();\n\n const getUniformLocation = (name) => {\n if (!uniformCache.has(name)) {\n uniformCache.set(name, gl.getUniformLocation(program, name));\n }\n return uniformCache.get(name);\n };\n\n return {\n program,\n setUniform(name, value) {\n const location = getUniformLocation(name);\n if (!location) return;\n if (typeof value === \"boolean\") {\n gl.uniform1i(location, value ? 1 : 0);\n return;\n }\n if (typeof value === \"number\") {\n gl.uniform1f(location, value);\n return;\n }\n if (Array.isArray(value)) {\n if (value.length === 3) gl.uniform3f(location, value[0], value[1], value[2]);\n else if (value.length === 4) gl.uniform4f(location, value[0], value[1], value[2], value[3]);\n return;\n }\n },\n };\n}\n\nfunction ensureBlendShaderProgram(renderer, vertSrc, fragSrc) {\n renderer.shaderProgram ??= makeShader(renderer.drawingContext, vertSrc, fragSrc);\n return renderer.shaderProgram;\n}\n\nfunction createFramebufferTexture(gl, width, height) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n gl.RGBA,\n width,\n height,\n 0,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n null,\n );\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 gl.bindTexture(gl.TEXTURE_2D, null);\n return texture;\n}\n\nfunction createFramebuffer(renderer, options) {\n const gl = renderer.drawingContext;\n const density = options.density ?? 1;\n const framebuffer = gl.createFramebuffer();\n const width = Math.max(1, options.width);\n const height = Math.max(1, options.height);\n const pixelWidth = Math.max(1, Math.round(width * density));\n const pixelHeight = Math.max(1, Math.round(height * density));\n const colorTexture = createFramebufferTexture(gl, pixelWidth, pixelHeight);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER,\n gl.COLOR_ATTACHMENT0,\n gl.TEXTURE_2D,\n colorTexture,\n 0,\n );\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n\n return {\n __brushFramebuffer: true,\n framebuffer,\n colorTexture,\n width,\n height,\n density,\n pixelDensity: () => density,\n remove() {\n gl.deleteFramebuffer(framebuffer);\n gl.deleteTexture(colorTexture);\n },\n };\n}\n\nfunction ensureBlendSourceFramebuffer(\n renderer,\n currentFramebuffer,\n width,\n height,\n density,\n) {\n currentFramebuffer?.remove?.();\n return createFramebuffer(renderer, {\n width,\n height,\n density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n}\n\nfunction runBlendShaderPass({\n renderer,\n shader,\n source,\n mask,\n color,\n isBrushMask,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n}) {\n const gl = renderer.drawingContext;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousProgram = gl.getParameter(gl.CURRENT_PROGRAM);\n const previousVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);\n\n const quadVao = gl.createVertexArray();\n gl.bindVertexArray(quadVao);\n gl.useProgram(shader.program);\n gl.disable(gl.DEPTH_TEST);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, source.colorTexture);\n gl.uniform1i(gl.getUniformLocation(shader.program, \"u_source\"), 0);\n\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, mask.colorTexture);\n gl.uniform1i(gl.getUniformLocation(shader.program, \"u_mask\"), 1);\n\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n gl.uniform3f(\n gl.getUniformLocation(shader.program, \"u_color\"),\n color[0],\n color[1],\n color[2],\n );\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n withScissor(\n gl,\n dirtyRect,\n () => {\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n },\n !targetIsFramebuffer,\n );\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.activeTexture(gl.TEXTURE0);\n gl.bindVertexArray(previousVao);\n gl.useProgram(previousProgram);\n gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n gl.deleteVertexArray(quadVao);\n}\n\nfunction blitSourceToFramebuffer(args) {\n return blitDefaultFramebufferSource(args);\n}\n\nexport function initStandaloneCompositorRuntime() {\n setCompositorRuntime({\n clearTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n createFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Stroke Hooks\n// =============================================================================\n\nimport { create2DCanvas, get2DContext } from \"../../core/compositor_runtime.js\";\nimport { setStrokeRuntime } from \"../../stroke/runtime.js\";\n\nfunction cssColor(value) {\n if (typeof value === \"number\") {\n const c = Math.max(0, Math.min(255, value));\n return `rgb(${c} ${c} ${c})`;\n }\n return value ?? \"black\";\n}\n\nfunction buildTipSurface(canvas) {\n const ctx = get2DContext(canvas, true);\n const surface = {\n canvas,\n drawingContext: ctx,\n width: canvas.width,\n height: canvas.height,\n pixels: null,\n _fillStyle: \"#ffffff\",\n _strokeStyle: \"transparent\",\n _lineWidth: 1,\n\n pixelDensity() {\n return 1;\n },\n\n background(value) {\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.fillStyle = cssColor(value);\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n ctx.restore();\n },\n\n noSmooth() {\n ctx.imageSmoothingEnabled = false;\n },\n\n push() {\n ctx.save();\n },\n\n pop() {\n ctx.restore();\n },\n\n translate(x, y) {\n ctx.translate(x, y);\n },\n\n scale(x, y = x) {\n ctx.scale(x, y);\n },\n\n rotate(angle) {\n ctx.rotate(angle);\n },\n\n noStroke() {\n surface._strokeStyle = \"transparent\";\n },\n\n stroke(value) {\n surface._strokeStyle = cssColor(value);\n },\n\n noFill() {\n surface._fillStyle = \"transparent\";\n },\n\n fill(value) {\n surface._fillStyle = cssColor(value);\n },\n\n strokeWeight(value) {\n surface._lineWidth = value;\n },\n\n rect(x, y, w, h) {\n ctx.beginPath();\n ctx.rect(x, y, w, h);\n surface._paint();\n },\n\n circle(x, y, d) {\n ctx.beginPath();\n ctx.arc(x, y, d / 2, 0, Math.PI * 2);\n surface._paint();\n },\n\n ellipse(x, y, w, h) {\n ctx.beginPath();\n ctx.ellipse(x, y, w / 2, h / 2, 0, 0, Math.PI * 2);\n surface._paint();\n },\n\n line(x1, y1, x2, y2) {\n ctx.beginPath();\n ctx.moveTo(x1, y1);\n ctx.lineTo(x2, y2);\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n },\n\n beginShape() {\n ctx.beginPath();\n surface._shapeStarted = false;\n },\n\n vertex(x, y) {\n if (!surface._shapeStarted) {\n ctx.moveTo(x, y);\n surface._shapeStarted = true;\n } else {\n ctx.lineTo(x, y);\n }\n },\n\n endShape(close = false) {\n if (close) ctx.closePath();\n surface._paint();\n },\n\n loadPixels() {\n surface.pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;\n },\n\n updatePixels() {\n const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n imageData.data.set(surface.pixels);\n ctx.putImageData(imageData, 0, 0);\n },\n\n _paint() {\n if (surface._fillStyle !== \"transparent\") {\n ctx.fillStyle = surface._fillStyle;\n ctx.fill();\n }\n if (surface._strokeStyle !== \"transparent\") {\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n }\n },\n };\n\n return surface;\n}\n\nfunction createTipSurface(width, height) {\n return buildTipSurface(create2DCanvas(width, height, true));\n}\n\nfunction loadImageTip(src, imageToWhite) {\n return new Promise((resolve, reject) => {\n const NativeImage = globalThis.Image;\n if (!NativeImage) {\n reject(new Error(\"Standalone image brush loading requires Image support.\"));\n return;\n }\n\n const nativeImg = new NativeImage();\n nativeImg.onload = () => {\n const surface = buildTipSurface(\n create2DCanvas(nativeImg.naturalWidth, nativeImg.naturalHeight, true),\n );\n surface.drawingContext.drawImage(nativeImg, 0, 0);\n imageToWhite(surface);\n resolve(surface);\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\nexport function initStandaloneStrokeRuntime() {\n setStrokeRuntime({\n createTipSurface,\n loadImageTip,\n });\n}\n","/**\n * @fileoverview Standalone entry point for brush.\n */\n\nexport * from \"./adapters/standalone/runtime.js\";\nexport * from \"./adapters/standalone/frame.js\";\nexport { createCanvas } from \"./adapters/standalone/target.js\";\nexport * from \"./index.shared.js\";\n\nimport { initStandaloneTargetRuntime } from \"./adapters/standalone/target.js\";\nimport { initStandaloneRendererRuntime } from \"./adapters/standalone/renderer.js\";\nimport { initStandaloneCompositorRuntime } from \"./adapters/standalone/compositor.js\";\nimport { initStandaloneStrokeRuntime } from \"./adapters/standalone/stroke.js\";\nimport { initStandaloneRuntime } from \"./adapters/standalone/runtime.js\";\n\ninitStandaloneTargetRuntime();\ninitStandaloneRuntime();\ninitStandaloneRendererRuntime();\ninitStandaloneCompositorRuntime();\ninitStandaloneStrokeRuntime();\n"],"names":["identityMatrix","a","b","c","d","x","y","Cwidth","Cheight","Renderer","Density","usesRadians","fromDegrees","angle","createColor","Error","getAffineMatrix","targetRuntime","load","syncDensity","isCanvasReady","instance","inst","activateInstance","deactivateInstance","getActiveFramebuffer","isFramebufferTarget","setTargetState","state","Instance","target","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","create2DCanvas","width","height","willReadFrequently","canvas","OffscreenCanvas","element","document","createElement","drawingContext","getContext","undefined","compositorRuntime","clearTarget","ensureBlendShaderProgram","ensureBlendSourceFramebuffer","createFramebuffer","runBlendShaderPass","blitSourceToFramebuffer","args","strokeComposite","fillComposite","clearRenderTarget","getTargetPixelSize","Math","max","round","normalizeDirtyRect","floor","min","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","draw","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","this","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","pixelDensity","ensureResources","fillResources","mask","ctx","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","shaderProgram","activeFramebuffer","source","renderer","sourceTarget","sourceFramebuffer","targetIsFramebuffer","shaderMask","getShaderMask","color","flushActiveComposite","buffer","loadTarget","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","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","push","callback","noise","noise2","noiseSeed","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","withinBounds","constrain","low","high","nAngle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","sin","toDegrees","rad","isRad","runtimeUsesRadians","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","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","m","mx","my","update","plotted","colIdx","rowIdx","reset","isIn","isActive","isInCanvas","skipCheck","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","steps","fieldActive","usePlot","getRowIndex","y_offset","getColIndex","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","angleMode","has","generateField","entry","normalizeFieldAngles","gen","refreshField","currentField","keys","join","noField","name","funct","set","listFields","fn","_stateStack","clamp","DEGREES","RADIANS","colorContext","currentAngleMode","transformStack","currentTransform","multiplyTransform","left","right","Color","g","hex","rgbToHex","rgbaMatch","exec","alpha","parseFloat","standardize","rgb","hexToRgb","toString","slice","replace","_match","red","green","blue","result","getColorContext","fillStyle","_getRed","_getGreen","_getBlue","mode","getAngleMode","wash","stroke","hatch","mass","pop","saved","brush","popState","translate","theta","cosTheta","sinTheta","scale","initStandaloneRuntime","hooks","render","clear","bindFramebuffer","FRAMEBUFFER","clearColor","COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","_current","_curvature","_strokeArray","_strokeOrigin","activeTarget","activeDensity","activeWidth","activeHeight","applyLoadedTarget","density","premultipliedAlpha","getTargetContext","createRenderer","createCanvas","logicalWidth","logicalHeight","Number","style","id","parent","querySelector","appendChild","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","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","polygon","beginShape","vertex","endShape","circle","radius","arcLength","angleOffset","randomFactor","randomAngle","offsetX","offsetY","arc","startDeg","sweepDeg","segmentCount","segmentSweep","startX","startY","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","strokeRuntime","createTipSurface","loadImageTip","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","createShader","shaderSource","compileShader","attachShader","linkProgram","rendererRuntime","beginDirectMaskDraw","endDirectMaskDraw","resetDirectShaderTracking","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","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","getProjectionMatrix","beginMaskTarget","endMaskTarget","accumulateDirtyRect","currentRect","diameter","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","targetState","tex","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","activeTexture","TEXTURE0","uniform1i","u_tex","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","flush","needsStrokeMask","remove","antialias","depth","stencil","_Renderer","weight","opacity","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","add","params","includes","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","rest","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","background","noSmooth","noStroke","T","imageToWhite","tips","tipKey","param","colors","buffers","image","getBrushParams","brushName","scaleBrushes","values","spacing","pick","arguments","strokeWeight","clip","region","noClip","_position","initializeDrawingState","plot","snapshotMatrix","gaussians","angleScale","isPlot","cp","ct","cs","ck","noiseoffset","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","saveState","stepSize","totalSteps","pressureCount","cachedPressure","lineNoiseCount","cachedLineNoise","u_matrix","drawArrays","POINTS","glDraw","restoreState","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawImageTip","plotAngle","plotCos","plotSin","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","vibrate","rx","ry","size","overscan","maxPressure","scatterReach","tipReach","getImageTipOverscan","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","flowLine","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","then","HatchState","HatchSetState","rand","continuous","gradient","hatchStyle","hBrush","noHatch","scanlineHatch","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","scanY","getHatchLines","polygons","segs","poly","getHatchSegments","getActiveHatchConfig","lines","isConnector","prev","createHatch","drawSegment","save","Object","drawFn","withHatchStyle","renderHatchSegments","noMass","jitterPolygon","jitterX","jitterY","projectAnchorToBisector","anchor","nx","ny","getShortArcAngles","toAngleUnit","endDeg","splitSegment","seg","gap","gx","gy","drawMassArcs","pivotBias","bias","bounds","getPolygonBounds","sx","sy","getPivotAnchor","parts","part","center","startAngle","endAngle","drawMassPass","createMass","shape","pols","isPolygon","basePolygon","maxJitter","jitters","getMassPolygons","hatchState","brushState","fieldState","precision","strength","outline","hatchDist","baseAngle","_dist","_angle","_options","FillMaskUploadCanvas","isFillCompositeRegistered","maskWidth","maskHeight","needsFillMaskCanvas","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","clearRect","drawImage","colorTexture","texSubImage2D","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","noFill","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","keep","dst","trimStart","trimEnd","edgeStart","edgeEnd","edgeVec","newVertex","insertIdx","splice","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","setTransform","strokeStyle","lineCap","darker","sparse","layer","numLayers","erase","restore","lineWidth","matrix","getTransform","beginPath","first","tx","ty","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","filterPoints","again","steiner","equals","area","removeNode","earcutLinked","ear","triangles","dim","invSize","pass","z","zOrder","prevZ","nextZ","numMerges","inSize","tail","q","pSize","qSize","sortLinked","indexCurve","stop","isEarHashed","isEar","cureLocalIntersections","splitEarcut","ax","bx","pointInTriangleExceptFirst","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","pointInTriangle","intersectsPolygon","inside","middleInside","q1","q2","o1","sign","o2","o3","o4","onSegment","num","createNode","b2","an","bp","insertNode","last","_opacity","_bleed","fluid","modifiers","_","shift","shifted","pts","point","cross","_center","createFill","FillSetState","washProgram","washVao","washBuffer","washProjection","washGpuBufferSize","WashAttr","WashUniform","noWash","transformVertexToScreen","_renderer","hadDepthTest","isEnabled","DEPTH_TEST","framebuffer","viewport","resetStandaloneShaderTracking","blendEquation","FUNC_ADD","ONE_MINUS_SRC_ALPHA","previousFramebuffer","getParameter","FRAMEBUFFER_BINDING","previousViewport","VIEWPORT","vertSrc","fragSrc","uniformCache","setUniform","location","uniform3f","uniform1f","makeShader","pixelWidth","pixelHeight","createFramebufferTexture","framebufferTexture2D","COLOR_ATTACHMENT0","__brushFramebuffer","deleteFramebuffer","currentFramebuffer","previousProgram","CURRENT_PROGRAM","previousVao","VERTEX_ARRAY_BINDING","quadVao","TEXTURE1","TRIANGLES","deleteVertexArray","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","blitFramebuffer","NEAREST","blitDefaultFramebufferSource","cssColor","buildTipSurface","get2DContext","surface","_fillStyle","_strokeStyle","_lineWidth","fillRect","_paint","ellipse","_shapeStarted","getImageData","imageData","putImageData","resolve","reject","NativeImage","globalThis","Image","nativeImg","onload","naturalWidth","naturalHeight","onerror","crossOrigin","ensureWashReady","vertexCount","flat","holeIndices","outerLen","outerNode","signedArea","linkedList","earcut","buildTriangleBuffer","drawWashPolygon","HTMLCanvasElement","isCanvasTarget","isOffscreenCanvasTarget","isSupportedTarget","initStandaloneRendererRuntime","initStandaloneCompositorRuntime","initStandaloneStrokeRuntime"],"mappings":"AAIA,MAAMA,EAAiB,CACrBC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,GAGE,ICEIC,EAAQC,EAAmBC,EAAUC,EDFrCC,EAAc,KAAM,EACpBC,EAAeC,GAAUA,EACzBC,EAAc,KACvB,MAAM,IAAIC,MAAM,yCAEPC,EAAkB,IAAMhB,ECD/BiB,EAAgB,CAClBC,KAAM,KACJ,MAAM,IAAIH,MAAM,0CAElBI,YAAa,IAAMT,EACnBU,cAAe,KACb,MAAM,IAAIL,MAAM,0CAElBM,SAAWC,MAGXC,iBAAmBD,MAGnBE,mBA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zC,CCzKAuxB","x_google_ignoreList":[5,6,27]}
\ No newline at end of file
diff --git a/dist/brush.js b/dist/brush.js
index 4071f9a..f0b7b90 100644
--- a/dist/brush.js
+++ b/dist/brush.js
@@ -1,2 +1,2 @@
-var t,e;t=this,e=function(t){const e={a:1,b:0,c:0,d:1,x:0,y:0};let r,n,i,a,o=()=>!1,s=t=>t,c=()=>{throw new Error("No runtime color adapter registered.")},l=()=>e,u={load:()=>{throw new Error("No target runtime adapter registered.")},syncDensity:()=>a,isCanvasReady:()=>{throw new Error("No target runtime adapter registered.")},instance:t=>{},activateInstance:t=>{},deactivateInstance:()=>{},getActiveFramebuffer:()=>null,isFramebufferTarget:()=>!1};function h(t){"Cwidth"in t&&(r=t.Cwidth),"Cheight"in t&&(n=t.Cheight),"Instance"in t&&t.Instance,"Renderer"in t&&(i=t.Renderer),"Density"in t&&(a=t.Density)}const f=()=>u.isCanvasReady(),m=()=>u.getActiveFramebuffer(),d=t=>u.isFramebufferTarget(t),x=(t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null,g=(t,e,r=!1)=>{const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,e):(()=>{const r=document.createElement("canvas");return r.width=t,r.height=e,r})();return n.drawingContext=n.getContext("2d",r?{willReadFrequently:!0}:void 0),n};let p={clearTarget:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendShaderProgram:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendSourceFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},createFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},runBlendShaderPass:()=>{throw new Error("No compositor runtime adapter registered.")},blitSourceToFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")}};const y=(...t)=>p.createFramebuffer(...t);let b=null,v=null;const _=t=>{((...t)=>{p.clearTarget(...t)})(i,t,d)},R=()=>({width:Math.max(1,Math.round(r*a)),height:Math.max(1,Math.round(n*a))}),w=t=>{if(!t)return null;const{width:e,height:r}=R();return((t,e,r)=>{if(!t)return null;const 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}})(t,e,r)},E=()=>{const{width:t,height:e}=R();return((t,e)=>({minX:0,minY:0,maxX:t,maxY:e}))(t,e)},A=(t,e=!0)=>{const r=w(t);if(!r)return null;const{height:n}=R();return{x:r.minX,y:e?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},M=(t,e,r,n=!0)=>{const i=A(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()},S={},T=()=>{i?.loaded||(f(),P.load())},P={isBlending:!1,cachedColor:null,markDirtyRect(t,e){const r=w(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){if(!t)return;const e=t===this.glMask?b:v;e?.clearMask?.(t,_)},getCompositeRect(t,e){const r=e?b:v;return r?.getCompositeRect?.(t,m,E,x,w)},load(){u.syncDensity();const t=!i.blendSourceFramebuffer||i.blendSourceFramebuffer.width!==r||i.blendSourceFramebuffer.height!==n||"function"==typeof i.blendSourceFramebuffer.pixelDensity&&i.blendSourceFramebuffer.pixelDensity()!==a;((...t)=>{p.ensureBlendShaderProgram(...t)})(i,"#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.);}"),this.glMask=b?.ensureResources?.(i,r,n,a);const e=v?.ensureResources?.(i,r,n,a,_)??{mask:null,ctx:null};t&&(i.blendSourceFramebuffer=((...t)=>p.ensureBlendSourceFramebuffer(...t))(i,i.blendSourceFramebuffer,r,n,a)),this.mask=e.mask,this.ctx=e.ctx},blend(t=!1,e=!1){T();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,this.clearMask(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,this.cachedColor=null))},applyShader(t,e){if(!t?.isDrawn)return;const a=this.getCompositeRect(t,e);if(!a)return void this.clearMask(t);i.drawingContext;const o=i.shaderProgram,s=m(),c=((...t)=>p.blitSourceToFramebuffer(...t))({renderer:i,sourceTarget:s??i,sourceFramebuffer:i.blendSourceFramebuffer,dirtyRect:a,isFramebufferTarget:d,Cwidth:r,Cheight:n,getTargetPixelSize:R,toScissorBox:A,withScissor:M}),l=!!s,u=(e?b:v).getShaderMask(i,t,a,w,E,_);((...t)=>{p.runBlendShaderPass(...t)})({renderer:i,shader:o,source:c,mask:u,color:this.cachedColor,isBrushMask:e,Cwidth:r,Cheight:n,dirtyRect:a,targetIsFramebuffer:l,withScissor:M}),this.clearMask(t)}},C=()=>{T(),P.blend(!1,!0),P.clearMask(P.glMask),P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null},F=Math.sqrt(3),k=.5*(F-1),I=(3-F)/6,D=t=>0|Math.floor(t),L=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 N(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=>L[t%12*2]),n=new Float64Array(e).map(t=>L[t%12*2+1]);return function(t,i){let a=0,o=0,s=0;const c=(t+i)*k,l=D(t+c),u=D(i+c),h=(l+u)*I,f=t-(l-h),m=i-(u-h);let d,x;f>m?(d=1,x=0):(d=0,x=1);const g=f-d+I,p=m-x+I,y=f-1+2*I,b=m-1+2*I,v=255&l,_=255&u;let R=.5-f*f-m*m;if(R>=0){const t=v+e[_];R*=R,a=R*R*(r[t]*f+n[t]*m)}let w=.5-g*g-p*p;if(w>=0){const t=v+d+e[_+x];w*=w,o=w*w*(r[t]*g+n[t]*p)}let E=.5-y*y-b*b;if(E>=0){const t=v+1+e[_+1];E*=E,s=E*E*(r[t]*y+n[t]*b)}return 70*(a+o+s)}}function B(t,e){let r=new U(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class U{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 O=B(Math.random()),Y=B(Math.random());const z=[],X=t=>z.push(t);let G=N(B(Math.random())),Z=N(B(Math.random()));const V=(t=0,e=1)=>t+O()*(e-t),$=(t=0,e=1)=>t+Y()*(e-t),H=t=>t[~~(O()*t.length)],W=(t,e)=>~~V(t,e),q=(t,e)=>~~$(t,e),j=(t=0,e=1)=>{const r=1-O(),n=O();return Math.sqrt(-2*Math.log(r))*at(360*n)*e+t},K=t=>{let e=0;const r=[];for(const n in t)e+=t[n],r.push({key:n,cumulative:e});const n=O()*e;for(const{key:t,cumulative:e}of r)if(n<e)return isNaN(t)?t:parseInt(t)},J=(t,e,r,n,i,a=!1)=>{let o=n+(t-e)/(r-e)*(i-n);return a?n<i?Q(o,n,i):Q(o,i,n):o},Q=(t,e,r)=>Math.max(Math.min(t,r),e),tt=t=>(t%=360)<0?t+360:t,et=1440,rt=2*Math.PI/et,nt=new Float32Array(et).fill(NaN),it=new Float32Array(et).fill(NaN),at=t=>{const e=~~(4*tt(t));let r=nt[e];return isNaN(r)&&(r=Math.cos(e*rt),nt[e]=r),r},ot=t=>{const e=~~(4*tt(t));let r=it[e];return isNaN(r)&&(r=Math.sin(e*rt),it[e]=r),r},st=(t,e=!1)=>{if(e||o()){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},ct=(t,e=!1)=>e||o()?180*t/Math.PI:t,lt=(t,e,r,n,i)=>{let a=at(i),o=ot(i);return{x:a*(r-t)+o*(n-e)+t,y:a*(n-e)-o*(r-t)+e}},ut=(t,e,r,n)=>Math.hypot(r-t,n-e),ht=(t,e,r,n)=>st(Math.atan2(-(n-e),r-t),!0),ft=(t,e,r,n,i=!1)=>{let a=t.x,o=t.y,s=e.x,c=e.y,l=r.x,u=r.y,h=n.x,f=n.y;if(a===s&&o===c||l===h&&u===f)return!1;let m=s-a,d=c-o,x=h-l,g=f-u,p=g*m-x*d;if(0===p)return!1;let y=(x*(o-u)-g*(a-l))/p,b=(m*(o-u)-d*(a-l))/p;return!(!i&&(b<0||b>1))&&{x:a+y*m,y:o+y*d}};let mt=!1;function dt(){mt||(T(),gt=.01*r,pt=-.5*r,yt=-.5*n,bt=Math.round(2*r/gt),vt=Math.round(2*n/gt),Mt("hand",(t,e)=>{const r=$(.2,.8),n=q(5,10);return Tt(e,(e,i)=>.5*n*ot(r*i*e+q(15,25))*.2*at(t)+Z(e,i)*n*.7)}),Mt("curved",(t,e)=>{let r=q(-10,10);return q(0,100)%2==0&&(r*=-1),Tt(e,(e,n)=>3*J(Z(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),Mt("zigzag",(t,e)=>{let r=q(-30,-15)+Math.abs(44*ot(t));q(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t<bt;t++){for(let r=0;r<vt;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),Mt("waves",(t,e)=>{const r=q(10,15)+5*ot(t),n=q(3,6)+3*at(t),i=q(20,35);return Tt(e,(t,e)=>ot(r*t)*i*at(e*n)+q(-3,3))}),Mt("seabed",(t,e)=>{const r=$(.4,.8),n=q(18,26);return Tt(e,(e,i)=>1.1*n*ot(r*i*e+q(15,20))*at(t))}),Mt("spiral",(t,e)=>{const r=q(5,10),n=2*q(0,2)-1,i=q(65,80),a=Array.from({length:r},()=>({x:$(.1,.9)*bt,y:$(.1,.9)*vt}));return Tt(e,(t,e)=>{let r=0,o=0;for(const s of a){const a=t-s.x,c=e-s.y,l=1/(a*a+c*c+1),u=Math.atan2(c,a)*(180/Math.PI),h=n*(u+i)*Math.PI/180;r+=l*Math.cos(h),o+=l*Math.sin(h)}return Math.atan2(o,r)*(180/Math.PI)})}),Mt("columns",(t,e)=>{const r=q(3,8),n=q(25,45);return Tt(e,(t,e)=>ot(t*r)*n)}),mt=!0)}class xt{constructor(t,e){dt();const r=l();this.mx=r.x,this.my=r.y,this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=Math.round((t+this.mx-pt)/gt),this.rowIdx=Math.round((e+this.my-yt)/gt)}reset(){this.plotted=0}isIn(){return S.field.isActive?xt.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=r,e=n,i=this.x+this.mx,a=this.y+this.my;return i>=-.3*t&&i<=1.3*t&&a>=-.3*e&&a<=1.3*e}angle(t=!1){return S.field.isActive&&(t||this.isIn())?_t.get(S.field.current).field[this.colIdx][this.rowIdx]*S.field.wiggle:0}moveTo(t,e,r=1){this.movePos(ct(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())return void(this.plotted+=r/i);const a=e/r,o=S.field.isActive,s=!!n;for(let e=0;e<a;e++){const e=(o?this.angle(!0):0)-(s?t.angle(this.plotted):t);this.update(this.x+r*at(e),this.y+r*ot(e)),this.plotted+=r/i}}static getRowIndex(t,e=1){const r=t+l().y-yt;return Math.round(r/gt/e)}static getColIndex(t,e=1){const r=t+l().x-pt;return Math.round(r/gt/e)}static isIn(t,e){return t>=0&&e>=0&&t<bt&&e<vt}}S.field={isActive:!1,current:null,wiggle:1};let gt,pt,yt,bt,vt,_t=new Map;const Rt=new Set(["degrees","radians"]);function wt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!Rt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function Et(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]=ct(t[e][r],!0);return t}(t.gen(e,new Array(bt).fill(null).map(()=>new Float32Array(vt))),t.angleMode)}function At(t){if(S.field.wiggle||(S.field.wiggle=1),dt(),!_t.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(_t.keys()).join(", ")}.`);S.field.isActive=!0,S.field.current=t;const e=_t.get(t);e.field||(e.field=Et(e,0))}function Mt(t,e,r={}){_t.set(t,{gen:e,field:null,angleMode:wt(r)})}function St(t=1){At("hand"),S.field.wiggle=t}function Tt(t,e){for(let r=0;r<bt;r++)for(let n=0;n<vt;n++)t[r][n]=e(r,n);return t}const Pt=[],Ct=(t,e,r)=>Math.max(e,Math.min(t,r)),Ft="degrees",kt="radians";let It=null,Dt=Ft;const Lt=[];let Nt={a:1,b:0,c:0,d:1,x:0,y:0};function Bt(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,x:t.a*e.x+t.c*e.y+t.x,y:t.b*e.x+t.d*e.y+t.y}}class Ut{constructor(t,e,r){if(t?._array)return this.r=Math.round(255*t._array[0]),this.g=Math.round(255*t._array[1]),this.b=Math.round(255*t._array[2]),this.hex=this.rgbToHex(this.r,this.g,this.b),this._array=[...t._array],void(this.gl=this._array);if("string"==typeof t){this.hex=this.standardize(t);const e=this.hexToRgb(this.hex);this.r=e.r,this.g=e.g,this.b=e.b}else this.r=Ct(t??0,0,255),this.g=Ct(e??t??0,0,255),this.b=Ct(r??t??0,0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);this._array=[this.r/255,this.g/255,this.b/255,1],this.gl=this._array}rgbToHex(t,e,r){return`#${(1<<24|t<<16|e<<8|r).toString(16).slice(1)}`}hexToRgb(t){t=t.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(t,e,r,n)=>e+e+r+r+n+n);const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(!e)throw new Error(`Invalid color value "${t}".`);return{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}}standardize(t){const e=function(){if(It)return It;if("undefined"!=typeof document)return It=document.createElement("canvas").getContext("2d"),It;if("undefined"!=typeof OffscreenCanvas)return It=new OffscreenCanvas(1,1).getContext("2d"),It;throw new Error("Standalone color parsing requires CanvasRenderingContext2D support.")}();return e.fillStyle=t,e.fillStyle}_getRed(){return this.r}_getGreen(){return this.g}_getBlue(){return this.b}}function Ot(){var t;(t={usesRadians:()=>"radians"===Dt,fromDegrees:t=>"radians"===Dt?t*Math.PI/180:t,createColor:(...t)=>1===t.length&&t[0]?._array?t[0]:new Ut(...t),getAffineMatrix:()=>Nt}).usesRadians&&(o=t.usesRadians),t.fromDegrees&&(s=t.fromDegrees),t.createColor&&(c=t.createColor),t.getAffineMatrix&&(l=t.getAffineMatrix)}let Yt,zt,Xt,Gt,Zt=null,Vt=!1,$t=1,Ht=0,Wt=0;function qt(t,e,r,n){Zt=t,Ht=e,Wt=r,$t=n;const i=function(t,e,r,n){const i=function(t){return t.getContext("webgl2",{premultipliedAlpha:!0})??t.getContext("webgl2")}(t);if(!i)throw new Error("brush.load(target) requires a canvas with a WebGL2 context.");return{canvas:t,drawingContext:i,width:e,height:r,pixelDensity:()=>n}}(t,e,r,n);h({Renderer:i,Cwidth:e,Cheight:r,Density:n}),Vt=!0}class jt{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=ft(t.point1,t.point2,e,n);i&&r.push(i)}return this._intersectionCache[e]=r,r}show(){S.wash&&this.wash(),S.fill&&this.fill(),S.mass&&this.mass(),S.hatch&&this.hatch(),S.stroke&&this.draw()}}class Kt{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:st(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:st(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=st(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)),J(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,e,i=1,a){dt();const o=a<0?4:1,s=[],c=Math.round(this.length/o),l=new xt(t+r/2,e+n/2);let u=0,h=0;for(let t=0;t<c;t++){l.plotTo(this,o,o);const t=this.calcIndex(l.plotted);u+=o,(u>=(a<=0?8:Math.max(this.segments[t]*a*$(.7,1.3),20))||t>=h)&&l.x&&(s.push([l.x-r/2,l.y-n/2]),u=0,t>=h&&h++)}return new jt(s)}show(t,e,r=1){S.wash&&this.wash(t,e,r),S.fill&&this.fill(t,e,r),S.mass&&this.mass(t,e,r),S.hatch&&this.hatch(t,e,r),S.stroke&&this.draw(t,e,r)}}function Jt(t,e,r,n,i){const a=ct(n),o=((ct(i)-a)%360+360)%360;if(0===o)return;const s=new Kt("curve"),c=Math.max(1,Math.ceil(o/90)),l=o/c,u=Math.PI*r*l/180;for(let t=0;t<c;t++)s.addSegment(a+t*l+90,u,1,!0);s.endPlot(a+o+90,1,!0);const h=t+r*at(a),f=e-r*ot(a);s.draw(h,f,1)}class Qt{constructor(){this.isClosed=!1,this.curvature=zt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){ne(this.vert,this.curvature,this.isClosed).show()}}function te(t=0){zt=Q(t,0,1),Yt=new Qt}function ee(t,e,r=1){if(!Yt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Yt.vertex(t,e,r)}function re(t=!1){if(!Yt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(Yt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(Yt.vertex(...Yt.vert[0]),Yt.isClosed=!0),Yt.show(),Yt=!1}function ne(t,e=.5,r=!1){const n=new Kt(0===e?"segments":"curve"),i=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let a,o,s,c=0;for(let l=0;l<t.length-1;l++)if(e>0&&l<t.length-2){const u=t[l],h=t[l+1],f=t[l+2],m=ut(u[0],u[1],h[0],h[1]),d=ut(h[0],h[1],f[0],f[1]),x=ht(u[0],u[1],h[0],h[1]),g=ht(h[0],h[1],f[0],f[1]),p=e*Math.min(m,d,.5*Math.min(m,d)),y=Math.max(m,d),b=m-p,v=d-p;if(Math.floor(x)===Math.floor(g)){const e=r&&0===l?0:m-c,i=r?0===l?0:d-s:d;n.addSegment(x,e,u[2],!0),l===t.length-3&&n.addSegment(g,i,h[2],!0),c=0,0===l&&(a=m,s=p,o=t[1],c=0)}else{const e={x:h[0]-p*at(-x),y:h[1]-p*ot(-x)},f={x:e.x+y*at(90-x),y:e.y+y*ot(90-x)},m={x:h[0]+p*at(-g),y:h[1]+p*ot(-g)},d={x:m.x+y*at(90-g),y:m.y+y*ot(90-g)},_=ft(e,f,m,d,!0),R=ut(e.x,e.y,_.x,_.y),w=ut(e.x,e.y,m.x,m.y)/2,E=i*R*(2*Math.asin(w/R)*(180/Math.PI))/360,A=r&&0===l?0:b-c,M=l===t.length-3?r?a-p:v:0;n.addSegment(x,A,u[2],!0),n.addSegment(x,isNaN(E)?0:E,u[2],!0),n.addSegment(g,M,h[2],!0),c=p,0===l&&(a=b,s=p,o=[e.x,e.y])}l===t.length-3&&n.endPlot(g,h[2],!0)}else if(0===e){const e=t[l],r=t[l+1],i=ut(e[0],e[1],r[0],r[1]),a=ht(e[0],e[1],r[0],r[1]);n.addSegment(a,i,r[2],!0),l===t.length-2&&n.endPlot(a,1,!0)}n.origin=r&&0!==e?o:t[0]}return n}let ie={createTipSurface:()=>{throw new Error("No stroke runtime adapter registered.")},loadImageTip:()=>{throw new Error("No stroke runtime adapter registered.")}},ae=!1;const oe=(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 se={beginDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},endDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},resetDirectShaderTracking:()=>{}};const ce=(t,e)=>se.resetDirectShaderTracking(t,e);let le,ue,he,fe,me,de=!1,xe=0,ge=0,pe=null;const ye={},be={};let ve=1,_e=0,Re=0,we=1,Ee=0,Ae=0,Me=0,Se=0,Te=1,Pe=1,Ce=new Float32Array(8192),Fe=0,ke=2048,Ie=32768,De=null,Le=null,Ne=null,Be=null,Ue=null;const Oe={},Ye={};let ze=0,Xe=new Float32Array(1280),Ge=0,Ze=256,Ve=null;const $e=new Map,He=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function We(){return ue}function qe(){return((t,e,r)=>se.beginDirectMaskDraw(t,e,r))(i,le,P.glMask)}function je(t){((t,e,r)=>{se.endDirectMaskDraw(t,e,r)})(i,le,t)}function Ke(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 Je(t,e,r,n){if(Fe>=ke){ke*=2;const t=new Float32Array(4*ke);t.set(Ce),Ce=t}const i=t-Me,a=e-Se,o=4*Fe,s=ve*i+Re*a+Ee+Me,c=_e*i+we*a+Ae+Se,l=Pe*r*Te/2;Ce[o]=s,Ce[o+1]=c,Ce[o+2]=l,Ce[o+3]=n/255;const u=s*Pe,h=c*Pe;De=Ke(De,u-l-1,h-l-1,u+l+1,h+l+1),Fe++}function Qe(t,e){if(0===Ge)return;P.glMask.isDrawn=!0;const r=qe();let n=$e.get(e);n||(n=le.createTexture(),le.bindTexture(le.TEXTURE_2D,n),le.texImage2D(le.TEXTURE_2D,0,le.RGBA,le.RGBA,le.UNSIGNED_BYTE,t.canvas),le.texParameteri(le.TEXTURE_2D,le.TEXTURE_MIN_FILTER,le.LINEAR),le.texParameteri(le.TEXTURE_2D,le.TEXTURE_MAG_FILTER,le.LINEAR),le.texParameteri(le.TEXTURE_2D,le.TEXTURE_WRAP_S,le.CLAMP_TO_EDGE),le.texParameteri(le.TEXTURE_2D,le.TEXTURE_WRAP_T,le.CLAMP_TO_EDGE),$e.set(e,n)),le.useProgram(Le),le.enable(le.BLEND),le.blendFunc(le.ONE_MINUS_DST_ALPHA,le.ONE),le.activeTexture(le.TEXTURE0),le.bindTexture(le.TEXTURE_2D,n),le.uniform1i(Ye.u_tex,0);const a=S.stroke.color._array;le.uniform4f(Ye.u_color,...a),le.uniformMatrix4fv(Ye.u_proj,!1,We()),le.bindVertexArray(Ne),le.bindBuffer(le.ARRAY_BUFFER,Ue);const o=5*Ge*4,s=Xe.subarray(0,5*Ge);o>ze?(le.bufferData(le.ARRAY_BUFFER,Xe,le.DYNAMIC_DRAW),ze=Xe.byteLength):le.bufferSubData(le.ARRAY_BUFFER,0,s),le.drawArraysInstanced(le.TRIANGLE_STRIP,0,4,Ge),le.flush(),le.bindVertexArray(null),le.bindTexture(le.TEXTURE_2D,null),je(r),Ve&&(P.markDirtyRect(P.glMask,Ve),Ve=null),Ge=0,ce(i,le)}ae||(b={ensureResources:function(t,e,r,n){return function(t,e,r,n){return!t.glMask||t.glMask.width!==e||t.glMask.height!==r||"function"==typeof t.glMask.pixelDensity&&t.glMask.pixelDensity()!==n}(t,e,r,n)&&(t.glMask?.remove&&t.glMask.remove(),t.glMask=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1})),t.glMask.dirtyRect??=null,t.glMask.isDrawn??=!1,t.glMask},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?e()?r():i(n(t.dirtyRect,2)):r():null},getShaderMask:function(t,e){return e}},ae=!0),S.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let tr=new Map;const er={offset:.08,scale:.08,warp:.06,tilt:.06};function rr(){return{...S.stroke}}function nr(t){S.stroke={...t}}function ir(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0===e.markerTip&&(e.markerTip=!0),void 0===e.noise&&(e.noise=.3),e.noise=Math.max(0,Math.min(1,e.noise)),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:{...er}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...er,...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,c,l]=[(e-i)/o,(r-i)/o,(n-i)/o];return{type:"custom",min_max:[i,a],variation:{...er},curve:t=>t<.5?s+(c-s)*t*2:c+(l-c)*(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&&le&&le.deleteTexture(e),$e.delete(t)}(r);const n=ie.createTipSurface(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 tr.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),tr.set(t,{param:e,colors:[],buffers:[]}),Sr.load()}tr.set(t,{param:e,colors:[],buffers:[]})}function ar(t){return tr.get(t)?.param??null}function or(t){if(!tr.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...tr.keys()].join(", ")}.`);S.stroke.type=t}function sr(t,e,r){f(),S.stroke.color=c(...arguments),S.stroke.isActive=!0}function cr(t){S.stroke.weight=t}function lr(t,e,r=1){or(t),sr(e),cr(r)}let ur,hr,fr,mr;const dr={};function xr(t,e,i,o=!1){!function(){const t=l();ve=t.a,_e=t.b,Re=t.c,we=t.d,Ee=t.x,Ae=t.y,Me=r/2,Se=n/2,Te=Math.sqrt(ve*ve+_e*_e),Pe=a}(),ur=new xt(t+r/2,e+n/2),hr=i,fr=o,fr&&fr.calcIndex(0)}const gr=[];function pr(t,e){e||(mr=t),function(){dr.seed=999999*V();const{param:t}=tr.get(S.stroke.type)??{};if(!t)return;dr.p=t;const{pressure:e}=t;if(dr.a="custom"!==e.type?V(-1,1):0,dr.b="custom"!==e.type?V(1,1.5):0,"custom"!==e.type)dr.cp=V(3,3.5),dr.ct=0,dr.cs=1,dr.ck=0;else{const t=e.variation??er;dr.cp=V(-t.offset,t.offset),dr.ct=V(-t.warp,t.warp),dr.cs=V(1-t.scale,1+t.scale),dr.ck=V(-t.tilt,t.tilt)}[dr.min,dr.max]=e.min_max,dr.noiseoffset=.05*dr.p.noise,fr||(dr.cos=at(mr),dr.sin=ot(mr)),function(){T(),function(){const t=i?.glMask;t&&(pe=t,pe.dirtyRect??=null,pe.isDrawn??=!1,P.glMask=pe)}();const t=i.drawingContext,e=!de||le!==t;(e||xe!==r||ge!==n)&&(ue=new Float32Array([2/r,0,0,0,0,2/n,0,0,0,0,1,0,-1,-1,0,1]),xe=r,ge=n),e&&(le=t,me=oe(le,"#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);}"),le.useProgram(me),le.enable(le.BLEND),le.blendFunc(le.ONE_MINUS_DST_ALPHA,le.ONE),["a_position","a_radius","a_alpha"].forEach(t=>ye[t]=le.getAttribLocation(me,t)),["u_matrix","u_color"].forEach(t=>be[t]=le.getUniformLocation(me,t)),he=le.createVertexArray(),le.bindVertexArray(he),fe=le.createBuffer(),le.bindBuffer(le.ARRAY_BUFFER,fe),le.bufferData(le.ARRAY_BUFFER,Ce.byteLength,le.DYNAMIC_DRAW),Ie=Ce.byteLength,le.enableVertexAttribArray(ye.a_position),le.vertexAttribPointer(ye.a_position,2,le.FLOAT,!1,16,0),le.enableVertexAttribArray(ye.a_radius),le.vertexAttribPointer(ye.a_radius,1,le.FLOAT,!1,16,8),le.enableVertexAttribArray(ye.a_alpha),le.vertexAttribPointer(ye.a_alpha,1,le.FLOAT,!1,16,12),le.bindVertexArray(null),$e.clear(),Le=oe(le,"#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=>Oe[t]=le.getAttribLocation(Le,t)),["u_proj","u_color","u_tex"].forEach(t=>Ye[t]=le.getUniformLocation(Le,t)),Ne=le.createVertexArray(),le.bindVertexArray(Ne),Be=le.createBuffer(),le.bindBuffer(le.ARRAY_BUFFER,Be),le.bufferData(le.ARRAY_BUFFER,He,le.STATIC_DRAW),le.enableVertexAttribArray(Oe.a_corner),le.vertexAttribPointer(Oe.a_corner,2,le.FLOAT,!1,0,0),Ue=le.createBuffer(),le.bindBuffer(le.ARRAY_BUFFER,Ue),le.bufferData(le.ARRAY_BUFFER,Xe.byteLength,le.DYNAMIC_DRAW),ze=Xe.byteLength,le.enableVertexAttribArray(Oe.a_pos),le.vertexAttribPointer(Oe.a_pos,2,le.FLOAT,!1,20,0),le.vertexAttribDivisor(Oe.a_pos,1),le.enableVertexAttribArray(Oe.a_size),le.vertexAttribPointer(Oe.a_size,1,le.FLOAT,!1,20,8),le.vertexAttribDivisor(Oe.a_size,1),le.enableVertexAttribArray(Oe.a_angle),le.vertexAttribPointer(Oe.a_angle,1,le.FLOAT,!1,20,12),le.vertexAttribDivisor(Oe.a_angle,1),le.enableVertexAttribArray(Oe.a_alpha),le.vertexAttribPointer(Oe.a_alpha,1,le.FLOAT,!1,20,16),le.vertexAttribDivisor(Oe.a_alpha,1),le.bindVertexArray(null),de=!0)}();const a=!0!==P.isBrush;P.isBrush=!0,a&&(P.justChanged=!0),P.blend(S.stroke.color),dr.alpha=["default","spray"].includes(dr.p.type)?dr.p.opacity:dr.p.opacity/Math.min(S.stroke.weight,1.3),wr()}();const a=function(){const{param:t}=tr.get(S.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(hr*(e?t:1)/a);dr.pressureCount=10,dr.cachedPressure=void 0,dr.lineNoiseCount=5,dr.cachedLineNoise=void 0;for(let r=0;r<o;r++)gr.length<2*o&&gr.push(j()),yr(),e?ur.plotTo(fr,a,a,t,r<10):ur._moveToDegrees(t,a,a);!function(){wr(),function(){if(0===Fe)return;P.glMask.isDrawn=!0;const t=qe(),e=S.stroke.color._array;le.useProgram(me),le.enable(le.BLEND),le.blendFunc(le.ONE_MINUS_DST_ALPHA,le.ONE),le.bindVertexArray(he),le.bindBuffer(le.ARRAY_BUFFER,fe);const r=16*Fe,n=Ce.subarray(0,4*Fe);r>Ie?(le.bufferData(le.ARRAY_BUFFER,Ce,le.DYNAMIC_DRAW),Ie=Ce.byteLength):le.bufferSubData(le.ARRAY_BUFFER,0,n),le.uniform4f(be.u_color,...e),le.uniformMatrix4fv(be.u_matrix,!1,We()),le.drawArrays(le.POINTS,0,Fe),le.flush(),le.bindVertexArray(null),je(t),De&&(P.markDirtyRect(P.glMask,De),De=null),Fe=0,ce(i,le)}();const t=dr.p?.type;"image"===t?Qe(Sr.tips.get(dr.p.image.src),dr.p.image.src):"custom"===t&&Qe(Sr.tips.get(dr.p.tipKey),dr.p.tipKey)}()}function yr(){const t=br(),e=((dr.lineNoiseCount>=10||void 0===dr.cachedLineNoise)&&(dr.cachedLineNoise=J(G(dr.seed+.01*ur.plotted,0),-1,1,1-dr.noiseoffset,1+dr.noiseoffset),dr.lineNoiseCount=0),dr.lineNoiseCount++,dr.cachedLineNoise);if(!(e>V(1,1.02)&&V(0,1)<.7))switch(dr.p.type){case"spray":!function(t){const e=S.stroke.weight*dr.p.scatter*t+S.stroke.weight*H(gr)*dr.p.scatter/3,r=dr.p.weight*V(.9,1.1),n=Math.ceil(dr.p.grain/t);for(let t=0;t<n;t++){const t=V(.9,1.1),n=t*e*V(-1,1),i=V(-1,1),a=Math.sqrt((t*e)**2-n**2);Je(ur.x+n,ur.y+i*a,r,dr.alpha)}}(t*e);break;case"marker":_r(t*e);break;case"custom":case"image":Rr(t*e);break;default:!function(t,e=1){const r=(e=J(e,0,1,.9,1.05))*S.stroke.weight*dr.p.scatter*(dr.p.sharpness+(1-dr.p.sharpness)*H(gr)/t);if(V(0,dr.p.grain*t)>.4){let e,n;if(fr){const t=fr.angle(ur.plotted),i=at(t),a=ot(t),o=r*V(-1,1),s=.3*r*V(-1,1);e=o*a+s*i,n=o*i-s*a}else{const t=r*V(-1,1),i=.3*r*V(-1,1);e=t*dr.sin+i*dr.cos,n=t*dr.cos-i*dr.sin}const i=t*t*dr.p.weight*V(.85,1.15)*S.stroke.weight,a=Math.max(.9,t)*dr.alpha*V(.75,1.1);Je(ur.x+e,ur.y+n,i,a)}}(t*e)}}function br(){return(dr.pressureCount>=10||void 0===dr.cachedPressure)&&(dr.cachedPressure=fr?vr()*fr.pressure(ur.plotted):vr(),dr.pressureCount=0),dr.pressureCount++,dr.cachedPressure}function vr(){return"custom"===dr.p.pressure.type?J(dr.p.pressure.curve(Math.max(0,Math.min(1,.5+(ur.plotted/hr-.5+dr.ct)*dr.cs)))+dr.cp+dr.ck*(ur.plotted/hr-.5),0,1,dr.min,dr.max,!0):function(t=.5+dr.p.pressure.curve[0]*dr.a,e=1-dr.p.pressure.curve[1]*dr.b,r=dr.cp,n=dr.min,i=dr.max){const a=t*hr,o=(ur.plotted<a?1.2*e:.8*e)*(hr/2);return J(1/(1+Math.pow(Math.abs((ur.plotted-a)/o),2*r)),0,1,n,i)}()}function _r(t,e=!0,r=dr.alpha){const n=e?S.stroke.weight*dr.p.scatter:0,i=e?n*V(-1,1):0,a=e?n*V(-1,1):0;Je(ur.x+i,ur.y+a,S.stroke.weight*dr.p.weight*t,r*Math.max(.8,t)*V(.9,1.1))}function Rr(t,e=dr.alpha){const r=S.stroke.weight*dr.p.scatter,n=r*V(-1,1),i=r*V(-1,1),a=dr.p.weight*S.stroke.weight*t,o=function(){const t=Math.max(1,dr.max??1),e=S.stroke.weight*dr.p.scatter,r=S.stroke.weight*dr.p.weight*t;return Math.max(8,1.5*e+.75*r)}();let s=0;"random"===dr.p.rotate?s=W(0,360)*(Math.PI/180):"natural"===dr.p.rotate&&(s=((fr?-fr.angle(ur.plotted):-mr)+ur.angle())*(Math.PI/180)),function(t,e,r,n,i,a=0){if(Ge>=Ze){Ze*=2;const t=new Float32Array(5*Ze);t.set(Xe),Xe=t}const o=t-Me,s=e-Se,c=ve*o+Re*s+Ee+Me,l=_e*o+we*s+Ae+Se,u=Pe*r*Te/2,h=Pe*a*Te,f=5*Ge;Xe[f]=c,Xe[f+1]=l,Xe[f+2]=u,Xe[f+3]=n,Xe[f+4]=i/255;const m=c*Pe,d=l*Pe,x=1.42*u+h;Ve=Ke(Ve,m-x-1,d-x-1,m+x+1,d+x+1),Ge++}(ur.x+n,ur.y+i,a,s,e*Math.max(.8,t)*V(.9,1.1),o)}function wr(){if(!1===dr.p.markerTip)return;let t=br(),e=dr.alpha;if("marker"===dr.p.type)for(let r=1;r<10;r++)_r(t*r/10,!0,8*e);else if("custom"===dr.p.type||"image"===dr.p.type)for(let r=1;r<5;r++)Rr(t*r/10,2*e)}function Er(t,e,r,n){if(!S.stroke.isActive||!S.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");dt();let i=ut(t,e,r,n);0!=i&&(xr(t,e,i),pr(ht(t,e,r,n),!1))}X(()=>{gr.length=0});const Ar=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],Mr=[["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]}]],["pastel",[2.05/3,13.4/3,.91,28,35,.085/3,{mode:"gaussian",curve:[.4,.05],min_max:[1.09,.93]},"default",void 0,"natural",!0,1]],["crayon",[.3,5.45/3,.75,250,159,.23/3,[1.1,.9],"default",void 0,"natural",!0,1]],["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 Mr){let e={};for(let r=0;r<t[1].length;r++)e[Ar[r]]=t[1][r];ir(t[0],e)}jt.prototype.draw=function(t=!1,e,r){let n=rr();if(t&&lr(t,e,r),n.isActive)for(let t of this.sides)Er(t[0].x,t[0].y,t[1].x,t[1].y);nr(n)},Kt.prototype.draw=function(t,e,r){rr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,n){dt(),xr(e,r,t.length,t),pr(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=>((t,e)=>ie.loadImageTip(t,e))(t,Sr.imageToWhite).then(e=>{this.tips.set(t,e)})))}};function Tr(){return{...S.hatch}}function Pr(t){S.hatch={...t}}function Cr(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=S.hatch;n.isActive=!0,n.dist=t,n.angle=ct(e),n.options=r}function Fr(t,e,r,n){const i=e*Math.PI/180,a=Math.cos(i),o=Math.sin(i),s=Math.cos(-i),c=Math.sin(-i),l=t.a,u=l.length,h=new Array(u);let f=Infinity,m=-Infinity;for(let t=0;t<u;t++){const e=l[t][0],r=l[t][1],n=[e*a-r*o,e*o+r*a];h[t]=n,n[1]<f&&(f=n[1]),n[1]>m&&(m=n[1])}const d=[];for(let t=0;t<u;t++){const e=h[t],r=h[(t+1)%u];e[1]!==r[1]&&d.push(e,r)}const x=d.length,g=[];let p=f+.5*r,y=r;for(;p<m;){const t=[];for(let e=0;e<x;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)g.push({scanY:p,x1:t[e]*s-p*c,y1:t[e]*c+p*s,x2:t[e+1]*s-p*c,y2:t[e+1]*c+p*s});p+=y,y*=n}return g}function kr(t){const{dist:e,options:r,segs:n}=function(t){const e=S.hatch.dist,r=(S.hatch.angle%180+180)%180,n=S.hatch.options,i=function(t,e,r,n){Array.isArray(t)||(t=[t]);const i=[];for(const a of t)for(const t of Fr(a,r,e,n))i.push(t);return i.sort((t,e)=>t.scanY===e.scanY?t.x1-e.x1:t.scanY-e.scanY),i}(t,e,r,n.gradient?J(n.gradient,0,1,1,1.1,!0):1);return{dist:e,options:n,segs:i}}(t),i=r.rand||0,a=[];for(let t=0;t<n.length;t++){const o=n[t];let s=o.x1,c=o.y1,l=o.x2,u=o.y2;i&&(s+=2*i*e*V(-1,1),c+=2*i*e*V(-1,1),l+=2*i*e*V(-1,1),u+=2*i*e*V(-1,1));const h=r.continuous&&t%2==1?{x1:l,y1:u,x2:s,y2:c,scanY:o.scanY,isConnector:!1}:{x1:s,y1:c,x2:l,y2:u,scanY:o.scanY,isConnector:!1};if(a.push(h),t>0&&r.continuous){const t=a[a.length-2];a.push({x1:t.x2,y1:t.y2,x2:h.x1,y2:h.y1,scanY:o.scanY,isConnector:!0})}}return a}function Ir(t){!function(t,e){const r=kr(t);!function(){const t=rr();S.hatch.hBrush&&lr(...Object.values(S.hatch.hBrush)),(()=>{for(let t=0;t<r.length;t++){const n=r[t];e(n.x1,n.y1,n.x2,n.y2,t,r)}})(),nr(t)}()}(t,(t,e,r,n)=>{Er(t,e,r,n)})}function Dr(t,e,r){return new jt(t.vertices.map(t=>[t.x+e,t.y+r]))}function Lr(t,e,r,n,i){const a=(e+n)/2,o=(r+i)/2,s=n-e,c=i-r,l=Math.hypot(s,c);if(!l)return null;const u=-c/l,h=s/l,f=(t.x-a)*u+(t.y-o)*h;return{x:a+u*f,y:o+h*f}}function Nr(t,e,r,n,i,a,o){let s=ht(t,e,r,n),c=ht(t,e,i,a);return((c-s)%360+360)%360>180&&([s,c]=[c,s]),[o(s),o(c)]}function Br(t){const e=$(.35,.65),r=t.x1+(t.x2-t.x1)*e,n=t.y1+(t.y2-t.y1)*e,i=t.x2-t.x1,a=t.y2-t.y1,o=Math.hypot(i,a)||1,s=$(.04,.1)*o,c=i/o*s*.5,l=a/o*s*.5;return[{x1:t.x1,y1:t.y1,x2:r-c,y2:n-l},{x1:r+c,y1:n+l,x2:t.x2,y2:t.y2}]}function Ur(t,e,r){const n=function(t,e){const r=function(t){const e=t?.a??[];let r=Infinity,n=Infinity,i=-Infinity,a=-Infinity;for(const[t,o]of e)t<r&&(r=t),o<n&&(n=o),t>i&&(i=t),o>a&&(a=o);return{minX:r,minY:n,maxX:i,maxY:a,cx:(r+i)/2,cy:(n+a)/2,size:Math.hypot(i-r,a-n)}}(t),n=r.size*$(.6,1.4),[i,a]=e;return{x:r.cx+i*n,y:r.cy+a*n}}(t,e);for(const e of kr(t)){const t=!e.isConnector&&$()<.35?Br(e):[e];for(const e of t){const t=Lr(n,e.x1,e.y1,e.x2,e.y2);if(!t)continue;const i=ut(t.x,t.y,e.x1,e.y1);if(!i)continue;const[a,o]=Nr(t.x,t.y,e.x1,e.y1,e.x2,e.y2,r);Jt(t.x,t.y,i,a,o)}}}function Or(t,e,r,n,i,a){Cr(e,r,n),Ur(t,i,a)}function Yr(t,e,r,n){const i=function(t,e,r,n){const i=!1===e,a=ar(S.mass.brush)?.scatter??0,o=i?t:t.genPol(e,r,n,.15),s=Math.min(2*a,5),c=[[$(-s,s),$(-s,s)],[$(-s,s),$(-s,s)]];return[o,Dr(o,c[0][0],c[0][1]),Dr(o,c[1][0],c[1][1])]}(t,e,r,n),a=Tr(),c=rr(),l={...S.field},u=S.mass.options?.precision??.5,h=S.mass.options?.strength??1,f=S.mass.options?.gradient??.1,m=S.mass.options?.outline??!1,d=ar(S.mass.brush)?.scatter??0,x=1.6*$(.65*d,.85*d)-.4*f,g=$(-90,90),p=((g+90)%180+180)%180-90>=0?$()<.5?[1,1]:[-1,-1]:$()<.5?[-1,1]:[1,-1],y=o()?t=>t*Math.PI/180:t=>t;lr(S.mass.brush,S.mass.color,1),St(2-u),m&&i[0].draw(),Or(i[0],.9*x,s(g),{gradient:f,rand:2-2*u,continuous:!0},p,y),h>.33&&Or(i[1],x,s(g+20*$(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),h>.66&&Or(i[2],.8*x,s(g+15*$(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),nr(c),Pr(a),S.field={...l}}function zr(t,e,r){const n=2*Math.PI,i=P.ctx,a=r/2;i.moveTo(t+a,e),i.arc(t,e,a,0,n)}S.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},jt.prototype.hatch=function(t=!1,e,r){let n=Tr();t&&Cr(t,e,r),S.hatch.isActive&&Ir(this),Pr(n)},Kt.prototype.hatch=function(t,e,r){Tr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.3),this.pol.hatch())},S.mass={isActive:!1,brush:null,color:null,options:{}},jt.prototype.mass=function(){S.mass?.isActive&&Yr(this,!1)},Kt.prototype.mass=function(t,e,r){S.mass?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),Yr(this,t,e,r))};let Xr=null,Gr=!1;Gr||(v={ensureResources:function(t,e,r,n,i){const a=Math.max(1,Math.round(e*n)),o=Math.max(1,Math.round(r*n));return function(t,e,r){return!t.mask||t.mask.width!==e||t.mask.height!==r}(t,a,o)&&(t.mask=g(a,o)),function(t,e,r,n){return!t.fillMaskFramebuffer||t.fillMaskFramebuffer.width!==e||t.fillMaskFramebuffer.height!==r||"function"==typeof t.fillMaskFramebuffer.pixelDensity&&t.fillMaskFramebuffer.pixelDensity()!==n}(t,e,r,n)&&(t.fillMaskFramebuffer?.remove&&t.fillMaskFramebuffer.remove(),t.fillMaskFramebuffer=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1}),i(t.fillMaskFramebuffer)),t.mask.dirtyRect??=null,t.mask.isDrawn??=!1,t.mask.drawingContext.imageSmoothingEnabled=!1,{mask:t.mask,ctx:t.mask.drawingContext}},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?i(n(t.dirtyRect,4)):r():null},getShaderMask:function(t,e,r,n,i,a){const o=t.fillMaskFramebuffer,s=t.drawingContext,c=n(r)??i(),l=c.maxX-c.minX,u=c.maxY-c.minY;Xr&&Xr.width===l&&Xr.height===u||(Xr=g(l,u));const h=Xr.drawingContext;return h.clearRect(0,0,l,u),h.drawImage(e,c.minX,c.minY,l,u,0,0,l,u),a(o),s.bindTexture(s.TEXTURE_2D,o.colorTexture),s.texSubImage2D(s.TEXTURE_2D,0,c.minX,c.minY,s.RGBA,s.UNSIGNED_BYTE,Xr),o}},Gr=!0),S.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Zr=()=>({...S.fill});function Vr(t,e,r,n){S.fill.opacity=(arguments.length<4?e:n)||150,S.fill.color=arguments.length<3?c(t):c(t,e,r),S.fill.isActive=!0}function $r(t,e="out"){S.fill.bleed_strength=Q(t,0,1),S.fill.direction=e}function Hr(t=.4,e=.4){S.fill.texture_strength=Q(t,0,1),S.fill.border_strength=Q(e,0,1)}let Wr;const qr=[[],[]];function jr(){for(let t=0;t<512;t++)qr[0][t]=j(.5,.2),qr[1][t]=j(0,.02)}function Kr(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}X(jr);class Jr{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 c=t[a],l=t[(a+1)%t.length],u={x:l.x-c.x,y:l.y-c.y},h=lt(0,0,u.x,u.y,90),f={x:c.x+u.x/2,y:c.y+u.y/2};i.push({v1:c,v2:l,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=e,this.sizeY=n,this.dir=Array(t.length),i.forEach((t,e)=>{let r=0;for(const e of Wr.intersect(t.ray))Kr(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const a=V(-.6,.6)*e,o=V(-.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];const c=r,l=r+e,u=this.v[(c-1+this.v.length)%this.v.length],h=this.v[l%this.v.length],f=h.x-u.x,m=h.y-u.y;for(let t=0;t<2;t++){const e=V(.25,.75),n={x:u.x+f*e,y:u.y+m*e},s=r+t;i.splice(s,0,n),a.splice(s,0,V(.4,.7)),o.splice(s,0,this.dir[c%this.dir.length])}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+V(0,.8*i)));const a=[],o=[],s=[],c=this.midP,l=Wr.sides;for(const t of n){const r=t%e;let n=this.v[r],i=0;for(const[t,e]of l){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:c.x+(n.x-c.x)*V(.3,.6),y:c.y+(n.y-c.y)*V(.3,.6)}),a.push(n),o.push(this.m[r]),s.push(!this.dir[r])}return new Jr(a,o,this.midP,s,!1,this.sizeX,this.sizeY)}flipDirs(){return new Jr(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),c=new Array(a),l=new Array(a),u="out"===S.fill.direction?-90:90;0===qr[0].length&&jr();const h=qr[0],f=h.length,m=qr[1],d=m.length;let x,g,p,y=0,b=0,v=999===t?V(.6,.8):S.fill.bleed_strength;for(let a=0;a<i;a++){const x=e[a],g=e[a+1<i?a+1:0],p=r[a],_=n[a];if(t<997&&(v=p),v<.05){c[y]=p,l[y]=_,y++,o[b]=(x.x+g.x)/2,s[b]=(x.y+g.y)/2,c[y]=p,l[y]=_,y++,b++;continue}const R=(_?u:-u)+5*V(-1,1),w=at(R),E=ot(R),A=g.x-x.x,M=g.y-x.y,S=w*A+E*M,T=w*M-E*A,P=h[~~(V(0,1)*f)]*V(.65,1.35)*v,C=p+m[~~(V(0,1)*d)];c[y]=p,l[y]=_,y++,o[b]=x.x+.5*A+S*P,s[b]=x.y+.5*M+T*P,c[y]=C,l[y]=_,y++,b++}const _=2024*Math.max(.1,2*S.fill.bleed_strength);if(_&&y>_){const t=Math.ceil(y/_),r=Math.ceil(y/t);x=new Array(r),g=new Array(r),p=new Array(r);let n=0;for(let r=0;r<y;r+=t,n++)x[n]=r%2==0?e[r>>1]:{x:o[r>>1],y:s[r>>1]},g[n]=c[r],p[n]=l[r]}else{x=new Array(y);for(let t=0;t<y;t++)x[t]=t%2==0?e[t>>1]:{x:o[t>>1],y:s[t>>1]};c.length=y,l.length=y,g=c,p=l}return new Jr(x,g,this.midP,p,!1,this.sizeX,this.sizeY)}fill(t,e,i){const o=3*i,s=2*e*(1+i/2),c=!1!==P.isBrush;P.isBrush=!1,c&&(P.justChanged=!0),P.blend(t);const u=l();P.ctx.save(),P.ctx.setTransform(a*u.a,a*u.b,a*u.c,a*u.d,a*(u.x+r/2),a*(u.y+n/2)),P.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*S.fill.border_strength})`,P.ctx.lineCap="round";const h=Math.max(this.sizeX,this.sizeY),f=V(.15,.7);let m=this.grow();const d=this.scatter(.1).grow().scatter(.75).flipDirs();let x;for(let r=0;r<20;r++){r%4==0&&(m=m.grow()),r%2==0&&(x=[m.grow(1-.0125*r),m.grow(.7-.0125*r),m.grow(.4-.0125*r)]);for(const e of x)e.grow(999).grow(997).layer(r,h,s,t);d.grow(999).flipDirs().grow(997).layer(r,h,s*o,t),r%2==0&&m.grow(f).grow(999).layer(r,h,2*s,t),r%8!=0&&19!==r||(0!==o&&m.erase(3*o,e),P.blend(t,!0))}P.ctx.restore()}layer(t,e,r,n){P.ctx.lineWidth=J(t,0,24,e/25,e/30,!0),P.ctx.fillStyle=`rgb(${n._getRed()} ${n._getGreen()} ${n._getBlue()} / ${r}%)`,function(t){const e=P.ctx,r=e.getTransform(),n=r.a,i=r.b,a=r.c,o=r.d,s=r.e,c=r.f;let l=Infinity,u=Infinity,h=-Infinity,f=-Infinity;e.beginPath();const m=t[0];let d=n*m.x+a*m.y+s,x=i*m.x+o*m.y+c;l=h=d,u=f=x,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,x=i*m.x+o*m.y+c,l=Math.min(l,d),u=Math.min(u,x),h=Math.max(h,d),f=Math.max(f,x),e.lineTo(m.x,m.y)}e.closePath();const g=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);P.markDirtyRect(P.mask,{minX:l-g,minY:u-g,maxX:h+g,maxY:f+g})}(this.v),P.ctx.fill(),P.ctx.stroke()}erase(t,e){P.ctx.save();const r=~~(V(80,110)*J(t,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,a=1.3*Math.min(this.sizeX,this.sizeY),o=.03*a,s=.45*a,{x:c,y:l}=this.midP;P.ctx.globalCompositeOperation="destination-out";const u=(5-J(e,80,100,.3,.7,!0))*t/255;P.ctx.fillStyle=`rgb(255 0 0 / ${u})`,P.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=c+j(0,n),r=l+j(0,i),a=V(o,s);P.ctx.beginPath(),zr(e,r,a),t%5!=0&&P.ctx.fill()}P.ctx.globalCompositeOperation="source-over",P.ctx.restore()}}function Qr(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!un(n,n.next)&&0!==ln(n.prev,n,n.next))n=n.next;else{if(pn(n),n=e=n.prev,n===n.next)break;r=!0}}while(r||n!==e);return e}function tn(t,e,r,n,i,a,o){if(!t)return;!o&&a&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=on(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let a=null;for(e=0;i;){e++;let o=i,s=0;for(let t=0;t<r&&(s++,o=o.nextZ,o);t++);let c=r;for(;s>0||c>0&&o;)0!==s&&(0===c||!o||i.z<=o.z)?(n=i,i=i.nextZ,s--):(n=o,o=o.nextZ,c--),a?a.nextZ=n:t=n,n.prevZ=a,a=n;i=o}a.nextZ=null,r*=2}while(e>1)}(i)}(t,n,i,a);let s=t;for(;t.prev!==t.next;){const c=t.prev,l=t.next;if(a?rn(t,n,i,a):en(t))e.push(c.i,t.i,l.i),pn(t),t=l.next,s=l.next;else if((t=l)===s){o?1===o?tn(t=nn(Qr(t),e),e,r,n,i,a,2):2===o&&an(t,e,r,n,i,a):tn(Qr(t),e,r,n,i,a,1);break}}}function en(t){const e=t.prev,r=t,n=t.next;if(ln(e,r,n)>=0)return!1;const i=e.x,a=r.x,o=n.x,s=e.y,c=r.y,l=n.y,u=Math.min(i,a,o),h=Math.min(s,c,l),f=Math.max(i,a,o),m=Math.max(s,c,l);let d=n.next;for(;d!==e;){if(d.x>=u&&d.x<=f&&d.y>=h&&d.y<=m&&sn(i,s,a,c,o,l,d.x,d.y)&&ln(d.prev,d,d.next)>=0)return!1;d=d.next}return!0}function rn(t,e,r,n){const i=t.prev,a=t,o=t.next;if(ln(i,a,o)>=0)return!1;const s=i.x,c=a.x,l=o.x,u=i.y,h=a.y,f=o.y,m=Math.min(s,c,l),d=Math.min(u,h,f),x=Math.max(s,c,l),g=Math.max(u,h,f),p=on(m,d,e,r,n),y=on(x,g,e,r,n);let b=t.prevZ,v=t.nextZ;for(;b&&b.z>=p&&v&&v.z<=y;){if(b.x>=m&&b.x<=x&&b.y>=d&&b.y<=g&&b!==i&&b!==o&&sn(s,u,c,h,l,f,b.x,b.y)&&ln(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,v.x>=m&&v.x<=x&&v.y>=d&&v.y<=g&&v!==i&&v!==o&&sn(s,u,c,h,l,f,v.x,v.y)&&ln(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;b&&b.z>=p;){if(b.x>=m&&b.x<=x&&b.y>=d&&b.y<=g&&b!==i&&b!==o&&sn(s,u,c,h,l,f,b.x,b.y)&&ln(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;v&&v.z<=y;){if(v.x>=m&&v.x<=x&&v.y>=d&&v.y<=g&&v!==i&&v!==o&&sn(s,u,c,h,l,f,v.x,v.y)&&ln(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function nn(t,e){let r=t;do{const n=r.prev,i=r.next.next;!un(n,i)&&hn(n,r,r.next,i)&&dn(n,i)&&dn(i,n)&&(e.push(n.i,r.i,i.i),pn(r),pn(r.next),r=t=i),r=r.next}while(r!==t);return Qr(r)}function an(t,e,r,n,i,a){let o=t;do{let t=o.next.next;for(;t!==o.prev;){if(o.i!==t.i&&cn(o,t)){let s=xn(o,t);return o=Qr(o,o.next),s=Qr(s,s.next),tn(o,e,r,n,i,a,0),void tn(s,e,r,n,i,a,0)}t=t.next}o=o.next}while(o!==t)}function on(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function sn(t,e,r,n,i,a,o,s){return!(t===o&&e===s)&&function(t,e,r,n,i,a,o,s){return(i-o)*(e-s)>=(t-o)*(a-s)&&(t-o)*(n-s)>=(r-o)*(e-s)&&(r-o)*(a-s)>=(i-o)*(n-s)}(t,e,r,n,i,a,o,s)}function cn(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&hn(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&(dn(t,e)&&dn(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)&&(ln(t.prev,t,e.prev)||ln(t,e.prev,e))||un(t,e)&&ln(t.prev,t,t.next)>0&&ln(e.prev,e,e.next)>0)}function ln(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function un(t,e){return t.x===e.x&&t.y===e.y}function hn(t,e,r,n){const i=mn(ln(t,e,r)),a=mn(ln(t,e,n)),o=mn(ln(r,n,t)),s=mn(ln(r,n,e));return i!==a&&o!==s||!(0!==i||!fn(t,r,e))||!(0!==a||!fn(t,n,e))||!(0!==o||!fn(r,t,n))||!(0!==s||!fn(r,e,n))}function fn(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function mn(t){return t>0?1:t<0?-1:0}function dn(t,e){return ln(t.prev,t,t.next)<0?ln(t,e,t.next)>=0&&ln(t,t.prev,e)>=0:ln(t,e,t.prev)<0||ln(t,t.next,e)<0}function xn(t,e){const r=yn(t.i,t.x,t.y),n=yn(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function gn(t,e,r,n){const i=yn(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function pn(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function yn(t,e,r){return{i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}jt.prototype.fill=function(t=!1,e,r,n,i,a){let o=Zr();t&&(Vr(t,e),$r(r,a),Hr(n,i)),o.isActive&&(dt(),function(t){if(!S.fill.isActive||!S.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Wr=t;const e=[...t.vertices],r=~~(.25*e.length*K({1:5,2:10,3:60})),n=S.fill.bleed_strength,i=e.map((t,e)=>(e>r?1:.3)*V(.85,1.4)*n),a=W(0,e.length),o=[...e.slice(a),...e.slice(0,a)],s=function(t){if(0===t.length)return{x:0,y:0};if(t.length<8){const e=t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0});return{x:e.x/t.length,y:e.y/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 Jr(o,i,s,[],!0).fill(S.fill.color,J(S.fill.opacity,0,255,0,1,!0),S.fill.texture_strength)}(this)),(t=>{S.fill={...t}})(o)},Kt.prototype.fill=function(t,e,r){Zr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,S.fill.bleed_strength<.06?0:J(S.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let bn=null,vn=null,_n=null,Rn=null,wn=null,En=0,An=0,Mn=0;const Sn={},Tn={};function Pn(t,e,r,n){f(),S.wash.opacity=(arguments.length<4?e:n)??150,S.wash.color=arguments.length<3?c(t):c(t,e,r),S.wash.isActive=!0}function Cn(t,e){const r=l();return[r.a*t+r.c*e+r.x+En/2,r.b*t+r.d*e+r.y+An/2]}function Fn(t,e,r){const n=e.isEnabled(e.DEPTH_TEST);return n&&e.disable(e.DEPTH_TEST),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.viewport(0,0,r.width*r.density,r.height*r.density),{hadDepthTest:n}}function kn(t,e,i){i?.hadDepthTest&&e.enable(e.DEPTH_TEST),e.bindFramebuffer(e.FRAMEBUFFER,null),e.viewport(0,0,Math.max(1,Math.round(r*a)),Math.max(1,Math.round(n*a)))}function In(t,e){e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA)}function Dn(t,e,r){if(!e)return;if(r(e)){const r=t.drawingContext,n=r.getParameter(r.FRAMEBUFFER_BINDING),i=r.getParameter(r.VIEWPORT);return r.bindFramebuffer(r.FRAMEBUFFER,e.framebuffer),r.viewport(0,0,e.width*e.density,e.height*e.density),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.bindFramebuffer(r.FRAMEBUFFER,n),void r.viewport(i[0],i[1],i[2],i[3])}const n=e.drawingContext;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,e.width,e.height),n.restore()}function Ln(t,e,r){return t.shaderProgram??=function(t,e,r){const n=oe(t,e,r),i=new Map;return{program:n,setUniform(e,r){const a=(e=>(i.has(e)||i.set(e,t.getUniformLocation(n,e)),i.get(e)))(e);a&&("boolean"!=typeof r?"number"!=typeof r?Array.isArray(r)&&(3===r.length?t.uniform3f(a,r[0],r[1],r[2]):4===r.length&&t.uniform4f(a,r[0],r[1],r[2],r[3])):t.uniform1f(a,r):t.uniform1i(a,r?1:0))}}}(t.drawingContext,e,r),t.shaderProgram}function Nn(t,e){const r=t.drawingContext,n=e.density??1,i=r.createFramebuffer(),a=Math.max(1,e.width),o=Math.max(1,e.height),s=Math.max(1,Math.round(a*n)),c=Math.max(1,Math.round(o*n)),l=function(t,e,r){const n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,r,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindTexture(t.TEXTURE_2D,null),n}(r,s,c);return r.bindFramebuffer(r.FRAMEBUFFER,i),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,l,0),r.bindFramebuffer(r.FRAMEBUFFER,null),{__brushFramebuffer:!0,framebuffer:i,colorTexture:l,width:a,height:o,density:n,pixelDensity:()=>n,remove(){r.deleteFramebuffer(i),r.deleteTexture(l)}}}function Bn(t,e,r,n,i){return e?.remove?.(),Nn(t,{width:r,height:n,density:i})}function Un({renderer:t,shader:e,source:r,mask:n,color:i,isBrushMask:a,dirtyRect:o,targetIsFramebuffer:s,withScissor:c}){const l=t.drawingContext,u=l.isEnabled(l.DEPTH_TEST),h=l.getParameter(l.FRAMEBUFFER_BINDING),f=l.getParameter(l.CURRENT_PROGRAM),m=l.getParameter(l.VERTEX_ARRAY_BINDING),d=l.createVertexArray();l.bindVertexArray(d),l.useProgram(e.program),l.disable(l.DEPTH_TEST),l.enable(l.BLEND),l.blendEquation(l.FUNC_ADD),l.blendFunc(l.ONE,l.ONE_MINUS_SRC_ALPHA),l.activeTexture(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,r.colorTexture),l.uniform1i(l.getUniformLocation(e.program,"u_source"),0),l.activeTexture(l.TEXTURE1),l.bindTexture(l.TEXTURE_2D,n.colorTexture),l.uniform1i(l.getUniformLocation(e.program,"u_mask"),1),e.setUniform("u_targetIsFramebuffer",s),e.setUniform("u_isBrush",a),l.uniform3f(l.getUniformLocation(e.program,"u_color"),i[0],i[1],i[2]),l.bindFramebuffer(l.FRAMEBUFFER,null),c(l,o,()=>{l.drawArrays(l.TRIANGLES,0,3)},!s),l.bindTexture(l.TEXTURE_2D,null),l.activeTexture(l.TEXTURE0),l.bindVertexArray(m),l.useProgram(f),l.bindFramebuffer(l.FRAMEBUFFER,h),u&&l.enable(l.DEPTH_TEST),l.deleteVertexArray(d)}function On(t){return function({renderer:t,sourceFramebuffer:e,dirtyRect:r,getTargetPixelSize:n,toScissorBox:i}){const a=t.drawingContext,{width:o,height:s}=n(),c=r?i(r):null,l=a.getParameter(a.READ_FRAMEBUFFER_BINDING),u=a.getParameter(a.DRAW_FRAMEBUFFER_BINDING);return a.bindFramebuffer(a.READ_FRAMEBUFFER,null),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,e.framebuffer),a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT),a.blitFramebuffer(c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,a.COLOR_BUFFER_BIT,a.NEAREST),a.bindFramebuffer(a.READ_FRAMEBUFFER,l),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,u),e}(t)}function Yn(t){if("number"==typeof t){const e=Math.max(0,Math.min(255,t));return`rgb(${e} ${e} ${e})`}return t??"black"}function zn(t){const e=((t,e=!1)=>(t.drawingContext??=t.getContext("2d",e?{willReadFrequently:!0}:void 0),t.drawingContext))(t,!0),r={canvas:t,drawingContext:e,width:t.width,height:t.height,pixels:null,_fillStyle:"#ffffff",_strokeStyle:"transparent",_lineWidth:1,pixelDensity:()=>1,background(r){e.save(),e.setTransform(1,0,0,1,0,0),e.fillStyle=Yn(r),e.fillRect(0,0,t.width,t.height),e.restore()},noSmooth(){e.imageSmoothingEnabled=!1},push(){e.save()},pop(){e.restore()},translate(t,r){e.translate(t,r)},scale(t,r=t){e.scale(t,r)},rotate(t){e.rotate(t)},noStroke(){r._strokeStyle="transparent"},stroke(t){r._strokeStyle=Yn(t)},noFill(){r._fillStyle="transparent"},fill(t){r._fillStyle=Yn(t)},strokeWeight(t){r._lineWidth=t},rect(t,n,i,a){e.beginPath(),e.rect(t,n,i,a),r._paint()},circle(t,n,i){e.beginPath(),e.arc(t,n,i/2,0,2*Math.PI),r._paint()},ellipse(t,n,i,a){e.beginPath(),e.ellipse(t,n,i/2,a/2,0,0,2*Math.PI),r._paint()},line(t,n,i,a){e.beginPath(),e.moveTo(t,n),e.lineTo(i,a),e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke()},beginShape(){e.beginPath(),r._shapeStarted=!1},vertex(t,n){r._shapeStarted?e.lineTo(t,n):(e.moveTo(t,n),r._shapeStarted=!0)},endShape(t=!1){t&&e.closePath(),r._paint()},loadPixels(){r.pixels=e.getImageData(0,0,t.width,t.height).data},updatePixels(){const n=e.getImageData(0,0,t.width,t.height);n.data.set(r.pixels),e.putImageData(n,0,0)},_paint(){"transparent"!==r._fillStyle&&(e.fillStyle=r._fillStyle,e.fill()),"transparent"!==r._strokeStyle&&(e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke())}};return r}function Xn(t,e){return zn(g(t,e,!0))}function Gn(t,e){return new Promise((r,n)=>{const i=globalThis.Image;if(!i)return void n(new Error("Standalone image brush loading requires Image support."));const a=new i;a.onload=()=>{const t=zn(g(a.naturalWidth,a.naturalHeight,!0));t.drawingContext.drawImage(a,0,0),e(t),r(t)},a.onerror=()=>n(new Error(`Failed to load image tip: ${t}`)),a.crossOrigin="anonymous",a.src=t})}var Zn;S.wash={color:null,opacity:150,isActive:!1},jt.prototype.wash=function(t=!1,e){const a={...S.wash};!1!==t&&Pn(t,e),S.wash.isActive&&function(t){if(!S.wash?.isActive||!S.wash.color||t.vertices.length<3)return;C(),function(){const t=i.drawingContext;wn&&!(En!==r||An!==n)||(En=r,An=n,wn=new Float32Array([2/En,0,0,0,0,-2/An,0,0,0,0,1,0,-1,1,0,1])),bn===t&&vn&&_n&&Rn||(bn=t,vn=oe(bn,"#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}","#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}"),Sn.a_position=bn.getAttribLocation(vn,"a_position"),Tn.u_matrix=bn.getUniformLocation(vn,"u_matrix"),Tn.u_color=bn.getUniformLocation(vn,"u_color"),_n=bn.createVertexArray(),bn.bindVertexArray(_n),Rn=bn.createBuffer(),bn.bindBuffer(bn.ARRAY_BUFFER,Rn),bn.bufferData(bn.ARRAY_BUFFER,0,bn.DYNAMIC_DRAW),Mn=0,bn.enableVertexAttribArray(Sn.a_position),bn.vertexAttribPointer(Sn.a_position,2,bn.FLOAT,!1,8,0),bn.bindVertexArray(null),bn.bindBuffer(bn.ARRAY_BUFFER,null))}();const{triangles:e,vertexCount:a}=function(t){const e=new Float32Array(2*t.vertices.length);for(let r=0;r<t.vertices.length;r++){const n=t.vertices[r];e[2*r]=n.x,e[2*r+1]=n.y}const r=function(t,e,r=2){const n=t.length;let i=function(t,e,r,n){let i;if(1==function(t,e,r,n){let i=0;for(let e=0,a=r-n;e<r;e+=n)i+=(t[a]-t[e])*(t[e+1]+t[a+1]),a=e;return i}(t,0,r,n)>0)for(let e=0;e<r;e+=n)i=gn(e/n|0,t[e],t[e+1],i);else for(let e=r-n;e>=0;e-=n)i=gn(e/n|0,t[e],t[e+1],i);return i&&un(i,i.next)&&(pn(i),i=i.next),i}(t,0,n,r);const a=[];if(!i||i.next===i.prev)return a;let o,s,c;if(t.length>80*r){o=t[0],s=t[1];let e=o,i=s;for(let a=r;a<n;a+=r){const r=t[a],n=t[a+1];r<o&&(o=r),n<s&&(s=n),r>e&&(e=r),n>i&&(i=n)}c=Math.max(e-o,i-s),c=0!==c?32767/c:0}return tn(i,a,r,o,s,c,0),a}(e),n=new Float32Array(2*r.length);for(let t=0;t<r.length;t++){const i=r[t],[a,o]=Cn(e[2*i],e[2*i+1]);n[2*t]=a,n[2*t+1]=o}return{triangles:n,vertexCount:r.length}}(t),o=e.byteLength;bn.useProgram(vn),bn.enable(bn.BLEND),bn.blendEquation(bn.FUNC_ADD),bn.blendFunc(bn.ONE,bn.ONE_MINUS_SRC_ALPHA),bn.bindVertexArray(_n),bn.bindBuffer(bn.ARRAY_BUFFER,Rn),o>Mn?(bn.bufferData(bn.ARRAY_BUFFER,e,bn.DYNAMIC_DRAW),Mn=o):bn.bufferSubData(bn.ARRAY_BUFFER,0,e);const s=S.wash.color._array;bn.uniformMatrix4fv(Tn.u_matrix,!1,wn),bn.uniform4f(Tn.u_color,s[0],s[1],s[2],S.wash.opacity/255),bn.drawArrays(bn.TRIANGLES,0,a),bn.bindVertexArray(null),bn.bindBuffer(bn.ARRAY_BUFFER,null),ce(i,bn)}(this),S.wash={...a}},Kt.prototype.wash=function(t,e,r){S.wash?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,0,-1),this.pol.wash())},Zn={load:function(t=Zt){if(!function(t){return function(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement}(t)||function(t){return"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas}(t)}(t))throw new Error("Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.");qt(t,t.width,t.height,1)},syncDensity:function(){return h({Cwidth:Ht,Cheight:Wt,Density:$t}),$t},isCanvasReady:function(){if(!Vt)throw new Error("No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.")},instance:function(){},activateInstance:function(){},deactivateInstance:function(){},getActiveFramebuffer:function(){return null},isFramebufferTarget:function(){return!0===arguments[0]?.__brushFramebuffer}},u={...u,...Zn},Ot(),function(){var t;t={beginDirectMaskDraw:Fn,endDirectMaskDraw:kn,resetDirectShaderTracking:In},se={...se,...t}}(),function(){var t;t={clearTarget:Dn,ensureBlendShaderProgram:Ln,ensureBlendSourceFramebuffer:Bn,createFramebuffer:Nn,runBlendShaderPass:Un,blitSourceToFramebuffer:On},p={...p,...t}}(),function(){var t;t={createTipSurface:Xn,loadImageTip:Gn},ie={...ie,...t}}(),t.Color=Ut,t.DEGREES=Ft,t.Plot=Kt,t.Polygon=jt,t.Position=xt,t.RADIANS=kt,t.add=ir,t.addField=Mt,t.angleMode=function(t){if(t!==Ft&&t!==kt)throw new Error(`Invalid angle mode "${t}". Use "degrees" or "radians".`);Dt=t},t.arc=Jt,t.beginShape=te,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Gt=[e,r],Xt=new Kt(t)},t.box=function(){return[...tr.keys()]},t.circle=function(t,e,r,n=!1){const i=new Kt("curve"),a=Math.PI*r,o=$(0,360),s=n?()=>1+.2*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*q(-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 c=t-r*ot(o),l=e-r*at(-o);i.show(c,l,1)},t.clear=function(...t){f(),P.glMask&&P.clearMask(P.glMask),P.mask&&P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null;const e=i.drawingContext,r=0===t.length?[1,1,1,0]:[...c(...t)._array.slice(0,3),1];e.bindFramebuffer(e.FRAMEBUFFER,null),e.disable(e.SCISSOR_TEST),e.clearColor(r[0],r[1],r[2],r[3]),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)},t.clip=function(t){return f(),t},t.createCanvas=function(t,e,r={}){if("undefined"==typeof document)throw new Error("brush.createCanvas() requires a browser document.");const n=Math.max(1,Math.round(t)),i=Math.max(1,Math.round(e)),a=Math.max(1,Number(r.pixelDensity)||1),o=document.createElement("canvas");if(o.width=Math.max(1,Math.round(n*a)),o.height=Math.max(1,Math.round(i*a)),o.style.width=`${n}px`,o.style.height=`${i}px`,r.id&&(o.id=r.id),r.parent){const t="string"==typeof r.parent?document.querySelector(r.parent):r.parent;if(!t)throw new Error(`Could not find parent "${r.parent}" for brush.createCanvas().`);t.appendChild(o)}return qt(o,n,i,a),o},t.endShape=re,t.endStroke=function(t,e){if(!Xt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Xt.endPlot(t,e),Xt.draw(Gt[0],Gt[1],1),Xt=!1},t.field=At,t.fill=Vr,t.fillBleed=$r,t.fillTexture=Hr,t.flowLine=function(t,e,r,n){if(!S.stroke.isActive||!S.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");dt(),xr(t,e,r),pr(st(n),!1)},t.getAngleMode=function(){return Dt},t.hatch=Cr,t.hatchArray=Ir,t.hatchStyle=function(t,e="black",r=1){S.hatch.hBrush={brush:t,color:e,weight:r}},t.initStandaloneRuntime=Ot,t.instance=t=>u.instance(t),t.line=Er,t.listFields=function(){return dt(),Array.from(_t.keys())},t.load=(t=!1)=>{((t=!1)=>{u.load(t)})(t),i.loaded&&P.load()},t.mass=function(t,e,r={}){S.mass.brush=t,S.mass.color=e,S.mass.options=r,S.mass.isActive=!0},t.move=function(t,e,r){if(!Xt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Xt.addSegment(t,e,r)},t.noClip=function(){},t.noField=function(){dt(),S.field.isActive=!1},t.noFill=function(){S.fill.isActive=!1},t.noHatch=function(){S.hatch.isActive=!1,S.hatch.hBrush=!1},t.noMass=function(){S.mass.isActive=!1,S.mass.brush=null,S.mass.color=null,S.mass.options={}},t.noStroke=function(){S.stroke.isActive=!1},t.noWash=function(){S.wash.isActive=!1},t.noiseSeed=t=>{G=N(B(t)),Z=N(B(`${t}:2`))},t.pick=or,t.polygon=function(t){new jt(t).show()},t.pop=function(){0!==Lt.length&&(Nt=Lt.pop(),function(){const t=Pt.pop();t&&(S.stroke={...t.stroke},S.field={...t.field},S.hatch={...t.hatch},S.fill={...t.fill},t.wash&&(S.wash={...t.wash}),t.mass?S.mass={...t.mass}:S.mass&&(S.mass={...S.mass,isActive:!1,brush:null,color:null,options:{}}))}())},t.push=function(){dt(),Pt.push({fill:{...S.fill},wash:S.wash?{...S.wash}:null,stroke:{...S.stroke},hatch:{...S.hatch},mass:S.mass?{...S.mass}:null,field:{...S.field}}),Lt.push({...Nt})},t.rect=function(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),te(0),ee(t,e),ee(t+r,e),ee(t+r,e+n),ee(t,e+n),re(!0)},t.refreshField=function(t=0){if(!S.field.isActive||!S.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=_t.get(S.field.current);e.field=Et(e,t)},t.render=function(){C()},t.rotate=function(t){const e=Dt===kt?t:t*Math.PI/180,r=Math.cos(e),n=Math.sin(e);Nt=Bt(Nt,{a:r,b:n,c:-n,d:r,x:0,y:0})},t.scale=function(t,e=t){Nt=Bt(Nt,{a:t,b:0,c:0,d:e,x:0,y:0})},t.scaleBrushes=function(t){for(const{param:e}of tr.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.seed=t=>{O=B(t),Y=B(`${t}:2`);for(const t of z)t()},t.set=lr,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].");ne(t,e).draw()},t.stroke=sr,t.strokeWeight=cr,t.translate=function(t,e){Nt=Bt(Nt,{a:1,b:0,c:0,d:1,x:t,y:e})},t.vertex=ee,t.wRand=K,t.wash=Pn,t.wiggle=St},"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){const e={a:1,b:0,c:0,d:1,x:0,y:0};let r,n,i,a,o=()=>!1,s=t=>t,c=()=>{throw new Error("No runtime color adapter registered.")},l=()=>e,u={load:()=>{throw new Error("No target runtime adapter registered.")},syncDensity:()=>a,isCanvasReady:()=>{throw new Error("No target runtime adapter registered.")},instance:t=>{},activateInstance:t=>{},deactivateInstance:()=>{},getActiveFramebuffer:()=>null,isFramebufferTarget:()=>!1};function h(t){"Cwidth"in t&&(r=t.Cwidth),"Cheight"in t&&(n=t.Cheight),"Instance"in t&&t.Instance,"Renderer"in t&&(i=t.Renderer),"Density"in t&&(a=t.Density)}const f=()=>u.isCanvasReady(),d=()=>u.getActiveFramebuffer(),m=t=>u.isFramebufferTarget(t),x=(t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null,g=(t,e,r=!1)=>{const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,e):(()=>{const r=document.createElement("canvas");return r.width=t,r.height=e,r})();return n.drawingContext=n.getContext("2d",r?{willReadFrequently:!0}:void 0),n};let p={clearTarget:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendShaderProgram:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendSourceFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},createFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},runBlendShaderPass:()=>{throw new Error("No compositor runtime adapter registered.")},blitSourceToFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")}};const y=(...t)=>p.createFramebuffer(...t);let b=null,v=null;const _=t=>{((...t)=>{p.clearTarget(...t)})(i,t,m)},R=()=>({width:Math.max(1,Math.round(r*a)),height:Math.max(1,Math.round(n*a))}),w=t=>{if(!t)return null;const{width:e,height:r}=R();return((t,e,r)=>{if(!t)return null;const 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}})(t,e,r)},E=()=>{const{width:t,height:e}=R();return((t,e)=>({minX:0,minY:0,maxX:t,maxY:e}))(t,e)},A=(t,e=!0)=>{const r=w(t);if(!r)return null;const{height:n}=R();return{x:r.minX,y:e?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},M=(t,e,r,n=!0)=>{const i=A(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()},S={},T=()=>{i?.loaded||(f(),P.load())},P={isBlending:!1,cachedColor:null,markDirtyRect(t,e){const r=w(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){if(!t)return;const e=t===this.glMask?b:v;e?.clearMask?.(t,_)},getCompositeRect(t,e){const r=e?b:v;return r?.getCompositeRect?.(t,d,E,x,w)},load(){u.syncDensity();const t=!i.blendSourceFramebuffer||i.blendSourceFramebuffer.width!==r||i.blendSourceFramebuffer.height!==n||"function"==typeof i.blendSourceFramebuffer.pixelDensity&&i.blendSourceFramebuffer.pixelDensity()!==a;((...t)=>{p.ensureBlendShaderProgram(...t)})(i,"#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.);}"),this.glMask=b?.ensureResources?.(i,r,n,a);const e=v?.ensureResources?.(i,r,n,a,_)??{mask:null,ctx:null};t&&(i.blendSourceFramebuffer=((...t)=>p.ensureBlendSourceFramebuffer(...t))(i,i.blendSourceFramebuffer,r,n,a)),this.mask=e.mask,this.ctx=e.ctx},blend(t=!1,e=!1){T();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,this.clearMask(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,this.cachedColor=null))},applyShader(t,e){if(!t?.isDrawn)return;const a=this.getCompositeRect(t,e);if(!a)return void this.clearMask(t);i.drawingContext;const o=i.shaderProgram,s=d(),c=((...t)=>p.blitSourceToFramebuffer(...t))({renderer:i,sourceTarget:s??i,sourceFramebuffer:i.blendSourceFramebuffer,dirtyRect:a,isFramebufferTarget:m,Cwidth:r,Cheight:n,getTargetPixelSize:R,toScissorBox:A,withScissor:M}),l=!!s,u=(e?b:v).getShaderMask(i,t,a,w,E,_);((...t)=>{p.runBlendShaderPass(...t)})({renderer:i,shader:o,source:c,mask:u,color:this.cachedColor,isBrushMask:e,Cwidth:r,Cheight:n,dirtyRect:a,targetIsFramebuffer:l,withScissor:M}),this.clearMask(t)}},C=()=>{T(),P.blend(!1,!0),P.clearMask(P.glMask),P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null},F=Math.sqrt(3),k=.5*(F-1),I=(3-F)/6,D=t=>0|Math.floor(t),L=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 N(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=>L[t%12*2]),n=new Float64Array(e).map(t=>L[t%12*2+1]);return function(t,i){let a=0,o=0,s=0;const c=(t+i)*k,l=D(t+c),u=D(i+c),h=(l+u)*I,f=t-(l-h),d=i-(u-h);let m,x;f>d?(m=1,x=0):(m=0,x=1);const g=f-m+I,p=d-x+I,y=f-1+2*I,b=d-1+2*I,v=255&l,_=255&u;let R=.5-f*f-d*d;if(R>=0){const t=v+e[_];R*=R,a=R*R*(r[t]*f+n[t]*d)}let w=.5-g*g-p*p;if(w>=0){const t=v+m+e[_+x];w*=w,o=w*w*(r[t]*g+n[t]*p)}let E=.5-y*y-b*b;if(E>=0){const t=v+1+e[_+1];E*=E,s=E*E*(r[t]*y+n[t]*b)}return 70*(a+o+s)}}function B(t,e){let r=new U(t),n=()=>r.next();return n.double=()=>n()+11102230246251565e-32*(2097152*n()|0),n.int32=()=>4294967296*r.next()|0,n.quick=n,n}class U{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 O=B(Math.random()),Y=B(Math.random());const z=[],X=t=>z.push(t);let G=N(B(Math.random())),Z=N(B(Math.random()));const V=(t=0,e=1)=>t+O()*(e-t),$=(t=0,e=1)=>t+Y()*(e-t),H=t=>t[~~(O()*t.length)],W=(t,e)=>~~V(t,e),q=(t,e)=>~~$(t,e),j=(t=0,e=1)=>{const r=1-O(),n=O();return Math.sqrt(-2*Math.log(r))*at(360*n)*e+t},K=t=>{let e=0;const r=[];for(const n in t)e+=t[n],r.push({key:n,cumulative:e});const n=O()*e;for(const{key:t,cumulative:e}of r)if(n<e)return isNaN(t)?t:parseInt(t)},J=(t,e,r,n,i,a=!1)=>{let o=n+(t-e)/(r-e)*(i-n);return a?n<i?Q(o,n,i):Q(o,i,n):o},Q=(t,e,r)=>Math.max(Math.min(t,r),e),tt=t=>(t%=360)<0?t+360:t,et=1440,rt=2*Math.PI/et,nt=new Float32Array(et).fill(NaN),it=new Float32Array(et).fill(NaN),at=t=>{const e=~~(4*tt(t));let r=nt[e];return isNaN(r)&&(r=Math.cos(e*rt),nt[e]=r),r},ot=t=>{const e=~~(4*tt(t));let r=it[e];return isNaN(r)&&(r=Math.sin(e*rt),it[e]=r),r},st=(t,e=!1)=>{if(e||o()){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},ct=(t,e=!1)=>e||o()?180*t/Math.PI:t,lt=(t,e,r,n,i)=>{let a=at(i),o=ot(i);return{x:a*(r-t)+o*(n-e)+t,y:a*(n-e)-o*(r-t)+e}},ut=(t,e,r,n)=>Math.hypot(r-t,n-e),ht=(t,e,r,n)=>st(Math.atan2(-(n-e),r-t),!0),ft=(t,e,r,n,i=!1)=>{let a=t.x,o=t.y,s=e.x,c=e.y,l=r.x,u=r.y,h=n.x,f=n.y;if(a===s&&o===c||l===h&&u===f)return!1;let d=s-a,m=c-o,x=h-l,g=f-u,p=g*d-x*m;if(0===p)return!1;let y=(x*(o-u)-g*(a-l))/p,b=(d*(o-u)-m*(a-l))/p;return!(!i&&(b<0||b>1))&&{x:a+y*d,y:o+y*m}};let dt=!1;function mt(){dt||(T(),gt=.01*r,pt=-.5*r,yt=-.5*n,bt=Math.round(2*r/gt),vt=Math.round(2*n/gt),Mt("hand",(t,e)=>{const r=$(.2,.8),n=q(5,10);return Tt(e,(e,i)=>.5*n*ot(r*i*e+q(15,25))*.2*at(t)+Z(e,i)*n*.7)}),Mt("curved",(t,e)=>{let r=q(-10,10);return q(0,100)%2==0&&(r*=-1),Tt(e,(e,n)=>3*J(Z(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),Mt("zigzag",(t,e)=>{let r=q(-30,-15)+Math.abs(44*ot(t));q(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t<bt;t++){for(let r=0;r<vt;r++)e[t][r]=i,i+=n,n*=-1;i+=n,n*=-1}return e}),Mt("waves",(t,e)=>{const r=q(10,15)+5*ot(t),n=q(3,6)+3*at(t),i=q(20,35);return Tt(e,(t,e)=>ot(r*t)*i*at(e*n)+q(-3,3))}),Mt("seabed",(t,e)=>{const r=$(.4,.8),n=q(18,26);return Tt(e,(e,i)=>1.1*n*ot(r*i*e+q(15,20))*at(t))}),Mt("spiral",(t,e)=>{const r=q(5,10),n=2*q(0,2)-1,i=q(65,80),a=Array.from({length:r},()=>({x:$(.1,.9)*bt,y:$(.1,.9)*vt}));return Tt(e,(t,e)=>{let r=0,o=0;for(const s of a){const a=t-s.x,c=e-s.y,l=1/(a*a+c*c+1),u=Math.atan2(c,a)*(180/Math.PI),h=n*(u+i)*Math.PI/180;r+=l*Math.cos(h),o+=l*Math.sin(h)}return Math.atan2(o,r)*(180/Math.PI)})}),Mt("columns",(t,e)=>{const r=q(3,8),n=q(25,45);return Tt(e,(t,e)=>ot(t*r)*n)}),dt=!0)}class xt{constructor(t,e){mt();const r=l();this.mx=r.x,this.my=r.y,this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,this.colIdx=Math.round((t+this.mx-pt)/gt),this.rowIdx=Math.round((e+this.my-yt)/gt)}reset(){this.plotted=0}isIn(){return S.field.isActive?xt.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=r,e=n,i=this.x+this.mx,a=this.y+this.my;return i>=-.3*t&&i<=1.3*t&&a>=-.3*e&&a<=1.3*e}angle(t=!1){return S.field.isActive&&(t||this.isIn())?_t.get(S.field.current).field[this.colIdx][this.rowIdx]*S.field.wiggle:0}moveTo(t,e,r=1){this.movePos(ct(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())return void(this.plotted+=r/i);const a=e/r,o=S.field.isActive,s=!!n;for(let e=0;e<a;e++){const e=(o?this.angle(!0):0)-(s?t.angle(this.plotted):t);this.update(this.x+r*at(e),this.y+r*ot(e)),this.plotted+=r/i}}static getRowIndex(t,e=1){const r=t+l().y-yt;return Math.round(r/gt/e)}static getColIndex(t,e=1){const r=t+l().x-pt;return Math.round(r/gt/e)}static isIn(t,e){return t>=0&&e>=0&&t<bt&&e<vt}}S.field={isActive:!1,current:null,wiggle:1};let gt,pt,yt,bt,vt,_t=new Map;const Rt=new Set(["degrees","radians"]);function wt(t={}){const e=("string"==typeof t?{angleMode:t}:t||{}).angleMode??"degrees";if(!Rt.has(e))throw new Error(`Invalid field angle mode "${e}". Use "degrees" or "radians".`);return e}function Et(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]=ct(t[e][r],!0);return t}(t.gen(e,new Array(bt).fill(null).map(()=>new Float32Array(vt))),t.angleMode)}function At(t){if(S.field.wiggle||(S.field.wiggle=1),mt(),!_t.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(_t.keys()).join(", ")}.`);S.field.isActive=!0,S.field.current=t;const e=_t.get(t);e.field||(e.field=Et(e,0))}function Mt(t,e,r={}){_t.set(t,{gen:e,field:null,angleMode:wt(r)})}function St(t=1){At("hand"),S.field.wiggle=t}function Tt(t,e){for(let r=0;r<bt;r++)for(let n=0;n<vt;n++)t[r][n]=e(r,n);return t}const Pt=[],Ct=(t,e,r)=>Math.max(e,Math.min(t,r)),Ft="degrees",kt="radians";let It=null,Dt=Ft;const Lt=[];let Nt={a:1,b:0,c:0,d:1,x:0,y:0};function Bt(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,x:t.a*e.x+t.c*e.y+t.x,y:t.b*e.x+t.d*e.y+t.y}}class Ut{constructor(t,e,r){if(t?._array)return this.r=Math.round(255*t._array[0]),this.g=Math.round(255*t._array[1]),this.b=Math.round(255*t._array[2]),this.hex=this.rgbToHex(this.r,this.g,this.b),this._array=[...t._array],void(this.gl=this._array);if("string"==typeof t){const e=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)$/i.exec(t);if(e){this.r=Ct(parseInt(e[1]),0,255),this.g=Ct(parseInt(e[2]),0,255),this.b=Ct(parseInt(e[3]),0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);const t=void 0!==e[4]?Ct(parseFloat(e[4]),0,1):1;return this._array=[this.r/255,this.g/255,this.b/255,t],void(this.gl=this._array)}this.hex=this.standardize(t);const r=this.hexToRgb(this.hex);this.r=r.r,this.g=r.g,this.b=r.b}else this.r=Ct(t??0,0,255),this.g=Ct(e??t??0,0,255),this.b=Ct(r??t??0,0,255),this.hex=this.rgbToHex(this.r,this.g,this.b);this._array=[this.r/255,this.g/255,this.b/255,1],this.gl=this._array}rgbToHex(t,e,r){return`#${(1<<24|t<<16|e<<8|r).toString(16).slice(1)}`}hexToRgb(t){t=t.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(t,e,r,n)=>e+e+r+r+n+n);const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(!e)throw new Error(`Invalid color value "${t}".`);return{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}}standardize(t){const e=function(){if(It)return It;if("undefined"!=typeof document)return It=document.createElement("canvas").getContext("2d"),It;if("undefined"!=typeof OffscreenCanvas)return It=new OffscreenCanvas(1,1).getContext("2d"),It;throw new Error("Standalone color parsing requires CanvasRenderingContext2D support.")}();return e.fillStyle=t,e.fillStyle}_getRed(){return this.r}_getGreen(){return this.g}_getBlue(){return this.b}}function Ot(){var t;(t={usesRadians:()=>"radians"===Dt,fromDegrees:t=>"radians"===Dt?t*Math.PI/180:t,createColor:(...t)=>1===t.length&&t[0]?._array?t[0]:new Ut(...t),getAffineMatrix:()=>Nt}).usesRadians&&(o=t.usesRadians),t.fromDegrees&&(s=t.fromDegrees),t.createColor&&(c=t.createColor),t.getAffineMatrix&&(l=t.getAffineMatrix)}let Yt,zt,Xt,Gt,Zt=null,Vt=!1,$t=1,Ht=0,Wt=0;function qt(t,e,r,n){Zt=t,Ht=e,Wt=r,$t=n;const i=function(t,e,r,n){const i=function(t){return t.getContext("webgl2",{premultipliedAlpha:!0})??t.getContext("webgl2")}(t);if(!i)throw new Error("brush.load(target) requires a canvas with a WebGL2 context.");return{canvas:t,drawingContext:i,width:e,height:r,pixelDensity:()=>n}}(t,e,r,n);h({Renderer:i,Cwidth:e,Cheight:r,Density:n}),Vt=!0}class jt{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=ft(t.point1,t.point2,e,n);i&&r.push(i)}return this._intersectionCache[e]=r,r}show(){S.wash&&this.wash(),S.fill&&this.fill(),S.mass&&this.mass(),S.hatch&&this.hatch(),S.stroke&&this.draw()}}class Kt{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:st(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:st(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=st(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)),J(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,e,i=1,a){mt();const o=a<0?4:1,s=[],c=Math.round(this.length/o),l=new xt(t+r/2,e+n/2);let u=0,h=0;for(let t=0;t<c;t++){l.plotTo(this,o,o);const t=this.calcIndex(l.plotted);u+=o,(u>=(a<=0?8:Math.max(this.segments[t]*a*$(.7,1.3),20))||t>=h)&&l.x&&(s.push([l.x-r/2,l.y-n/2]),u=0,t>=h&&h++)}return new jt(s)}show(t,e,r=1){S.wash&&this.wash(t,e,r),S.fill&&this.fill(t,e,r),S.mass&&this.mass(t,e,r),S.hatch&&this.hatch(t,e,r),S.stroke&&this.draw(t,e,r)}}function Jt(t,e,r,n,i){const a=ct(n),o=((ct(i)-a)%360+360)%360;if(0===o)return;const s=new Kt("curve"),c=Math.max(1,Math.ceil(o/90)),l=o/c,u=Math.PI*r*l/180;for(let t=0;t<c;t++)s.addSegment(a+t*l+90,u,1,!0);s.endPlot(a+o+90,1,!0);const h=t+r*at(a),f=e-r*ot(a);s.draw(h,f,1)}class Qt{constructor(){this.isClosed=!1,this.curvature=zt,this.vert=[]}vertex(t,e,r){this.vert.push([t,e,r])}show(){ne(this.vert,this.curvature,this.isClosed).show()}}function te(t=0){zt=Q(t,0,1),Yt=new Qt}function ee(t,e,r=1){if(!Yt)throw new Error("vertex() called outside of beginShape()/endShape(). Call beginShape() first.");Yt.vertex(t,e,r)}function re(t=!1){if(!Yt)throw new Error("endShape() called without beginShape(). Call beginShape() first.");if(Yt.vert.length<2)throw new Error("endShape() requires at least 2 vertices. Add more with vertex().");t&&(Yt.vertex(...Yt.vert[0]),Yt.isClosed=!0),Yt.show(),Yt=!1}function ne(t,e=.5,r=!1){const n=new Kt(0===e?"segments":"curve"),i=2*Math.PI;if(r&&0!==e&&t.push(t[1]),t&&t.length>0){let a,o,s,c=0;for(let l=0;l<t.length-1;l++)if(e>0&&l<t.length-2){const u=t[l],h=t[l+1],f=t[l+2],d=ut(u[0],u[1],h[0],h[1]),m=ut(h[0],h[1],f[0],f[1]),x=ht(u[0],u[1],h[0],h[1]),g=ht(h[0],h[1],f[0],f[1]),p=e*Math.min(d,m,.5*Math.min(d,m)),y=Math.max(d,m),b=d-p,v=m-p;if(Math.floor(x)===Math.floor(g)){const e=r&&0===l?0:d-c,i=r?0===l?0:m-s:m;n.addSegment(x,e,u[2],!0),l===t.length-3&&n.addSegment(g,i,h[2],!0),c=0,0===l&&(a=d,s=p,o=t[1],c=0)}else{const e={x:h[0]-p*at(-x),y:h[1]-p*ot(-x)},f={x:e.x+y*at(90-x),y:e.y+y*ot(90-x)},d={x:h[0]+p*at(-g),y:h[1]+p*ot(-g)},m={x:d.x+y*at(90-g),y:d.y+y*ot(90-g)},_=ft(e,f,d,m,!0),R=ut(e.x,e.y,_.x,_.y),w=ut(e.x,e.y,d.x,d.y)/2,E=i*R*(2*Math.asin(w/R)*(180/Math.PI))/360,A=r&&0===l?0:b-c,M=l===t.length-3?r?a-p:v:0;n.addSegment(x,A,u[2],!0),n.addSegment(x,isNaN(E)?0:E,u[2],!0),n.addSegment(g,M,h[2],!0),c=p,0===l&&(a=b,s=p,o=[e.x,e.y])}l===t.length-3&&n.endPlot(g,h[2],!0)}else if(0===e){const e=t[l],r=t[l+1],i=ut(e[0],e[1],r[0],r[1]),a=ht(e[0],e[1],r[0],r[1]);n.addSegment(a,i,r[2],!0),l===t.length-2&&n.endPlot(a,1,!0)}n.origin=r&&0!==e?o:t[0]}return n}let ie={createTipSurface:()=>{throw new Error("No stroke runtime adapter registered.")},loadImageTip:()=>{throw new Error("No stroke runtime adapter registered.")}},ae=!1;const oe=(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 se={beginDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},endDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},resetDirectShaderTracking:()=>{}};const ce=(t,e)=>se.resetDirectShaderTracking(t,e);let le,ue,he,fe,de,me=!1,xe=0,ge=0,pe=null;const ye={},be={};let ve=1,_e=0,Re=0,we=1,Ee=0,Ae=0,Me=0,Se=0,Te=1,Pe=1,Ce=new Float32Array(8192),Fe=0,ke=2048,Ie=32768,De=null,Le=null,Ne=null,Be=null,Ue=null;const Oe={},Ye={};let ze=0,Xe=new Float32Array(1280),Ge=0,Ze=256,Ve=null;const $e=new Map,He=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function We(){return ue}function qe(){return((t,e,r)=>se.beginDirectMaskDraw(t,e,r))(i,le,P.glMask)}function je(t){((t,e,r)=>{se.endDirectMaskDraw(t,e,r)})(i,le,t)}function Ke(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 Je(t,e,r,n){if(Fe>=ke){ke*=2;const t=new Float32Array(4*ke);t.set(Ce),Ce=t}const i=t-Me,a=e-Se,o=4*Fe,s=ve*i+Re*a+Ee+Me,c=_e*i+we*a+Ae+Se,l=Pe*r*Te/2;Ce[o]=s,Ce[o+1]=c,Ce[o+2]=l,Ce[o+3]=n/255;const u=s*Pe,h=c*Pe;De=Ke(De,u-l-1,h-l-1,u+l+1,h+l+1),Fe++}function Qe(t,e){if(0===Ge)return;P.glMask.isDrawn=!0;const r=qe();let n=$e.get(e);n||(n=le.createTexture(),le.bindTexture(le.TEXTURE_2D,n),le.texImage2D(le.TEXTURE_2D,0,le.RGBA,le.RGBA,le.UNSIGNED_BYTE,t.canvas),le.texParameteri(le.TEXTURE_2D,le.TEXTURE_MIN_FILTER,le.LINEAR),le.texParameteri(le.TEXTURE_2D,le.TEXTURE_MAG_FILTER,le.LINEAR),le.texParameteri(le.TEXTURE_2D,le.TEXTURE_WRAP_S,le.CLAMP_TO_EDGE),le.texParameteri(le.TEXTURE_2D,le.TEXTURE_WRAP_T,le.CLAMP_TO_EDGE),$e.set(e,n)),le.useProgram(Le),le.enable(le.BLEND),le.blendFunc(le.ONE_MINUS_DST_ALPHA,le.ONE),le.activeTexture(le.TEXTURE0),le.bindTexture(le.TEXTURE_2D,n),le.uniform1i(Ye.u_tex,0);const a=S.stroke.color._array;le.uniform4f(Ye.u_color,...a),le.uniformMatrix4fv(Ye.u_proj,!1,We()),le.bindVertexArray(Ne),le.bindBuffer(le.ARRAY_BUFFER,Ue);const o=5*Ge*4,s=Xe.subarray(0,5*Ge);o>ze?(le.bufferData(le.ARRAY_BUFFER,Xe,le.DYNAMIC_DRAW),ze=Xe.byteLength):le.bufferSubData(le.ARRAY_BUFFER,0,s),le.drawArraysInstanced(le.TRIANGLE_STRIP,0,4,Ge),le.flush(),le.bindVertexArray(null),le.bindTexture(le.TEXTURE_2D,null),je(r),Ve&&(P.markDirtyRect(P.glMask,Ve),Ve=null),Ge=0,ce(i,le)}ae||(b={ensureResources:function(t,e,r,n){return function(t,e,r,n){return!t.glMask||t.glMask.width!==e||t.glMask.height!==r||"function"==typeof t.glMask.pixelDensity&&t.glMask.pixelDensity()!==n}(t,e,r,n)&&(t.glMask?.remove&&t.glMask.remove(),t.glMask=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1})),t.glMask.dirtyRect??=null,t.glMask.isDrawn??=!1,t.glMask},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?e()?r():i(n(t.dirtyRect,2)):r():null},getShaderMask:function(t,e){return e}},ae=!0),S.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let tr=new Map;const er={offset:.08,scale:.08,warp:.06,tilt:.06};function rr(){return{...S.stroke}}function nr(t){S.stroke={...t}}function ir(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0===e.markerTip&&(e.markerTip=!0),void 0===e.noise&&(e.noise=.3),e.noise=Math.max(0,Math.min(1,e.noise)),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:{...er}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...er,...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,c,l]=[(e-i)/o,(r-i)/o,(n-i)/o];return{type:"custom",min_max:[i,a],variation:{...er},curve:t=>t<.5?s+(c-s)*t*2:c+(l-c)*(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&&le&&le.deleteTexture(e),$e.delete(t)}(r);const n=ie.createTipSurface(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 tr.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),tr.set(t,{param:e,colors:[],buffers:[]}),Sr.load()}tr.set(t,{param:e,colors:[],buffers:[]})}function ar(t){return tr.get(t)?.param??null}function or(t){if(!tr.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...tr.keys()].join(", ")}.`);S.stroke.type=t}function sr(t,e,r){f(),S.stroke.color=c(...arguments),S.stroke.isActive=!0}function cr(t){S.stroke.weight=t}function lr(t,e,r=1){or(t),sr(e),cr(r)}let ur,hr,fr,dr;const mr={};function xr(t,e,i,o=!1){!function(){const t=l();ve=t.a,_e=t.b,Re=t.c,we=t.d,Ee=t.x,Ae=t.y,Me=r/2,Se=n/2,Te=Math.sqrt(ve*ve+_e*_e),Pe=a}(),ur=new xt(t+r/2,e+n/2),hr=i,fr=o,fr&&fr.calcIndex(0)}const gr=[];function pr(t,e){e||(dr=t),function(){mr.seed=999999*V();const{param:t}=tr.get(S.stroke.type)??{};if(!t)return;mr.p=t;const{pressure:e}=t;if(mr.a="custom"!==e.type?V(-1,1):0,mr.b="custom"!==e.type?V(1,1.5):0,"custom"!==e.type)mr.cp=V(3,3.5),mr.ct=0,mr.cs=1,mr.ck=0;else{const t=e.variation??er;mr.cp=V(-t.offset,t.offset),mr.ct=V(-t.warp,t.warp),mr.cs=V(1-t.scale,1+t.scale),mr.ck=V(-t.tilt,t.tilt)}[mr.min,mr.max]=e.min_max,mr.noiseoffset=.05*mr.p.noise,fr||(mr.cos=at(dr),mr.sin=ot(dr)),function(){T(),function(){const t=i?.glMask;t&&(pe=t,pe.dirtyRect??=null,pe.isDrawn??=!1,P.glMask=pe)}();const t=i.drawingContext,e=!me||le!==t;(e||xe!==r||ge!==n)&&(ue=new Float32Array([2/r,0,0,0,0,2/n,0,0,0,0,1,0,-1,-1,0,1]),xe=r,ge=n),e&&(le=t,de=oe(le,"#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);}"),le.useProgram(de),le.enable(le.BLEND),le.blendFunc(le.ONE_MINUS_DST_ALPHA,le.ONE),["a_position","a_radius","a_alpha"].forEach(t=>ye[t]=le.getAttribLocation(de,t)),["u_matrix","u_color"].forEach(t=>be[t]=le.getUniformLocation(de,t)),he=le.createVertexArray(),le.bindVertexArray(he),fe=le.createBuffer(),le.bindBuffer(le.ARRAY_BUFFER,fe),le.bufferData(le.ARRAY_BUFFER,Ce.byteLength,le.DYNAMIC_DRAW),Ie=Ce.byteLength,le.enableVertexAttribArray(ye.a_position),le.vertexAttribPointer(ye.a_position,2,le.FLOAT,!1,16,0),le.enableVertexAttribArray(ye.a_radius),le.vertexAttribPointer(ye.a_radius,1,le.FLOAT,!1,16,8),le.enableVertexAttribArray(ye.a_alpha),le.vertexAttribPointer(ye.a_alpha,1,le.FLOAT,!1,16,12),le.bindVertexArray(null),$e.clear(),Le=oe(le,"#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=>Oe[t]=le.getAttribLocation(Le,t)),["u_proj","u_color","u_tex"].forEach(t=>Ye[t]=le.getUniformLocation(Le,t)),Ne=le.createVertexArray(),le.bindVertexArray(Ne),Be=le.createBuffer(),le.bindBuffer(le.ARRAY_BUFFER,Be),le.bufferData(le.ARRAY_BUFFER,He,le.STATIC_DRAW),le.enableVertexAttribArray(Oe.a_corner),le.vertexAttribPointer(Oe.a_corner,2,le.FLOAT,!1,0,0),Ue=le.createBuffer(),le.bindBuffer(le.ARRAY_BUFFER,Ue),le.bufferData(le.ARRAY_BUFFER,Xe.byteLength,le.DYNAMIC_DRAW),ze=Xe.byteLength,le.enableVertexAttribArray(Oe.a_pos),le.vertexAttribPointer(Oe.a_pos,2,le.FLOAT,!1,20,0),le.vertexAttribDivisor(Oe.a_pos,1),le.enableVertexAttribArray(Oe.a_size),le.vertexAttribPointer(Oe.a_size,1,le.FLOAT,!1,20,8),le.vertexAttribDivisor(Oe.a_size,1),le.enableVertexAttribArray(Oe.a_angle),le.vertexAttribPointer(Oe.a_angle,1,le.FLOAT,!1,20,12),le.vertexAttribDivisor(Oe.a_angle,1),le.enableVertexAttribArray(Oe.a_alpha),le.vertexAttribPointer(Oe.a_alpha,1,le.FLOAT,!1,20,16),le.vertexAttribDivisor(Oe.a_alpha,1),le.bindVertexArray(null),me=!0)}();const a=!0!==P.isBrush;P.isBrush=!0,a&&(P.justChanged=!0),P.blend(S.stroke.color),mr.alpha=["default","spray"].includes(mr.p.type)?mr.p.opacity:mr.p.opacity/Math.min(S.stroke.weight,1.3),wr()}();const a=function(){const{param:t}=tr.get(S.stroke.type)??{};return t?t.spacing:1}(),o=Math.round(hr*(e?t:1)/a);mr.pressureCount=10,mr.cachedPressure=void 0,mr.lineNoiseCount=5,mr.cachedLineNoise=void 0;for(let r=0;r<o;r++)gr.length<2*o&&gr.push(j()),yr(),e?ur.plotTo(fr,a,a,t,r<10):ur._moveToDegrees(t,a,a);!function(){wr(),function(){if(0===Fe)return;P.glMask.isDrawn=!0;const t=qe(),e=S.stroke.color._array;le.useProgram(de),le.enable(le.BLEND),le.blendFunc(le.ONE_MINUS_DST_ALPHA,le.ONE),le.bindVertexArray(he),le.bindBuffer(le.ARRAY_BUFFER,fe);const r=16*Fe,n=Ce.subarray(0,4*Fe);r>Ie?(le.bufferData(le.ARRAY_BUFFER,Ce,le.DYNAMIC_DRAW),Ie=Ce.byteLength):le.bufferSubData(le.ARRAY_BUFFER,0,n),le.uniform4f(be.u_color,...e),le.uniformMatrix4fv(be.u_matrix,!1,We()),le.drawArrays(le.POINTS,0,Fe),le.flush(),le.bindVertexArray(null),je(t),De&&(P.markDirtyRect(P.glMask,De),De=null),Fe=0,ce(i,le)}();const t=mr.p?.type;"image"===t?Qe(Sr.tips.get(mr.p.image.src),mr.p.image.src):"custom"===t&&Qe(Sr.tips.get(mr.p.tipKey),mr.p.tipKey)}()}function yr(){const t=br(),e=((mr.lineNoiseCount>=10||void 0===mr.cachedLineNoise)&&(mr.cachedLineNoise=J(G(mr.seed+.01*ur.plotted,0),-1,1,1-mr.noiseoffset,1+mr.noiseoffset),mr.lineNoiseCount=0),mr.lineNoiseCount++,mr.cachedLineNoise);if(!(e>V(1,1.02)&&V(0,1)<.7))switch(mr.p.type){case"spray":!function(t){const e=S.stroke.weight*mr.p.scatter*t+S.stroke.weight*H(gr)*mr.p.scatter/3,r=mr.p.weight*V(.9,1.1),n=Math.ceil(mr.p.grain/t);for(let t=0;t<n;t++){const t=V(.9,1.1),n=t*e*V(-1,1),i=V(-1,1),a=Math.sqrt((t*e)**2-n**2);Je(ur.x+n,ur.y+i*a,r,mr.alpha)}}(t*e);break;case"marker":_r(t*e);break;case"custom":case"image":Rr(t*e);break;default:!function(t,e=1){const r=(e=J(e,0,1,.9,1.05))*S.stroke.weight*mr.p.scatter*(mr.p.sharpness+(1-mr.p.sharpness)*H(gr)/t);if(V(0,mr.p.grain*t)>.4){let e,n;if(fr){const t=fr.angle(ur.plotted),i=at(t),a=ot(t),o=r*V(-1,1),s=.3*r*V(-1,1);e=o*a+s*i,n=o*i-s*a}else{const t=r*V(-1,1),i=.3*r*V(-1,1);e=t*mr.sin+i*mr.cos,n=t*mr.cos-i*mr.sin}const i=t*t*mr.p.weight*V(.85,1.15)*S.stroke.weight,a=Math.max(.9,t)*mr.alpha*V(.75,1.1);Je(ur.x+e,ur.y+n,i,a)}}(t*e)}}function br(){return(mr.pressureCount>=10||void 0===mr.cachedPressure)&&(mr.cachedPressure=fr?vr()*fr.pressure(ur.plotted):vr(),mr.pressureCount=0),mr.pressureCount++,mr.cachedPressure}function vr(){return"custom"===mr.p.pressure.type?J(mr.p.pressure.curve(Math.max(0,Math.min(1,.5+(ur.plotted/hr-.5+mr.ct)*mr.cs)))+mr.cp+mr.ck*(ur.plotted/hr-.5),0,1,mr.min,mr.max,!0):function(t=.5+mr.p.pressure.curve[0]*mr.a,e=1-mr.p.pressure.curve[1]*mr.b,r=mr.cp,n=mr.min,i=mr.max){const a=t*hr,o=(ur.plotted<a?1.2*e:.8*e)*(hr/2);return J(1/(1+Math.pow(Math.abs((ur.plotted-a)/o),2*r)),0,1,n,i)}()}function _r(t,e=!0,r=mr.alpha){const n=e?S.stroke.weight*mr.p.scatter:0,i=e?n*V(-1,1):0,a=e?n*V(-1,1):0;Je(ur.x+i,ur.y+a,S.stroke.weight*mr.p.weight*t,r*Math.max(.8,t)*V(.9,1.1))}function Rr(t,e=mr.alpha){const r=S.stroke.weight*mr.p.scatter,n=r*V(-1,1),i=r*V(-1,1),a=mr.p.weight*S.stroke.weight*t,o=function(){const t=Math.max(1,mr.max??1),e=S.stroke.weight*mr.p.scatter,r=S.stroke.weight*mr.p.weight*t;return Math.max(8,1.5*e+.75*r)}();let s=0;"random"===mr.p.rotate?s=W(0,360)*(Math.PI/180):"natural"===mr.p.rotate&&(s=((fr?-fr.angle(ur.plotted):-dr)+ur.angle())*(Math.PI/180)),function(t,e,r,n,i,a=0){if(Ge>=Ze){Ze*=2;const t=new Float32Array(5*Ze);t.set(Xe),Xe=t}const o=t-Me,s=e-Se,c=ve*o+Re*s+Ee+Me,l=_e*o+we*s+Ae+Se,u=Pe*r*Te/2,h=Pe*a*Te,f=5*Ge;Xe[f]=c,Xe[f+1]=l,Xe[f+2]=u,Xe[f+3]=n,Xe[f+4]=i/255;const d=c*Pe,m=l*Pe,x=1.42*u+h;Ve=Ke(Ve,d-x-1,m-x-1,d+x+1,m+x+1),Ge++}(ur.x+n,ur.y+i,a,s,e*Math.max(.8,t)*V(.9,1.1),o)}function wr(){if(!1===mr.p.markerTip)return;let t=br(),e=mr.alpha;if("marker"===mr.p.type)for(let r=1;r<10;r++)_r(t*r/10,!0,8*e);else if("custom"===mr.p.type||"image"===mr.p.type)for(let r=1;r<5;r++)Rr(t*r/10,2*e)}function Er(t,e,r,n){if(!S.stroke.isActive||!S.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");mt();let i=ut(t,e,r,n);0!=i&&(xr(t,e,i),pr(ht(t,e,r,n),!1))}X(()=>{gr.length=0});const Ar=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],Mr=[["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]}]],["pastel",[2.05/3,13.4/3,.91,28,35,.085/3,{mode:"gaussian",curve:[.4,.05],min_max:[1.09,.93]},"default",void 0,"natural",!0,1]],["crayon",[.3,5.45/3,.75,250,159,.23/3,[1.1,.9],"default",void 0,"natural",!0,1]],["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 Mr){let e={};for(let r=0;r<t[1].length;r++)e[Ar[r]]=t[1][r];ir(t[0],e)}jt.prototype.draw=function(t=!1,e,r){let n=rr();if(t&&lr(t,e,r),n.isActive)for(let t of this.sides)Er(t[0].x,t[0].y,t[1].x,t[1].y);nr(n)},Kt.prototype.draw=function(t,e,r){rr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),function(t,e,r,n){mt(),xr(e,r,t.length,t),pr(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=>((t,e)=>ie.loadImageTip(t,e))(t,Sr.imageToWhite).then(e=>{this.tips.set(t,e)})))}};function Tr(){return{...S.hatch}}function Pr(t){S.hatch={...t}}function Cr(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=S.hatch;n.isActive=!0,n.dist=t,n.angle=ct(e),n.options=r}function Fr(t,e,r,n){const i=e*Math.PI/180,a=Math.cos(i),o=Math.sin(i),s=Math.cos(-i),c=Math.sin(-i),l=t.a,u=l.length,h=new Array(u);let f=Infinity,d=-Infinity;for(let t=0;t<u;t++){const e=l[t][0],r=l[t][1],n=[e*a-r*o,e*o+r*a];h[t]=n,n[1]<f&&(f=n[1]),n[1]>d&&(d=n[1])}const m=[];for(let t=0;t<u;t++){const e=h[t],r=h[(t+1)%u];e[1]!==r[1]&&m.push(e,r)}const x=m.length,g=[];let p=f+.5*r,y=r;for(;p<d;){const t=[];for(let e=0;e<x;e+=2){const r=m[e][1],n=m[e+1][1];(r<=p&&p<n||n<=p&&p<r)&&t.push(m[e][0]+(p-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)g.push({scanY:p,x1:t[e]*s-p*c,y1:t[e]*c+p*s,x2:t[e+1]*s-p*c,y2:t[e+1]*c+p*s});p+=y,y*=n}return g}function kr(t){const{dist:e,options:r,segs:n}=function(t){const e=S.hatch.dist,r=(S.hatch.angle%180+180)%180,n=S.hatch.options,i=function(t,e,r,n){Array.isArray(t)||(t=[t]);const i=[];for(const a of t)for(const t of Fr(a,r,e,n))i.push(t);return i.sort((t,e)=>t.scanY===e.scanY?t.x1-e.x1:t.scanY-e.scanY),i}(t,e,r,n.gradient?J(n.gradient,0,1,1,1.1,!0):1);return{dist:e,options:n,segs:i}}(t),i=r.rand||0,a=[];for(let t=0;t<n.length;t++){const o=n[t];let s=o.x1,c=o.y1,l=o.x2,u=o.y2;i&&(s+=2*i*e*V(-1,1),c+=2*i*e*V(-1,1),l+=2*i*e*V(-1,1),u+=2*i*e*V(-1,1));const h=r.continuous&&t%2==1?{x1:l,y1:u,x2:s,y2:c,scanY:o.scanY,isConnector:!1}:{x1:s,y1:c,x2:l,y2:u,scanY:o.scanY,isConnector:!1};if(a.push(h),t>0&&r.continuous){const t=a[a.length-2];a.push({x1:t.x2,y1:t.y2,x2:h.x1,y2:h.y1,scanY:o.scanY,isConnector:!0})}}return a}function Ir(t){!function(t,e){const r=kr(t);!function(){const t=rr();S.hatch.hBrush&&lr(...Object.values(S.hatch.hBrush)),(()=>{for(let t=0;t<r.length;t++){const n=r[t];e(n.x1,n.y1,n.x2,n.y2,t,r)}})(),nr(t)}()}(t,(t,e,r,n)=>{Er(t,e,r,n)})}function Dr(t,e,r){return new jt(t.vertices.map(t=>[t.x+e,t.y+r]))}function Lr(t,e,r,n,i){const a=(e+n)/2,o=(r+i)/2,s=n-e,c=i-r,l=Math.hypot(s,c);if(!l)return null;const u=-c/l,h=s/l,f=(t.x-a)*u+(t.y-o)*h;return{x:a+u*f,y:o+h*f}}function Nr(t,e,r,n,i,a,o){let s=ht(t,e,r,n),c=ht(t,e,i,a);return((c-s)%360+360)%360>180&&([s,c]=[c,s]),[o(s),o(c)]}function Br(t){const e=$(.35,.65),r=t.x1+(t.x2-t.x1)*e,n=t.y1+(t.y2-t.y1)*e,i=t.x2-t.x1,a=t.y2-t.y1,o=Math.hypot(i,a)||1,s=$(.04,.1)*o,c=i/o*s*.5,l=a/o*s*.5;return[{x1:t.x1,y1:t.y1,x2:r-c,y2:n-l},{x1:r+c,y1:n+l,x2:t.x2,y2:t.y2}]}function Ur(t,e,r){const n=function(t,e){const r=function(t){const e=t?.a??[];let r=Infinity,n=Infinity,i=-Infinity,a=-Infinity;for(const[t,o]of e)t<r&&(r=t),o<n&&(n=o),t>i&&(i=t),o>a&&(a=o);return{minX:r,minY:n,maxX:i,maxY:a,cx:(r+i)/2,cy:(n+a)/2,size:Math.hypot(i-r,a-n)}}(t),n=r.size*$(.6,1.4),[i,a]=e;return{x:r.cx+i*n,y:r.cy+a*n}}(t,e);for(const e of kr(t)){const t=!e.isConnector&&$()<.35?Br(e):[e];for(const e of t){const t=Lr(n,e.x1,e.y1,e.x2,e.y2);if(!t)continue;const i=ut(t.x,t.y,e.x1,e.y1);if(!i)continue;const[a,o]=Nr(t.x,t.y,e.x1,e.y1,e.x2,e.y2,r);Jt(t.x,t.y,i,a,o)}}}function Or(t,e,r,n,i,a){Cr(e,r,n),Ur(t,i,a)}function Yr(t,e,r,n){const i=function(t,e,r,n){const i=!1===e,a=ar(S.mass.brush)?.scatter??0,o=i?t:t.genPol(e,r,n,.15),s=Math.min(2*a,5),c=[[$(-s,s),$(-s,s)],[$(-s,s),$(-s,s)]];return[o,Dr(o,c[0][0],c[0][1]),Dr(o,c[1][0],c[1][1])]}(t,e,r,n),a=Tr(),c=rr(),l={...S.field},u=S.mass.options?.precision??.5,h=S.mass.options?.strength??1,f=S.mass.options?.gradient??.1,d=S.mass.options?.outline??!1,m=ar(S.mass.brush)?.scatter??0,x=1.6*$(.65*m,.85*m)-.4*f,g=$(-90,90),p=((g+90)%180+180)%180-90>=0?$()<.5?[1,1]:[-1,-1]:$()<.5?[-1,1]:[1,-1],y=o()?t=>t*Math.PI/180:t=>t;lr(S.mass.brush,S.mass.color,1),St(2-u),d&&i[0].draw(),Or(i[0],.9*x,s(g),{gradient:f,rand:2-2*u,continuous:!0},p,y),h>.33&&Or(i[1],x,s(g+20*$(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),h>.66&&Or(i[2],.8*x,s(g+15*$(-1,1)),{gradient:f,rand:.6-.6*u,continuous:!0},p,y),nr(c),Pr(a),S.field={...l}}function zr(t,e,r){const n=2*Math.PI,i=P.ctx,a=r/2;i.moveTo(t+a,e),i.arc(t,e,a,0,n)}S.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1},jt.prototype.hatch=function(t=!1,e,r){let n=Tr();t&&Cr(t,e,r),S.hatch.isActive&&Ir(this),Pr(n)},Kt.prototype.hatch=function(t,e,r){Tr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,.3),this.pol.hatch())},S.mass={isActive:!1,brush:null,color:null,options:{}},jt.prototype.mass=function(){S.mass?.isActive&&Yr(this,!1)},Kt.prototype.mass=function(t,e,r){S.mass?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),Yr(this,t,e,r))};let Xr=null,Gr=!1;Gr||(v={ensureResources:function(t,e,r,n,i){const a=Math.max(1,Math.round(e*n)),o=Math.max(1,Math.round(r*n));return function(t,e,r){return!t.mask||t.mask.width!==e||t.mask.height!==r}(t,a,o)&&(t.mask=g(a,o)),function(t,e,r,n){return!t.fillMaskFramebuffer||t.fillMaskFramebuffer.width!==e||t.fillMaskFramebuffer.height!==r||"function"==typeof t.fillMaskFramebuffer.pixelDensity&&t.fillMaskFramebuffer.pixelDensity()!==n}(t,e,r,n)&&(t.fillMaskFramebuffer?.remove&&t.fillMaskFramebuffer.remove(),t.fillMaskFramebuffer=y(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1}),i(t.fillMaskFramebuffer)),t.mask.dirtyRect??=null,t.mask.isDrawn??=!1,t.mask.drawingContext.imageSmoothingEnabled=!1,{mask:t.mask,ctx:t.mask.drawingContext}},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?i(n(t.dirtyRect,4)):r():null},getShaderMask:function(t,e,r,n,i,a){const o=t.fillMaskFramebuffer,s=t.drawingContext,c=n(r)??i(),l=c.maxX-c.minX,u=c.maxY-c.minY;Xr&&Xr.width===l&&Xr.height===u||(Xr=g(l,u));const h=Xr.drawingContext;return h.clearRect(0,0,l,u),h.drawImage(e,c.minX,c.minY,l,u,0,0,l,u),a(o),s.bindTexture(s.TEXTURE_2D,o.colorTexture),s.texSubImage2D(s.TEXTURE_2D,0,c.minX,c.minY,s.RGBA,s.UNSIGNED_BYTE,Xr),o}},Gr=!0),S.fill={opacity:150,bleed_strength:.07,texture_strength:.8,border_strength:.5,direction:"out",isActive:!1};const Zr=()=>({...S.fill});function Vr(t,e,r,n){S.fill.opacity=(arguments.length<4?e:n)||150,S.fill.color=arguments.length<3?c(t):c(t,e,r),S.fill.isActive=!0}function $r(t,e="out"){S.fill.bleed_strength=Q(t,0,1),S.fill.direction=e}function Hr(t=.4,e=.4){S.fill.texture_strength=Q(t,0,1),S.fill.border_strength=Q(e,0,1)}let Wr;const qr=[[],[]];function jr(){for(let t=0;t<512;t++)qr[0][t]=j(.5,.2),qr[1][t]=j(0,.02)}function Kr(t,e,r){return(e.x-t.x)*(r.y-t.y)-(e.y-t.y)*(r.x-t.x)>.01}X(jr);class Jr{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 c=t[a],l=t[(a+1)%t.length],u={x:l.x-c.x,y:l.y-c.y},h=lt(0,0,u.x,u.y,90),f={x:c.x+u.x/2,y:c.y+u.y/2};i.push({v1:c,v2:l,ray:{point1:f,point2:{x:f.x+h.x,y:f.y+h.y}}})}this.sizeX=e,this.sizeY=n,this.dir=Array(t.length),i.forEach((t,e)=>{let r=0;for(const e of Wr.intersect(t.ray))Kr(t.v1,t.v2,e)&&r++;this.dir[e]=r%2==0});const a=V(-.6,.6)*e,o=V(-.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];const c=r,l=r+e,u=this.v[(c-1+this.v.length)%this.v.length],h=this.v[l%this.v.length],f=h.x-u.x,d=h.y-u.y;for(let t=0;t<2;t++){const e=V(.25,.75),n={x:u.x+f*e,y:u.y+d*e},s=r+t;i.splice(s,0,n),a.splice(s,0,V(.4,.7)),o.splice(s,0,this.dir[c%this.dir.length])}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+V(0,.8*i)));const a=[],o=[],s=[],c=this.midP,l=Wr.sides;for(const t of n){const r=t%e;let n=this.v[r],i=0;for(const[t,e]of l){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:c.x+(n.x-c.x)*V(.3,.6),y:c.y+(n.y-c.y)*V(.3,.6)}),a.push(n),o.push(this.m[r]),s.push(!this.dir[r])}return new Jr(a,o,this.midP,s,!1,this.sizeX,this.sizeY)}flipDirs(){return new Jr(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),c=new Array(a),l=new Array(a),u="out"===S.fill.direction?-90:90;0===qr[0].length&&jr();const h=qr[0],f=h.length,d=qr[1],m=d.length;let x,g,p,y=0,b=0,v=999===t?V(.6,.8):S.fill.bleed_strength;for(let a=0;a<i;a++){const x=e[a],g=e[a+1<i?a+1:0],p=r[a],_=n[a];if(t<997&&(v=p),v<.05){c[y]=p,l[y]=_,y++,o[b]=(x.x+g.x)/2,s[b]=(x.y+g.y)/2,c[y]=p,l[y]=_,y++,b++;continue}const R=(_?u:-u)+5*V(-1,1),w=at(R),E=ot(R),A=g.x-x.x,M=g.y-x.y,S=w*A+E*M,T=w*M-E*A,P=h[~~(V(0,1)*f)]*V(.65,1.35)*v,C=p+d[~~(V(0,1)*m)];c[y]=p,l[y]=_,y++,o[b]=x.x+.5*A+S*P,s[b]=x.y+.5*M+T*P,c[y]=C,l[y]=_,y++,b++}const _=2024*Math.max(.1,2*S.fill.bleed_strength);if(_&&y>_){const t=Math.ceil(y/_),r=Math.ceil(y/t);x=new Array(r),g=new Array(r),p=new Array(r);let n=0;for(let r=0;r<y;r+=t,n++)x[n]=r%2==0?e[r>>1]:{x:o[r>>1],y:s[r>>1]},g[n]=c[r],p[n]=l[r]}else{x=new Array(y);for(let t=0;t<y;t++)x[t]=t%2==0?e[t>>1]:{x:o[t>>1],y:s[t>>1]};c.length=y,l.length=y,g=c,p=l}return new Jr(x,g,this.midP,p,!1,this.sizeX,this.sizeY)}fill(t,e,i){const o=3*i,s=2*e*(1+i/2),c=!1!==P.isBrush;P.isBrush=!1,c&&(P.justChanged=!0),P.blend(t);const u=l();P.ctx.save(),P.ctx.setTransform(a*u.a,a*u.b,a*u.c,a*u.d,a*(u.x+r/2),a*(u.y+n/2)),P.ctx.strokeStyle=`rgb(${t._getRed()} ${t._getGreen()} ${t._getBlue()} / ${.005*S.fill.border_strength})`,P.ctx.lineCap="round";const h=Math.max(this.sizeX,this.sizeY),f=V(.15,.7);let d=this.grow();const m=this.scatter(.1).grow().scatter(.75).flipDirs();let x;for(let r=0;r<20;r++){r%4==0&&(d=d.grow()),r%2==0&&(x=[d.grow(1-.0125*r),d.grow(.7-.0125*r),d.grow(.4-.0125*r)]);for(const e of x)e.grow(999).grow(997).layer(r,h,s,t);m.grow(999).flipDirs().grow(997).layer(r,h,s*o,t),r%2==0&&d.grow(f).grow(999).layer(r,h,2*s,t),r%8!=0&&19!==r||(0!==o&&d.erase(3*o,e),P.blend(t,!0))}P.ctx.restore()}layer(t,e,r,n){P.ctx.lineWidth=J(t,0,24,e/25,e/30,!0),P.ctx.fillStyle=`rgb(${n._getRed()} ${n._getGreen()} ${n._getBlue()} / ${r}%)`,function(t){const e=P.ctx,r=e.getTransform(),n=r.a,i=r.b,a=r.c,o=r.d,s=r.e,c=r.f;let l=Infinity,u=Infinity,h=-Infinity,f=-Infinity;e.beginPath();const d=t[0];let m=n*d.x+a*d.y+s,x=i*d.x+o*d.y+c;l=h=m,u=f=x,e.moveTo(d.x,d.y);for(let r=1;r<t.length;r++){const d=t[r];m=n*d.x+a*d.y+s,x=i*d.x+o*d.y+c,l=Math.min(l,m),u=Math.min(u,x),h=Math.max(h,m),f=Math.max(f,x),e.lineTo(d.x,d.y)}e.closePath();const g=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);P.markDirtyRect(P.mask,{minX:l-g,minY:u-g,maxX:h+g,maxY:f+g})}(this.v),P.ctx.fill(),P.ctx.stroke()}erase(t,e){P.ctx.save();const r=~~(V(80,110)*J(t,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,a=1.3*Math.min(this.sizeX,this.sizeY),o=.03*a,s=.45*a,{x:c,y:l}=this.midP;P.ctx.globalCompositeOperation="destination-out";const u=(5-J(e,80,100,.3,.7,!0))*t/255;P.ctx.fillStyle=`rgb(255 0 0 / ${u})`,P.ctx.lineWidth=0;for(let t=0;t<r;t++){const e=c+j(0,n),r=l+j(0,i),a=V(o,s);P.ctx.beginPath(),zr(e,r,a),t%5!=0&&P.ctx.fill()}P.ctx.globalCompositeOperation="source-over",P.ctx.restore()}}function Qr(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=!1,n.steiner||!un(n,n.next)&&0!==ln(n.prev,n,n.next))n=n.next;else{if(pn(n),n=e=n.prev,n===n.next)break;r=!0}}while(r||n!==e);return e}function tn(t,e,r,n,i,a,o){if(!t)return;!o&&a&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=on(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let a=null;for(e=0;i;){e++;let o=i,s=0;for(let t=0;t<r&&(s++,o=o.nextZ,o);t++);let c=r;for(;s>0||c>0&&o;)0!==s&&(0===c||!o||i.z<=o.z)?(n=i,i=i.nextZ,s--):(n=o,o=o.nextZ,c--),a?a.nextZ=n:t=n,n.prevZ=a,a=n;i=o}a.nextZ=null,r*=2}while(e>1)}(i)}(t,n,i,a);let s=t;for(;t.prev!==t.next;){const c=t.prev,l=t.next;if(a?rn(t,n,i,a):en(t))e.push(c.i,t.i,l.i),pn(t),t=l.next,s=l.next;else if((t=l)===s){o?1===o?tn(t=nn(Qr(t),e),e,r,n,i,a,2):2===o&&an(t,e,r,n,i,a):tn(Qr(t),e,r,n,i,a,1);break}}}function en(t){const e=t.prev,r=t,n=t.next;if(ln(e,r,n)>=0)return!1;const i=e.x,a=r.x,o=n.x,s=e.y,c=r.y,l=n.y,u=Math.min(i,a,o),h=Math.min(s,c,l),f=Math.max(i,a,o),d=Math.max(s,c,l);let m=n.next;for(;m!==e;){if(m.x>=u&&m.x<=f&&m.y>=h&&m.y<=d&&sn(i,s,a,c,o,l,m.x,m.y)&&ln(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function rn(t,e,r,n){const i=t.prev,a=t,o=t.next;if(ln(i,a,o)>=0)return!1;const s=i.x,c=a.x,l=o.x,u=i.y,h=a.y,f=o.y,d=Math.min(s,c,l),m=Math.min(u,h,f),x=Math.max(s,c,l),g=Math.max(u,h,f),p=on(d,m,e,r,n),y=on(x,g,e,r,n);let b=t.prevZ,v=t.nextZ;for(;b&&b.z>=p&&v&&v.z<=y;){if(b.x>=d&&b.x<=x&&b.y>=m&&b.y<=g&&b!==i&&b!==o&&sn(s,u,c,h,l,f,b.x,b.y)&&ln(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,v.x>=d&&v.x<=x&&v.y>=m&&v.y<=g&&v!==i&&v!==o&&sn(s,u,c,h,l,f,v.x,v.y)&&ln(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;b&&b.z>=p;){if(b.x>=d&&b.x<=x&&b.y>=m&&b.y<=g&&b!==i&&b!==o&&sn(s,u,c,h,l,f,b.x,b.y)&&ln(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;v&&v.z<=y;){if(v.x>=d&&v.x<=x&&v.y>=m&&v.y<=g&&v!==i&&v!==o&&sn(s,u,c,h,l,f,v.x,v.y)&&ln(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function nn(t,e){let r=t;do{const n=r.prev,i=r.next.next;!un(n,i)&&hn(n,r,r.next,i)&&mn(n,i)&&mn(i,n)&&(e.push(n.i,r.i,i.i),pn(r),pn(r.next),r=t=i),r=r.next}while(r!==t);return Qr(r)}function an(t,e,r,n,i,a){let o=t;do{let t=o.next.next;for(;t!==o.prev;){if(o.i!==t.i&&cn(o,t)){let s=xn(o,t);return o=Qr(o,o.next),s=Qr(s,s.next),tn(o,e,r,n,i,a,0),void tn(s,e,r,n,i,a,0)}t=t.next}o=o.next}while(o!==t)}function on(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function sn(t,e,r,n,i,a,o,s){return!(t===o&&e===s)&&function(t,e,r,n,i,a,o,s){return(i-o)*(e-s)>=(t-o)*(a-s)&&(t-o)*(n-s)>=(r-o)*(e-s)&&(r-o)*(a-s)>=(i-o)*(n-s)}(t,e,r,n,i,a,o,s)}function cn(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&hn(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&(mn(t,e)&&mn(e,t)&&function(t,e){let r=t,n=!1;const i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)&&(ln(t.prev,t,e.prev)||ln(t,e.prev,e))||un(t,e)&&ln(t.prev,t,t.next)>0&&ln(e.prev,e,e.next)>0)}function ln(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function un(t,e){return t.x===e.x&&t.y===e.y}function hn(t,e,r,n){const i=dn(ln(t,e,r)),a=dn(ln(t,e,n)),o=dn(ln(r,n,t)),s=dn(ln(r,n,e));return i!==a&&o!==s||!(0!==i||!fn(t,r,e))||!(0!==a||!fn(t,n,e))||!(0!==o||!fn(r,t,n))||!(0!==s||!fn(r,e,n))}function fn(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function dn(t){return t>0?1:t<0?-1:0}function mn(t,e){return ln(t.prev,t,t.next)<0?ln(t,e,t.next)>=0&&ln(t,t.prev,e)>=0:ln(t,e,t.prev)<0||ln(t,t.next,e)<0}function xn(t,e){const r=yn(t.i,t.x,t.y),n=yn(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function gn(t,e,r,n){const i=yn(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function pn(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function yn(t,e,r){return{i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}jt.prototype.fill=function(t=!1,e,r,n,i,a){let o=Zr();t&&(Vr(t,e),$r(r,a),Hr(n,i)),o.isActive&&(mt(),function(t){if(!S.fill.isActive||!S.fill.color)throw new Error("No fill color set. Call brush.fill(color) before drawing shapes.");Wr=t;const e=[...t.vertices],r=~~(.25*e.length*K({1:5,2:10,3:60})),n=S.fill.bleed_strength,i=e.map((t,e)=>(e>r?1:.3)*V(.85,1.4)*n),a=W(0,e.length),o=[...e.slice(a),...e.slice(0,a)],s=function(t){if(0===t.length)return{x:0,y:0};if(t.length<8){const e=t.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0});return{x:e.x/t.length,y:e.y/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 Jr(o,i,s,[],!0).fill(S.fill.color,J(S.fill.opacity,0,255,0,1,!0),S.fill.texture_strength)}(this)),(t=>{S.fill={...t}})(o)},Kt.prototype.fill=function(t,e,r){Zr().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,S.fill.bleed_strength<.06?0:J(S.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())};let bn=null,vn=null,_n=null,Rn=null,wn=null,En=0,An=0,Mn=0;const Sn={},Tn={};function Pn(t,e,r,n){f(),S.wash.opacity=(arguments.length<4?e:n)??150,S.wash.color=arguments.length<3?c(t):c(t,e,r),S.wash.isActive=!0}function Cn(t,e){const r=l();return[r.a*t+r.c*e+r.x+En/2,r.b*t+r.d*e+r.y+An/2]}function Fn(t,e,r){const n=e.isEnabled(e.DEPTH_TEST);return n&&e.disable(e.DEPTH_TEST),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.viewport(0,0,r.width*r.density,r.height*r.density),{hadDepthTest:n}}function kn(t,e,i){i?.hadDepthTest&&e.enable(e.DEPTH_TEST),e.bindFramebuffer(e.FRAMEBUFFER,null),e.viewport(0,0,Math.max(1,Math.round(r*a)),Math.max(1,Math.round(n*a)))}function In(t,e){e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA)}function Dn(t,e,r){if(!e)return;if(r(e)){const r=t.drawingContext,n=r.getParameter(r.FRAMEBUFFER_BINDING),i=r.getParameter(r.VIEWPORT);return r.bindFramebuffer(r.FRAMEBUFFER,e.framebuffer),r.viewport(0,0,e.width*e.density,e.height*e.density),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.bindFramebuffer(r.FRAMEBUFFER,n),void r.viewport(i[0],i[1],i[2],i[3])}const n=e.drawingContext;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,e.width,e.height),n.restore()}function Ln(t,e,r){return t.shaderProgram??=function(t,e,r){const n=oe(t,e,r),i=new Map;return{program:n,setUniform(e,r){const a=(e=>(i.has(e)||i.set(e,t.getUniformLocation(n,e)),i.get(e)))(e);a&&("boolean"!=typeof r?"number"!=typeof r?Array.isArray(r)&&(3===r.length?t.uniform3f(a,r[0],r[1],r[2]):4===r.length&&t.uniform4f(a,r[0],r[1],r[2],r[3])):t.uniform1f(a,r):t.uniform1i(a,r?1:0))}}}(t.drawingContext,e,r),t.shaderProgram}function Nn(t,e){const r=t.drawingContext,n=e.density??1,i=r.createFramebuffer(),a=Math.max(1,e.width),o=Math.max(1,e.height),s=Math.max(1,Math.round(a*n)),c=Math.max(1,Math.round(o*n)),l=function(t,e,r){const n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,r,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindTexture(t.TEXTURE_2D,null),n}(r,s,c);return r.bindFramebuffer(r.FRAMEBUFFER,i),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,l,0),r.bindFramebuffer(r.FRAMEBUFFER,null),{__brushFramebuffer:!0,framebuffer:i,colorTexture:l,width:a,height:o,density:n,pixelDensity:()=>n,remove(){r.deleteFramebuffer(i),r.deleteTexture(l)}}}function Bn(t,e,r,n,i){return e?.remove?.(),Nn(t,{width:r,height:n,density:i})}function Un({renderer:t,shader:e,source:r,mask:n,color:i,isBrushMask:a,dirtyRect:o,targetIsFramebuffer:s,withScissor:c}){const l=t.drawingContext,u=l.isEnabled(l.DEPTH_TEST),h=l.getParameter(l.FRAMEBUFFER_BINDING),f=l.getParameter(l.CURRENT_PROGRAM),d=l.getParameter(l.VERTEX_ARRAY_BINDING),m=l.createVertexArray();l.bindVertexArray(m),l.useProgram(e.program),l.disable(l.DEPTH_TEST),l.enable(l.BLEND),l.blendEquation(l.FUNC_ADD),l.blendFunc(l.ONE,l.ONE_MINUS_SRC_ALPHA),l.activeTexture(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,r.colorTexture),l.uniform1i(l.getUniformLocation(e.program,"u_source"),0),l.activeTexture(l.TEXTURE1),l.bindTexture(l.TEXTURE_2D,n.colorTexture),l.uniform1i(l.getUniformLocation(e.program,"u_mask"),1),e.setUniform("u_targetIsFramebuffer",s),e.setUniform("u_isBrush",a),l.uniform3f(l.getUniformLocation(e.program,"u_color"),i[0],i[1],i[2]),l.bindFramebuffer(l.FRAMEBUFFER,null),c(l,o,()=>{l.drawArrays(l.TRIANGLES,0,3)},!s),l.bindTexture(l.TEXTURE_2D,null),l.activeTexture(l.TEXTURE0),l.bindVertexArray(d),l.useProgram(f),l.bindFramebuffer(l.FRAMEBUFFER,h),u&&l.enable(l.DEPTH_TEST),l.deleteVertexArray(m)}function On(t){return function({renderer:t,sourceFramebuffer:e,dirtyRect:r,getTargetPixelSize:n,toScissorBox:i}){const a=t.drawingContext,{width:o,height:s}=n(),c=r?i(r):null,l=a.getParameter(a.READ_FRAMEBUFFER_BINDING),u=a.getParameter(a.DRAW_FRAMEBUFFER_BINDING);return a.bindFramebuffer(a.READ_FRAMEBUFFER,null),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,e.framebuffer),a.clearColor(0,0,0,0),a.clear(a.COLOR_BUFFER_BIT),a.blitFramebuffer(c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,c?.x??0,c?.y??0,c?c.x+c.width:o,c?c.y+c.height:s,a.COLOR_BUFFER_BIT,a.NEAREST),a.bindFramebuffer(a.READ_FRAMEBUFFER,l),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,u),e}(t)}function Yn(t){if("number"==typeof t){const e=Math.max(0,Math.min(255,t));return`rgb(${e} ${e} ${e})`}return t??"black"}function zn(t){const e=((t,e=!1)=>(t.drawingContext??=t.getContext("2d",e?{willReadFrequently:!0}:void 0),t.drawingContext))(t,!0),r={canvas:t,drawingContext:e,width:t.width,height:t.height,pixels:null,_fillStyle:"#ffffff",_strokeStyle:"transparent",_lineWidth:1,pixelDensity:()=>1,background(r){e.save(),e.setTransform(1,0,0,1,0,0),e.fillStyle=Yn(r),e.fillRect(0,0,t.width,t.height),e.restore()},noSmooth(){e.imageSmoothingEnabled=!1},push(){e.save()},pop(){e.restore()},translate(t,r){e.translate(t,r)},scale(t,r=t){e.scale(t,r)},rotate(t){e.rotate(t)},noStroke(){r._strokeStyle="transparent"},stroke(t){r._strokeStyle=Yn(t)},noFill(){r._fillStyle="transparent"},fill(t){r._fillStyle=Yn(t)},strokeWeight(t){r._lineWidth=t},rect(t,n,i,a){e.beginPath(),e.rect(t,n,i,a),r._paint()},circle(t,n,i){e.beginPath(),e.arc(t,n,i/2,0,2*Math.PI),r._paint()},ellipse(t,n,i,a){e.beginPath(),e.ellipse(t,n,i/2,a/2,0,0,2*Math.PI),r._paint()},line(t,n,i,a){e.beginPath(),e.moveTo(t,n),e.lineTo(i,a),e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke()},beginShape(){e.beginPath(),r._shapeStarted=!1},vertex(t,n){r._shapeStarted?e.lineTo(t,n):(e.moveTo(t,n),r._shapeStarted=!0)},endShape(t=!1){t&&e.closePath(),r._paint()},loadPixels(){r.pixels=e.getImageData(0,0,t.width,t.height).data},updatePixels(){const n=e.getImageData(0,0,t.width,t.height);n.data.set(r.pixels),e.putImageData(n,0,0)},_paint(){"transparent"!==r._fillStyle&&(e.fillStyle=r._fillStyle,e.fill()),"transparent"!==r._strokeStyle&&(e.strokeStyle=r._strokeStyle,e.lineWidth=r._lineWidth,e.stroke())}};return r}function Xn(t,e){return zn(g(t,e,!0))}function Gn(t,e){return new Promise((r,n)=>{const i=globalThis.Image;if(!i)return void n(new Error("Standalone image brush loading requires Image support."));const a=new i;a.onload=()=>{const t=zn(g(a.naturalWidth,a.naturalHeight,!0));t.drawingContext.drawImage(a,0,0),e(t),r(t)},a.onerror=()=>n(new Error(`Failed to load image tip: ${t}`)),a.crossOrigin="anonymous",a.src=t})}var Zn;S.wash={color:null,opacity:150,isActive:!1},jt.prototype.wash=function(t=!1,e){const a={...S.wash};!1!==t&&Pn(t,e),S.wash.isActive&&function(t){if(!S.wash?.isActive||!S.wash.color||t.vertices.length<3)return;C(),function(){const t=i.drawingContext;wn&&!(En!==r||An!==n)||(En=r,An=n,wn=new Float32Array([2/En,0,0,0,0,-2/An,0,0,0,0,1,0,-1,1,0,1])),bn===t&&vn&&_n&&Rn||(bn=t,vn=oe(bn,"#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}","#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}"),Sn.a_position=bn.getAttribLocation(vn,"a_position"),Tn.u_matrix=bn.getUniformLocation(vn,"u_matrix"),Tn.u_color=bn.getUniformLocation(vn,"u_color"),_n=bn.createVertexArray(),bn.bindVertexArray(_n),Rn=bn.createBuffer(),bn.bindBuffer(bn.ARRAY_BUFFER,Rn),bn.bufferData(bn.ARRAY_BUFFER,0,bn.DYNAMIC_DRAW),Mn=0,bn.enableVertexAttribArray(Sn.a_position),bn.vertexAttribPointer(Sn.a_position,2,bn.FLOAT,!1,8,0),bn.bindVertexArray(null),bn.bindBuffer(bn.ARRAY_BUFFER,null))}();const{triangles:e,vertexCount:a}=function(t){const e=new Float32Array(2*t.vertices.length);for(let r=0;r<t.vertices.length;r++){const n=t.vertices[r];e[2*r]=n.x,e[2*r+1]=n.y}const r=function(t,e,r=2){const n=t.length;let i=function(t,e,r,n){let i;if(1==function(t,e,r,n){let i=0;for(let e=0,a=r-n;e<r;e+=n)i+=(t[a]-t[e])*(t[e+1]+t[a+1]),a=e;return i}(t,0,r,n)>0)for(let e=0;e<r;e+=n)i=gn(e/n|0,t[e],t[e+1],i);else for(let e=r-n;e>=0;e-=n)i=gn(e/n|0,t[e],t[e+1],i);return i&&un(i,i.next)&&(pn(i),i=i.next),i}(t,0,n,r);const a=[];if(!i||i.next===i.prev)return a;let o,s,c;if(t.length>80*r){o=t[0],s=t[1];let e=o,i=s;for(let a=r;a<n;a+=r){const r=t[a],n=t[a+1];r<o&&(o=r),n<s&&(s=n),r>e&&(e=r),n>i&&(i=n)}c=Math.max(e-o,i-s),c=0!==c?32767/c:0}return tn(i,a,r,o,s,c,0),a}(e),n=new Float32Array(2*r.length);for(let t=0;t<r.length;t++){const i=r[t],[a,o]=Cn(e[2*i],e[2*i+1]);n[2*t]=a,n[2*t+1]=o}return{triangles:n,vertexCount:r.length}}(t),o=e.byteLength;bn.useProgram(vn),bn.enable(bn.BLEND),bn.blendEquation(bn.FUNC_ADD),bn.blendFunc(bn.ONE,bn.ONE_MINUS_SRC_ALPHA),bn.bindVertexArray(_n),bn.bindBuffer(bn.ARRAY_BUFFER,Rn),o>Mn?(bn.bufferData(bn.ARRAY_BUFFER,e,bn.DYNAMIC_DRAW),Mn=o):bn.bufferSubData(bn.ARRAY_BUFFER,0,e);const s=S.wash.color._array;bn.uniformMatrix4fv(Tn.u_matrix,!1,wn),bn.uniform4f(Tn.u_color,s[0],s[1],s[2],S.wash.opacity/255),bn.drawArrays(bn.TRIANGLES,0,a),bn.bindVertexArray(null),bn.bindBuffer(bn.ARRAY_BUFFER,null),ce(i,bn)}(this),S.wash={...a}},Kt.prototype.wash=function(t,e,r){S.wash?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,0,-1),this.pol.wash())},Zn={load:function(t=Zt){if(!function(t){return function(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement}(t)||function(t){return"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas}(t)}(t))throw new Error("Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.");qt(t,t.width,t.height,1)},syncDensity:function(){return h({Cwidth:Ht,Cheight:Wt,Density:$t}),$t},isCanvasReady:function(){if(!Vt)throw new Error("No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.")},instance:function(){},activateInstance:function(){},deactivateInstance:function(){},getActiveFramebuffer:function(){return null},isFramebufferTarget:function(){return!0===arguments[0]?.__brushFramebuffer}},u={...u,...Zn},Ot(),function(){var t;t={beginDirectMaskDraw:Fn,endDirectMaskDraw:kn,resetDirectShaderTracking:In},se={...se,...t}}(),function(){var t;t={clearTarget:Dn,ensureBlendShaderProgram:Ln,ensureBlendSourceFramebuffer:Bn,createFramebuffer:Nn,runBlendShaderPass:Un,blitSourceToFramebuffer:On},p={...p,...t}}(),function(){var t;t={createTipSurface:Xn,loadImageTip:Gn},ie={...ie,...t}}(),t.Color=Ut,t.DEGREES=Ft,t.Plot=Kt,t.Polygon=jt,t.Position=xt,t.RADIANS=kt,t.add=ir,t.addField=Mt,t.angleMode=function(t){if(t!==Ft&&t!==kt)throw new Error(`Invalid angle mode "${t}". Use "degrees" or "radians".`);Dt=t},t.arc=Jt,t.beginShape=te,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Gt=[e,r],Xt=new Kt(t)},t.box=function(){return[...tr.keys()]},t.circle=function(t,e,r,n=!1){const i=new Kt("curve"),a=Math.PI*r,o=$(0,360),s=n?()=>1+.2*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*q(-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 c=t-r*ot(o),l=e-r*at(-o);i.show(c,l,1)},t.clear=function(...t){f(),P.glMask&&P.clearMask(P.glMask),P.mask&&P.clearMask(P.mask),P.justChanged=!1,P.isBlending=!1,P.isBrush=null,P.cachedColor=null;const e=i.drawingContext,r=0===t.length?[1,1,1,0]:[...c(...t)._array.slice(0,3),1];e.bindFramebuffer(e.FRAMEBUFFER,null),e.disable(e.SCISSOR_TEST),e.clearColor(r[0],r[1],r[2],r[3]),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)},t.clip=function(t){return f(),t},t.createCanvas=function(t,e,r={}){if("undefined"==typeof document)throw new Error("brush.createCanvas() requires a browser document.");const n=Math.max(1,Math.round(t)),i=Math.max(1,Math.round(e)),a=Math.max(1,Number(r.pixelDensity)||1),o=document.createElement("canvas");if(o.width=Math.max(1,Math.round(n*a)),o.height=Math.max(1,Math.round(i*a)),o.style.width=`${n}px`,o.style.height=`${i}px`,r.id&&(o.id=r.id),r.parent){const t="string"==typeof r.parent?document.querySelector(r.parent):r.parent;if(!t)throw new Error(`Could not find parent "${r.parent}" for brush.createCanvas().`);t.appendChild(o)}return qt(o,n,i,a),o},t.endShape=re,t.endStroke=function(t,e){if(!Xt)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Xt.endPlot(t,e),Xt.draw(Gt[0],Gt[1],1),Xt=!1},t.field=At,t.fill=Vr,t.fillBleed=$r,t.fillTexture=Hr,t.flowLine=function(t,e,r,n){if(!S.stroke.isActive||!S.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");mt(),xr(t,e,r),pr(st(n),!1)},t.getAngleMode=function(){return Dt},t.hatch=Cr,t.hatchArray=Ir,t.hatchStyle=function(t,e="black",r=1){S.hatch.hBrush={brush:t,color:e,weight:r}},t.initStandaloneRuntime=Ot,t.instance=t=>u.instance(t),t.line=Er,t.listFields=function(){return mt(),Array.from(_t.keys())},t.load=(t=!1)=>{((t=!1)=>{u.load(t)})(t),i.loaded&&P.load()},t.mass=function(t,e,r={}){S.mass.brush=t,S.mass.color=e,S.mass.options=r,S.mass.isActive=!0},t.move=function(t,e,r){if(!Xt)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Xt.addSegment(t,e,r)},t.noClip=function(){},t.noField=function(){mt(),S.field.isActive=!1},t.noFill=function(){S.fill.isActive=!1},t.noHatch=function(){S.hatch.isActive=!1,S.hatch.hBrush=!1},t.noMass=function(){S.mass.isActive=!1,S.mass.brush=null,S.mass.color=null,S.mass.options={}},t.noStroke=function(){S.stroke.isActive=!1},t.noWash=function(){S.wash.isActive=!1},t.noiseSeed=t=>{G=N(B(t)),Z=N(B(`${t}:2`))},t.pick=or,t.polygon=function(t){new jt(t).show()},t.pop=function(){0!==Lt.length&&(Nt=Lt.pop(),function(){const t=Pt.pop();t&&(S.stroke={...t.stroke},S.field={...t.field},S.hatch={...t.hatch},S.fill={...t.fill},t.wash&&(S.wash={...t.wash}),t.mass?S.mass={...t.mass}:S.mass&&(S.mass={...S.mass,isActive:!1,brush:null,color:null,options:{}}))}())},t.push=function(){mt(),Pt.push({fill:{...S.fill},wash:S.wash?{...S.wash}:null,stroke:{...S.stroke},hatch:{...S.hatch},mass:S.mass?{...S.mass}:null,field:{...S.field}}),Lt.push({...Nt})},t.rect=function(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),te(0),ee(t,e),ee(t+r,e),ee(t+r,e+n),ee(t,e+n),re(!0)},t.refreshField=function(t=0){if(!S.field.isActive||!S.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=_t.get(S.field.current);e.field=Et(e,t)},t.render=function(){C()},t.rotate=function(t){const e=Dt===kt?t:t*Math.PI/180,r=Math.cos(e),n=Math.sin(e);Nt=Bt(Nt,{a:r,b:n,c:-n,d:r,x:0,y:0})},t.scale=function(t,e=t){Nt=Bt(Nt,{a:t,b:0,c:0,d:e,x:0,y:0})},t.scaleBrushes=function(t){for(const{param:e}of tr.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.seed=t=>{O=B(t),Y=B(`${t}:2`);for(const t of z)t()},t.set=lr,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].");ne(t,e).draw()},t.stroke=sr,t.strokeWeight=cr,t.translate=function(t,e){Nt=Bt(Nt,{a:1,b:0,c:0,d:1,x:t,y:e})},t.vertex=ee,t.wRand=K,t.wash=Pn,t.wiggle=St},"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=brush.js.map
diff --git a/dist/brush.js.map b/dist/brush.js.map
index 0107e1b..c010b62 100644
--- a/dist/brush.js.map
+++ b/dist/brush.js.map
@@ -1 +1 @@
-{"version":3,"file":"brush.js","sources":["../src/core/runtime.js","../src/core/target.js","../src/core/dirty_rect.js","../src/core/compositor_runtime.js","../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/save.js","../src/adapters/standalone/runtime.js","../src/adapters/standalone/target.js","../src/core/primitives.js","../src/core/polygon.js","../src/core/plot.js","../src/stroke/runtime.js","../src/stroke/composite.js","../src/core/gl/utils.js","../src/core/renderer_runtime.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/hatch/mass.js","../src/fill/mask.js","../src/fill/composite.js","../src/fill/fill.js","../node_modules/earcut/src/earcut.js","../src/fill/wash.js","../src/adapters/standalone/renderer.js","../src/adapters/standalone/compositor.js","../src/adapters/standalone/stroke.js","../src/index.standalone.js","../src/adapters/standalone/frame.js"],"sourcesContent":["// =============================================================================\n// Runtime Hooks\n// =============================================================================\n\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nexport let usesRadians = () => false;\nexport let fromDegrees = (angle) => angle;\nexport let createColor = () => {\n throw new Error(\"No runtime color adapter registered.\");\n};\nexport let getAffineMatrix = () => identityMatrix;\n\n/**\n * Registers or updates host-runtime hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setRuntime(hooks) {\n if (hooks.usesRadians) usesRadians = hooks.usesRadians;\n if (hooks.fromDegrees) fromDegrees = hooks.fromDegrees;\n if (hooks.createColor) createColor = hooks.createColor;\n if (hooks.getAffineMatrix) getAffineMatrix = hooks.getAffineMatrix;\n}\n","// =============================================================================\n// Target Runtime Hooks\n// =============================================================================\n\n/**\n * Shared target state exposed to core modules.\n *\n * Host adapters are expected to keep these bindings updated with the currently\n * active drawing target. The exact object type is adapter-defined, but core code\n * assumes the active renderer exposes:\n * - `drawingContext`: the active WebGL context\n * - target dimensions through `Cwidth` / `Cheight`\n * - pixel density through `Density`\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\n\nlet targetRuntime = {\n load: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n syncDensity: () => Density,\n isCanvasReady: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n instance: (inst) => {\n Instance = inst;\n },\n activateInstance: (inst) => {\n Instance = inst;\n },\n deactivateInstance: () => {},\n getActiveFramebuffer: () => null,\n isFramebufferTarget: () => false,\n};\n\n/**\n * Updates the shared target state consumed by core modules.\n *\n * @param {object} state\n */\nexport function setTargetState(state) {\n if (\"Cwidth\" in state) Cwidth = state.Cwidth;\n if (\"Cheight\" in state) Cheight = state.Cheight;\n if (\"Instance\" in state) Instance = state.Instance;\n if (\"Renderer\" in state) Renderer = state.Renderer;\n if (\"Density\" in state) Density = state.Density;\n}\n\n/**\n * Registers or updates host target hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setTargetRuntime(hooks) {\n targetRuntime = { ...targetRuntime, ...hooks };\n}\n\nexport const load = (buffer = false) => targetRuntime.load(buffer);\nexport const syncDensity = () => targetRuntime.syncDensity();\nexport const isCanvasReady = () => targetRuntime.isCanvasReady();\nexport const instance = (inst) => targetRuntime.instance(inst);\nexport const activateInstance = (inst) => targetRuntime.activateInstance(inst);\nexport const deactivateInstance = () => targetRuntime.deactivateInstance();\nexport const getActiveFramebuffer = () => targetRuntime.getActiveFramebuffer();\nexport const isFramebufferTarget = (target) =>\n targetRuntime.isFramebufferTarget(target);\n","// =============================================================================\n// Module: Dirty Rect Utilities\n// =============================================================================\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n *\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 */\nexport const 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 explicit target bounds.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nexport const normalizeDirtyRect = (rect, width, height) => {\n if (!rect) return null;\n\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 *\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 */\nexport const 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 target bounds.\n *\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nexport const getFullDirtyRect = (width, height) => ({\n minX: 0,\n minY: 0,\n maxX: width,\n maxY: height,\n});\n","// =============================================================================\n// Compositor Runtime Hooks\n// =============================================================================\n\n/**\n * Shared compositor helpers and host hooks.\n *\n * The shared code in this module assumes framebuffer-like targets expose:\n * - `framebuffer`: native WebGL framebuffer handle\n * - optional lifecycle methods supplied by the host adapter\n *\n * Higher-level core modules also attach their own bookkeeping fields onto the\n * active renderer and mask targets, such as:\n * - `shaderProgram`\n * - `blendSourceFramebuffer`\n * - `glMask`\n * - `fillMaskFramebuffer`\n * - `mask`\n *\n * These are library-level contract fields, not host-specific internals.\n */\n\nexport const create2DCanvas = (width, height, willReadFrequently = false) => {\n const canvas =\n typeof OffscreenCanvas !== \"undefined\"\n ? new OffscreenCanvas(width, height)\n : (() => {\n const element = document.createElement(\"canvas\");\n element.width = width;\n element.height = height;\n return element;\n })();\n canvas.drawingContext = canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas;\n};\n\nexport const get2DContext = (canvas, willReadFrequently = false) => {\n canvas.drawingContext ??= canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas.drawingContext;\n};\n\nexport function blitDefaultFramebufferSource({\n renderer,\n sourceFramebuffer,\n dirtyRect,\n getTargetPixelSize,\n toScissorBox,\n}) {\n const gl = renderer.drawingContext;\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 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\nlet compositorRuntime = {\n clearTarget: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendShaderProgram: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendSourceFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n createFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n runBlendShaderPass: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n blitSourceToFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host compositor hooks used by core compositing code.\n *\n * @param {object} hooks\n */\nexport function setCompositorRuntime(hooks) {\n compositorRuntime = { ...compositorRuntime, ...hooks };\n}\n\nexport const clearTarget = (...args) => compositorRuntime.clearTarget(...args);\nexport const ensureBlendShaderProgram = (...args) =>\n compositorRuntime.ensureBlendShaderProgram(...args);\nexport const ensureBlendSourceFramebuffer = (...args) =>\n compositorRuntime.ensureBlendSourceFramebuffer(...args);\nexport const createFramebuffer = (...args) =>\n compositorRuntime.createFramebuffer(...args);\nexport const runBlendShaderPass = (...args) =>\n compositorRuntime.runBlendShaderPass(...args);\nexport const blitSourceToFramebuffer = (...args) =>\n compositorRuntime.blitSourceToFramebuffer(...args);\n","import {\n Cwidth,\n Cheight,\n Renderer,\n Density,\n load as loadTarget,\n isCanvasReady,\n syncDensity,\n getActiveFramebuffer,\n isFramebufferTarget,\n} from \"./target.js\";\nimport {\n expandDirtyRect,\n normalizeDirtyRect as clampDirtyRect,\n unionDirtyRect,\n getFullDirtyRect as getFullRect,\n} from \"./dirty_rect.js\";\nimport {\n clearTarget as clearRenderTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n} from \"./compositor_runtime.js\";\n\nimport 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\nlet strokeComposite = null;\nlet fillComposite = null;\n\nexport const registerStrokeComposite = (composite) => {\n strokeComposite = composite;\n};\n\nexport const registerFillComposite = (composite) => {\n fillComposite = composite;\n};\n\nconst clearTarget = (target) => {\n clearRenderTarget(Renderer, target, isFramebufferTarget);\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\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\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n const { width, height } = getTargetPixelSize();\n return clampDirtyRect(rect, width, height);\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 getFullRect(width, 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 * 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/**\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: null,\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 const composite = target === this.glMask ? strokeComposite : fillComposite;\n composite?.clearMask?.(target, clearTarget);\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 GL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n const composite = isBrushMask ? strokeComposite : fillComposite;\n return composite?.getCompositeRect?.(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\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 syncDensity();\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 ensureBlendShaderProgram(Renderer, vertSrc, fragSrc);\n\n this.glMask = strokeComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n );\n const fillResources = fillComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n ) ?? {\n mask: null,\n ctx: null,\n };\n\n if (needsBlendSourceFramebuffer) {\n Renderer.blendSourceFramebuffer = ensureBlendSourceFramebuffer(\n Renderer,\n Renderer.blendSourceFramebuffer,\n Cwidth,\n Cheight,\n Density,\n );\n }\n\n this.mask = fillResources.mask;\n this.ctx = fillResources.ctx;\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 // 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 fully at the start of each blend cycle so stale\n // dirty-rect bookkeeping cannot leak an old stroke into the next color.\n this.clearMask(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) {\n this.isBlending = false;\n this.cachedColor = null;\n \n }\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 GL 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 = blitSourceToFramebuffer({\n renderer: Renderer,\n sourceTarget: activeFramebuffer ?? Renderer,\n sourceFramebuffer: Renderer.blendSourceFramebuffer,\n dirtyRect,\n isFramebufferTarget,\n Cwidth,\n Cheight,\n getTargetPixelSize,\n toScissorBox,\n withScissor,\n });\n const targetIsFramebuffer = !!activeFramebuffer;\n const composite = isBrushMask ? strokeComposite : fillComposite;\n const shaderMask = composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n );\n\n runBlendShaderPass({\n renderer: Renderer,\n shader,\n source,\n mask: shaderMask,\n color: this.cachedColor,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n });\n this.clearMask(mask);\n },\n};\n\n/**\n * Flushes any pending stroke/fill mask work into the current target and resets\n * the shared compositor back to its initial idle state.\n */\nexport const flushActiveComposite = () => {\n isMixReady();\n Mix.blend(false, true);\n Mix.clearMask(Mix.glMask);\n Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n};\n\n/**\n * Loads and initializes the drawing target, then refreshes compositing\n * resources if the renderer was already active.\n *\n * @param {object|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\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 { usesRadians as runtimeUsesRadians } from \"./runtime.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());\nlet rng2 = 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 rng2 = prng_alea(`${s}:2`);\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()));\nexport let noise2 = 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 noise2 = createNoise2D(prng_alea(`${s}:2`));\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);\nexport const rr2 = (e = 0, r = 1) => e + rng2() * (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);\nexport const randInt2 = (e, r) => ~~rr2(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 if (isRad || runtimeUsesRadians()) {\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 || runtimeUsesRadians()\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 { Cwidth, Cheight } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\nimport { getAffineMatrix } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Matrix transformations\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 const m = getAffineMatrix();\n this.mx = m.x;\n this.my = m.y;\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 = Math.round((x + this.mx - left_x) / resolution);\n this.rowIdx = Math.round((y + this.my - top_y) / resolution);\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 + this.mx;\n const y = this.y + this.my;\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(skipCheck = false) {\n if (!State.field.isActive) return 0;\n return (skipCheck || this.isIn())\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 runtime angle units.\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 const steps = _length / _step;\n const fieldActive = State.field.isActive;\n const usePlot = !!_scale;\n for (let i = 0; i < steps; i++) {\n const angle =\n (fieldActive ? this.angle(true) : 0) - (usePlot ? _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 + getAffineMatrix().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 + getAffineMatrix().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 = rr2(0.2, 0.8),\n ba = randInt2(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt2(15, 25));\n return 0.2 * angle * cos(t) + noise2(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt2(-10, 10);\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise2(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 = randInt2(-30, -15) + Math.abs(44 * sin(t));\n if (randInt2(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 = randInt2(10, 15) + 5 * sin(t),\n cr = randInt2(3, 6) + 3 * cos(t),\n ba = randInt2(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt2(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr2(0.4, 0.8),\n ba = randInt2(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt2(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt2(5, 10);\n const dir = randInt2(0, 2) * 2 - 1;\n const offset = randInt2(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr2(0.1, 0.9) * num_columns,\n y: rr2(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 = randInt2(3, 8),\n amp = randInt2(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\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 wash: State.wash ? { ...State.wash } : null,\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n mass: State.mass ? { ...State.mass } : null,\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 if (saved.wash) State.wash = { ...saved.wash };\n if (saved.mass) {\n State.mass = { ...saved.mass };\n } else if (State.mass) {\n State.mass = {\n ...State.mass,\n isActive: false,\n brush: null,\n color: null,\n options: {},\n };\n }\n}\n","// =============================================================================\n// Adapter: Standalone Runtime Hooks\n// =============================================================================\n\nimport { setRuntime } from \"../../core/runtime.js\";\nimport { push as pushState, pop as popState } from \"../../core/save.js\";\n\nconst clamp = (value, min, max) => Math.max(min, Math.min(value, max));\n\nexport const DEGREES = \"degrees\";\nexport const RADIANS = \"radians\";\n\nlet colorContext = null;\nlet currentAngleMode = DEGREES;\nconst transformStack = [];\nlet currentTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nfunction getColorContext() {\n if (colorContext) return colorContext;\n\n if (typeof document !== \"undefined\") {\n colorContext = document.createElement(\"canvas\").getContext(\"2d\");\n return colorContext;\n }\n\n if (typeof OffscreenCanvas !== \"undefined\") {\n colorContext = new OffscreenCanvas(1, 1).getContext(\"2d\");\n return colorContext;\n }\n\n throw new Error(\"Standalone color parsing requires CanvasRenderingContext2D support.\");\n}\n\nfunction multiplyTransform(left, right) {\n return {\n a: left.a * right.a + left.c * right.b,\n b: left.b * right.a + left.d * right.b,\n c: left.a * right.c + left.c * right.d,\n d: left.b * right.c + left.d * right.d,\n x: left.a * right.x + left.c * right.y + left.x,\n y: left.b * right.x + left.d * right.y + left.y,\n };\n}\n\n/**\n * Runtime-native color object compatible with the expectations of core modules.\n */\nexport class Color {\n constructor(r, g, b) {\n if (r?._array) {\n this.r = Math.round(r._array[0] * 255);\n this.g = Math.round(r._array[1] * 255);\n this.b = Math.round(r._array[2] * 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n this._array = [...r._array];\n this.gl = this._array;\n return;\n }\n\n if (typeof r === \"string\") {\n this.hex = this.standardize(r);\n const rgb = this.hexToRgb(this.hex);\n this.r = rgb.r;\n this.g = rgb.g;\n this.b = rgb.b;\n } else {\n this.r = clamp(r ?? 0, 0, 255);\n this.g = clamp(g ?? r ?? 0, 0, 255);\n this.b = clamp(b ?? r ?? 0, 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n }\n\n this._array = [this.r / 255, this.g / 255, this.b / 255, 1];\n this.gl = this._array;\n }\n\n rgbToHex(r, g, b) {\n return `#${((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1)}`;\n }\n\n hexToRgb(hex) {\n hex = hex.replace(\n /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i,\n (_match, red, green, blue) => red + red + green + green + blue + blue,\n );\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n if (!result) {\n throw new Error(`Invalid color value \"${hex}\".`);\n }\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n };\n }\n\n standardize(value) {\n const ctx = getColorContext();\n ctx.fillStyle = value;\n return ctx.fillStyle;\n }\n\n _getRed() {\n return this.r;\n }\n\n _getGreen() {\n return this.g;\n }\n\n _getBlue() {\n return this.b;\n }\n}\n\n/**\n * Sets the active standalone angle mode.\n *\n * @param {\"degrees\"|\"radians\"} mode\n */\nexport function angleMode(mode) {\n if (mode !== DEGREES && mode !== RADIANS) {\n throw new Error(`Invalid angle mode \"${mode}\". Use \"degrees\" or \"radians\".`);\n }\n currentAngleMode = mode;\n}\n\n/**\n * Returns the current standalone angle mode.\n *\n * @returns {\"degrees\"|\"radians\"}\n */\nexport function getAngleMode() {\n return currentAngleMode;\n}\n\n/**\n * Pushes the current standalone transform onto the stack.\n */\nexport function push() {\n pushState();\n transformStack.push({ ...currentTransform });\n}\n\n/**\n * Pops the last standalone transform from the stack.\n */\nexport function pop() {\n if (transformStack.length === 0) return;\n currentTransform = transformStack.pop();\n popState();\n}\n\n/**\n * Applies a translation to the current standalone transform.\n *\n * @param {number} x\n * @param {number} y\n */\nexport function translate(x, y) {\n currentTransform = multiplyTransform(currentTransform, {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x,\n y,\n });\n}\n\n/**\n * Applies a rotation to the current standalone transform.\n *\n * @param {number} angle\n */\nexport function rotate(angle) {\n const theta =\n currentAngleMode === RADIANS ? angle : (angle * Math.PI) / 180;\n const cosTheta = Math.cos(theta);\n const sinTheta = Math.sin(theta);\n currentTransform = multiplyTransform(currentTransform, {\n a: cosTheta,\n b: sinTheta,\n c: -sinTheta,\n d: cosTheta,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Applies a scale to the current standalone transform.\n *\n * @param {number} x\n * @param {number} [y=x]\n */\nexport function scale(x, y = x) {\n currentTransform = multiplyTransform(currentTransform, {\n a: x,\n b: 0,\n c: 0,\n d: y,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Installs the standalone runtime hooks used by core modules.\n */\nexport function initStandaloneRuntime() {\n setRuntime({\n usesRadians: () => currentAngleMode === \"radians\",\n fromDegrees: (angle) =>\n currentAngleMode === \"radians\" ? (angle * Math.PI) / 180 : angle,\n createColor: (...args) => {\n if (args.length === 1 && args[0]?._array) return args[0];\n return new Color(...args);\n },\n getAffineMatrix: () => currentTransform,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Target Hooks\n// =============================================================================\n\nimport {\n setTargetRuntime,\n setTargetState,\n} from \"../../core/target.js\";\n\nlet activeTarget = null;\nlet isLoaded = false;\nlet activeDensity = 1;\nlet activeWidth = 0;\nlet activeHeight = 0;\n\nfunction isCanvasTarget(target) {\n return (\n typeof HTMLCanvasElement !== \"undefined\" &&\n target instanceof HTMLCanvasElement\n );\n}\n\nfunction isOffscreenCanvasTarget(target) {\n return (\n typeof OffscreenCanvas !== \"undefined\" &&\n target instanceof OffscreenCanvas\n );\n}\n\nfunction isSupportedTarget(target) {\n return isCanvasTarget(target) || isOffscreenCanvasTarget(target);\n}\n\nfunction getTargetContext(target) {\n return (\n target.getContext(\"webgl2\", { premultipliedAlpha: true }) ??\n target.getContext(\"webgl2\")\n );\n}\n\nfunction createRenderer(target, width, height, density) {\n const drawingContext = getTargetContext(target);\n if (!drawingContext) {\n throw new Error(\"brush.load(target) requires a canvas with a WebGL2 context.\");\n }\n\n return {\n canvas: target,\n drawingContext,\n width,\n height,\n pixelDensity: () => density,\n };\n}\n\nfunction applyLoadedTarget(target, width, height, density) {\n activeTarget = target;\n activeWidth = width;\n activeHeight = height;\n activeDensity = density;\n\n const renderer = createRenderer(target, width, height, density);\n setTargetState({\n Renderer: renderer,\n Cwidth: width,\n Cheight: height,\n Density: density,\n });\n isLoaded = true;\n}\n\n/**\n * Loads a standalone draw target from a DOM canvas or OffscreenCanvas.\n *\n * @param {HTMLCanvasElement|OffscreenCanvas} target\n */\nexport function load(target = activeTarget) {\n if (!isSupportedTarget(target)) {\n throw new Error(\n \"Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.\",\n );\n }\n\n applyLoadedTarget(target, target.width, target.height, 1);\n}\n\n/**\n * Creates a standalone DOM canvas, configures its backing resolution according\n * to the provided pixel density, appends it optionally to the DOM, and loads it\n * as the active brush target.\n *\n * @param {number} width Logical canvas width.\n * @param {number} height Logical canvas height.\n * @param {{pixelDensity?: number, parent?: string|Element|null, id?: string}} [options]\n * @returns {HTMLCanvasElement}\n */\nexport function createCanvas(width, height, options = {}) {\n if (typeof document === \"undefined\") {\n throw new Error(\"brush.createCanvas() requires a browser document.\");\n }\n\n const logicalWidth = Math.max(1, Math.round(width));\n const logicalHeight = Math.max(1, Math.round(height));\n const density = Math.max(1, Number(options.pixelDensity) || 1);\n const canvas = document.createElement(\"canvas\");\n\n canvas.width = Math.max(1, Math.round(logicalWidth * density));\n canvas.height = Math.max(1, Math.round(logicalHeight * density));\n canvas.style.width = `${logicalWidth}px`;\n canvas.style.height = `${logicalHeight}px`;\n if (options.id) canvas.id = options.id;\n\n if (options.parent) {\n const parent =\n typeof options.parent === \"string\"\n ? document.querySelector(options.parent)\n : options.parent;\n if (!parent) {\n throw new Error(`Could not find parent \"${options.parent}\" for brush.createCanvas().`);\n }\n parent.appendChild(canvas);\n }\n\n applyLoadedTarget(canvas, logicalWidth, logicalHeight, density);\n return canvas;\n}\n\n/**\n * Refreshes the standalone target density.\n *\n * Standalone targets currently use a fixed density of 1.\n *\n * @returns {number}\n */\nexport function syncDensity() {\n setTargetState({\n Cwidth: activeWidth,\n Cheight: activeHeight,\n Density: activeDensity,\n });\n return activeDensity;\n}\n\n/**\n * Ensures a standalone target has been loaded.\n */\nexport function isCanvasReady() {\n if (!isLoaded) {\n throw new Error(\n \"No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.\",\n );\n }\n}\n\n/**\n * Standalone build does not use p5 instance switching, so these are no-ops.\n */\nexport function instance() {}\nexport function activateInstance() {}\nexport function deactivateInstance() {}\n\n/**\n * Standalone build does not yet support framebuffer targets.\n *\n * @returns {null}\n */\nexport function getActiveFramebuffer() {\n return null;\n}\n\n/**\n * Returns whether the given target behaves like a framebuffer target.\n *\n * Standalone targets currently only accept canvases and offscreen canvases.\n *\n * @returns {boolean}\n */\nexport function isFramebufferTarget() {\n return arguments[0]?.__brushFramebuffer === true;\n}\n\nexport function initStandaloneTargetRuntime() {\n setTargetRuntime({\n load,\n syncDensity,\n isCanvasReady,\n instance,\n activateInstance,\n deactivateInstance,\n getActiveFramebuffer,\n isFramebufferTarget,\n });\n}\n","import {\n rr2,\n randInt2,\n sin,\n cos,\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 * Polygons ignore fields and won't be good for fills and masses\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 = rr2(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr2() : () => 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 * randInt2(-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 runtime angle units.\n * @param {number} end - End angle in the current runtime angle units.\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","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.wash) this.wash();\n if (State.fill) this.fill();\n if (State.mass) this.mass();\n if (State.hatch) this.hatch();\n if (State.stroke) this.draw();\n }\n}","import { Cwidth, Cheight } from \"./target.js\";\nimport { State } from \"./color.js\";\nimport { toDegrees, map, rr2 } 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 = _side < 0 ? 4 : 1;\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 let maxSize = _side <= 0 ? 8 : Math.max(this.segments[idx] * _side * rr2(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.wash) this.wash(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n if (State.mass) this.mass(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.stroke) this.draw(x, y, scale);\n }\n}\n","// =============================================================================\n// Stroke Runtime Hooks\n// =============================================================================\n\nlet strokeRuntime = {\n createTipSurface: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n loadImageTip: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host stroke hooks used by brush-tip loading code.\n *\n * @param {object} hooks\n */\nexport function setStrokeRuntime(hooks) {\n strokeRuntime = { ...strokeRuntime, ...hooks };\n}\n\nexport const createTipSurface = (width, height) =>\n strokeRuntime.createTipSurface(width, height);\nexport const loadImageTip = (src, imageToWhite) =>\n strokeRuntime.loadImageTip(src, imageToWhite);\n","import * as Color from \"../core/color.js\";\nimport { createFramebuffer } from \"../core/compositor_runtime.js\";\n\nlet isStrokeCompositeRegistered = false;\nconst DIRTY_BRUSH_PADDING = 2;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the current stroke mask framebuffer must be recreated.\n * This happens when the renderer has no mask yet, or when the canvas size or\n * pixel density changed since the last allocation.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the stroke mask must be rebuilt.\n */\nfunction needsStrokeMask(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.glMask ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight ||\n (typeof Renderer.glMask.pixelDensity === \"function\" &&\n Renderer.glMask.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures the stroke compositor owns a framebuffer-backed mask with the current\n * canvas dimensions. Stroke stamps are rendered into this mask in WebGL before\n * being blended into the main target.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {object} The framebuffer used as stroke mask.\n */\nexport function ensureStrokeCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n) {\n if (needsStrokeMask(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n Renderer.glMask = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n Renderer.glMask.dirtyRect ??= null;\n Renderer.glMask.isDrawn ??= false;\n return Renderer.glMask;\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current stroke mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearStrokeMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the rect that should be composited from the stroke mask into the\n * main canvas. Stroke bounds are normally tight dirty rects, but when drawing\n * into an active framebuffer we keep the result conservative and composite the\n * full target.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} getActiveFramebuffer - Returns the currently bound framebuffer.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {number} padding - Extra brush padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getStrokeCompositeRect(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n if (getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_BRUSH_PADDING),\n );\n}\n\n/**\n * Returns the resource that should be bound to the blend shader's `u_mask`\n * uniform for stroke compositing.\n *\n * @param {object} _Renderer - Active host renderer.\n * @param {object} mask - Stroke mask framebuffer.\n * @returns {object} Stroke mask framebuffer.\n */\nexport function getStrokeShaderMask(_Renderer, mask) {\n return mask;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the stroke compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initStrokeComposite() {\n if (isStrokeCompositeRegistered) return;\n Color.registerStrokeComposite?.({\n ensureResources: ensureStrokeCompositeResources,\n clearMask: clearStrokeMask,\n getCompositeRect: getStrokeCompositeRect,\n getShaderMask: getStrokeShaderMask,\n });\n isStrokeCompositeRegistered = true;\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// Renderer Runtime Hooks\n// =============================================================================\n\n/**\n * Direct-render hooks used by modules that issue raw WebGL commands.\n *\n * These hooks are intentionally narrow:\n * - begin drawing into an offscreen GL mask target\n * - restore the previous draw target afterward\n * - reset any host-side shader/program bookkeeping after direct GL usage\n */\n\nlet rendererRuntime = {\n beginDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n endDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n resetDirectShaderTracking: () => {},\n};\n\n/**\n * Registers or updates host renderer hooks used by direct WebGL drawing paths.\n *\n * @param {object} hooks\n */\nexport function setRendererRuntime(hooks) {\n rendererRuntime = { ...rendererRuntime, ...hooks };\n}\n\nexport const beginDirectMaskDraw = (renderer, gl, target) =>\n rendererRuntime.beginDirectMaskDraw(renderer, gl, target);\nexport const endDirectMaskDraw = (renderer, gl, state) =>\n rendererRuntime.endDirectMaskDraw(renderer, gl, state);\nexport const resetDirectShaderTracking = (renderer, gl) =>\n rendererRuntime.resetDirectShaderTracking(renderer, gl);\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 { Cwidth, Cheight, Density, Renderer } from \"../core/target.js\";\nimport {\n Mix,\n isMixReady,\n State,\n} from \"../core/color.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport {\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking,\n} from \"../core/renderer_runtime.js\";\nimport { getAffineMatrix } from \"../core/runtime.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;\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 runtime affine transform. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n const m = getAffineMatrix();\n _ma = m.a;\n _mb = m.b;\n _mc = m.c;\n _md = m.d;\n _mx = m.x;\n _my = m.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 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 return beginDirectMaskDraw(Renderer, gl, Mix.glMask);\n}\n\nfunction endMaskTarget(state) {\n endDirectMaskDraw(Renderer, gl, state);\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 * the current runtime transform 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 * @param {number} [extraPadding=0] - Conservative extra padding in user units.\n */\nexport function stampImage(x, y, size, angle, alpha, extraPadding = 0) {\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 const extraRadius = _density * extraPadding * _scale;\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 const boundsRadius = halfSize * 1.42 + extraRadius;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - boundsRadius - 1,\n dScreenY - boundsRadius - 1,\n dScreenX + boundsRadius + 1,\n dScreenY + boundsRadius + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {object} p5img - The preprocessed brush-tip image/canvas (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 const targetState = beginMaskTarget();\n\n // Lazy-create the WebGL texture from the tip 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(targetState);\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let the host adapter know we changed the active program.\n resetDirectShaderTracking(Renderer, gl);\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 const targetState = beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader in case host drawing 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(targetState);\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 host shader tracking.\n // Reset it so the host is forced to re-activate its own shader next time\n // it draws — otherwise it may skip gl.useProgram() and set uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetDirectShaderTracking(Renderer, gl);\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\n// Core imports\nimport { Cwidth, Cheight, Renderer, isCanvasReady } from \"../core/target.js\";\nimport {\n Mix,\n State,\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 cos,\n sin\n} from \"../core/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { createTipSurface, loadImageTip } from \"./runtime.js\";\n\n// Internal module imports\nimport { initStrokeComposite } from \"./composite.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\n\ninitStrokeComposite(); // Register the stroke composite system for offscreen mask rendering and compositing.\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 type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\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 if (params.markerTip === undefined) params.markerTip = true;\n if (params.noise === undefined) params.noise = 0.3;\n params.noise = Math.max(0, Math.min(1, params.noise));\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 g = createTipSurface(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\nexport function getBrushParams(brushName) {\n return list.get(brushName)?.param ?? null;\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 = createColor(...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\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current runtime 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 return region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n return;\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 _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 current.pressureCount = 10;\n current.cachedPressure = undefined;\n current.lineNoiseCount = 5;\n current.cachedLineNoise = undefined;\n\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n if (isPlot) {\n _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n );\n } else {\n _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\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.05 * current.p.noise;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n current.cos = cos(_dir);\n current.sin = sin(_dir);\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 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 pressure = calculatePressure();\n const lineNoise = calculateLineNoise();\n\n if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;\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 if (current.pressureCount >= 10 || current.cachedPressure === undefined) {\n current.cachedPressure = _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n current.pressureCount = 0;\n }\n current.pressureCount++;\n return current.cachedPressure;\n}\n\nfunction calculateLineNoise() {\n if (current.lineNoiseCount >= 10 || current.cachedLineNoise === undefined) {\n current.cachedLineNoise = map(\n noise(current.seed + _position.plotted * 0.01, 0),\n -1,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n current.lineNoiseCount = 0;\n }\n current.lineNoiseCount++;\n return current.cachedLineNoise;\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 * 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\nfunction getImageTipOverscan() {\n const maxPressure = Math.max(1, current.max ?? 1);\n const scatterReach = State.stroke.weight * current.p.scatter;\n const tipReach = State.stroke.weight * current.p.weight * maxPressure;\n\n // Custom/image tips can extend beyond their nominal square because the tip\n // drawing itself may be large and because high scatter creates sparse large\n // stamps near the edge. Keep culling/dirty tracking conservative.\n return Math.max(8, scatterReach * 1.5 + tipReach * 0.75);\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 const overscan = getImageTipOverscan();\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(\n _position.x + rx,\n _position.y + ry,\n size,\n angle,\n alpha * Math.max(0.8, pressure) * rr(0.9, 1.1),\n overscan,\n );\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\n let dx, dy;\n if (_plot) {\n const plotAngle = _plot.angle(_position.plotted);\n const plotCos = cos(plotAngle);\n const plotSin = sin(plotAngle);\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * plotSin + along * plotCos;\n dy = perp * plotCos - along * plotSin;\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 (current.p.markerTip === false) return;\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// 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 runtime angle units.\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 \"markerTip\",\n \"noise\",\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 \"pastel\",\n [\n 2.05 / 3,\n 13.4 / 3,\n 0.91,\n 28,\n 35,\n 0.085 / 3,\n { mode: \"gaussian\", curve: [0.4, 0.05], min_max: [1.09, 0.93] },\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"crayon\",\n [\n 0.9 / 3,\n 5.45 / 3,\n 0.75,\n 250,\n 159,\n 0.23 / 3,\n [1.1, 0.9],\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\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 active host image pipeline.\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 host image object 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 loadImageTip(src, T.imageToWhite).then((p5img) => {\n this.tips.set(src, p5img);\n }),\n ),\n );\n },\n};\n","import { 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// Module: Classic Hatch\n// =============================================================================\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\n/**\n * Returns a shallow snapshot of the current hatch modifier state.\n *\n * @returns {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}}\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Restores hatch modifier state from a previously captured snapshot.\n *\n * @param {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}} state\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Activates classic scanline hatching for subsequent shapes.\n *\n * @param {number} [dist=5] Distance between scanlines.\n * @param {number} [angle=45] Hatch angle in the current runtime angle units.\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [options]\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Overrides the brush, color, and weight used specifically for hatch strokes.\n *\n * @param {string} brush\n * @param {string|object} [color=\"black\"]\n * @param {number} [weight=1]\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Deactivates hatching and clears any hatch-specific brush override.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Generation\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for one polygon by rotating it into scanline space,\n * intersecting horizontal scanlines against its edges, and rotating the\n * resulting segments back into canvas space.\n *\n * @param {Polygon} polygon\n * @param {number} angle Hatch angle in degrees.\n * @param {number} dist Base scanline spacing.\n * @param {number} gradient Multiplicative spacing growth per scanline.\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad),\n sinA = Math.sin(rad);\n const cosB = Math.cos(-rad),\n sinB = Math.sin(-rad);\n\n const verts = polygon.a,\n n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity,\n maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0],\n 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],\n 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,\n step = dist;\n while (Y < maxY) {\n const cx = [];\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1],\n y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(\n edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0])\n );\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n scanY: Y,\n x1: cx[i] * cosB - Y * sinB,\n y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB,\n y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n/**\n * Collects and orders hatch segments for one polygon or a polygon list.\n *\n * Segments are sorted in scanline traversal order so downstream rendering can\n * optionally connect them into a continuous serpentine path.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {number} dist\n * @param {number} angle\n * @param {number} gradient\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction getHatchSegments(polygons, dist, angle, gradient) {\n if (!Array.isArray(polygons)) polygons = [polygons];\n const segs = [];\n for (const poly of polygons) {\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n }\n segs.sort((a, b) => (a.scanY === b.scanY ? a.x1 - b.x1 : a.scanY - b.scanY));\n return segs;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Runs hatch drawing with the temporary hatch-specific brush style if one is active,\n * then restores the outer stroke state.\n *\n * @param {() => void} drawFn\n */\nfunction withHatchStyle(drawFn) {\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n drawFn();\n BrushSetState(save);\n}\n\n/**\n * Resolves the active hatch parameters and precomputes the ordered scanline segments.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{dist:number, options:Object, segs:Object[]}}\n */\nfunction getActiveHatchConfig(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n const segs = getHatchSegments(polygons, dist, angle, gradient);\n return { dist, options, segs };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Lines\n// ---------------------------------------------------------------------------\n\n/**\n * Expands ordered hatch segments into the actual line list that will be drawn.\n *\n * This includes endpoint jitter when `rand` is active and inserts the serpentine\n * connector lines when `continuous` is enabled.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{x1:number, y1:number, x2:number, y2:number, scanY:number, isConnector:boolean}[]}\n */\nexport function getHatchLines(polygons) {\n const { dist, options, segs } = getActiveHatchConfig(polygons);\n const r = options.rand || 0;\n const lines = [];\n\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 += 2 * r * dist * rr(-1, 1);\n y1 += 2 * r * dist * rr(-1, 1);\n x2 += 2 * r * dist * rr(-1, 1);\n y2 += 2 * r * dist * rr(-1, 1);\n }\n const reverse = options.continuous && j % 2 === 1;\n const line = reverse\n ? { x1: x2, y1: y2, x2: x1, y2: y1, scanY: s.scanY, isConnector: false }\n : { x1, y1, x2, y2, scanY: s.scanY, isConnector: false };\n lines.push(line);\n if (j > 0 && options.continuous) {\n const prev = lines[lines.length - 2];\n lines.push({\n x1: prev.x2,\n y1: prev.y2,\n x2: line.x1,\n y2: line.y1,\n scanY: s.scanY,\n isConnector: true,\n });\n }\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Iterates the generated hatch lines and delegates the actual rendering of each\n * segment to the provided callback.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {(x1:number, y1:number, x2:number, y2:number, index:number, segs:Object[]) => void} drawSegment\n */\nfunction renderHatchSegments(polygons, drawSegment) {\n const segs = getHatchLines(polygons);\n withHatchStyle(() => {\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n drawSegment(s.x1, s.y1, s.x2, s.y2, j, segs);\n }\n });\n}\n\n/**\n * Draws classic hatch lines over one polygon or an array of polygons.\n *\n * @param {Polygon|Polygon[]} polygons\n */\nexport function createHatch(polygons) {\n renderHatchSegments(polygons, (x1, y1, x2, y2) => {\n line(x1, y1, x2, y2);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies the currently active hatch modifier to a polygon, or temporarily\n * overrides hatch parameters for this call only.\n *\n * @param {number|false} [_dist=false]\n * @param {number} [_angle]\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [_options]\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (State.hatch.isActive) createHatch(this);\n HatchSetState(state);\n};\n\n/**\n * Converts the plot to a polygon and applies the currently active hatch modifier.\n *\n * @param {number} x\n * @param {number} y\n * @param {number} scale\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.3);\n this.pol.hatch();\n }\n};\n","// =============================================================================\n// Module: Mass\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { arc } from \"../core/primitives.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { rr2, dist, calcAngle } from \"../core/utils.js\";\nimport { fromDegrees, usesRadians } from \"../core/runtime.js\";\nimport { HatchState, HatchSetState, hatch, getHatchLines } from \"./hatch.js\";\nimport { BrushState, BrushSetState, getBrushParams, set } from \"../stroke/stroke.js\";\nimport { wiggle } from \"../core/flowfield.js\";\n\n// ---------------------------------------------------------------------------\n// Mass State\n// ---------------------------------------------------------------------------\n\nState.mass = {\n isActive: false,\n brush: null,\n color: null,\n options: {},\n};\n\n/**\n * Returns a shallow copy of the current mass state.\n * @returns {object}\n */\nexport function MassState() {\n return { ...State.mass };\n}\n\n/**\n * Restores a previously saved mass state.\n * @param {object} state\n */\nexport function MassSetState(state) {\n State.mass = { ...state };\n}\n\n/**\n * Enables massing mode with a brush, color, and optional configuration.\n *\n * @param {string} brush - Brush name to use for the mass pass.\n * @param {string|Color} color - Color to use for the mass pass.\n * @param {object} [options={}] - Massing options such as precision, strength, gradient, and outline.\n */\nexport function mass(brush, color, options = {}) {\n State.mass.brush = brush;\n State.mass.color = color;\n State.mass.options = options;\n State.mass.isActive = true;\n}\n\n/**\n * Disables massing mode for subsequent geometry.\n */\nexport function noMass() {\n State.mass.isActive = false;\n State.mass.brush = null;\n State.mass.color = null;\n State.mass.options = {};\n}\n\n// ---------------------------------------------------------------------------\n// Polygon Preparation\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a translated copy of a polygon.\n * Used to build the secondary mass layers from an existing base polygon.\n * @param {Polygon} polygon\n * @param {number} jitterX\n * @param {number} jitterY\n * @returns {Polygon}\n */\nfunction jitterPolygon(polygon, jitterX, jitterY) {\n return new Polygon(\n polygon.vertices.map((vertex) => [vertex.x + jitterX, vertex.y + jitterY]),\n );\n}\n\n/**\n * Builds the three polygons used for a mass pass.\n * Both polygon and plot inputs use one base polygon plus two translated copies,\n * so plot-based massing only needs a single `genPol(...)` call.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n * @returns {Polygon[]}\n */\nfunction getMassPolygons(shape, x, y, scale) {\n const isPolygon = x === false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const basePolygon = isPolygon ? shape : shape.genPol(x, y, scale, 0.15);\n const maxJitter = Math.min(scatter * 2, 5);\n const jitters = [\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n ];\n\n return [\n basePolygon,\n jitterPolygon(basePolygon, jitters[0][0], jitters[0][1]),\n jitterPolygon(basePolygon, jitters[1][0], jitters[1][1]),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Angle & Bounds Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts degree values into the current runtime angle units.\n * @param {number} angle\n * @returns {number}\n */\nfunction getAngleConverter() {\n return usesRadians()\n ? (angle) => (angle * Math.PI) / 180\n : (angle) => angle;\n}\n\n/**\n * Computes an axis-aligned bounding box for a polygon.\n * The diagonal is used as a size reference for pivot distance.\n * @param {Polygon} polygon\n * @returns {{minX:number,minY:number,maxX:number,maxY:number,cx:number,cy:number,size:number}}\n */\nfunction getPolygonBounds(polygon) {\n const points = polygon?.a ?? [];\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n for (const [x, y] of points) {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n return {\n minX,\n minY,\n maxX,\n maxY,\n cx: (minX + maxX) / 2,\n cy: (minY + maxY) / 2,\n size: Math.hypot(maxX - minX, maxY - minY),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pivot Geometry\n// ---------------------------------------------------------------------------\n\n/**\n * Chooses the diagonal corner family for a whole mass gesture.\n * Positive-angle hatching uses either bottom-right or top-left; negative-angle\n * hatching uses either bottom-left or top-right.\n * @param {number} angleDeg\n * @returns {[number, number]}\n */\nfunction getPivotBias(angleDeg) {\n const normalizedAngle = ((((angleDeg + 90) % 180) + 180) % 180) - 90;\n if (normalizedAngle >= 0) {\n return rr2() < 0.5 ? [1, 1] : [-1, -1];\n } else {\n return rr2() < 0.5 ? [-1, 1] : [1, -1];\n }\n}\n\n/**\n * Places the global pivot anchor outside the polygon, along the selected bias.\n * Distance varies per layer while the bias stays fixed for the whole mass.\n * @param {Polygon} polygon\n * @param {[number, number]} bias\n * @returns {{x:number,y:number}}\n */\nfunction getPivotAnchor(polygon, bias) {\n const bounds = getPolygonBounds(polygon);\n const offset = bounds.size * rr2(0.6, 1.4);\n const [sx, sy] = bias;\n return {\n x: bounds.cx + sx * offset,\n y: bounds.cy + sy * offset,\n };\n}\n\n/**\n * Projects the global pivot anchor onto the perpendicular bisector of a line.\n * This yields a valid circle center equidistant from both endpoints.\n * @param {{x:number,y:number}} anchor\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {{x:number,y:number}|null}\n */\nfunction projectAnchorToBisector(anchor, x1, y1, x2, y2) {\n const mx = (x1 + x2) / 2;\n const my = (y1 + y2) / 2;\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n if (!length) return null;\n const nx = -dy / length;\n const ny = dx / length;\n const offset = (anchor.x - mx) * nx + (anchor.y - my) * ny;\n return {\n x: mx + nx * offset,\n y: my + ny * offset,\n };\n}\n\n/**\n * Returns the shortest arc between two endpoints around a given center.\n * The returned angles are already converted into the current runtime angle units.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {[number, number]}\n */\nfunction getShortArcAngles(cx, cy, x1, y1, x2, y2, toAngleUnit) {\n let startDeg = calcAngle(cx, cy, x1, y1);\n let endDeg = calcAngle(cx, cy, x2, y2);\n const sweep = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweep > 180) [startDeg, endDeg] = [endDeg, startDeg];\n return [\n toAngleUnit(startDeg),\n toAngleUnit(endDeg),\n ];\n}\n\n/**\n * Splits a hatch line into two slightly separated segments so some gestures\n * read as interrupted rather than perfectly continuous.\n * @param {{x1:number,y1:number,x2:number,y2:number}} seg\n * @returns {Array<{x1:number,y1:number,x2:number,y2:number}>}\n */\nfunction splitSegment(seg) {\n const t = rr2(0.35, 0.65);\n const mx = seg.x1 + (seg.x2 - seg.x1) * t;\n const my = seg.y1 + (seg.y2 - seg.y1) * t;\n const dx = seg.x2 - seg.x1;\n const dy = seg.y2 - seg.y1;\n const length = Math.hypot(dx, dy) || 1;\n const gap = rr2(0.04, 0.1) * length;\n const gx = (dx / length) * gap * 0.5;\n const gy = (dy / length) * gap * 0.5;\n return [\n { x1: seg.x1, y1: seg.y1, x2: mx - gx, y2: my - gy },\n { x1: mx + gx, y1: my + gy, x2: seg.x2, y2: seg.y2 },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Mass Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Draws one polygon of the mass as a family of arcs derived from hatch lines.\n * The same pivot bias is used across layers, while each layer gets its own\n * anchor distance from the shape.\n * @param {Polygon} polygon\n * @param {[number, number]} pivotBias\n */\nfunction drawMassArcs(polygon, pivotBias, toAngleUnit) {\n const anchor = getPivotAnchor(polygon, pivotBias);\n for (const seg of getHatchLines(polygon)) {\n const parts = !seg.isConnector && rr2() < 0.35 ? splitSegment(seg) : [seg];\n for (const part of parts) {\n const center = projectAnchorToBisector(anchor, part.x1, part.y1, part.x2, part.y2);\n if (!center) continue;\n const radius = dist(center.x, center.y, part.x1, part.y1);\n if (!radius) continue;\n const [startAngle, endAngle] = getShortArcAngles(\n center.x,\n center.y,\n part.x1,\n part.y1,\n part.x2,\n part.y2,\n toAngleUnit,\n );\n arc(center.x, center.y, radius, startAngle, endAngle);\n }\n }\n}\n\n/**\n * Configures a hatch pass and immediately reinterprets the generated lines as arcs.\n * @param {Polygon} polygon\n * @param {number} dist\n * @param {number} angle\n * @param {object} options\n * @param {[number, number]} pivotBias\n */\nfunction drawMassPass(polygon, dist, angle, options, pivotBias, toAngleUnit) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias, toAngleUnit);\n}\n\n/**\n * Creates the built-in \"massing\" effect for a polygon or plot.\n * A mass is built from up to three jittered polygon layers, each hatched and\n * then redrawn as arc gestures around a shared pivot bias.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n */\nexport function createMass(shape, x, y, scale) {\n const pols = getMassPolygons(shape, x, y, scale);\n const hatchState = HatchState();\n const brushState = BrushState();\n const fieldState = { ...State.field };\n const precision = State.mass.options?.precision ?? 0.5;\n const strength = State.mass.options?.strength ?? 1;\n const gradient = State.mass.options?.gradient ?? 0.1;\n const outline = State.mass.options?.outline ?? false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const hatchDist = 1.6 * rr2(scatter * 0.65, scatter * 0.85) - 0.4 * gradient;\n const baseAngle = rr2(-90, 90);\n const pivotBias = getPivotBias(baseAngle);\n const toAngleUnit = getAngleConverter();\n\n set(State.mass.brush, State.mass.color, 1);\n wiggle(2 - precision);\n if (outline) pols[0].draw();\n\n drawMassPass(\n pols[0],\n hatchDist * 0.9,\n fromDegrees(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n fromDegrees(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n fromDegrees(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n BrushSetState(brushState);\n HatchSetState(hatchState);\n State.field = { ...fieldState };\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies massing to polygon geometry.\n */\nPolygon.prototype.mass = function () {\n if (State.mass?.isActive) {\n createMass(this, false);\n }\n};\n\n/**\n * Applies massing to plots by generating their polygon first.\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.mass = function (x, y, scale) {\n if (State.mass?.isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n createMass(this, x, y, scale);\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","import * as Color from \"../core/color.js\";\nimport {\n createFramebuffer,\n create2DCanvas,\n} from \"../core/compositor_runtime.js\";\n\n// Small staging canvas used to upload only the dirty fill sub-rect into the\n// framebuffer-backed mask mirror consumed by the blend shader.\nlet FillMaskUploadCanvas = null;\nlet isFillCompositeRegistered = false;\nconst DIRTY_FILL_PADDING = 4;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the CPU-side 2D fill mask must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} maskWidth - Mask width in physical pixels.\n * @param {number} maskHeight - Mask height in physical pixels.\n * @returns {boolean} True when the 2D fill mask needs reallocation.\n */\nfunction needsFillMaskCanvas(Renderer, maskWidth, maskHeight) {\n return (\n !Renderer.mask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight\n );\n}\n\n/**\n * Returns whether the framebuffer-backed fill mask mirror must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the fill mask framebuffer needs reallocation.\n */\nfunction needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density) {\n return (\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 );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures fill compositing resources exist for the active renderer.\n *\n * Fill draws first into a CPU-side 2D mask canvas. That mask is later uploaded,\n * dirty-rect by dirty-rect, into a framebuffer-backed mirror used by the final\n * blend shader pass.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {{mask: object, ctx: CanvasRenderingContext2D}} Fill mask resources.\n */\nexport function ensureFillCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n) {\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n\n if (needsFillMaskCanvas(Renderer, maskWidth, maskHeight)) {\n Renderer.mask = create2DCanvas(maskWidth, maskHeight);\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = createFramebuffer(Renderer, {\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 Renderer.mask.dirtyRect ??= null;\n Renderer.mask.isDrawn ??= false;\n Renderer.mask.drawingContext.imageSmoothingEnabled = false;\n return {\n mask: Renderer.mask,\n ctx: Renderer.mask.drawingContext,\n };\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current fill mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Fill mask canvas or framebuffer mirror.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearFillMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the fill dirty rect to composite into the main target. Fill bounds are\n * taken directly from the accumulated 2D mask dirty area plus a small padding.\n *\n * @param {object|null} target - Fill mask canvas.\n * @param {Function} _getActiveFramebuffer - Unused for fill masks.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getFillCompositeRect(\n target,\n _getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_FILL_PADDING),\n );\n}\n\n// =============================================================================\n// Section: Upload\n// =============================================================================\n/**\n * Uploads only the dirty portion of the CPU-side 2D fill mask into the\n * framebuffer-backed fill mask mirror used by the shader compositor.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {object} mask - CPU-side 2D fill mask canvas.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} dirtyRect - Dirty rect to upload.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {object} Framebuffer-backed fill mask mirror.\n */\nexport function getFillShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n) {\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 = create2DCanvas(uploadWidth, uploadHeight);\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 return target;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the fill compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initFillComposite() {\n if (isFillCompositeRegistered) return;\n Color.registerFillComposite?.({\n ensureResources: ensureFillCompositeResources,\n clearMask: clearFillMask,\n getCompositeRect: getFillCompositeRect,\n getShaderMask: getFillShaderMask,\n });\n isFillCompositeRegistered = true;\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\n// Core imports\nimport { Renderer, Cwidth, Cheight, Density } from \"../core/target.js\";\nimport {\n Mix,\n State,\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 } from \"../core/flowfield.js\";\nimport { createColor, getAffineMatrix } from \"../core/runtime.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// Internal module imports\nimport { initFillComposite } from \"./composite.js\";\n\ninitFillComposite(); // Register the fill composite with the core color module\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 = 2024;\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 = arguments.length < 3 ? createColor(a) : createColor(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 === 0) {\n return { x: 0, y: 0 };\n }\n\n if (pts.length < 8) {\n // Simple average for small polygons\n const sum = pts.reduce(\n (center, point) => ({ x: center.x + point.x, y: center.y + point.y }),\n { x: 0, y: 0 },\n );\n return { x: sum.x / pts.length, y: sum.y / 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\n // We want to add at least two vertices to divide the new edge that appears after trimming, at random distances along its path\n const trimStart = s;\n const trimEnd = s + n;\n const edgeStart = this.v[(trimStart - 1 + this.v.length) % this.v.length];\n const edgeEnd = this.v[trimEnd % this.v.length];\n const edgeVec = { x: edgeEnd.x - edgeStart.x, y: edgeEnd.y - edgeStart.y };\n \n // Insert two new vertices at random positions along the new edge\n const insertCount = 2;\n for (let i = 0; i < insertCount; i++) {\n const t = rr(0.25, 0.75); // Random position between 25% and 75% along the edge\n const newVertex = { x: edgeStart.x + edgeVec.x * t, y: edgeStart.y + edgeVec.y * t };\n const insertIdx = s + i;\n v.splice(insertIdx, 0, newVertex);\n m.splice(insertIdx, 0, rr(0.4, 0.7));\n dir.splice(insertIdx, 0, this.dir[trimStart % this.dir.length]);\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 // If mod is smaller than 0.02, skip growing math and just insert the middle vertex\n if (mod < 0.05) {\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedX[insertedIdx] = (cv.x + nv.x) / 2;\n insertedY[insertedIdx] = (cv.y + nv.y) / 2;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n continue;\n }\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 * Math.max(0.1, 2 * State.fill.bleed_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 const m = getAffineMatrix();\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * m.a,\n Density * m.b,\n Density * m.c,\n Density * m.d,\n Density * (m.x + Cwidth / 2),\n Density * (m.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);\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.3);\n const minSizeFactor = 0.03 * minSize;\n const maxSizeFactor = 0.45 * 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 State.fill.bleed_strength < 0.06\n ? 0\n : map(State.fill.bleed_strength, 0, 0.6, 0.2, 0.60, true),\n );\n this.pol.fill();\n }\n};\n","\nexport default function earcut(data, holeIndices, dim = 2) {\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let minX, minY, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = data[0];\n minY = data[1];\n let maxX = minX;\n let maxY = minY;\n\n for (let i = dim; i < outerLen; i += dim) {\n const x = data[i];\n const y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n let last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n } else {\n for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n let p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n let stop = ear;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n const prev = ear.prev;\n const next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n triangles.push(prev.i, ear.i, next.i); // cut off the triangle\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n let p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n // z-order range for the current triangle bbox;\n const minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n let p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles) {\n let p = start;\n do {\n const a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i, p.i, b.i);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n let a = start;\n do {\n let b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n let c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n const queue = [];\n\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n const list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareXYSlope);\n\n // process holes from left to right\n for (let i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareXYSlope(a, b) {\n let result = a.x - b.x;\n // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find\n // the bridge to the outer shell is always the point that they meet at.\n if (result === 0) {\n result = a.y - b.y;\n if (result === 0) {\n const aSlope = (a.next.y - a.y) / (a.next.x - a.x);\n const bSlope = (b.next.y - b.y) / (b.next.x - b.x);\n result = aSlope - bSlope;\n }\n }\n return result;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole(hole, outerNode) {\n const bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n const bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n // unless they intersect at a vertex, then choose the vertex\n if (equals(hole, p)) return p;\n do {\n if (equals(hole, p.next)) return p.next;\n else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n let p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n let numMerges;\n let inSize = 1;\n\n do {\n let p = list;\n let e;\n list = null;\n let tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n let q = p;\n let pSize = 0;\n for (let i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n let qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n let p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a point lies within a convex triangle but false if its equal to the first point of the triangle\nfunction pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {\n return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n let p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n const a2 = createNode(a.i, a.x, a.y),\n b2 = createNode(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n const p = createNode(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction createNode(i, x, y) {\n return {\n i, // vertex index in coordinates array\n x, y, // vertex coordinates\n prev: null, // previous and next vertex nodes in a polygon ring\n next: null,\n z: 0, // z-order curve value\n prevZ: null, // previous and next nodes in z-order\n nextZ: null,\n steiner: false // indicates whether this is a steiner point\n };\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nexport function deviation(data, holeIndices, dim, triangles) {\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n let trianglesArea = 0;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = triangles[i] * dim;\n const b = triangles[i + 1] * dim;\n const c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n}\n\nfunction signedArea(data, start, end, dim) {\n let sum = 0;\n for (let i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nexport function flatten(data) {\n const vertices = [];\n const holes = [];\n const dimensions = data[0][0].length;\n let holeIndex = 0;\n let prevLen = 0;\n\n for (const ring of data) {\n for (const p of ring) {\n for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n }\n if (prevLen) {\n holeIndex += prevLen;\n holes.push(holeIndex);\n }\n prevLen = ring.length;\n }\n return {vertices, holes, dimensions};\n}\n","// =============================================================================\n// Module: Wash\n// =============================================================================\n/**\n * Minimal stateful API for the `wash()` fill modifier.\n */\n\nimport earcut from \"earcut\";\nimport { Renderer, Cwidth, Cheight, isCanvasReady } from \"../core/target.js\";\nimport { State, flushActiveComposite } from \"../core/color.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { resetDirectShaderTracking } from \"../core/renderer_runtime.js\";\n\nlet gl = null;\nlet washProgram = null;\nlet washVao = null;\nlet washBuffer = null;\nlet washProjection = null;\nlet loadedWidth = 0;\nlet loadedHeight = 0;\nlet washGpuBufferSize = 0;\n\nconst WashAttr = {};\nconst WashUniform = {};\n\nconst washVertSrc = `#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}`;\n\nconst washFragSrc = `#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}`;\n\nState.wash = {\n color: null,\n opacity: 150,\n isActive: false,\n};\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Enables wash mode with a color and opacity.\n *\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 wash(a, b, c, d) {\n isCanvasReady();\n State.wash.opacity = (arguments.length < 4 ? b : d) ?? 150;\n State.wash.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.wash.isActive = true;\n}\n\n/**\n * Disables wash mode for subsequent drawing operations.\n */\nexport function noWash() {\n State.wash.isActive = false;\n}\n\n// =============================================================================\n// GL helpers\n// =============================================================================\n\n/**\n * Lazily creates the reusable program/buffer state for solid wash drawing and\n * refreshes the orthographic projection when the active target size changes.\n */\nfunction ensureWashReady() {\n const nextGl = Renderer.drawingContext;\n const sizeChanged = loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (!washProjection || sizeChanged) {\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n washProjection = new Float32Array([\n 2 / loadedWidth,\n 0,\n 0,\n 0,\n 0,\n -2 / loadedHeight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n }\n\n if (gl === nextGl && washProgram && washVao && washBuffer) return;\n\n gl = nextGl;\n washProgram = createProgram(gl, washVertSrc, washFragSrc);\n WashAttr.a_position = gl.getAttribLocation(washProgram, \"a_position\");\n WashUniform.u_matrix = gl.getUniformLocation(washProgram, \"u_matrix\");\n WashUniform.u_color = gl.getUniformLocation(washProgram, \"u_color\");\n\n washVao = gl.createVertexArray();\n gl.bindVertexArray(washVao);\n\n washBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, 0, gl.DYNAMIC_DRAW);\n washGpuBufferSize = 0;\n\n gl.enableVertexAttribArray(WashAttr.a_position);\n gl.vertexAttribPointer(WashAttr.a_position, 2, gl.FLOAT, false, 8, 0);\n\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n}\n\n/**\n * Applies the current runtime affine transform and converts the result into\n * the screen-space coordinates used by the direct GL wash pipeline.\n *\n * @param {number} x - The source x-coordinate in brush drawing space.\n * @param {number} y - The source y-coordinate in brush drawing space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n const m = getAffineMatrix();\n return [\n m.a * x + m.c * y + m.x + loadedWidth / 2,\n m.b * x + m.d * y + m.y + loadedHeight / 2,\n ];\n}\n\n/**\n * Triangulates a polygon in local space and returns the transformed triangle\n * vertex buffer ready for upload to the GPU.\n *\n * @param {Polygon} polygon - The polygon to triangulate.\n * @returns {{ triangles: Float32Array, vertexCount: number }} Screen-space\n * triangle vertices plus the number of vertices to draw.\n */\nfunction buildTriangleBuffer(polygon) {\n const flat = new Float32Array(polygon.vertices.length * 2);\n for (let i = 0; i < polygon.vertices.length; i++) {\n const vertex = polygon.vertices[i];\n flat[i * 2] = vertex.x;\n flat[i * 2 + 1] = vertex.y;\n }\n\n const indices = earcut(flat);\n const triangles = new Float32Array(indices.length * 2);\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n const [screenX, screenY] = transformVertexToScreen(flat[idx * 2], flat[idx * 2 + 1]);\n triangles[i * 2] = screenX;\n triangles[i * 2 + 1] = screenY;\n }\n\n return {\n triangles,\n vertexCount: indices.length,\n };\n}\n\n/**\n * Draws a triangulated solid wash directly to the current GL target.\n *\n * @param {Polygon} polygon - The polygon to fill with the current wash state.\n */\nfunction drawWashPolygon(polygon) {\n if (!State.wash?.isActive || !State.wash.color || polygon.vertices.length < 3) return;\n\n flushActiveComposite();\n ensureWashReady();\n const { triangles, vertexCount } = buildTriangleBuffer(polygon);\n const byteCount = triangles.byteLength;\n gl.useProgram(washProgram);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.bindVertexArray(washVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n if (byteCount > washGpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.DYNAMIC_DRAW);\n washGpuBufferSize = byteCount;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, triangles);\n }\n const color = State.wash.color._array;\n gl.uniformMatrix4fv(WashUniform.u_matrix, false, washProjection);\n gl.uniform4f(\n WashUniform.u_color,\n color[0],\n color[1],\n color[2],\n State.wash.opacity / 255,\n );\n\n gl.drawArrays(gl.TRIANGLES, 0, vertexCount);\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n resetDirectShaderTracking(Renderer, gl);\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct GL wash fill to the polygon using the current wash state.\n *\n * @param {Color|string|false} [_color] - Optional override color for this call.\n * @param {number} [_opacity] - Optional override opacity for this call.\n */\nPolygon.prototype.wash = function (_color = false, _opacity) {\n const state = { ...State.wash };\n if (_color !== false) wash(_color, _opacity);\n\n if (State.wash.isActive) {\n drawWashPolygon(this);\n }\n\n State.wash = { ...state };\n};\n\n/**\n * Applies wash to a plot by first generating the plot polygon, mirroring the\n * existing fill-path behavior, and then drawing that polygon with wash.\n *\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\nPlot.prototype.wash = function (x, y, scale) {\n if (!State.wash?.isActive) return;\n if (this.origin) {\n x = this.origin[0];\n y = this.origin[1];\n scale = 1;\n }\n this.pol = this.genPol(x, y, scale, 0, -1);\n this.pol.wash();\n};\n","// =============================================================================\n// Adapter: Standalone Renderer Hooks\n// =============================================================================\n\nimport { Cwidth, Cheight, Density } from \"../../core/target.js\";\nimport { setRendererRuntime } from \"../../core/renderer_runtime.js\";\n\nfunction beginDirectMaskDraw(_renderer, gl, target) {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n\n return { hadDepthTest };\n}\n\nfunction endDirectMaskDraw(renderer, gl, state) {\n if (state?.hadDepthTest) gl.enable(gl.DEPTH_TEST);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.viewport(\n 0,\n 0,\n Math.max(1, Math.round(Cwidth * Density)),\n Math.max(1, Math.round(Cheight * Density)),\n );\n}\n\nfunction resetStandaloneShaderTracking(_renderer, gl) {\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\nexport function initStandaloneRendererRuntime() {\n setRendererRuntime({\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking: resetStandaloneShaderTracking,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Compositor Hooks\n// =============================================================================\n\nimport { createProgram } from \"../../core/gl/utils.js\";\nimport {\n setCompositorRuntime,\n blitDefaultFramebufferSource,\n} from \"../../core/compositor_runtime.js\";\n\nfunction clearTarget(renderer, target, isFramebufferTarget) {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n const gl = renderer.drawingContext;\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousViewport = gl.getParameter(gl.VIEWPORT);\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\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 gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n gl.viewport(\n previousViewport[0],\n previousViewport[1],\n previousViewport[2],\n previousViewport[3],\n );\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\nfunction makeShader(gl, vertSrc, fragSrc) {\n const program = createProgram(gl, vertSrc, fragSrc);\n const uniformCache = new Map();\n\n const getUniformLocation = (name) => {\n if (!uniformCache.has(name)) {\n uniformCache.set(name, gl.getUniformLocation(program, name));\n }\n return uniformCache.get(name);\n };\n\n return {\n program,\n setUniform(name, value) {\n const location = getUniformLocation(name);\n if (!location) return;\n if (typeof value === \"boolean\") {\n gl.uniform1i(location, value ? 1 : 0);\n return;\n }\n if (typeof value === \"number\") {\n gl.uniform1f(location, value);\n return;\n }\n if (Array.isArray(value)) {\n if (value.length === 3) gl.uniform3f(location, value[0], value[1], value[2]);\n else if (value.length === 4) gl.uniform4f(location, value[0], value[1], value[2], value[3]);\n return;\n }\n },\n };\n}\n\nfunction ensureBlendShaderProgram(renderer, vertSrc, fragSrc) {\n renderer.shaderProgram ??= makeShader(renderer.drawingContext, vertSrc, fragSrc);\n return renderer.shaderProgram;\n}\n\nfunction createFramebufferTexture(gl, width, height) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n gl.RGBA,\n width,\n height,\n 0,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n null,\n );\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 gl.bindTexture(gl.TEXTURE_2D, null);\n return texture;\n}\n\nfunction createFramebuffer(renderer, options) {\n const gl = renderer.drawingContext;\n const density = options.density ?? 1;\n const framebuffer = gl.createFramebuffer();\n const width = Math.max(1, options.width);\n const height = Math.max(1, options.height);\n const pixelWidth = Math.max(1, Math.round(width * density));\n const pixelHeight = Math.max(1, Math.round(height * density));\n const colorTexture = createFramebufferTexture(gl, pixelWidth, pixelHeight);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER,\n gl.COLOR_ATTACHMENT0,\n gl.TEXTURE_2D,\n colorTexture,\n 0,\n );\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n\n return {\n __brushFramebuffer: true,\n framebuffer,\n colorTexture,\n width,\n height,\n density,\n pixelDensity: () => density,\n remove() {\n gl.deleteFramebuffer(framebuffer);\n gl.deleteTexture(colorTexture);\n },\n };\n}\n\nfunction ensureBlendSourceFramebuffer(\n renderer,\n currentFramebuffer,\n width,\n height,\n density,\n) {\n currentFramebuffer?.remove?.();\n return createFramebuffer(renderer, {\n width,\n height,\n density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n}\n\nfunction runBlendShaderPass({\n renderer,\n shader,\n source,\n mask,\n color,\n isBrushMask,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n}) {\n const gl = renderer.drawingContext;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousProgram = gl.getParameter(gl.CURRENT_PROGRAM);\n const previousVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);\n\n const quadVao = gl.createVertexArray();\n gl.bindVertexArray(quadVao);\n gl.useProgram(shader.program);\n gl.disable(gl.DEPTH_TEST);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, source.colorTexture);\n gl.uniform1i(gl.getUniformLocation(shader.program, \"u_source\"), 0);\n\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, mask.colorTexture);\n gl.uniform1i(gl.getUniformLocation(shader.program, \"u_mask\"), 1);\n\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n gl.uniform3f(\n gl.getUniformLocation(shader.program, \"u_color\"),\n color[0],\n color[1],\n color[2],\n );\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n withScissor(\n gl,\n dirtyRect,\n () => {\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n },\n !targetIsFramebuffer,\n );\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.activeTexture(gl.TEXTURE0);\n gl.bindVertexArray(previousVao);\n gl.useProgram(previousProgram);\n gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n gl.deleteVertexArray(quadVao);\n}\n\nfunction blitSourceToFramebuffer(args) {\n return blitDefaultFramebufferSource(args);\n}\n\nexport function initStandaloneCompositorRuntime() {\n setCompositorRuntime({\n clearTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n createFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Stroke Hooks\n// =============================================================================\n\nimport { create2DCanvas, get2DContext } from \"../../core/compositor_runtime.js\";\nimport { setStrokeRuntime } from \"../../stroke/runtime.js\";\n\nfunction cssColor(value) {\n if (typeof value === \"number\") {\n const c = Math.max(0, Math.min(255, value));\n return `rgb(${c} ${c} ${c})`;\n }\n return value ?? \"black\";\n}\n\nfunction buildTipSurface(canvas) {\n const ctx = get2DContext(canvas, true);\n const surface = {\n canvas,\n drawingContext: ctx,\n width: canvas.width,\n height: canvas.height,\n pixels: null,\n _fillStyle: \"#ffffff\",\n _strokeStyle: \"transparent\",\n _lineWidth: 1,\n\n pixelDensity() {\n return 1;\n },\n\n background(value) {\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.fillStyle = cssColor(value);\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n ctx.restore();\n },\n\n noSmooth() {\n ctx.imageSmoothingEnabled = false;\n },\n\n push() {\n ctx.save();\n },\n\n pop() {\n ctx.restore();\n },\n\n translate(x, y) {\n ctx.translate(x, y);\n },\n\n scale(x, y = x) {\n ctx.scale(x, y);\n },\n\n rotate(angle) {\n ctx.rotate(angle);\n },\n\n noStroke() {\n surface._strokeStyle = \"transparent\";\n },\n\n stroke(value) {\n surface._strokeStyle = cssColor(value);\n },\n\n noFill() {\n surface._fillStyle = \"transparent\";\n },\n\n fill(value) {\n surface._fillStyle = cssColor(value);\n },\n\n strokeWeight(value) {\n surface._lineWidth = value;\n },\n\n rect(x, y, w, h) {\n ctx.beginPath();\n ctx.rect(x, y, w, h);\n surface._paint();\n },\n\n circle(x, y, d) {\n ctx.beginPath();\n ctx.arc(x, y, d / 2, 0, Math.PI * 2);\n surface._paint();\n },\n\n ellipse(x, y, w, h) {\n ctx.beginPath();\n ctx.ellipse(x, y, w / 2, h / 2, 0, 0, Math.PI * 2);\n surface._paint();\n },\n\n line(x1, y1, x2, y2) {\n ctx.beginPath();\n ctx.moveTo(x1, y1);\n ctx.lineTo(x2, y2);\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n },\n\n beginShape() {\n ctx.beginPath();\n surface._shapeStarted = false;\n },\n\n vertex(x, y) {\n if (!surface._shapeStarted) {\n ctx.moveTo(x, y);\n surface._shapeStarted = true;\n } else {\n ctx.lineTo(x, y);\n }\n },\n\n endShape(close = false) {\n if (close) ctx.closePath();\n surface._paint();\n },\n\n loadPixels() {\n surface.pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;\n },\n\n updatePixels() {\n const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n imageData.data.set(surface.pixels);\n ctx.putImageData(imageData, 0, 0);\n },\n\n _paint() {\n if (surface._fillStyle !== \"transparent\") {\n ctx.fillStyle = surface._fillStyle;\n ctx.fill();\n }\n if (surface._strokeStyle !== \"transparent\") {\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n }\n },\n };\n\n return surface;\n}\n\nfunction createTipSurface(width, height) {\n return buildTipSurface(create2DCanvas(width, height, true));\n}\n\nfunction loadImageTip(src, imageToWhite) {\n return new Promise((resolve, reject) => {\n const NativeImage = globalThis.Image;\n if (!NativeImage) {\n reject(new Error(\"Standalone image brush loading requires Image support.\"));\n return;\n }\n\n const nativeImg = new NativeImage();\n nativeImg.onload = () => {\n const surface = buildTipSurface(\n create2DCanvas(nativeImg.naturalWidth, nativeImg.naturalHeight, true),\n );\n surface.drawingContext.drawImage(nativeImg, 0, 0);\n imageToWhite(surface);\n resolve(surface);\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\nexport function initStandaloneStrokeRuntime() {\n setStrokeRuntime({\n createTipSurface,\n loadImageTip,\n });\n}\n","/**\n * @fileoverview Standalone entry point for brush.\n */\n\nexport * from \"./adapters/standalone/runtime.js\";\nexport * from \"./adapters/standalone/frame.js\";\nexport { createCanvas } from \"./adapters/standalone/target.js\";\nexport * from \"./index.shared.js\";\n\nimport { initStandaloneTargetRuntime } from \"./adapters/standalone/target.js\";\nimport { initStandaloneRendererRuntime } from \"./adapters/standalone/renderer.js\";\nimport { initStandaloneCompositorRuntime } from \"./adapters/standalone/compositor.js\";\nimport { initStandaloneStrokeRuntime } from \"./adapters/standalone/stroke.js\";\nimport { initStandaloneRuntime } from \"./adapters/standalone/runtime.js\";\n\ninitStandaloneTargetRuntime();\ninitStandaloneRuntime();\ninitStandaloneRendererRuntime();\ninitStandaloneCompositorRuntime();\ninitStandaloneStrokeRuntime();\n","// =============================================================================\n// Adapter: Standalone Frame Helpers\n// =============================================================================\n\nimport { Renderer, isCanvasReady } from \"../../core/target.js\";\nimport { Mix, flushActiveComposite } from \"../../core/color.js\";\nimport { createColor } from \"../../core/runtime.js\";\n\nfunction resetCompositeState() {\n if (Mix.glMask) Mix.clearMask(Mix.glMask);\n if (Mix.mask) Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n}\n\n/**\n * Flushes any pending stroke/fill compositing into the active standalone target.\n *\n * Standalone users should call this at the end of a drawing pass or frame.\n */\nexport function render() {\n flushActiveComposite();\n}\n\n/**\n * Clears the active standalone target.\n *\n * With no arguments, clears to transparent white.\n * With a color, clears to that color at full opacity.\n *\n * @param {...*} args\n */\nexport function clear(...args) {\n isCanvasReady();\n resetCompositeState();\n\n const gl = Renderer.drawingContext;\n const color =\n args.length === 0\n ? [1, 1, 1, 0]\n : [...createColor(...args)._array.slice(0, 3), 1];\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.disable(gl.SCISSOR_TEST);\n gl.clearColor(color[0], color[1], color[2], color[3]);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n}\n"],"names":["identityMatrix","a","b","c","d","x","y","Cwidth","Cheight","Renderer","Density","usesRadians","fromDegrees","angle","createColor","Error","getAffineMatrix","targetRuntime","load","syncDensity","isCanvasReady","instance","inst","activateInstance","deactivateInstance","getActiveFramebuffer","isFramebufferTarget","setTargetState","state","Instance","target","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","create2DCanvas","width","height","willReadFrequently","canvas","OffscreenCanvas","element","document","createElement","drawingContext","getContext","undefined","compositorRuntime","clearTarget","ensureBlendShaderProgram","ensureBlendSourceFramebuffer","createFramebuffer","runBlendShaderPass","blitSourceToFramebuffer","args","strokeComposite","fillComposite","clearRenderTarget","getTargetPixelSize","Math","max","round","normalizeDirtyRect","floor","min","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","draw","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","this","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","pixelDensity","ensureResources","fillResources","mask","ctx","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","shaderProgram","activeFramebuffer","source","renderer","sourceTarget","sourceFramebuffer","targetIsFramebuffer","shaderMask","getShaderMask","color","flushActiveComposite","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","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","push","noise","noise2","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","withinBounds","constrain","low","high","nAngle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","sin","toDegrees","rad","isRad","runtimeUsesRadians","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","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","m","mx","my","update","plotted","colIdx","rowIdx","reset","isIn","isActive","isInCanvas","skipCheck","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","steps","fieldActive","usePlot","getRowIndex","y_offset","getColIndex","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","angleMode","has","generateField","entry","normalizeFieldAngles","gen","keys","join","name","funct","set","fn","_stateStack","clamp","DEGREES","RADIANS","colorContext","currentAngleMode","transformStack","currentTransform","multiplyTransform","left","right","Color","g","hex","rgbToHex","standardize","rgb","hexToRgb","toString","slice","replace","_match","red","green","blue","result","exec","getColorContext","fillStyle","_getRed","_getGreen","_getBlue","initStandaloneRuntime","hooks","_current","_curvature","_strokeArray","_strokeOrigin","activeTarget","activeDensity","activeWidth","activeHeight","applyLoadedTarget","density","premultipliedAlpha","getTargetContext","createRenderer","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","wash","mass","hatch","stroke","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","pop","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","arc","radius","startDeg","sweepDeg","segmentCount","segmentSweep","arcLength","startX","startY","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","halfDist","asin","origin","strokeRuntime","createTipSurface","loadImageTip","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","createShader","shaderSource","compileShader","attachShader","linkProgram","rendererRuntime","beginDirectMaskDraw","endDirectMaskDraw","resetDirectShaderTracking","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","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","getProjectionMatrix","beginMaskTarget","endMaskTarget","accumulateDirtyRect","currentRect","circle","diameter","alpha","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","targetState","tex","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","activeTexture","TEXTURE0","uniform1i","u_tex","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","flush","needsStrokeMask","remove","antialias","depth","stencil","_Renderer","weight","opacity","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","add","params","includes","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","mode","rest","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","background","noSmooth","translate","noStroke","T","imageToWhite","tips","tipKey","param","colors","buffers","image","getBrushParams","brushName","pick","arguments","strokeWeight","_position","initializeDrawingState","plot","snapshotMatrix","gaussians","angleScale","isPlot","cp","ct","cs","ck","noiseoffset","rendererMask","ensureBrushMaskTarget","nextGl","needsContextRefresh","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","clear","STATIC_DRAW","a_corner","a_pos","IMG_FLOATS","vertexAttribDivisor","a_size","a_angle","isReady","switchingToBrush","saveState","stepSize","spacing","totalSteps","pressureCount","cachedPressure","lineNoiseCount","cachedLineNoise","u_matrix","drawArrays","POINTS","glDraw","restoreState","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawImageTip","plotAngle","plotCos","plotSin","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","vibrate","rx","ry","size","overscan","maxPressure","scatterReach","tipReach","getImageTipOverscan","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","then","HatchState","HatchSetState","rand","continuous","gradient","scanlineHatch","polygon","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","scanY","getHatchLines","polygons","segs","poly","getHatchSegments","getActiveHatchConfig","lines","isConnector","prev","createHatch","drawSegment","save","hBrush","Object","values","drawFn","withHatchStyle","renderHatchSegments","jitterPolygon","jitterX","jitterY","projectAnchorToBisector","anchor","nx","ny","getShortArcAngles","toAngleUnit","endDeg","splitSegment","seg","gap","gx","gy","drawMassArcs","pivotBias","bias","bounds","getPolygonBounds","sx","sy","getPivotAnchor","parts","part","center","startAngle","endAngle","drawMassPass","createMass","shape","pols","isPolygon","brush","basePolygon","maxJitter","jitters","getMassPolygons","hatchState","brushState","fieldState","precision","strength","outline","hatchDist","baseAngle","_dist","_angle","_options","FillMaskUploadCanvas","isFillCompositeRegistered","maskWidth","maskHeight","needsFillMaskCanvas","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","clearRect","drawImage","colorTexture","texSubImage2D","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","keep","dst","trimStart","trimEnd","edgeStart","edgeEnd","edgeVec","newVertex","insertIdx","splice","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","setTransform","strokeStyle","lineCap","darker","sparse","layer","numLayers","erase","restore","lineWidth","matrix","getTransform","beginPath","first","tx","ty","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","filterPoints","again","steiner","equals","area","removeNode","earcutLinked","ear","triangles","dim","invSize","pass","z","zOrder","prevZ","nextZ","numMerges","inSize","tail","q","pSize","qSize","sortLinked","indexCurve","stop","isEarHashed","isEar","cureLocalIntersections","splitEarcut","ax","bx","pointInTriangleExceptFirst","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","pointInTriangle","intersectsPolygon","inside","middleInside","q1","q2","o1","sign","o2","o3","o4","onSegment","num","createNode","b2","an","bp","insertNode","last","_opacity","_bleed","fluid","modifiers","_","shift","shifted","pts","point","cross","_center","createFill","FillSetState","washProgram","washVao","washBuffer","washProjection","washGpuBufferSize","WashAttr","WashUniform","transformVertexToScreen","_renderer","hadDepthTest","isEnabled","DEPTH_TEST","bindFramebuffer","FRAMEBUFFER","framebuffer","viewport","resetStandaloneShaderTracking","blendEquation","FUNC_ADD","ONE_MINUS_SRC_ALPHA","previousFramebuffer","getParameter","FRAMEBUFFER_BINDING","previousViewport","VIEWPORT","clearColor","COLOR_BUFFER_BIT","vertSrc","fragSrc","uniformCache","setUniform","location","uniform3f","uniform1f","makeShader","pixelWidth","pixelHeight","createFramebufferTexture","framebufferTexture2D","COLOR_ATTACHMENT0","__brushFramebuffer","deleteFramebuffer","currentFramebuffer","previousProgram","CURRENT_PROGRAM","previousVao","VERTEX_ARRAY_BINDING","quadVao","TEXTURE1","TRIANGLES","deleteVertexArray","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","blitFramebuffer","NEAREST","blitDefaultFramebufferSource","cssColor","buildTipSurface","get2DContext","surface","_fillStyle","_strokeStyle","_lineWidth","fillRect","noFill","_paint","ellipse","_shapeStarted","getImageData","imageData","putImageData","resolve","reject","NativeImage","globalThis","Image","nativeImg","onload","naturalWidth","naturalHeight","onerror","crossOrigin","ensureWashReady","vertexCount","flat","holeIndices","outerLen","outerNode","signedArea","linkedList","earcut","buildTriangleBuffer","drawWashPolygon","HTMLCanvasElement","isCanvasTarget","isOffscreenCanvasTarget","isSupportedTarget","initStandaloneRendererRuntime","initStandaloneCompositorRuntime","initStandaloneStrokeRuntime","angleOffset","randomFactor","randomAngle","offsetX","offsetY","DEPTH_BUFFER_BIT","region","logicalWidth","logicalHeight","Number","style","id","parent","querySelector","appendChild","buffer","loadTarget","saved","popState","currentField","theta","cosTheta","sinTheta","callback","_array_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,GACpBE,EAAWnmC,KAAKiL,IAAIg7B,GAC1BlzB,GAAmBC,GAAkBD,GAAkB,CACrD5W,EAAG+pC,EACH9pC,EAAG+pC,EACH9pC,GAAI8pC,EACJ7pC,EAAG4pC,EACH3pC,EAAG,EACHC,EAAG,GAEP,UAQO,SAAeD,EAAGC,EAAID,GAC3BwW,GAAmBC,GAAkBD,GAAkB,CACrD5W,EAAGI,EACHH,EAAG,EACHC,EAAG,EACHC,EAAGE,EACHD,EAAG,EACHC,EAAG,GAEP,iBUsBO,SAAsBqU,GAC3B,IAAK,MAAMyU,MAAEA,KAAWxV,GAAKue,SACvB/I,IACFA,EAAMxC,QAAUjS,EAChByU,EAAM5B,SAAW7S,EACjByU,EAAMgD,SAAWzX,EAGvB,SblNqBpL,IACnB2C,EAAMxB,EAAUnB,GAChB4C,EAAOzB,EAAU,GAAGnB,OACpB,IAAK,MAAM2gC,KAAY99B,EACrB89B,uBKuNG,SAAgBC,EAAe1xB,EAAa,IACjD,IAAK0xB,GAAiBA,EAAcz+B,OAAS,EAC3C,MAAM,IAAI3K,MACR,+EAGI2c,GAAcysB,EAAe1xB,GACnC5T,MACJ,4CF7FO,SAAmBxE,EAAGC,GAC3BuW,GAAmBC,GAAkBD,GAAkB,CACrD5W,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,IACAC,KAEJ","x_google_ignoreList":[5,6,26]}
\ No newline at end of file
+{"version":3,"file":"brush.js","sources":["../src/core/runtime.js","../src/core/target.js","../src/core/dirty_rect.js","../src/core/compositor_runtime.js","../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/save.js","../src/adapters/standalone/runtime.js","../src/adapters/standalone/target.js","../src/core/primitives.js","../src/core/polygon.js","../src/core/plot.js","../src/stroke/runtime.js","../src/stroke/composite.js","../src/core/gl/utils.js","../src/core/renderer_runtime.js","../src/stroke/gl_draw.js","../src/stroke/stroke.js","../src/hatch/hatch.js","../src/hatch/mass.js","../src/fill/mask.js","../src/fill/composite.js","../src/fill/fill.js","../node_modules/earcut/src/earcut.js","../src/fill/wash.js","../src/adapters/standalone/renderer.js","../src/adapters/standalone/compositor.js","../src/adapters/standalone/stroke.js","../src/index.standalone.js","../src/adapters/standalone/frame.js"],"sourcesContent":["// =============================================================================\n// Runtime Hooks\n// =============================================================================\n\nconst identityMatrix = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nexport let usesRadians = () => false;\nexport let fromDegrees = (angle) => angle;\nexport let createColor = () => {\n throw new Error(\"No runtime color adapter registered.\");\n};\nexport let getAffineMatrix = () => identityMatrix;\n\n/**\n * Registers or updates host-runtime hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setRuntime(hooks) {\n if (hooks.usesRadians) usesRadians = hooks.usesRadians;\n if (hooks.fromDegrees) fromDegrees = hooks.fromDegrees;\n if (hooks.createColor) createColor = hooks.createColor;\n if (hooks.getAffineMatrix) getAffineMatrix = hooks.getAffineMatrix;\n}\n","// =============================================================================\n// Target Runtime Hooks\n// =============================================================================\n\n/**\n * Shared target state exposed to core modules.\n *\n * Host adapters are expected to keep these bindings updated with the currently\n * active drawing target. The exact object type is adapter-defined, but core code\n * assumes the active renderer exposes:\n * - `drawingContext`: the active WebGL context\n * - target dimensions through `Cwidth` / `Cheight`\n * - pixel density through `Density`\n */\n\nexport let Cwidth, Cheight, Instance, Renderer, Density;\n\nlet targetRuntime = {\n load: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n syncDensity: () => Density,\n isCanvasReady: () => {\n throw new Error(\"No target runtime adapter registered.\");\n },\n instance: (inst) => {\n Instance = inst;\n },\n activateInstance: (inst) => {\n Instance = inst;\n },\n deactivateInstance: () => {},\n getActiveFramebuffer: () => null,\n isFramebufferTarget: () => false,\n};\n\n/**\n * Updates the shared target state consumed by core modules.\n *\n * @param {object} state\n */\nexport function setTargetState(state) {\n if (\"Cwidth\" in state) Cwidth = state.Cwidth;\n if (\"Cheight\" in state) Cheight = state.Cheight;\n if (\"Instance\" in state) Instance = state.Instance;\n if (\"Renderer\" in state) Renderer = state.Renderer;\n if (\"Density\" in state) Density = state.Density;\n}\n\n/**\n * Registers or updates host target hooks used by core modules.\n *\n * @param {object} hooks\n */\nexport function setTargetRuntime(hooks) {\n targetRuntime = { ...targetRuntime, ...hooks };\n}\n\nexport const load = (buffer = false) => targetRuntime.load(buffer);\nexport const syncDensity = () => targetRuntime.syncDensity();\nexport const isCanvasReady = () => targetRuntime.isCanvasReady();\nexport const instance = (inst) => targetRuntime.instance(inst);\nexport const activateInstance = (inst) => targetRuntime.activateInstance(inst);\nexport const deactivateInstance = () => targetRuntime.deactivateInstance();\nexport const getActiveFramebuffer = () => targetRuntime.getActiveFramebuffer();\nexport const isFramebufferTarget = (target) =>\n targetRuntime.isFramebufferTarget(target);\n","// =============================================================================\n// Module: Dirty Rect Utilities\n// =============================================================================\n/**\n * Expands a dirty rectangle outward by a constant padding value.\n *\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 */\nexport const 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 explicit target bounds.\n *\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} rect - Candidate rect.\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Clamped rect.\n */\nexport const normalizeDirtyRect = (rect, width, height) => {\n if (!rect) return null;\n\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 *\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 */\nexport const 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 target bounds.\n *\n * @param {number} width - Target width in physical pixels.\n * @param {number} height - Target height in physical pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}} Full-target rect.\n */\nexport const getFullDirtyRect = (width, height) => ({\n minX: 0,\n minY: 0,\n maxX: width,\n maxY: height,\n});\n","// =============================================================================\n// Compositor Runtime Hooks\n// =============================================================================\n\n/**\n * Shared compositor helpers and host hooks.\n *\n * The shared code in this module assumes framebuffer-like targets expose:\n * - `framebuffer`: native WebGL framebuffer handle\n * - optional lifecycle methods supplied by the host adapter\n *\n * Higher-level core modules also attach their own bookkeeping fields onto the\n * active renderer and mask targets, such as:\n * - `shaderProgram`\n * - `blendSourceFramebuffer`\n * - `glMask`\n * - `fillMaskFramebuffer`\n * - `mask`\n *\n * These are library-level contract fields, not host-specific internals.\n */\n\nexport const create2DCanvas = (width, height, willReadFrequently = false) => {\n const canvas =\n typeof OffscreenCanvas !== \"undefined\"\n ? new OffscreenCanvas(width, height)\n : (() => {\n const element = document.createElement(\"canvas\");\n element.width = width;\n element.height = height;\n return element;\n })();\n canvas.drawingContext = canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas;\n};\n\nexport const get2DContext = (canvas, willReadFrequently = false) => {\n canvas.drawingContext ??= canvas.getContext(\n \"2d\",\n willReadFrequently ? { willReadFrequently: true } : undefined,\n );\n return canvas.drawingContext;\n};\n\nexport function blitDefaultFramebufferSource({\n renderer,\n sourceFramebuffer,\n dirtyRect,\n getTargetPixelSize,\n toScissorBox,\n}) {\n const gl = renderer.drawingContext;\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 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\nlet compositorRuntime = {\n clearTarget: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendShaderProgram: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n ensureBlendSourceFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n createFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n runBlendShaderPass: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n blitSourceToFramebuffer: () => {\n throw new Error(\"No compositor runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host compositor hooks used by core compositing code.\n *\n * @param {object} hooks\n */\nexport function setCompositorRuntime(hooks) {\n compositorRuntime = { ...compositorRuntime, ...hooks };\n}\n\nexport const clearTarget = (...args) => compositorRuntime.clearTarget(...args);\nexport const ensureBlendShaderProgram = (...args) =>\n compositorRuntime.ensureBlendShaderProgram(...args);\nexport const ensureBlendSourceFramebuffer = (...args) =>\n compositorRuntime.ensureBlendSourceFramebuffer(...args);\nexport const createFramebuffer = (...args) =>\n compositorRuntime.createFramebuffer(...args);\nexport const runBlendShaderPass = (...args) =>\n compositorRuntime.runBlendShaderPass(...args);\nexport const blitSourceToFramebuffer = (...args) =>\n compositorRuntime.blitSourceToFramebuffer(...args);\n","import {\n Cwidth,\n Cheight,\n Renderer,\n Density,\n load as loadTarget,\n isCanvasReady,\n syncDensity,\n getActiveFramebuffer,\n isFramebufferTarget,\n} from \"./target.js\";\nimport {\n expandDirtyRect,\n normalizeDirtyRect as clampDirtyRect,\n unionDirtyRect,\n getFullDirtyRect as getFullRect,\n} from \"./dirty_rect.js\";\nimport {\n clearTarget as clearRenderTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n} from \"./compositor_runtime.js\";\n\nimport 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\nlet strokeComposite = null;\nlet fillComposite = null;\n\nexport const registerStrokeComposite = (composite) => {\n strokeComposite = composite;\n};\n\nexport const registerFillComposite = (composite) => {\n fillComposite = composite;\n};\n\nconst clearTarget = (target) => {\n clearRenderTarget(Renderer, target, isFramebufferTarget);\n};\n\n// =============================================================================\n// Section: Dirty Rect Utilities\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\nconst normalizeDirtyRect = (rect) => {\n if (!rect) return null;\n const { width, height } = getTargetPixelSize();\n return clampDirtyRect(rect, width, height);\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 getFullRect(width, 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 * 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/**\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: null,\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 const composite = target === this.glMask ? strokeComposite : fillComposite;\n composite?.clearMask?.(target, clearTarget);\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 GL brush mask.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\n getCompositeRect(target, isBrushMask) {\n const composite = isBrushMask ? strokeComposite : fillComposite;\n return composite?.getCompositeRect?.(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\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 syncDensity();\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 ensureBlendShaderProgram(Renderer, vertSrc, fragSrc);\n\n this.glMask = strokeComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n );\n const fillResources = fillComposite?.ensureResources?.(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n ) ?? {\n mask: null,\n ctx: null,\n };\n\n if (needsBlendSourceFramebuffer) {\n Renderer.blendSourceFramebuffer = ensureBlendSourceFramebuffer(\n Renderer,\n Renderer.blendSourceFramebuffer,\n Cwidth,\n Cheight,\n Density,\n );\n }\n\n this.mask = fillResources.mask;\n this.ctx = fillResources.ctx;\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 // 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 fully at the start of each blend cycle so stale\n // dirty-rect bookkeeping cannot leak an old stroke into the next color.\n this.clearMask(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) {\n this.isBlending = false;\n this.cachedColor = null;\n \n }\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 GL 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 = blitSourceToFramebuffer({\n renderer: Renderer,\n sourceTarget: activeFramebuffer ?? Renderer,\n sourceFramebuffer: Renderer.blendSourceFramebuffer,\n dirtyRect,\n isFramebufferTarget,\n Cwidth,\n Cheight,\n getTargetPixelSize,\n toScissorBox,\n withScissor,\n });\n const targetIsFramebuffer = !!activeFramebuffer;\n const composite = isBrushMask ? strokeComposite : fillComposite;\n const shaderMask = composite.getShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n );\n\n runBlendShaderPass({\n renderer: Renderer,\n shader,\n source,\n mask: shaderMask,\n color: this.cachedColor,\n isBrushMask,\n Cwidth,\n Cheight,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n });\n this.clearMask(mask);\n },\n};\n\n/**\n * Flushes any pending stroke/fill mask work into the current target and resets\n * the shared compositor back to its initial idle state.\n */\nexport const flushActiveComposite = () => {\n isMixReady();\n Mix.blend(false, true);\n Mix.clearMask(Mix.glMask);\n Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n};\n\n/**\n * Loads and initializes the drawing target, then refreshes compositing\n * resources if the renderer was already active.\n *\n * @param {object|false} [buffer=false] - Optional offscreen target.\n */\nexport const load = (buffer = false) => {\n loadTarget(buffer);\n if (Renderer.loaded) Mix.load();\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 { usesRadians as runtimeUsesRadians } from \"./runtime.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());\nlet rng2 = 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 rng2 = prng_alea(`${s}:2`);\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()));\nexport let noise2 = 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 noise2 = createNoise2D(prng_alea(`${s}:2`));\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);\nexport const rr2 = (e = 0, r = 1) => e + rng2() * (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);\nexport const randInt2 = (e, r) => ~~rr2(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 if (isRad || runtimeUsesRadians()) {\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 || runtimeUsesRadians()\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 { Cwidth, Cheight } from \"./target.js\";\nimport { isMixReady, State } from \"./color.js\";\nimport { randInt2, noise2, rr2, sin, cos, map, toDegreesSigned } from \"./utils.js\";\nimport { getAffineMatrix } from \"./runtime.js\";\n\n// =============================================================================\n// Section: Matrix transformations\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 const m = getAffineMatrix();\n this.mx = m.x;\n this.my = m.y;\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 = Math.round((x + this.mx - left_x) / resolution);\n this.rowIdx = Math.round((y + this.my - top_y) / resolution);\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 + this.mx;\n const y = this.y + this.my;\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(skipCheck = false) {\n if (!State.field.isActive) return 0;\n return (skipCheck || this.isIn())\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 runtime angle units.\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 const steps = _length / _step;\n const fieldActive = State.field.isActive;\n const usePlot = !!_scale;\n for (let i = 0; i < steps; i++) {\n const angle =\n (fieldActive ? this.angle(true) : 0) - (usePlot ? _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 + getAffineMatrix().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 + getAffineMatrix().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 = rr2(0.2, 0.8),\n ba = randInt2(5, 10);\n return fillField(field, (c, r) => {\n const angle = 0.5 * ba * sin(bs * r * c + randInt2(15, 25));\n return 0.2 * angle * cos(t) + noise2(c, r) * ba * 0.7;\n });\n });\n // Smooth large-scale noise curves\n addField(\"curved\", (t, field) => {\n let ar = randInt2(-10, 10);\n if (randInt2(0, 100) % 2 == 0) ar *= -1;\n return fillField(\n field,\n (c, r) =>\n 3 * map(noise2(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 = randInt2(-30, -15) + Math.abs(44 * sin(t));\n if (randInt2(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 = randInt2(10, 15) + 5 * sin(t),\n cr = randInt2(3, 6) + 3 * cos(t),\n ba = randInt2(20, 35);\n return fillField(\n field,\n (c, r) => sin(sr * c) * ba * cos(r * cr) + randInt2(-3, 3),\n );\n });\n // Dense oscillation from row×col product\n addField(\"seabed\", (t, field) => {\n const bs = rr2(0.4, 0.8),\n ba = randInt2(18, 26);\n return fillField(\n field,\n (c, r) => 1.1 * ba * sin(bs * r * c + randInt2(15, 20)) * cos(t),\n );\n });\n // Radial vortex — angles spiral around the field centre\n addField(\"spiral\", (_t, field) => {\n const n = randInt2(5, 10);\n const dir = randInt2(0, 2) * 2 - 1;\n const offset = randInt2(65, 80); // <90 = inward spiral\n const attractors = Array.from({ length: n }, () => ({\n x: rr2(0.1, 0.9) * num_columns,\n y: rr2(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 = randInt2(3, 8),\n amp = randInt2(25, 45);\n return fillField(field, (c, _r) => sin(c * freq) * amp);\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 wash: State.wash ? { ...State.wash } : null,\n stroke: { ...State.stroke },\n hatch: { ...State.hatch },\n mass: State.mass ? { ...State.mass } : null,\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 if (saved.wash) State.wash = { ...saved.wash };\n if (saved.mass) {\n State.mass = { ...saved.mass };\n } else if (State.mass) {\n State.mass = {\n ...State.mass,\n isActive: false,\n brush: null,\n color: null,\n options: {},\n };\n }\n}\n","// =============================================================================\n// Adapter: Standalone Runtime Hooks\n// =============================================================================\n\nimport { setRuntime } from \"../../core/runtime.js\";\nimport { push as pushState, pop as popState } from \"../../core/save.js\";\n\nconst clamp = (value, min, max) => Math.max(min, Math.min(value, max));\n\nexport const DEGREES = \"degrees\";\nexport const RADIANS = \"radians\";\n\nlet colorContext = null;\nlet currentAngleMode = DEGREES;\nconst transformStack = [];\nlet currentTransform = {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x: 0,\n y: 0,\n};\n\nfunction getColorContext() {\n if (colorContext) return colorContext;\n\n if (typeof document !== \"undefined\") {\n colorContext = document.createElement(\"canvas\").getContext(\"2d\");\n return colorContext;\n }\n\n if (typeof OffscreenCanvas !== \"undefined\") {\n colorContext = new OffscreenCanvas(1, 1).getContext(\"2d\");\n return colorContext;\n }\n\n throw new Error(\"Standalone color parsing requires CanvasRenderingContext2D support.\");\n}\n\nfunction multiplyTransform(left, right) {\n return {\n a: left.a * right.a + left.c * right.b,\n b: left.b * right.a + left.d * right.b,\n c: left.a * right.c + left.c * right.d,\n d: left.b * right.c + left.d * right.d,\n x: left.a * right.x + left.c * right.y + left.x,\n y: left.b * right.x + left.d * right.y + left.y,\n };\n}\n\n/**\n * Runtime-native color object compatible with the expectations of core modules.\n */\nexport class Color {\n constructor(r, g, b) {\n if (r?._array) {\n this.r = Math.round(r._array[0] * 255);\n this.g = Math.round(r._array[1] * 255);\n this.b = Math.round(r._array[2] * 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n this._array = [...r._array];\n this.gl = this._array;\n return;\n }\n\n if (typeof r === \"string\") {\n const rgbaMatch = /^rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*([\\d.]+))?\\s*\\)$/i.exec(r);\n if (rgbaMatch) {\n this.r = clamp(parseInt(rgbaMatch[1]), 0, 255);\n this.g = clamp(parseInt(rgbaMatch[2]), 0, 255);\n this.b = clamp(parseInt(rgbaMatch[3]), 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n const alpha = rgbaMatch[4] !== undefined ? clamp(parseFloat(rgbaMatch[4]), 0, 1) : 1;\n this._array = [this.r / 255, this.g / 255, this.b / 255, alpha];\n this.gl = this._array;\n return;\n }\n this.hex = this.standardize(r);\n const rgb = this.hexToRgb(this.hex);\n this.r = rgb.r;\n this.g = rgb.g;\n this.b = rgb.b;\n } else {\n this.r = clamp(r ?? 0, 0, 255);\n this.g = clamp(g ?? r ?? 0, 0, 255);\n this.b = clamp(b ?? r ?? 0, 0, 255);\n this.hex = this.rgbToHex(this.r, this.g, this.b);\n }\n\n this._array = [this.r / 255, this.g / 255, this.b / 255, 1];\n this.gl = this._array;\n }\n\n rgbToHex(r, g, b) {\n return `#${((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1)}`;\n }\n\n hexToRgb(hex) {\n hex = hex.replace(\n /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i,\n (_match, red, green, blue) => red + red + green + green + blue + blue,\n );\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n if (!result) {\n throw new Error(`Invalid color value \"${hex}\".`);\n }\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n };\n }\n\n standardize(value) {\n const ctx = getColorContext();\n ctx.fillStyle = value;\n return ctx.fillStyle;\n }\n\n _getRed() {\n return this.r;\n }\n\n _getGreen() {\n return this.g;\n }\n\n _getBlue() {\n return this.b;\n }\n}\n\n/**\n * Sets the active standalone angle mode.\n *\n * @param {\"degrees\"|\"radians\"} mode\n */\nexport function angleMode(mode) {\n if (mode !== DEGREES && mode !== RADIANS) {\n throw new Error(`Invalid angle mode \"${mode}\". Use \"degrees\" or \"radians\".`);\n }\n currentAngleMode = mode;\n}\n\n/**\n * Returns the current standalone angle mode.\n *\n * @returns {\"degrees\"|\"radians\"}\n */\nexport function getAngleMode() {\n return currentAngleMode;\n}\n\n/**\n * Pushes the current standalone transform onto the stack.\n */\nexport function push() {\n pushState();\n transformStack.push({ ...currentTransform });\n}\n\n/**\n * Pops the last standalone transform from the stack.\n */\nexport function pop() {\n if (transformStack.length === 0) return;\n currentTransform = transformStack.pop();\n popState();\n}\n\n/**\n * Applies a translation to the current standalone transform.\n *\n * @param {number} x\n * @param {number} y\n */\nexport function translate(x, y) {\n currentTransform = multiplyTransform(currentTransform, {\n a: 1,\n b: 0,\n c: 0,\n d: 1,\n x,\n y,\n });\n}\n\n/**\n * Applies a rotation to the current standalone transform.\n *\n * @param {number} angle\n */\nexport function rotate(angle) {\n const theta =\n currentAngleMode === RADIANS ? angle : (angle * Math.PI) / 180;\n const cosTheta = Math.cos(theta);\n const sinTheta = Math.sin(theta);\n currentTransform = multiplyTransform(currentTransform, {\n a: cosTheta,\n b: sinTheta,\n c: -sinTheta,\n d: cosTheta,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Applies a scale to the current standalone transform.\n *\n * @param {number} x\n * @param {number} [y=x]\n */\nexport function scale(x, y = x) {\n currentTransform = multiplyTransform(currentTransform, {\n a: x,\n b: 0,\n c: 0,\n d: y,\n x: 0,\n y: 0,\n });\n}\n\n/**\n * Installs the standalone runtime hooks used by core modules.\n */\nexport function initStandaloneRuntime() {\n setRuntime({\n usesRadians: () => currentAngleMode === \"radians\",\n fromDegrees: (angle) =>\n currentAngleMode === \"radians\" ? (angle * Math.PI) / 180 : angle,\n createColor: (...args) => {\n if (args.length === 1 && args[0]?._array) return args[0];\n return new Color(...args);\n },\n getAffineMatrix: () => currentTransform,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Target Hooks\n// =============================================================================\n\nimport {\n setTargetRuntime,\n setTargetState,\n} from \"../../core/target.js\";\n\nlet activeTarget = null;\nlet isLoaded = false;\nlet activeDensity = 1;\nlet activeWidth = 0;\nlet activeHeight = 0;\n\nfunction isCanvasTarget(target) {\n return (\n typeof HTMLCanvasElement !== \"undefined\" &&\n target instanceof HTMLCanvasElement\n );\n}\n\nfunction isOffscreenCanvasTarget(target) {\n return (\n typeof OffscreenCanvas !== \"undefined\" &&\n target instanceof OffscreenCanvas\n );\n}\n\nfunction isSupportedTarget(target) {\n return isCanvasTarget(target) || isOffscreenCanvasTarget(target);\n}\n\nfunction getTargetContext(target) {\n return (\n target.getContext(\"webgl2\", { premultipliedAlpha: true }) ??\n target.getContext(\"webgl2\")\n );\n}\n\nfunction createRenderer(target, width, height, density) {\n const drawingContext = getTargetContext(target);\n if (!drawingContext) {\n throw new Error(\"brush.load(target) requires a canvas with a WebGL2 context.\");\n }\n\n return {\n canvas: target,\n drawingContext,\n width,\n height,\n pixelDensity: () => density,\n };\n}\n\nfunction applyLoadedTarget(target, width, height, density) {\n activeTarget = target;\n activeWidth = width;\n activeHeight = height;\n activeDensity = density;\n\n const renderer = createRenderer(target, width, height, density);\n setTargetState({\n Renderer: renderer,\n Cwidth: width,\n Cheight: height,\n Density: density,\n });\n isLoaded = true;\n}\n\n/**\n * Loads a standalone draw target from a DOM canvas or OffscreenCanvas.\n *\n * @param {HTMLCanvasElement|OffscreenCanvas} target\n */\nexport function load(target = activeTarget) {\n if (!isSupportedTarget(target)) {\n throw new Error(\n \"Standalone brush.load(target) requires an HTMLCanvasElement or OffscreenCanvas.\",\n );\n }\n\n applyLoadedTarget(target, target.width, target.height, 1);\n}\n\n/**\n * Creates a standalone DOM canvas, configures its backing resolution according\n * to the provided pixel density, appends it optionally to the DOM, and loads it\n * as the active brush target.\n *\n * @param {number} width Logical canvas width.\n * @param {number} height Logical canvas height.\n * @param {{pixelDensity?: number, parent?: string|Element|null, id?: string}} [options]\n * @returns {HTMLCanvasElement}\n */\nexport function createCanvas(width, height, options = {}) {\n if (typeof document === \"undefined\") {\n throw new Error(\"brush.createCanvas() requires a browser document.\");\n }\n\n const logicalWidth = Math.max(1, Math.round(width));\n const logicalHeight = Math.max(1, Math.round(height));\n const density = Math.max(1, Number(options.pixelDensity) || 1);\n const canvas = document.createElement(\"canvas\");\n\n canvas.width = Math.max(1, Math.round(logicalWidth * density));\n canvas.height = Math.max(1, Math.round(logicalHeight * density));\n canvas.style.width = `${logicalWidth}px`;\n canvas.style.height = `${logicalHeight}px`;\n if (options.id) canvas.id = options.id;\n\n if (options.parent) {\n const parent =\n typeof options.parent === \"string\"\n ? document.querySelector(options.parent)\n : options.parent;\n if (!parent) {\n throw new Error(`Could not find parent \"${options.parent}\" for brush.createCanvas().`);\n }\n parent.appendChild(canvas);\n }\n\n applyLoadedTarget(canvas, logicalWidth, logicalHeight, density);\n return canvas;\n}\n\n/**\n * Refreshes the standalone target density.\n *\n * Standalone targets currently use a fixed density of 1.\n *\n * @returns {number}\n */\nexport function syncDensity() {\n setTargetState({\n Cwidth: activeWidth,\n Cheight: activeHeight,\n Density: activeDensity,\n });\n return activeDensity;\n}\n\n/**\n * Ensures a standalone target has been loaded.\n */\nexport function isCanvasReady() {\n if (!isLoaded) {\n throw new Error(\n \"No standalone target loaded. Call brush.load(canvasOrOffscreenCanvas) first.\",\n );\n }\n}\n\n/**\n * Standalone build does not use p5 instance switching, so these are no-ops.\n */\nexport function instance() {}\nexport function activateInstance() {}\nexport function deactivateInstance() {}\n\n/**\n * Standalone build does not yet support framebuffer targets.\n *\n * @returns {null}\n */\nexport function getActiveFramebuffer() {\n return null;\n}\n\n/**\n * Returns whether the given target behaves like a framebuffer target.\n *\n * Standalone targets currently only accept canvases and offscreen canvases.\n *\n * @returns {boolean}\n */\nexport function isFramebufferTarget() {\n return arguments[0]?.__brushFramebuffer === true;\n}\n\nexport function initStandaloneTargetRuntime() {\n setTargetRuntime({\n load,\n syncDensity,\n isCanvasReady,\n instance,\n activateInstance,\n deactivateInstance,\n getActiveFramebuffer,\n isFramebufferTarget,\n });\n}\n","import {\n rr2,\n randInt2,\n sin,\n cos,\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 * Polygons ignore fields and won't be good for fills and masses\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 = rr2(0, 360);\n const randomFactor = r ? () => 1 + r * 0.2 * rr2() : () => 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 * randInt2(-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 runtime angle units.\n * @param {number} end - End angle in the current runtime angle units.\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","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.wash) this.wash();\n if (State.fill) this.fill();\n if (State.mass) this.mass();\n if (State.hatch) this.hatch();\n if (State.stroke) this.draw();\n }\n}","import { Cwidth, Cheight } from \"./target.js\";\nimport { State } from \"./color.js\";\nimport { toDegrees, map, rr2 } 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 = _side < 0 ? 4 : 1;\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 let maxSize = _side <= 0 ? 8 : Math.max(this.segments[idx] * _side * rr2(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.wash) this.wash(x, y, scale);\n if (State.fill) this.fill(x, y, scale);\n if (State.mass) this.mass(x, y, scale);\n if (State.hatch) this.hatch(x, y, scale);\n if (State.stroke) this.draw(x, y, scale);\n }\n}\n","// =============================================================================\n// Stroke Runtime Hooks\n// =============================================================================\n\nlet strokeRuntime = {\n createTipSurface: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n loadImageTip: () => {\n throw new Error(\"No stroke runtime adapter registered.\");\n },\n};\n\n/**\n * Registers or updates host stroke hooks used by brush-tip loading code.\n *\n * @param {object} hooks\n */\nexport function setStrokeRuntime(hooks) {\n strokeRuntime = { ...strokeRuntime, ...hooks };\n}\n\nexport const createTipSurface = (width, height) =>\n strokeRuntime.createTipSurface(width, height);\nexport const loadImageTip = (src, imageToWhite) =>\n strokeRuntime.loadImageTip(src, imageToWhite);\n","import * as Color from \"../core/color.js\";\nimport { createFramebuffer } from \"../core/compositor_runtime.js\";\n\nlet isStrokeCompositeRegistered = false;\nconst DIRTY_BRUSH_PADDING = 2;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the current stroke mask framebuffer must be recreated.\n * This happens when the renderer has no mask yet, or when the canvas size or\n * pixel density changed since the last allocation.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the stroke mask must be rebuilt.\n */\nfunction needsStrokeMask(Renderer, Cwidth, Cheight, Density) {\n return (\n !Renderer.glMask ||\n Renderer.glMask.width !== Cwidth ||\n Renderer.glMask.height !== Cheight ||\n (typeof Renderer.glMask.pixelDensity === \"function\" &&\n Renderer.glMask.pixelDensity() !== Density)\n );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures the stroke compositor owns a framebuffer-backed mask with the current\n * canvas dimensions. Stroke stamps are rendered into this mask in WebGL before\n * being blended into the main target.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {object} The framebuffer used as stroke mask.\n */\nexport function ensureStrokeCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n) {\n if (needsStrokeMask(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.glMask?.remove) Renderer.glMask.remove();\n Renderer.glMask = createFramebuffer(Renderer, {\n width: Cwidth,\n height: Cheight,\n density: Density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n }\n\n Renderer.glMask.dirtyRect ??= null;\n Renderer.glMask.isDrawn ??= false;\n return Renderer.glMask;\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current stroke mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearStrokeMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the rect that should be composited from the stroke mask into the\n * main canvas. Stroke bounds are normally tight dirty rects, but when drawing\n * into an active framebuffer we keep the result conservative and composite the\n * full target.\n *\n * @param {object|null} target - Stroke mask framebuffer.\n * @param {Function} getActiveFramebuffer - Returns the currently bound framebuffer.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {number} padding - Extra brush padding in pixels.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getStrokeCompositeRect(\n target,\n getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n if (getActiveFramebuffer()) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_BRUSH_PADDING),\n );\n}\n\n/**\n * Returns the resource that should be bound to the blend shader's `u_mask`\n * uniform for stroke compositing.\n *\n * @param {object} _Renderer - Active host renderer.\n * @param {object} mask - Stroke mask framebuffer.\n * @returns {object} Stroke mask framebuffer.\n */\nexport function getStrokeShaderMask(_Renderer, mask) {\n return mask;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the stroke compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initStrokeComposite() {\n if (isStrokeCompositeRegistered) return;\n Color.registerStrokeComposite?.({\n ensureResources: ensureStrokeCompositeResources,\n clearMask: clearStrokeMask,\n getCompositeRect: getStrokeCompositeRect,\n getShaderMask: getStrokeShaderMask,\n });\n isStrokeCompositeRegistered = true;\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// Renderer Runtime Hooks\n// =============================================================================\n\n/**\n * Direct-render hooks used by modules that issue raw WebGL commands.\n *\n * These hooks are intentionally narrow:\n * - begin drawing into an offscreen GL mask target\n * - restore the previous draw target afterward\n * - reset any host-side shader/program bookkeeping after direct GL usage\n */\n\nlet rendererRuntime = {\n beginDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n endDirectMaskDraw: () => {\n throw new Error(\"No renderer runtime adapter registered.\");\n },\n resetDirectShaderTracking: () => {},\n};\n\n/**\n * Registers or updates host renderer hooks used by direct WebGL drawing paths.\n *\n * @param {object} hooks\n */\nexport function setRendererRuntime(hooks) {\n rendererRuntime = { ...rendererRuntime, ...hooks };\n}\n\nexport const beginDirectMaskDraw = (renderer, gl, target) =>\n rendererRuntime.beginDirectMaskDraw(renderer, gl, target);\nexport const endDirectMaskDraw = (renderer, gl, state) =>\n rendererRuntime.endDirectMaskDraw(renderer, gl, state);\nexport const resetDirectShaderTracking = (renderer, gl) =>\n rendererRuntime.resetDirectShaderTracking(renderer, gl);\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 { Cwidth, Cheight, Density, Renderer } from \"../core/target.js\";\nimport {\n Mix,\n isMixReady,\n State,\n} from \"../core/color.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport {\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking,\n} from \"../core/renderer_runtime.js\";\nimport { getAffineMatrix } from \"../core/runtime.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;\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 runtime affine transform. Call once at the start of each stroke.\n */\nexport function snapshotMatrix() {\n const m = getAffineMatrix();\n _ma = m.a;\n _mb = m.b;\n _mc = m.c;\n _md = m.d;\n _mx = m.x;\n _my = m.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 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 return beginDirectMaskDraw(Renderer, gl, Mix.glMask);\n}\n\nfunction endMaskTarget(state) {\n endDirectMaskDraw(Renderer, gl, state);\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 * the current runtime transform 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 * @param {number} [extraPadding=0] - Conservative extra padding in user units.\n */\nexport function stampImage(x, y, size, angle, alpha, extraPadding = 0) {\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 const extraRadius = _density * extraPadding * _scale;\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 const boundsRadius = halfSize * 1.42 + extraRadius;\n imgDirtyRect = accumulateDirtyRect(\n imgDirtyRect,\n dScreenX - boundsRadius - 1,\n dScreenY - boundsRadius - 1,\n dScreenX + boundsRadius + 1,\n dScreenY + boundsRadius + 1,\n );\n\n imgCount++;\n}\n\n/**\n * Flush all queued image stamps in a single instanced draw call.\n * @param {object} p5img - The preprocessed brush-tip image/canvas (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 const targetState = beginMaskTarget();\n\n // Lazy-create the WebGL texture from the tip 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(targetState);\n\n if (imgDirtyRect) {\n Mix.markDirtyRect(Mix.glMask, imgDirtyRect);\n imgDirtyRect = null;\n }\n\n imgCount = 0;\n\n // Let the host adapter know we changed the active program.\n resetDirectShaderTracking(Renderer, gl);\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 const targetState = beginMaskTarget();\n\n const color = State.stroke.color._array;\n\n // Re-activate our shader in case host drawing 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(targetState);\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 host shader tracking.\n // Reset it so the host is forced to re-activate its own shader next time\n // it draws — otherwise it may skip gl.useProgram() and set uniforms on the\n // wrong active program, causing \"location is not from the associated program\".\n resetDirectShaderTracking(Renderer, gl);\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\n// Core imports\nimport { Cwidth, Cheight, Renderer, isCanvasReady } from \"../core/target.js\";\nimport {\n Mix,\n State,\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 cos,\n sin\n} from \"../core/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { Position, isFieldReady } from \"../core/flowfield.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { createTipSurface, loadImageTip } from \"./runtime.js\";\n\n// Internal module imports\nimport { initStrokeComposite } from \"./composite.js\";\nimport {\n isReady,\n glDraw,\n glDrawImages,\n circle,\n stampImage,\n invalidateTexEntry,\n snapshotMatrix,\n} from \"./gl_draw.js\";\n\ninitStrokeComposite(); // Register the stroke composite system for offscreen mask rendering and compositing.\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 type: \"HB\",\n isActive: false,\n opacity: 1,\n};\n\nlet list = new Map();\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 if (params.markerTip === undefined) params.markerTip = true;\n if (params.noise === undefined) params.noise = 0.3;\n params.noise = Math.max(0, Math.min(1, params.noise));\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 g = createTipSurface(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\nexport function getBrushParams(brushName) {\n return list.get(brushName)?.param ?? null;\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 = createColor(...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\n/**\n * Defines a clipping region for strokes.\n * The region uses the same coordinate space as brush drawing commands,\n * with the current runtime 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 return region;\n}\n\n/**\n * Disables the clipping region.\n */\nexport function noClip() {\n return;\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 _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 current.pressureCount = 10;\n current.cachedPressure = undefined;\n current.lineNoiseCount = 5;\n current.cachedLineNoise = undefined;\n\n for (let i = 0; i < totalSteps; i++) {\n if (gaussians.length < totalSteps * 2) {\n gaussians.push(gaussian());\n }\n tip();\n if (isPlot) {\n _position.plotTo(\n _plot,\n stepSize,\n stepSize,\n angleScale,\n i < 10 ? true : false,\n );\n } else {\n _position._moveToDegrees(angleScale, stepSize, stepSize);\n }\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.05 * current.p.noise;\n\n // Cache stroke direction for direction-aware dispersion (non-plot strokes only)\n if (!_plot) {\n current.cos = cos(_dir);\n current.sin = sin(_dir);\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 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 pressure = calculatePressure();\n const lineNoise = calculateLineNoise();\n\n if (lineNoise > rr(1,1.02) && rr(0,1) < 0.7) return;\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 if (current.pressureCount >= 10 || current.cachedPressure === undefined) {\n current.cachedPressure = _plot\n ? simPressure() * _plot.pressure(_position.plotted)\n : simPressure();\n current.pressureCount = 0;\n }\n current.pressureCount++;\n return current.cachedPressure;\n}\n\nfunction calculateLineNoise() {\n if (current.lineNoiseCount >= 10 || current.cachedLineNoise === undefined) {\n current.cachedLineNoise = map(\n noise(current.seed + _position.plotted * 0.01, 0),\n -1,\n 1,\n 1 - current.noiseoffset,\n 1 + current.noiseoffset,\n );\n current.lineNoiseCount = 0;\n }\n current.lineNoiseCount++;\n return current.cachedLineNoise;\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 * 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\nfunction getImageTipOverscan() {\n const maxPressure = Math.max(1, current.max ?? 1);\n const scatterReach = State.stroke.weight * current.p.scatter;\n const tipReach = State.stroke.weight * current.p.weight * maxPressure;\n\n // Custom/image tips can extend beyond their nominal square because the tip\n // drawing itself may be large and because high scatter creates sparse large\n // stamps near the edge. Keep culling/dirty tracking conservative.\n return Math.max(8, scatterReach * 1.5 + tipReach * 0.75);\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 const overscan = getImageTipOverscan();\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(\n _position.x + rx,\n _position.y + ry,\n size,\n angle,\n alpha * Math.max(0.8, pressure) * rr(0.9, 1.1),\n overscan,\n );\n}\n\n/**\n * Draws the default brush tip.\n * @param {number} pressure - Current pressure.\n */\nfunction drawDefault(pressure, wiggle = 1) {\n wiggle = map(wiggle, 0, 1, 0.9, 1.05);\n const vibration =\n wiggle *\n State.stroke.weight *\n current.p.scatter *\n (current.p.sharpness +\n ((1 - current.p.sharpness) * rArray(gaussians)) / pressure);\n const passesGate = rr(0, current.p.grain * pressure) > 0.4;\n if (passesGate) {\n let dx, dy;\n if (_plot) {\n const plotAngle = _plot.angle(_position.plotted);\n const plotCos = cos(plotAngle);\n const plotSin = sin(plotAngle);\n const perp = vibration * rr(-1, 1);\n const along = 0.3 * vibration * rr(-1, 1);\n dx = perp * plotSin + along * plotCos;\n dy = perp * plotCos - along * plotSin;\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 (current.p.markerTip === false) return;\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// 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 runtime angle units.\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 \"markerTip\",\n \"noise\",\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 \"pastel\",\n [\n 2.05 / 3,\n 13.4 / 3,\n 0.91,\n 28,\n 35,\n 0.085 / 3,\n { mode: \"gaussian\", curve: [0.4, 0.05], min_max: [1.09, 0.93] },\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\n ],\n [\n \"crayon\",\n [\n 0.9 / 3,\n 5.45 / 3,\n 0.75,\n 250,\n 159,\n 0.23 / 3,\n [1.1, 0.9],\n \"default\",\n undefined,\n \"natural\",\n true,\n 1,\n ],\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 active host image pipeline.\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 host image object 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 loadImageTip(src, T.imageToWhite).then((p5img) => {\n this.tips.set(src, p5img);\n }),\n ),\n );\n },\n};\n","import { 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// Module: Classic Hatch\n// =============================================================================\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\n/**\n * Returns a shallow snapshot of the current hatch modifier state.\n *\n * @returns {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}}\n */\nexport function HatchState() {\n return { ...State.hatch };\n}\n\n/**\n * Restores hatch modifier state from a previously captured snapshot.\n *\n * @param {{isActive:boolean, dist:number, angle:number, options:Object, hBrush:Object|false}} state\n */\nexport function HatchSetState(state) {\n State.hatch = { ...state };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Activates classic scanline hatching for subsequent shapes.\n *\n * @param {number} [dist=5] Distance between scanlines.\n * @param {number} [angle=45] Hatch angle in the current runtime angle units.\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [options]\n */\nexport function hatch(\n dist = 5,\n angle = 45,\n options = { rand: false, continuous: false, gradient: false }\n) {\n let s = State.hatch;\n s.isActive = true;\n s.dist = dist;\n s.angle = toDegreesSigned(angle);\n s.options = options;\n}\n\n/**\n * Overrides the brush, color, and weight used specifically for hatch strokes.\n *\n * @param {string} brush\n * @param {string|object} [color=\"black\"]\n * @param {number} [weight=1]\n */\nexport function hatchStyle(brush, color = \"black\", weight = 1) {\n State.hatch.hBrush = { brush, color, weight };\n}\n\n/**\n * Deactivates hatching and clears any hatch-specific brush override.\n */\nexport function noHatch() {\n State.hatch.isActive = false;\n State.hatch.hBrush = false;\n}\n\n// ---------------------------------------------------------------------------\n// Scanline Generation\n// ---------------------------------------------------------------------------\n\n/**\n * Computes hatch segments for one polygon by rotating it into scanline space,\n * intersecting horizontal scanlines against its edges, and rotating the\n * resulting segments back into canvas space.\n *\n * @param {Polygon} polygon\n * @param {number} angle Hatch angle in degrees.\n * @param {number} dist Base scanline spacing.\n * @param {number} gradient Multiplicative spacing growth per scanline.\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction scanlineHatch(polygon, angle, dist, gradient) {\n const rad = (angle * Math.PI) / 180;\n const cosA = Math.cos(rad),\n sinA = Math.sin(rad);\n const cosB = Math.cos(-rad),\n sinB = Math.sin(-rad);\n\n const verts = polygon.a,\n n = verts.length;\n\n // Rotate vertices; track Y extent\n const rotated = new Array(n);\n let minY = Infinity,\n maxY = -Infinity;\n for (let i = 0; i < n; i++) {\n const x = verts[i][0],\n 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],\n 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,\n step = dist;\n while (Y < maxY) {\n const cx = [];\n for (let i = 0; i < eLen; i += 2) {\n const y1 = edges[i][1],\n y2 = edges[i + 1][1];\n if ((y1 <= Y && Y < y2) || (y2 <= Y && Y < y1))\n cx.push(\n edges[i][0] + ((Y - y1) / (y2 - y1)) * (edges[i + 1][0] - edges[i][0])\n );\n }\n cx.sort((a, b) => a - b);\n for (let i = 0; i < cx.length - 1; i += 2) {\n segments.push({\n scanY: Y,\n x1: cx[i] * cosB - Y * sinB,\n y1: cx[i] * sinB + Y * cosB,\n x2: cx[i + 1] * cosB - Y * sinB,\n y2: cx[i + 1] * sinB + Y * cosB,\n });\n }\n Y += step;\n step *= gradient;\n }\n return segments;\n}\n\n/**\n * Collects and orders hatch segments for one polygon or a polygon list.\n *\n * Segments are sorted in scanline traversal order so downstream rendering can\n * optionally connect them into a continuous serpentine path.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {number} dist\n * @param {number} angle\n * @param {number} gradient\n * @returns {{scanY:number, x1:number, y1:number, x2:number, y2:number}[]}\n */\nfunction getHatchSegments(polygons, dist, angle, gradient) {\n if (!Array.isArray(polygons)) polygons = [polygons];\n const segs = [];\n for (const poly of polygons) {\n for (const s of scanlineHatch(poly, angle, dist, gradient)) segs.push(s);\n }\n segs.sort((a, b) => (a.scanY === b.scanY ? a.x1 - b.x1 : a.scanY - b.scanY));\n return segs;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Runs hatch drawing with the temporary hatch-specific brush style if one is active,\n * then restores the outer stroke state.\n *\n * @param {() => void} drawFn\n */\nfunction withHatchStyle(drawFn) {\n const save = BrushState();\n if (State.hatch.hBrush) set(...Object.values(State.hatch.hBrush));\n drawFn();\n BrushSetState(save);\n}\n\n/**\n * Resolves the active hatch parameters and precomputes the ordered scanline segments.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{dist:number, options:Object, segs:Object[]}}\n */\nfunction getActiveHatchConfig(polygons) {\n const dist = State.hatch.dist;\n const angle = ((State.hatch.angle % 180) + 180) % 180;\n const options = State.hatch.options;\n const gradient = options.gradient ? map(options.gradient, 0, 1, 1, 1.1, true) : 1;\n const segs = getHatchSegments(polygons, dist, angle, gradient);\n return { dist, options, segs };\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Lines\n// ---------------------------------------------------------------------------\n\n/**\n * Expands ordered hatch segments into the actual line list that will be drawn.\n *\n * This includes endpoint jitter when `rand` is active and inserts the serpentine\n * connector lines when `continuous` is enabled.\n *\n * @param {Polygon|Polygon[]} polygons\n * @returns {{x1:number, y1:number, x2:number, y2:number, scanY:number, isConnector:boolean}[]}\n */\nexport function getHatchLines(polygons) {\n const { dist, options, segs } = getActiveHatchConfig(polygons);\n const r = options.rand || 0;\n const lines = [];\n\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 += 2 * r * dist * rr(-1, 1);\n y1 += 2 * r * dist * rr(-1, 1);\n x2 += 2 * r * dist * rr(-1, 1);\n y2 += 2 * r * dist * rr(-1, 1);\n }\n const reverse = options.continuous && j % 2 === 1;\n const line = reverse\n ? { x1: x2, y1: y2, x2: x1, y2: y1, scanY: s.scanY, isConnector: false }\n : { x1, y1, x2, y2, scanY: s.scanY, isConnector: false };\n lines.push(line);\n if (j > 0 && options.continuous) {\n const prev = lines[lines.length - 2];\n lines.push({\n x1: prev.x2,\n y1: prev.y2,\n x2: line.x1,\n y2: line.y1,\n scanY: s.scanY,\n isConnector: true,\n });\n }\n }\n\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Hatch Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Iterates the generated hatch lines and delegates the actual rendering of each\n * segment to the provided callback.\n *\n * @param {Polygon|Polygon[]} polygons\n * @param {(x1:number, y1:number, x2:number, y2:number, index:number, segs:Object[]) => void} drawSegment\n */\nfunction renderHatchSegments(polygons, drawSegment) {\n const segs = getHatchLines(polygons);\n withHatchStyle(() => {\n for (let j = 0; j < segs.length; j++) {\n const s = segs[j];\n drawSegment(s.x1, s.y1, s.x2, s.y2, j, segs);\n }\n });\n}\n\n/**\n * Draws classic hatch lines over one polygon or an array of polygons.\n *\n * @param {Polygon|Polygon[]} polygons\n */\nexport function createHatch(polygons) {\n renderHatchSegments(polygons, (x1, y1, x2, y2) => {\n line(x1, y1, x2, y2);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies the currently active hatch modifier to a polygon, or temporarily\n * overrides hatch parameters for this call only.\n *\n * @param {number|false} [_dist=false]\n * @param {number} [_angle]\n * @param {{rand?: number|false, continuous?: boolean, gradient?: number|false}} [_options]\n */\nPolygon.prototype.hatch = function (_dist = false, _angle, _options) {\n let state = HatchState();\n if (_dist) hatch(_dist, _angle, _options);\n if (State.hatch.isActive) createHatch(this);\n HatchSetState(state);\n};\n\n/**\n * Converts the plot to a polygon and applies the currently active hatch modifier.\n *\n * @param {number} x\n * @param {number} y\n * @param {number} scale\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.3);\n this.pol.hatch();\n }\n};\n","// =============================================================================\n// Module: Mass\n// =============================================================================\n\nimport { State } from \"../core/color.js\";\nimport { arc } from \"../core/primitives.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { rr2, dist, calcAngle } from \"../core/utils.js\";\nimport { fromDegrees, usesRadians } from \"../core/runtime.js\";\nimport { HatchState, HatchSetState, hatch, getHatchLines } from \"./hatch.js\";\nimport { BrushState, BrushSetState, getBrushParams, set } from \"../stroke/stroke.js\";\nimport { wiggle } from \"../core/flowfield.js\";\n\n// ---------------------------------------------------------------------------\n// Mass State\n// ---------------------------------------------------------------------------\n\nState.mass = {\n isActive: false,\n brush: null,\n color: null,\n options: {},\n};\n\n/**\n * Returns a shallow copy of the current mass state.\n * @returns {object}\n */\nexport function MassState() {\n return { ...State.mass };\n}\n\n/**\n * Restores a previously saved mass state.\n * @param {object} state\n */\nexport function MassSetState(state) {\n State.mass = { ...state };\n}\n\n/**\n * Enables massing mode with a brush, color, and optional configuration.\n *\n * @param {string} brush - Brush name to use for the mass pass.\n * @param {string|Color} color - Color to use for the mass pass.\n * @param {object} [options={}] - Massing options such as precision, strength, gradient, and outline.\n */\nexport function mass(brush, color, options = {}) {\n State.mass.brush = brush;\n State.mass.color = color;\n State.mass.options = options;\n State.mass.isActive = true;\n}\n\n/**\n * Disables massing mode for subsequent geometry.\n */\nexport function noMass() {\n State.mass.isActive = false;\n State.mass.brush = null;\n State.mass.color = null;\n State.mass.options = {};\n}\n\n// ---------------------------------------------------------------------------\n// Polygon Preparation\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a translated copy of a polygon.\n * Used to build the secondary mass layers from an existing base polygon.\n * @param {Polygon} polygon\n * @param {number} jitterX\n * @param {number} jitterY\n * @returns {Polygon}\n */\nfunction jitterPolygon(polygon, jitterX, jitterY) {\n return new Polygon(\n polygon.vertices.map((vertex) => [vertex.x + jitterX, vertex.y + jitterY]),\n );\n}\n\n/**\n * Builds the three polygons used for a mass pass.\n * Both polygon and plot inputs use one base polygon plus two translated copies,\n * so plot-based massing only needs a single `genPol(...)` call.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n * @returns {Polygon[]}\n */\nfunction getMassPolygons(shape, x, y, scale) {\n const isPolygon = x === false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const basePolygon = isPolygon ? shape : shape.genPol(x, y, scale, 0.15);\n const maxJitter = Math.min(scatter * 2, 5);\n const jitters = [\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n [rr2(-maxJitter, maxJitter), rr2(-maxJitter, maxJitter)],\n ];\n\n return [\n basePolygon,\n jitterPolygon(basePolygon, jitters[0][0], jitters[0][1]),\n jitterPolygon(basePolygon, jitters[1][0], jitters[1][1]),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Angle & Bounds Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Converts degree values into the current runtime angle units.\n * @param {number} angle\n * @returns {number}\n */\nfunction getAngleConverter() {\n return usesRadians()\n ? (angle) => (angle * Math.PI) / 180\n : (angle) => angle;\n}\n\n/**\n * Computes an axis-aligned bounding box for a polygon.\n * The diagonal is used as a size reference for pivot distance.\n * @param {Polygon} polygon\n * @returns {{minX:number,minY:number,maxX:number,maxY:number,cx:number,cy:number,size:number}}\n */\nfunction getPolygonBounds(polygon) {\n const points = polygon?.a ?? [];\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n for (const [x, y] of points) {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n return {\n minX,\n minY,\n maxX,\n maxY,\n cx: (minX + maxX) / 2,\n cy: (minY + maxY) / 2,\n size: Math.hypot(maxX - minX, maxY - minY),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pivot Geometry\n// ---------------------------------------------------------------------------\n\n/**\n * Chooses the diagonal corner family for a whole mass gesture.\n * Positive-angle hatching uses either bottom-right or top-left; negative-angle\n * hatching uses either bottom-left or top-right.\n * @param {number} angleDeg\n * @returns {[number, number]}\n */\nfunction getPivotBias(angleDeg) {\n const normalizedAngle = ((((angleDeg + 90) % 180) + 180) % 180) - 90;\n if (normalizedAngle >= 0) {\n return rr2() < 0.5 ? [1, 1] : [-1, -1];\n } else {\n return rr2() < 0.5 ? [-1, 1] : [1, -1];\n }\n}\n\n/**\n * Places the global pivot anchor outside the polygon, along the selected bias.\n * Distance varies per layer while the bias stays fixed for the whole mass.\n * @param {Polygon} polygon\n * @param {[number, number]} bias\n * @returns {{x:number,y:number}}\n */\nfunction getPivotAnchor(polygon, bias) {\n const bounds = getPolygonBounds(polygon);\n const offset = bounds.size * rr2(0.6, 1.4);\n const [sx, sy] = bias;\n return {\n x: bounds.cx + sx * offset,\n y: bounds.cy + sy * offset,\n };\n}\n\n/**\n * Projects the global pivot anchor onto the perpendicular bisector of a line.\n * This yields a valid circle center equidistant from both endpoints.\n * @param {{x:number,y:number}} anchor\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {{x:number,y:number}|null}\n */\nfunction projectAnchorToBisector(anchor, x1, y1, x2, y2) {\n const mx = (x1 + x2) / 2;\n const my = (y1 + y2) / 2;\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n if (!length) return null;\n const nx = -dy / length;\n const ny = dx / length;\n const offset = (anchor.x - mx) * nx + (anchor.y - my) * ny;\n return {\n x: mx + nx * offset,\n y: my + ny * offset,\n };\n}\n\n/**\n * Returns the shortest arc between two endpoints around a given center.\n * The returned angles are already converted into the current runtime angle units.\n * @param {number} cx\n * @param {number} cy\n * @param {number} x1\n * @param {number} y1\n * @param {number} x2\n * @param {number} y2\n * @returns {[number, number]}\n */\nfunction getShortArcAngles(cx, cy, x1, y1, x2, y2, toAngleUnit) {\n let startDeg = calcAngle(cx, cy, x1, y1);\n let endDeg = calcAngle(cx, cy, x2, y2);\n const sweep = ((endDeg - startDeg) % 360 + 360) % 360;\n if (sweep > 180) [startDeg, endDeg] = [endDeg, startDeg];\n return [\n toAngleUnit(startDeg),\n toAngleUnit(endDeg),\n ];\n}\n\n/**\n * Splits a hatch line into two slightly separated segments so some gestures\n * read as interrupted rather than perfectly continuous.\n * @param {{x1:number,y1:number,x2:number,y2:number}} seg\n * @returns {Array<{x1:number,y1:number,x2:number,y2:number}>}\n */\nfunction splitSegment(seg) {\n const t = rr2(0.35, 0.65);\n const mx = seg.x1 + (seg.x2 - seg.x1) * t;\n const my = seg.y1 + (seg.y2 - seg.y1) * t;\n const dx = seg.x2 - seg.x1;\n const dy = seg.y2 - seg.y1;\n const length = Math.hypot(dx, dy) || 1;\n const gap = rr2(0.04, 0.1) * length;\n const gx = (dx / length) * gap * 0.5;\n const gy = (dy / length) * gap * 0.5;\n return [\n { x1: seg.x1, y1: seg.y1, x2: mx - gx, y2: my - gy },\n { x1: mx + gx, y1: my + gy, x2: seg.x2, y2: seg.y2 },\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Mass Rendering\n// ---------------------------------------------------------------------------\n\n/**\n * Draws one polygon of the mass as a family of arcs derived from hatch lines.\n * The same pivot bias is used across layers, while each layer gets its own\n * anchor distance from the shape.\n * @param {Polygon} polygon\n * @param {[number, number]} pivotBias\n */\nfunction drawMassArcs(polygon, pivotBias, toAngleUnit) {\n const anchor = getPivotAnchor(polygon, pivotBias);\n for (const seg of getHatchLines(polygon)) {\n const parts = !seg.isConnector && rr2() < 0.35 ? splitSegment(seg) : [seg];\n for (const part of parts) {\n const center = projectAnchorToBisector(anchor, part.x1, part.y1, part.x2, part.y2);\n if (!center) continue;\n const radius = dist(center.x, center.y, part.x1, part.y1);\n if (!radius) continue;\n const [startAngle, endAngle] = getShortArcAngles(\n center.x,\n center.y,\n part.x1,\n part.y1,\n part.x2,\n part.y2,\n toAngleUnit,\n );\n arc(center.x, center.y, radius, startAngle, endAngle);\n }\n }\n}\n\n/**\n * Configures a hatch pass and immediately reinterprets the generated lines as arcs.\n * @param {Polygon} polygon\n * @param {number} dist\n * @param {number} angle\n * @param {object} options\n * @param {[number, number]} pivotBias\n */\nfunction drawMassPass(polygon, dist, angle, options, pivotBias, toAngleUnit) {\n hatch(dist, angle, options);\n drawMassArcs(polygon, pivotBias, toAngleUnit);\n}\n\n/**\n * Creates the built-in \"massing\" effect for a polygon or plot.\n * A mass is built from up to three jittered polygon layers, each hatched and\n * then redrawn as arc gestures around a shared pivot bias.\n * @param {Polygon|Plot} shape\n * @param {number|false} x\n * @param {number} y\n * @param {number} scale\n */\nexport function createMass(shape, x, y, scale) {\n const pols = getMassPolygons(shape, x, y, scale);\n const hatchState = HatchState();\n const brushState = BrushState();\n const fieldState = { ...State.field };\n const precision = State.mass.options?.precision ?? 0.5;\n const strength = State.mass.options?.strength ?? 1;\n const gradient = State.mass.options?.gradient ?? 0.1;\n const outline = State.mass.options?.outline ?? false;\n const scatter = getBrushParams(State.mass.brush)?.scatter ?? 0;\n const hatchDist = 1.6 * rr2(scatter * 0.65, scatter * 0.85) - 0.4 * gradient;\n const baseAngle = rr2(-90, 90);\n const pivotBias = getPivotBias(baseAngle);\n const toAngleUnit = getAngleConverter();\n\n set(State.mass.brush, State.mass.color, 1);\n wiggle(2 - precision);\n if (outline) pols[0].draw();\n\n drawMassPass(\n pols[0],\n hatchDist * 0.9,\n fromDegrees(baseAngle),\n {\n gradient,\n rand: 2 - 2 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n\n if (strength > 0.33) {\n drawMassPass(\n pols[1],\n hatchDist,\n fromDegrees(baseAngle + 20 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n if (strength > 0.66) {\n drawMassPass(\n pols[2],\n hatchDist * 0.8,\n fromDegrees(baseAngle + 15 * rr2(-1, 1)),\n {\n gradient,\n rand: 0.6 - 0.6 * precision,\n continuous: true,\n },\n pivotBias,\n toAngleUnit,\n );\n }\n\n BrushSetState(brushState);\n HatchSetState(hatchState);\n State.field = { ...fieldState };\n}\n\n// ---------------------------------------------------------------------------\n// Prototype Extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Applies massing to polygon geometry.\n */\nPolygon.prototype.mass = function () {\n if (State.mass?.isActive) {\n createMass(this, false);\n }\n};\n\n/**\n * Applies massing to plots by generating their polygon first.\n * @param {number} x\n * @param {number} y\n * @param {number} scale\n */\nPlot.prototype.mass = function (x, y, scale) {\n if (State.mass?.isActive) {\n if (this.origin) ((x = this.origin[0]), (y = this.origin[1]), (scale = 1));\n createMass(this, x, y, scale);\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","import * as Color from \"../core/color.js\";\nimport {\n createFramebuffer,\n create2DCanvas,\n} from \"../core/compositor_runtime.js\";\n\n// Small staging canvas used to upload only the dirty fill sub-rect into the\n// framebuffer-backed mask mirror consumed by the blend shader.\nlet FillMaskUploadCanvas = null;\nlet isFillCompositeRegistered = false;\nconst DIRTY_FILL_PADDING = 4;\n\n// =============================================================================\n// Section: Helpers\n// =============================================================================\n/**\n * Returns whether the CPU-side 2D fill mask must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} maskWidth - Mask width in physical pixels.\n * @param {number} maskHeight - Mask height in physical pixels.\n * @returns {boolean} True when the 2D fill mask needs reallocation.\n */\nfunction needsFillMaskCanvas(Renderer, maskWidth, maskHeight) {\n return (\n !Renderer.mask ||\n Renderer.mask.width !== maskWidth ||\n Renderer.mask.height !== maskHeight\n );\n}\n\n/**\n * Returns whether the framebuffer-backed fill mask mirror must be recreated.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @returns {boolean} True when the fill mask framebuffer needs reallocation.\n */\nfunction needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density) {\n return (\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 );\n}\n\n// =============================================================================\n// Section: Resource Management\n// =============================================================================\n/**\n * Ensures fill compositing resources exist for the active renderer.\n *\n * Fill draws first into a CPU-side 2D mask canvas. That mask is later uploaded,\n * dirty-rect by dirty-rect, into a framebuffer-backed mirror used by the final\n * blend shader pass.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {number} Cwidth - Target width in sketch units.\n * @param {number} Cheight - Target height in sketch units.\n * @param {number} Density - Active pixel density.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {{mask: object, ctx: CanvasRenderingContext2D}} Fill mask resources.\n */\nexport function ensureFillCompositeResources(\n Renderer,\n Cwidth,\n Cheight,\n Density,\n clearTarget,\n) {\n const maskWidth = Math.max(1, Math.round(Cwidth * Density));\n const maskHeight = Math.max(1, Math.round(Cheight * Density));\n\n if (needsFillMaskCanvas(Renderer, maskWidth, maskHeight)) {\n Renderer.mask = create2DCanvas(maskWidth, maskHeight);\n }\n\n if (needsFillMaskFramebuffer(Renderer, Cwidth, Cheight, Density)) {\n if (Renderer.fillMaskFramebuffer?.remove) {\n Renderer.fillMaskFramebuffer.remove();\n }\n Renderer.fillMaskFramebuffer = createFramebuffer(Renderer, {\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 Renderer.mask.dirtyRect ??= null;\n Renderer.mask.isDrawn ??= false;\n Renderer.mask.drawingContext.imageSmoothingEnabled = false;\n return {\n mask: Renderer.mask,\n ctx: Renderer.mask.drawingContext,\n };\n}\n\n// =============================================================================\n// Section: Mask Lifecycle\n// =============================================================================\n/**\n * Clears the current fill mask and resets its bookkeeping flags.\n *\n * @param {object|null} target - Fill mask canvas or framebuffer mirror.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n */\nexport function clearFillMask(target, clearTarget) {\n if (!target) return;\n clearTarget(target);\n target.isDrawn = false;\n target.dirtyRect = null;\n}\n\n// =============================================================================\n// Section: Composite Bounds\n// =============================================================================\n/**\n * Returns the fill dirty rect to composite into the main target. Fill bounds are\n * taken directly from the accumulated 2D mask dirty area plus a small padding.\n *\n * @param {object|null} target - Fill mask canvas.\n * @param {Function} _getActiveFramebuffer - Unused for fill masks.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} expandDirtyRect - Expands a rect by a constant padding.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null} Composite rect.\n */\nexport function getFillCompositeRect(\n target,\n _getActiveFramebuffer,\n getFullDirtyRect,\n expandDirtyRect,\n normalizeDirtyRect,\n) {\n if (!target) return null;\n if (!target.dirtyRect) return getFullDirtyRect();\n return normalizeDirtyRect(\n expandDirtyRect(target.dirtyRect, DIRTY_FILL_PADDING),\n );\n}\n\n// =============================================================================\n// Section: Upload\n// =============================================================================\n/**\n * Uploads only the dirty portion of the CPU-side 2D fill mask into the\n * framebuffer-backed fill mask mirror used by the shader compositor.\n *\n * @param {object} Renderer - Active host renderer.\n * @param {object} mask - CPU-side 2D fill mask canvas.\n * @param {{minX:number,minY:number,maxX:number,maxY:number}|null} dirtyRect - Dirty rect to upload.\n * @param {Function} normalizeDirtyRect - Clamps a rect to target bounds.\n * @param {Function} getFullDirtyRect - Returns the full-target dirty rect.\n * @param {Function} clearTarget - Shared low-level clear helper from core.\n * @returns {object} Framebuffer-backed fill mask mirror.\n */\nexport function getFillShaderMask(\n Renderer,\n mask,\n dirtyRect,\n normalizeDirtyRect,\n getFullDirtyRect,\n clearTarget,\n) {\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 = create2DCanvas(uploadWidth, uploadHeight);\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 return target;\n}\n\n// =============================================================================\n// Section: Registration\n// =============================================================================\n/**\n * Registers the fill compositor with the shared color/composite core.\n * Safe to call multiple times.\n */\nexport function initFillComposite() {\n if (isFillCompositeRegistered) return;\n Color.registerFillComposite?.({\n ensureResources: ensureFillCompositeResources,\n clearMask: clearFillMask,\n getCompositeRect: getFillCompositeRect,\n getShaderMask: getFillShaderMask,\n });\n isFillCompositeRegistered = true;\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\n// Core imports\nimport { Renderer, Cwidth, Cheight, Density } from \"../core/target.js\";\nimport {\n Mix,\n State,\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 } from \"../core/flowfield.js\";\nimport { createColor, getAffineMatrix } from \"../core/runtime.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\n\n// Internal module imports\nimport { initFillComposite } from \"./composite.js\";\n\ninitFillComposite(); // Register the fill composite with the core color module\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 = 2024;\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 = arguments.length < 3 ? createColor(a) : createColor(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 === 0) {\n return { x: 0, y: 0 };\n }\n\n if (pts.length < 8) {\n // Simple average for small polygons\n const sum = pts.reduce(\n (center, point) => ({ x: center.x + point.x, y: center.y + point.y }),\n { x: 0, y: 0 },\n );\n return { x: sum.x / pts.length, y: sum.y / 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\n // We want to add at least two vertices to divide the new edge that appears after trimming, at random distances along its path\n const trimStart = s;\n const trimEnd = s + n;\n const edgeStart = this.v[(trimStart - 1 + this.v.length) % this.v.length];\n const edgeEnd = this.v[trimEnd % this.v.length];\n const edgeVec = { x: edgeEnd.x - edgeStart.x, y: edgeEnd.y - edgeStart.y };\n \n // Insert two new vertices at random positions along the new edge\n const insertCount = 2;\n for (let i = 0; i < insertCount; i++) {\n const t = rr(0.25, 0.75); // Random position between 25% and 75% along the edge\n const newVertex = { x: edgeStart.x + edgeVec.x * t, y: edgeStart.y + edgeVec.y * t };\n const insertIdx = s + i;\n v.splice(insertIdx, 0, newVertex);\n m.splice(insertIdx, 0, rr(0.4, 0.7));\n dir.splice(insertIdx, 0, this.dir[trimStart % this.dir.length]);\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 // If mod is smaller than 0.02, skip growing math and just insert the middle vertex\n if (mod < 0.05) {\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedX[insertedIdx] = (cv.x + nv.x) / 2;\n insertedY[insertedIdx] = (cv.y + nv.y) / 2;\n newMods[idx] = mi;\n newDirs[idx] = di;\n idx++;\n insertedIdx++;\n continue;\n }\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 * Math.max(0.1, 2 * State.fill.bleed_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 const m = getAffineMatrix();\n Mix.ctx.save();\n Mix.ctx.setTransform(\n Density * m.a,\n Density * m.b,\n Density * m.c,\n Density * m.d,\n Density * (m.x + Cwidth / 2),\n Density * (m.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);\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.3);\n const minSizeFactor = 0.03 * minSize;\n const maxSizeFactor = 0.45 * 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 State.fill.bleed_strength < 0.06\n ? 0\n : map(State.fill.bleed_strength, 0, 0.6, 0.2, 0.60, true),\n );\n this.pol.fill();\n }\n};\n","\nexport default function earcut(data, holeIndices, dim = 2) {\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let minX, minY, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = data[0];\n minY = data[1];\n let maxX = minX;\n let maxY = minY;\n\n for (let i = dim; i < outerLen; i += dim) {\n const x = data[i];\n const y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n let last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n } else {\n for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n let p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n let stop = ear;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n const prev = ear.prev;\n const next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n triangles.push(prev.i, ear.i, next.i); // cut off the triangle\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n let p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n const a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox\n const x0 = Math.min(ax, bx, cx),\n y0 = Math.min(ay, by, cy),\n x1 = Math.max(ax, bx, cx),\n y1 = Math.max(ay, by, cy);\n\n // z-order range for the current triangle bbox;\n const minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n let p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles) {\n let p = start;\n do {\n const a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i, p.i, b.i);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n let a = start;\n do {\n let b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n let c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n const queue = [];\n\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n const list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareXYSlope);\n\n // process holes from left to right\n for (let i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareXYSlope(a, b) {\n let result = a.x - b.x;\n // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find\n // the bridge to the outer shell is always the point that they meet at.\n if (result === 0) {\n result = a.y - b.y;\n if (result === 0) {\n const aSlope = (a.next.y - a.y) / (a.next.x - a.x);\n const bSlope = (b.next.y - b.y) / (b.next.x - b.x);\n result = aSlope - bSlope;\n }\n }\n return result;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole(hole, outerNode) {\n const bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n const bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n // unless they intersect at a vertex, then choose the vertex\n if (equals(hole, p)) return p;\n do {\n if (equals(hole, p.next)) return p.next;\n else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n let p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n let numMerges;\n let inSize = 1;\n\n do {\n let p = list;\n let e;\n list = null;\n let tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n let q = p;\n let pSize = 0;\n for (let i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n let qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n let p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a point lies within a convex triangle but false if its equal to the first point of the triangle\nfunction pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {\n return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n let p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n const a2 = createNode(a.i, a.x, a.y),\n b2 = createNode(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n const p = createNode(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction createNode(i, x, y) {\n return {\n i, // vertex index in coordinates array\n x, y, // vertex coordinates\n prev: null, // previous and next vertex nodes in a polygon ring\n next: null,\n z: 0, // z-order curve value\n prevZ: null, // previous and next nodes in z-order\n nextZ: null,\n steiner: false // indicates whether this is a steiner point\n };\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nexport function deviation(data, holeIndices, dim, triangles) {\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (let i = 0, len = holeIndices.length; i < len; i++) {\n const start = holeIndices[i] * dim;\n const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n let trianglesArea = 0;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = triangles[i] * dim;\n const b = triangles[i + 1] * dim;\n const c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n}\n\nfunction signedArea(data, start, end, dim) {\n let sum = 0;\n for (let i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nexport function flatten(data) {\n const vertices = [];\n const holes = [];\n const dimensions = data[0][0].length;\n let holeIndex = 0;\n let prevLen = 0;\n\n for (const ring of data) {\n for (const p of ring) {\n for (let d = 0; d < dimensions; d++) vertices.push(p[d]);\n }\n if (prevLen) {\n holeIndex += prevLen;\n holes.push(holeIndex);\n }\n prevLen = ring.length;\n }\n return {vertices, holes, dimensions};\n}\n","// =============================================================================\n// Module: Wash\n// =============================================================================\n/**\n * Minimal stateful API for the `wash()` fill modifier.\n */\n\nimport earcut from \"earcut\";\nimport { Renderer, Cwidth, Cheight, isCanvasReady } from \"../core/target.js\";\nimport { State, flushActiveComposite } from \"../core/color.js\";\nimport { Polygon } from \"../core/polygon.js\";\nimport { Plot } from \"../core/plot.js\";\nimport { getAffineMatrix } from \"../core/runtime.js\";\nimport { createProgram } from \"../core/gl/utils.js\";\nimport { createColor } from \"../core/runtime.js\";\nimport { resetDirectShaderTracking } from \"../core/renderer_runtime.js\";\n\nlet gl = null;\nlet washProgram = null;\nlet washVao = null;\nlet washBuffer = null;\nlet washProjection = null;\nlet loadedWidth = 0;\nlet loadedHeight = 0;\nlet washGpuBufferSize = 0;\n\nconst WashAttr = {};\nconst WashUniform = {};\n\nconst washVertSrc = `#version 300 es\nin vec2 a_position;\nuniform mat4 u_matrix;\nvoid main() {\n gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n}`;\n\nconst washFragSrc = `#version 300 es\nprecision highp float;\nuniform vec4 u_color;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(u_color.rgb * u_color.a, u_color.a);\n}`;\n\nState.wash = {\n color: null,\n opacity: 150,\n isActive: false,\n};\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Enables wash mode with a color and opacity.\n *\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 wash(a, b, c, d) {\n isCanvasReady();\n State.wash.opacity = (arguments.length < 4 ? b : d) ?? 150;\n State.wash.color = arguments.length < 3 ? createColor(a) : createColor(a, b, c);\n State.wash.isActive = true;\n}\n\n/**\n * Disables wash mode for subsequent drawing operations.\n */\nexport function noWash() {\n State.wash.isActive = false;\n}\n\n// =============================================================================\n// GL helpers\n// =============================================================================\n\n/**\n * Lazily creates the reusable program/buffer state for solid wash drawing and\n * refreshes the orthographic projection when the active target size changes.\n */\nfunction ensureWashReady() {\n const nextGl = Renderer.drawingContext;\n const sizeChanged = loadedWidth !== Cwidth || loadedHeight !== Cheight;\n\n if (!washProjection || sizeChanged) {\n loadedWidth = Cwidth;\n loadedHeight = Cheight;\n washProjection = new Float32Array([\n 2 / loadedWidth,\n 0,\n 0,\n 0,\n 0,\n -2 / loadedHeight,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n -1,\n 1,\n 0,\n 1,\n ]);\n }\n\n if (gl === nextGl && washProgram && washVao && washBuffer) return;\n\n gl = nextGl;\n washProgram = createProgram(gl, washVertSrc, washFragSrc);\n WashAttr.a_position = gl.getAttribLocation(washProgram, \"a_position\");\n WashUniform.u_matrix = gl.getUniformLocation(washProgram, \"u_matrix\");\n WashUniform.u_color = gl.getUniformLocation(washProgram, \"u_color\");\n\n washVao = gl.createVertexArray();\n gl.bindVertexArray(washVao);\n\n washBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, 0, gl.DYNAMIC_DRAW);\n washGpuBufferSize = 0;\n\n gl.enableVertexAttribArray(WashAttr.a_position);\n gl.vertexAttribPointer(WashAttr.a_position, 2, gl.FLOAT, false, 8, 0);\n\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n}\n\n/**\n * Applies the current runtime affine transform and converts the result into\n * the screen-space coordinates used by the direct GL wash pipeline.\n *\n * @param {number} x - The source x-coordinate in brush drawing space.\n * @param {number} y - The source y-coordinate in brush drawing space.\n * @returns {[number, number]} The transformed screen-space position.\n */\nfunction transformVertexToScreen(x, y) {\n const m = getAffineMatrix();\n return [\n m.a * x + m.c * y + m.x + loadedWidth / 2,\n m.b * x + m.d * y + m.y + loadedHeight / 2,\n ];\n}\n\n/**\n * Triangulates a polygon in local space and returns the transformed triangle\n * vertex buffer ready for upload to the GPU.\n *\n * @param {Polygon} polygon - The polygon to triangulate.\n * @returns {{ triangles: Float32Array, vertexCount: number }} Screen-space\n * triangle vertices plus the number of vertices to draw.\n */\nfunction buildTriangleBuffer(polygon) {\n const flat = new Float32Array(polygon.vertices.length * 2);\n for (let i = 0; i < polygon.vertices.length; i++) {\n const vertex = polygon.vertices[i];\n flat[i * 2] = vertex.x;\n flat[i * 2 + 1] = vertex.y;\n }\n\n const indices = earcut(flat);\n const triangles = new Float32Array(indices.length * 2);\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n const [screenX, screenY] = transformVertexToScreen(flat[idx * 2], flat[idx * 2 + 1]);\n triangles[i * 2] = screenX;\n triangles[i * 2 + 1] = screenY;\n }\n\n return {\n triangles,\n vertexCount: indices.length,\n };\n}\n\n/**\n * Draws a triangulated solid wash directly to the current GL target.\n *\n * @param {Polygon} polygon - The polygon to fill with the current wash state.\n */\nfunction drawWashPolygon(polygon) {\n if (!State.wash?.isActive || !State.wash.color || polygon.vertices.length < 3) return;\n\n flushActiveComposite();\n ensureWashReady();\n const { triangles, vertexCount } = buildTriangleBuffer(polygon);\n const byteCount = triangles.byteLength;\n gl.useProgram(washProgram);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.bindVertexArray(washVao);\n gl.bindBuffer(gl.ARRAY_BUFFER, washBuffer);\n if (byteCount > washGpuBufferSize) {\n gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.DYNAMIC_DRAW);\n washGpuBufferSize = byteCount;\n } else {\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, triangles);\n }\n const color = State.wash.color._array;\n gl.uniformMatrix4fv(WashUniform.u_matrix, false, washProjection);\n gl.uniform4f(\n WashUniform.u_color,\n color[0],\n color[1],\n color[2],\n State.wash.opacity / 255,\n );\n\n gl.drawArrays(gl.TRIANGLES, 0, vertexCount);\n gl.bindVertexArray(null);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n resetDirectShaderTracking(Renderer, gl);\n}\n\n// =============================================================================\n// Prototype methods\n// =============================================================================\n\n/**\n * Applies a direct GL wash fill to the polygon using the current wash state.\n *\n * @param {Color|string|false} [_color] - Optional override color for this call.\n * @param {number} [_opacity] - Optional override opacity for this call.\n */\nPolygon.prototype.wash = function (_color = false, _opacity) {\n const state = { ...State.wash };\n if (_color !== false) wash(_color, _opacity);\n\n if (State.wash.isActive) {\n drawWashPolygon(this);\n }\n\n State.wash = { ...state };\n};\n\n/**\n * Applies wash to a plot by first generating the plot polygon, mirroring the\n * existing fill-path behavior, and then drawing that polygon with wash.\n *\n * @param {number} x - The x-coordinate.\n * @param {number} y - The y-coordinate.\n * @param {number} scale - The scale factor.\n */\nPlot.prototype.wash = function (x, y, scale) {\n if (!State.wash?.isActive) return;\n if (this.origin) {\n x = this.origin[0];\n y = this.origin[1];\n scale = 1;\n }\n this.pol = this.genPol(x, y, scale, 0, -1);\n this.pol.wash();\n};\n","// =============================================================================\n// Adapter: Standalone Renderer Hooks\n// =============================================================================\n\nimport { Cwidth, Cheight, Density } from \"../../core/target.js\";\nimport { setRendererRuntime } from \"../../core/renderer_runtime.js\";\n\nfunction beginDirectMaskDraw(_renderer, gl, target) {\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n if (hadDepthTest) gl.disable(gl.DEPTH_TEST);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\n gl.viewport(0, 0, target.width * target.density, target.height * target.density);\n\n return { hadDepthTest };\n}\n\nfunction endDirectMaskDraw(renderer, gl, state) {\n if (state?.hadDepthTest) gl.enable(gl.DEPTH_TEST);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.viewport(\n 0,\n 0,\n Math.max(1, Math.round(Cwidth * Density)),\n Math.max(1, Math.round(Cheight * Density)),\n );\n}\n\nfunction resetStandaloneShaderTracking(_renderer, gl) {\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\nexport function initStandaloneRendererRuntime() {\n setRendererRuntime({\n beginDirectMaskDraw,\n endDirectMaskDraw,\n resetDirectShaderTracking: resetStandaloneShaderTracking,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Compositor Hooks\n// =============================================================================\n\nimport { createProgram } from \"../../core/gl/utils.js\";\nimport {\n setCompositorRuntime,\n blitDefaultFramebufferSource,\n} from \"../../core/compositor_runtime.js\";\n\nfunction clearTarget(renderer, target, isFramebufferTarget) {\n if (!target) return;\n\n if (isFramebufferTarget(target)) {\n const gl = renderer.drawingContext;\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousViewport = gl.getParameter(gl.VIEWPORT);\n gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer);\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 gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n gl.viewport(\n previousViewport[0],\n previousViewport[1],\n previousViewport[2],\n previousViewport[3],\n );\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\nfunction makeShader(gl, vertSrc, fragSrc) {\n const program = createProgram(gl, vertSrc, fragSrc);\n const uniformCache = new Map();\n\n const getUniformLocation = (name) => {\n if (!uniformCache.has(name)) {\n uniformCache.set(name, gl.getUniformLocation(program, name));\n }\n return uniformCache.get(name);\n };\n\n return {\n program,\n setUniform(name, value) {\n const location = getUniformLocation(name);\n if (!location) return;\n if (typeof value === \"boolean\") {\n gl.uniform1i(location, value ? 1 : 0);\n return;\n }\n if (typeof value === \"number\") {\n gl.uniform1f(location, value);\n return;\n }\n if (Array.isArray(value)) {\n if (value.length === 3) gl.uniform3f(location, value[0], value[1], value[2]);\n else if (value.length === 4) gl.uniform4f(location, value[0], value[1], value[2], value[3]);\n return;\n }\n },\n };\n}\n\nfunction ensureBlendShaderProgram(renderer, vertSrc, fragSrc) {\n renderer.shaderProgram ??= makeShader(renderer.drawingContext, vertSrc, fragSrc);\n return renderer.shaderProgram;\n}\n\nfunction createFramebufferTexture(gl, width, height) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n gl.RGBA,\n width,\n height,\n 0,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n null,\n );\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 gl.bindTexture(gl.TEXTURE_2D, null);\n return texture;\n}\n\nfunction createFramebuffer(renderer, options) {\n const gl = renderer.drawingContext;\n const density = options.density ?? 1;\n const framebuffer = gl.createFramebuffer();\n const width = Math.max(1, options.width);\n const height = Math.max(1, options.height);\n const pixelWidth = Math.max(1, Math.round(width * density));\n const pixelHeight = Math.max(1, Math.round(height * density));\n const colorTexture = createFramebufferTexture(gl, pixelWidth, pixelHeight);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER,\n gl.COLOR_ATTACHMENT0,\n gl.TEXTURE_2D,\n colorTexture,\n 0,\n );\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n\n return {\n __brushFramebuffer: true,\n framebuffer,\n colorTexture,\n width,\n height,\n density,\n pixelDensity: () => density,\n remove() {\n gl.deleteFramebuffer(framebuffer);\n gl.deleteTexture(colorTexture);\n },\n };\n}\n\nfunction ensureBlendSourceFramebuffer(\n renderer,\n currentFramebuffer,\n width,\n height,\n density,\n) {\n currentFramebuffer?.remove?.();\n return createFramebuffer(renderer, {\n width,\n height,\n density,\n antialias: false,\n depth: false,\n stencil: false,\n });\n}\n\nfunction runBlendShaderPass({\n renderer,\n shader,\n source,\n mask,\n color,\n isBrushMask,\n dirtyRect,\n targetIsFramebuffer,\n withScissor,\n}) {\n const gl = renderer.drawingContext;\n const hadDepthTest = gl.isEnabled(gl.DEPTH_TEST);\n const previousFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);\n const previousProgram = gl.getParameter(gl.CURRENT_PROGRAM);\n const previousVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);\n\n const quadVao = gl.createVertexArray();\n gl.bindVertexArray(quadVao);\n gl.useProgram(shader.program);\n gl.disable(gl.DEPTH_TEST);\n gl.enable(gl.BLEND);\n gl.blendEquation(gl.FUNC_ADD);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, source.colorTexture);\n gl.uniform1i(gl.getUniformLocation(shader.program, \"u_source\"), 0);\n\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, mask.colorTexture);\n gl.uniform1i(gl.getUniformLocation(shader.program, \"u_mask\"), 1);\n\n shader.setUniform(\"u_targetIsFramebuffer\", targetIsFramebuffer);\n shader.setUniform(\"u_isBrush\", isBrushMask);\n gl.uniform3f(\n gl.getUniformLocation(shader.program, \"u_color\"),\n color[0],\n color[1],\n color[2],\n );\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n withScissor(\n gl,\n dirtyRect,\n () => {\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n },\n !targetIsFramebuffer,\n );\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.activeTexture(gl.TEXTURE0);\n gl.bindVertexArray(previousVao);\n gl.useProgram(previousProgram);\n gl.bindFramebuffer(gl.FRAMEBUFFER, previousFramebuffer);\n if (hadDepthTest) gl.enable(gl.DEPTH_TEST);\n gl.deleteVertexArray(quadVao);\n}\n\nfunction blitSourceToFramebuffer(args) {\n return blitDefaultFramebufferSource(args);\n}\n\nexport function initStandaloneCompositorRuntime() {\n setCompositorRuntime({\n clearTarget,\n ensureBlendShaderProgram,\n ensureBlendSourceFramebuffer,\n createFramebuffer,\n runBlendShaderPass,\n blitSourceToFramebuffer,\n });\n}\n","// =============================================================================\n// Adapter: Standalone Stroke Hooks\n// =============================================================================\n\nimport { create2DCanvas, get2DContext } from \"../../core/compositor_runtime.js\";\nimport { setStrokeRuntime } from \"../../stroke/runtime.js\";\n\nfunction cssColor(value) {\n if (typeof value === \"number\") {\n const c = Math.max(0, Math.min(255, value));\n return `rgb(${c} ${c} ${c})`;\n }\n return value ?? \"black\";\n}\n\nfunction buildTipSurface(canvas) {\n const ctx = get2DContext(canvas, true);\n const surface = {\n canvas,\n drawingContext: ctx,\n width: canvas.width,\n height: canvas.height,\n pixels: null,\n _fillStyle: \"#ffffff\",\n _strokeStyle: \"transparent\",\n _lineWidth: 1,\n\n pixelDensity() {\n return 1;\n },\n\n background(value) {\n ctx.save();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.fillStyle = cssColor(value);\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n ctx.restore();\n },\n\n noSmooth() {\n ctx.imageSmoothingEnabled = false;\n },\n\n push() {\n ctx.save();\n },\n\n pop() {\n ctx.restore();\n },\n\n translate(x, y) {\n ctx.translate(x, y);\n },\n\n scale(x, y = x) {\n ctx.scale(x, y);\n },\n\n rotate(angle) {\n ctx.rotate(angle);\n },\n\n noStroke() {\n surface._strokeStyle = \"transparent\";\n },\n\n stroke(value) {\n surface._strokeStyle = cssColor(value);\n },\n\n noFill() {\n surface._fillStyle = \"transparent\";\n },\n\n fill(value) {\n surface._fillStyle = cssColor(value);\n },\n\n strokeWeight(value) {\n surface._lineWidth = value;\n },\n\n rect(x, y, w, h) {\n ctx.beginPath();\n ctx.rect(x, y, w, h);\n surface._paint();\n },\n\n circle(x, y, d) {\n ctx.beginPath();\n ctx.arc(x, y, d / 2, 0, Math.PI * 2);\n surface._paint();\n },\n\n ellipse(x, y, w, h) {\n ctx.beginPath();\n ctx.ellipse(x, y, w / 2, h / 2, 0, 0, Math.PI * 2);\n surface._paint();\n },\n\n line(x1, y1, x2, y2) {\n ctx.beginPath();\n ctx.moveTo(x1, y1);\n ctx.lineTo(x2, y2);\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n },\n\n beginShape() {\n ctx.beginPath();\n surface._shapeStarted = false;\n },\n\n vertex(x, y) {\n if (!surface._shapeStarted) {\n ctx.moveTo(x, y);\n surface._shapeStarted = true;\n } else {\n ctx.lineTo(x, y);\n }\n },\n\n endShape(close = false) {\n if (close) ctx.closePath();\n surface._paint();\n },\n\n loadPixels() {\n surface.pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;\n },\n\n updatePixels() {\n const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n imageData.data.set(surface.pixels);\n ctx.putImageData(imageData, 0, 0);\n },\n\n _paint() {\n if (surface._fillStyle !== \"transparent\") {\n ctx.fillStyle = surface._fillStyle;\n ctx.fill();\n }\n if (surface._strokeStyle !== \"transparent\") {\n ctx.strokeStyle = surface._strokeStyle;\n ctx.lineWidth = surface._lineWidth;\n ctx.stroke();\n }\n },\n };\n\n return surface;\n}\n\nfunction createTipSurface(width, height) {\n return buildTipSurface(create2DCanvas(width, height, true));\n}\n\nfunction loadImageTip(src, imageToWhite) {\n return new Promise((resolve, reject) => {\n const NativeImage = globalThis.Image;\n if (!NativeImage) {\n reject(new Error(\"Standalone image brush loading requires Image support.\"));\n return;\n }\n\n const nativeImg = new NativeImage();\n nativeImg.onload = () => {\n const surface = buildTipSurface(\n create2DCanvas(nativeImg.naturalWidth, nativeImg.naturalHeight, true),\n );\n surface.drawingContext.drawImage(nativeImg, 0, 0);\n imageToWhite(surface);\n resolve(surface);\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\nexport function initStandaloneStrokeRuntime() {\n setStrokeRuntime({\n createTipSurface,\n loadImageTip,\n });\n}\n","/**\n * @fileoverview Standalone entry point for brush.\n */\n\nexport * from \"./adapters/standalone/runtime.js\";\nexport * from \"./adapters/standalone/frame.js\";\nexport { createCanvas } from \"./adapters/standalone/target.js\";\nexport * from \"./index.shared.js\";\n\nimport { initStandaloneTargetRuntime } from \"./adapters/standalone/target.js\";\nimport { initStandaloneRendererRuntime } from \"./adapters/standalone/renderer.js\";\nimport { initStandaloneCompositorRuntime } from \"./adapters/standalone/compositor.js\";\nimport { initStandaloneStrokeRuntime } from \"./adapters/standalone/stroke.js\";\nimport { initStandaloneRuntime } from \"./adapters/standalone/runtime.js\";\n\ninitStandaloneTargetRuntime();\ninitStandaloneRuntime();\ninitStandaloneRendererRuntime();\ninitStandaloneCompositorRuntime();\ninitStandaloneStrokeRuntime();\n","// =============================================================================\n// Adapter: Standalone Frame Helpers\n// =============================================================================\n\nimport { Renderer, isCanvasReady } from \"../../core/target.js\";\nimport { Mix, flushActiveComposite } from \"../../core/color.js\";\nimport { createColor } from \"../../core/runtime.js\";\n\nfunction resetCompositeState() {\n if (Mix.glMask) Mix.clearMask(Mix.glMask);\n if (Mix.mask) Mix.clearMask(Mix.mask);\n Mix.justChanged = false;\n Mix.isBlending = false;\n Mix.isBrush = null;\n Mix.cachedColor = null;\n}\n\n/**\n * Flushes any pending stroke/fill compositing into the active standalone target.\n *\n * Standalone users should call this at the end of a drawing pass or frame.\n */\nexport function render() {\n flushActiveComposite();\n}\n\n/**\n * Clears the active standalone target.\n *\n * With no arguments, clears to transparent white.\n * With a color, clears to that color at full opacity.\n *\n * @param {...*} args\n */\nexport function clear(...args) {\n isCanvasReady();\n resetCompositeState();\n\n const gl = Renderer.drawingContext;\n const color =\n args.length === 0\n ? [1, 1, 1, 0]\n : [...createColor(...args)._array.slice(0, 3), 1];\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.disable(gl.SCISSOR_TEST);\n gl.clearColor(color[0], color[1], color[2], color[3]);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n}\n"],"names":["identityMatrix","a","b","c","d","x","y","Cwidth","Cheight","Renderer","Density","usesRadians","fromDegrees","angle","createColor","Error","getAffineMatrix","targetRuntime","load","syncDensity","isCanvasReady","instance","inst","activateInstance","deactivateInstance","getActiveFramebuffer","isFramebufferTarget","setTargetState","state","Instance","target","expandDirtyRect","rect","padding","minX","minY","maxX","maxY","create2DCanvas","width","height","willReadFrequently","canvas","OffscreenCanvas","element","document","createElement","drawingContext","getContext","undefined","compositorRuntime","clearTarget","ensureBlendShaderProgram","ensureBlendSourceFramebuffer","createFramebuffer","runBlendShaderPass","blitSourceToFramebuffer","args","strokeComposite","fillComposite","clearRenderTarget","getTargetPixelSize","Math","max","round","normalizeDirtyRect","floor","min","ceil","clampDirtyRect","getFullDirtyRect","getFullRect","toScissorBox","flipY","normalized","withScissor","gl","draw","box","enable","SCISSOR_TEST","scissor","disable","State","isMixReady","loaded","Mix","isBlending","cachedColor","markDirtyRect","dirtyRect","isDrawn","clearMask","composite","this","glMask","getCompositeRect","isBrushMask","needsBlendSourceFramebuffer","blendSourceFramebuffer","pixelDensity","ensureResources","fillResources","mask","ctx","blend","_color","_isLast","isBrush","otherMask","nextColor","_array","colorChanged","justChanged","applyShader","shader","shaderProgram","activeFramebuffer","source","renderer","sourceTarget","sourceFramebuffer","targetIsFramebuffer","shaderMask","getShaderMask","color","flushActiveComposite","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","s0","s1","s2","copy","f","rng","rng2","_seedCallbacks","_onSeed","cb","push","noise","noise2","rr","e","rr2","rArray","array","randInt","randInt2","gaussian","mean","stdev","u","log","cos","weightedRand","weights","totalWeight","entries","key","cumulative","rnd","isNaN","parseInt","value","withinBounds","constrain","low","high","nAngle","totalDegrees","radiansPerIndex","PI","cLookup","Float32Array","fill","NaN","sLookup","idx","sin","toDegrees","rad","isRad","runtimeUsesRadians","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","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","m","mx","my","update","plotted","colIdx","rowIdx","reset","isIn","isActive","isInCanvas","skipCheck","list","get","current","wiggle","moveTo","_dir","_length","_step_length","movePos","_moveToDegrees","plotTo","_plot","_scale","_dirPlot","_step","scaleFactor","steps","fieldActive","usePlot","getRowIndex","y_offset","getColIndex","x_offset","col","row","Map","FIELD_ANGLE_MODES","Set","normalizeFieldAngleMode","options","angleMode","has","generateField","entry","normalizeFieldAngles","gen","keys","join","name","funct","set","fn","_stateStack","clamp","DEGREES","RADIANS","colorContext","currentAngleMode","transformStack","currentTransform","multiplyTransform","left","right","Color","g","hex","rgbToHex","rgbaMatch","exec","alpha","parseFloat","standardize","rgb","hexToRgb","toString","slice","replace","_match","red","green","blue","result","getColorContext","fillStyle","_getRed","_getGreen","_getBlue","initStandaloneRuntime","hooks","_current","_curvature","_strokeArray","_strokeOrigin","activeTarget","activeDensity","activeWidth","activeHeight","applyLoadedTarget","density","premultipliedAlpha","getTargetContext","createRenderer","Polygon","pointsArray","useRawVertices","vertices","sides","arr","_intersectionCache","intersect","line","cacheKey","point1","point2","points","start","end","intersection","show","wash","mass","hatch","stroke","Plot","_type","segments","angles","pres","type","calcIndex","pol","addSegment","_a","_pres","_degrees","pop","reduce","sum","len","endPlot","pressure","_d","curving","index","map0","map1","suma","genPol","_x","_y","_side","step","numSteps","pos","pside","prevIdx","scale","arc","radius","startDeg","sweepDeg","segmentCount","segmentSweep","arcLength","startX","startY","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","halfDist","asin","origin","strokeRuntime","createTipSurface","loadImageTip","isStrokeCompositeRegistered","createProgram","frag","src","VERTEX_SHADER","FRAGMENT_SHADER","createShader","shaderSource","compileShader","attachShader","linkProgram","rendererRuntime","beginDirectMaskDraw","endDirectMaskDraw","resetDirectShaderTracking","framebufferProjMatrix","vao","buf","program","loadedWidth","loadedHeight","brushMaskTarget","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","getProjectionMatrix","beginMaskTarget","endMaskTarget","accumulateDirtyRect","currentRect","circle","diameter","newData","px","py","screenX","screenY","dScreenX","dScreenY","glDrawImages","p5img","targetState","tex","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","useProgram","BLEND","blendFunc","ONE_MINUS_DST_ALPHA","ONE","activeTexture","TEXTURE0","uniform1i","u_tex","uniform4f","u_color","uniformMatrix4fv","u_proj","bindVertexArray","bindBuffer","ARRAY_BUFFER","byteCount","dataView","subarray","bufferData","DYNAMIC_DRAW","byteLength","bufferSubData","drawArraysInstanced","TRIANGLE_STRIP","flush","needsStrokeMask","remove","antialias","depth","stencil","_Renderer","weight","opacity","DEFAULT_CUSTOM_PRESSURE_VARIATION","warp","tilt","BrushState","BrushSetState","add","params","includes","markerTip","vibration","scatter","definition","sharpness","quality","grain","min_max","curve","variation","isArray","mode","rest","range","ns","nm","ne","normalizePressure","tip","deleteTexture","delete","invalidateTexEntry","background","noSmooth","translate","noStroke","T","imageToWhite","tips","tipKey","param","colors","buffers","image","getBrushParams","brushName","pick","arguments","strokeWeight","_position","initializeDrawingState","plot","snapshotMatrix","gaussians","angleScale","isPlot","cp","ct","cs","ck","noiseoffset","rendererMask","ensureBrushMaskTarget","nextGl","needsContextRefresh","forEach","getAttribLocation","getUniformLocation","createVertexArray","createBuffer","enableVertexAttribArray","a_position","vertexAttribPointer","FLOAT","a_radius","a_alpha","clear","STATIC_DRAW","a_corner","a_pos","IMG_FLOATS","vertexAttribDivisor","a_size","a_angle","isReady","switchingToBrush","saveState","stepSize","spacing","totalSteps","pressureCount","cachedPressure","lineNoiseCount","cachedLineNoise","u_matrix","drawArrays","POINTS","glDraw","restoreState","calculatePressure","lineNoise","sw","iterations","rX","yRandomFactor","sqrtPart","drawSpray","drawMarker","drawImageTip","plotAngle","plotCos","plotSin","perp","along","drawDefault","simPressure","peakPos","halfWidth","pow","gauss","vibrate","rx","ry","size","overscan","maxPressure","scatterReach","tipReach","getImageTipOverscan","extraPadding","halfSize","extraRadius","base","boundsRadius","stampImage","_vals","_standard_brushes","obj","prototype","_brush","_weight","loadPixels","average","pixels","updatePixels","filter","k","Promise","all","then","HatchState","HatchSetState","rand","continuous","gradient","scanlineHatch","polygon","cosA","sinA","cosB","sinB","verts","rotated","Infinity","edges","eLen","Y","sort","scanY","getHatchLines","polygons","segs","poly","getHatchSegments","getActiveHatchConfig","lines","isConnector","prev","createHatch","drawSegment","save","hBrush","Object","values","drawFn","withHatchStyle","renderHatchSegments","jitterPolygon","jitterX","jitterY","projectAnchorToBisector","anchor","nx","ny","getShortArcAngles","toAngleUnit","endDeg","splitSegment","seg","gap","gx","gy","drawMassArcs","pivotBias","bias","bounds","getPolygonBounds","sx","sy","getPivotAnchor","parts","part","center","startAngle","endAngle","drawMassPass","createMass","shape","pols","isPolygon","brush","basePolygon","maxJitter","jitters","getMassPolygons","hatchState","brushState","fieldState","precision","strength","outline","hatchDist","baseAngle","_dist","_angle","_options","FillMaskUploadCanvas","isFillCompositeRegistered","maskWidth","maskHeight","needsFillMaskCanvas","fillMaskFramebuffer","needsFillMaskFramebuffer","imageSmoothingEnabled","_getActiveFramebuffer","uploadRect","uploadWidth","uploadHeight","uploadContext","clearRect","drawImage","colorTexture","texSubImage2D","bleed_strength","texture_strength","border_strength","direction","FillState","fillBleed","_i","_direction","fillTexture","_texture","_border","_polygon","_gaussians","_fillGaussianPools","_isLeft","FillPoly","isFirst","midP","rayCalc","v1","v2","side","rt","mid","ray","sizeX","sizeY","rc","count","isect","trim","keep","dst","trimStart","trimEnd","edgeStart","edgeEnd","edgeVec","newVertex","insertIdx","splice","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","setTransform","strokeStyle","lineCap","darker","sparse","layer","numLayers","erase","restore","lineWidth","matrix","getTransform","beginPath","first","tx","ty","lineTo","closePath","strokePadding","drawPolygon","numCircles","halfSizeX","halfSizeY","minSize","minSizeFactor","maxSizeFactor","midX","midY","globalCompositeOperation","filterPoints","again","steiner","equals","area","removeNode","earcutLinked","ear","triangles","dim","invSize","pass","z","zOrder","prevZ","nextZ","numMerges","inSize","tail","q","pSize","qSize","sortLinked","indexCurve","stop","isEarHashed","isEar","cureLocalIntersections","splitEarcut","ax","bx","pointInTriangleExceptFirst","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","pointInTriangle","intersectsPolygon","inside","middleInside","q1","q2","o1","sign","o2","o3","o4","onSegment","num","createNode","b2","an","bp","insertNode","last","_opacity","_bleed","fluid","modifiers","_","shift","shifted","pts","point","cross","_center","createFill","FillSetState","washProgram","washVao","washBuffer","washProjection","washGpuBufferSize","WashAttr","WashUniform","transformVertexToScreen","_renderer","hadDepthTest","isEnabled","DEPTH_TEST","bindFramebuffer","FRAMEBUFFER","framebuffer","viewport","resetStandaloneShaderTracking","blendEquation","FUNC_ADD","ONE_MINUS_SRC_ALPHA","previousFramebuffer","getParameter","FRAMEBUFFER_BINDING","previousViewport","VIEWPORT","clearColor","COLOR_BUFFER_BIT","vertSrc","fragSrc","uniformCache","setUniform","location","uniform3f","uniform1f","makeShader","pixelWidth","pixelHeight","createFramebufferTexture","framebufferTexture2D","COLOR_ATTACHMENT0","__brushFramebuffer","deleteFramebuffer","currentFramebuffer","previousProgram","CURRENT_PROGRAM","previousVao","VERTEX_ARRAY_BINDING","quadVao","TEXTURE1","TRIANGLES","deleteVertexArray","sourceBox","previousReadFramebuffer","READ_FRAMEBUFFER_BINDING","previousDrawFramebuffer","DRAW_FRAMEBUFFER_BINDING","READ_FRAMEBUFFER","DRAW_FRAMEBUFFER","blitFramebuffer","NEAREST","blitDefaultFramebufferSource","cssColor","buildTipSurface","get2DContext","surface","_fillStyle","_strokeStyle","_lineWidth","fillRect","noFill","_paint","ellipse","_shapeStarted","getImageData","imageData","putImageData","resolve","reject","NativeImage","globalThis","Image","nativeImg","onload","naturalWidth","naturalHeight","onerror","crossOrigin","ensureWashReady","vertexCount","flat","holeIndices","outerLen","outerNode","signedArea","linkedList","earcut","buildTriangleBuffer","drawWashPolygon","HTMLCanvasElement","isCanvasTarget","isOffscreenCanvasTarget","isSupportedTarget","initStandaloneRendererRuntime","initStandaloneCompositorRuntime","initStandaloneStrokeRuntime","angleOffset","randomFactor","randomAngle","offsetX","offsetY","DEPTH_BUFFER_BIT","region","logicalWidth","logicalHeight","Number","style","id","parent","querySelector","appendChild","buffer","loadTarget","saved","popState","currentField","theta","cosTheta","sinTheta","callback","_array_points"],"mappings":"6BAIA,MAAMA,EAAiB,CACrBC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,GAGE,ICEIC,EAAQC,EAAmBC,EAAUC,EDFrCC,EAAc,KAAM,EACpBC,EAAeC,GAAUA,EACzBC,EAAc,KACvB,MAAM,IAAIC,MAAM,yCAEPC,EAAkB,IAAMhB,ECD/BiB,EAAgB,CAClBC,KAAM,KACJ,MAAM,IAAIH,MAAM,0CAElBI,YAAa,IAAMT,EACnBU,cAAe,KACb,MAAM,IAAIL,MAAM,0CAElBM,SAAWC,MAGXC,iBAAmBD,MAGnBE,mBAAoB,OACpBC,qBAAsB,IAAM,KAC5BC,oBAAq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zB,KAAqBF,GAAU5V,EAASA,EAAQiD,KAAK0K,GAAM,IACvD07B,EAAWpmC,KAAKwJ,IAAI28B,GACpBE,EAAWrmC,KAAKiL,IAAIk7B,GAC1BpzB,GAAmBC,GAAkBD,GAAkB,CACrD5W,EAAGiqC,EACHhqC,EAAGiqC,EACHhqC,GAAIgqC,EACJ/pC,EAAG8pC,EACH7pC,EAAG,EACHC,EAAG,GAEP,UAQO,SAAeD,EAAGC,EAAID,GAC3BwW,GAAmBC,GAAkBD,GAAkB,CACrD5W,EAAGI,EACHH,EAAG,EACHC,EAAG,EACHC,EAAGE,EACHD,EAAG,EACHC,EAAG,GAEP,iBUWO,SAAsBqU,GAC3B,IAAK,MAAM2U,MAAEA,KAAW1V,GAAKye,SACvB/I,IACFA,EAAMxC,QAAUnS,EAChB2U,EAAM5B,SAAW/S,EACjB2U,EAAMgD,SAAW3X,EAGvB,SblNqBpL,IACnB2C,EAAMxB,EAAUnB,GAChB4C,EAAOzB,EAAU,GAAGnB,OACpB,IAAK,MAAM6gC,KAAYh+B,EACrBg+B,uBKuNG,SAAgBC,EAAezxB,EAAa,IACjD,IAAKyxB,GAAiBA,EAAc3+B,OAAS,EAC3C,MAAM,IAAI3K,MACR,+EAGI8c,GAAcwsB,EAAezxB,GACnC/T,MACJ,4CFlFO,SAAmBxE,EAAGC,GAC3BuW,GAAmBC,GAAkBD,GAAkB,CACrD5W,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,EAAG,EACHC,IACAC,KAEJ","x_google_ignoreList":[5,6,26]}
\ No newline at end of file
diff --git a/src/adapters/standalone/runtime.js b/src/adapters/standalone/runtime.js
index bbe89fa..5594f5f 100644
--- a/src/adapters/standalone/runtime.js
+++ b/src/adapters/standalone/runtime.js
@@ -65,6 +65,17 @@ export class Color {
}
if (typeof r === "string") {
+ const rgbaMatch = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)$/i.exec(r);
+ if (rgbaMatch) {
+ this.r = clamp(parseInt(rgbaMatch[1]), 0, 255);
+ this.g = clamp(parseInt(rgbaMatch[2]), 0, 255);
+ this.b = clamp(parseInt(rgbaMatch[3]), 0, 255);
+ this.hex = this.rgbToHex(this.r, this.g, this.b);
+ const alpha = rgbaMatch[4] !== undefined ? clamp(parseFloat(rgbaMatch[4]), 0, 1) : 1;
+ this._array = [this.r / 255, this.g / 255, this.b / 255, alpha];
+ this.gl = this._array;
+ return;
+ }
this.hex = this.standardize(r);
const rgb = this.hexToRgb(this.hex);
this.r = rgb.r;
diff --git a/test/angle_mode_test.html b/test/angle_mode_test.html
index 5b7e7a1..55459da 100644
--- a/test/angle_mode_test.html
+++ b/test/angle_mode_test.html
@@ -34,6 +34,8 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a {
@@ -45,6 +47,8 @@
text-decoration: underline;
}
+ .nav .sep { color: #8a9aa8; }
+
h1 {
margin: 0 0 8px;
font-size: clamp(24px, 3.6vw, 34px);
@@ -86,7 +90,11 @@
</head>
<body>
<main>
- <div class="nav"><a href="./index.html">All tests</a></div>
+ <div class="nav">
+ <a href="./index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="./standalone/angle_mode_test.html">Standalone →</a>
+ </div>
<h1>Angle Mode Test</h1>
<p>
Each row compares equivalent degree and radian inputs across public APIs.
diff --git a/test/field_explorer.html b/test/field_explorer.html
index 792e85a..0ebc1ce 100644
--- a/test/field_explorer.html
+++ b/test/field_explorer.html
@@ -41,6 +41,8 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a {
@@ -49,6 +51,7 @@
}
.nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
h1 {
margin: 0 0 8px;
@@ -122,7 +125,11 @@
</head>
<body>
<main>
- <div class="nav"><a href="./index.html">All tests</a></div>
+ <div class="nav">
+ <a href="./index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="./standalone/field_explorer.html">Standalone →</a>
+ </div>
<h1>Flow Field Explorer</h1>
<p>
Interactive browser page for comparing built-in vector fields with adjustable density and flow-line length.
diff --git a/test/fill_circle_explorer.html b/test/fill_circle_explorer.html
index b884066..8f11435 100644
--- a/test/fill_circle_explorer.html
+++ b/test/fill_circle_explorer.html
@@ -41,6 +41,8 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a {
@@ -49,6 +51,7 @@
}
.nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
h1 {
margin: 0 0 8px;
@@ -198,7 +201,11 @@
</head>
<body>
<main>
- <div class="nav"><a href="./index.html">All tests</a></div>
+ <div class="nav">
+ <a href="./index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="./standalone/fill_circle_explorer.html">Standalone →</a>
+ </div>
<h1>Fill Circle Explorer</h1>
<p>
Seeded browser page for checking watercolor fill behavior on a single centered circle with a fine HB stroke.
diff --git a/test/fill_circle_explorer.js b/test/fill_circle_explorer.js
index 5251a98..d9facac 100644
--- a/test/fill_circle_explorer.js
+++ b/test/fill_circle_explorer.js
@@ -23,7 +23,6 @@ const controls = {
textureVal: document.getElementById("textureVal"),
borderVal: document.getElementById("borderVal"),
seedVal: document.getElementById("seedVal"),
- firstLoadVal: document.getElementById("firstLoadVal"),
refreshSeed: document.getElementById("refreshSeed"),
palette: document.getElementById("palette"),
};
@@ -95,10 +94,6 @@ function queueRender() {
});
}
-function reportFirstLoad() {
- window.reportP5FirstFrame?.("fill_circle_explorer");
-}
-
function setupPalette() {
for (const color of PALETTE) {
const btn = document.createElement("button");
@@ -190,5 +185,5 @@ function draw() {
if (!needsRender) return;
needsRender = false;
renderScene();
- reportFirstLoad();
+ window.reportP5FirstFrame?.("fill_circle_explorer");
}
diff --git a/test/hatch_test.html b/test/hatch_test.html
index f4aa0b8..5f481e1 100644
--- a/test/hatch_test.html
+++ b/test/hatch_test.html
@@ -32,10 +32,13 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a { color: #153e5c; text-decoration: none; }
.nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
h1 {
margin: 0 0 8px;
@@ -68,7 +71,11 @@
</head>
<body>
<main>
- <div class="nav"><a href="./index.html">All tests</a></div>
+ <div class="nav">
+ <a href="./index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="./standalone/hatch_test.html">Standalone →</a>
+ </div>
<h1>Hatch Test</h1>
<p>
Coverage page for hatch angle, spacing, randomization, gradients, continuity, cross-hatching, brush styles, and multi-polygon inputs.
diff --git a/test/index.html b/test/index.html
index 1c5763a..557ab48 100644
--- a/test/index.html
+++ b/test/index.html
@@ -178,7 +178,7 @@
<section class="band">
<div class="band-head">
<h2>p5 Tests</h2>
- <p>Use these pages to visually inspect the p5 build directly in the browser.</p>
+ <p>Use these pages to visually inspect the p5 build. Each links to its standalone counterpart.</p>
</div>
<div class="grid">
<a class="card" href="./visual_suite.html">
@@ -188,6 +188,13 @@
<span class="path">test/visual_suite.html</span>
</a>
+ <a class="card" href="./hatch_test.html">
+ <h3>Hatch Test</h3>
+ <p>Exercises hatch angles, spacing, rand/continuous/gradient options, cross-hatching, brush types, shapes, and multi-polygon arrays.</p>
+ <span class="meta">Coverage</span>
+ <span class="path">test/hatch_test.html</span>
+ </a>
+
<a class="card" href="./fill_circle_explorer.html">
<h3>Fill Circle Explorer</h3>
<p>Seeded single-shape page for inspecting watercolor fill bleed, opacity, texture, border, and palette color on a centered circle.</p>
@@ -202,11 +209,11 @@
<span class="path">test/wash_test.html</span>
</a>
- <a class="card" href="./pastel_hatching_test.html">
- <h3>Pastel Hatching Test</h3>
- <p>Minimal global-mode sketch with a custom crayon brush and a single centered rectangle for pastel hatching experiments.</p>
- <span class="meta">Experiment</span>
- <span class="path">test/pastel_hatching_test.html</span>
+ <a class="card" href="./field_explorer.html">
+ <h3>Flow Field Explorer</h3>
+ <p>Interactive field inspector for comparing built-in fields with adjustable density and line length.</p>
+ <span class="meta">Explorer</span>
+ <span class="path">test/field_explorer.html</span>
</a>
<a class="card" href="./angle_mode_test.html">
@@ -216,27 +223,6 @@
<span class="path">test/angle_mode_test.html</span>
</a>
- <a class="card" href="./offscreen_target_test.html">
- <h3>Offscreen Targets</h3>
- <p>Checks brush.load() on p5.Graphics and custom-sized main framebuffers, with pixel-count diagnostics.</p>
- <span class="meta">Targets</span>
- <span class="path">test/offscreen_target_test.html</span>
- </a>
-
- <a class="card" href="./instance_mode_test.html">
- <h3>Instance Mode</h3>
- <p>Checks brush.instance(p) on the instance canvas, an instance p5.Graphics target, and an instance-owned main framebuffer.</p>
- <span class="meta">Instances</span>
- <span class="path">test/instance_mode_test.html</span>
- </a>
-
- <a class="card" href="./multi_instance_async_test.html">
- <h3>Async Multi-Instance</h3>
- <p>Stress-tests the old multi-instance startup race with many instance-mode sketches and repeated canvas ownership checks.</p>
- <span class="meta">Regression</span>
- <span class="path">test/multi_instance_async_test.html</span>
- </a>
-
<a class="card" href="./transform_test.html">
<h3>Transform Alignment</h3>
<p>Checks that brush strokes and fills align with native p5 reference geometry under translate, rotate, and scale.</p>
@@ -251,18 +237,11 @@
<span class="path">test/pushpop_test.html</span>
</a>
- <a class="card" href="./hatch_test.html">
- <h3>Hatch Test</h3>
- <p>Exercises hatch angles, spacing, rand/continuous/gradient options, cross-hatching, brush types, shapes, and multi-polygon arrays.</p>
- <span class="meta">Coverage</span>
- <span class="path">test/hatch_test.html</span>
- </a>
-
- <a class="card" href="./field_explorer.html">
- <h3>Flow Field Explorer</h3>
- <p>Interactive field inspector for comparing built-in fields with adjustable density and line length.</p>
- <span class="meta">Explorer</span>
- <span class="path">test/field_explorer.html</span>
+ <a class="card" href="./pastel_hatching_test.html">
+ <h3>Pastel Hatching Test</h3>
+ <p>Minimal global-mode sketch with a custom crayon brush and a single centered rectangle for pastel hatching experiments.</p>
+ <span class="meta">Experiment</span>
+ <span class="path">test/pastel_hatching_test.html</span>
</a>
</div>
</section>
@@ -270,56 +249,99 @@
<section class="band">
<div class="band-head">
<h2>Standalone Tests</h2>
- <p>Use these pages to inspect the standalone build without p5.</p>
+ <p>Same tests running the standalone build (no p5). Each links back to its p5 counterpart.</p>
</div>
<div class="grid">
<a class="card" href="./standalone/visual_suite.html">
- <h3>Standalone Visual API Suite</h3>
- <p>Broad standalone coverage page for brushes, fields, primitives, hatch, wash, mass, fill, and custom/image brush types.</p>
+ <h3>Visual API Suite</h3>
+ <p>Broad standalone coverage page for brushes, fields, primitives, hatch, wash, fill, and custom/image brush types.</p>
<span class="meta">Coverage</span>
<span class="path">test/standalone/visual_suite.html</span>
</a>
+ <a class="card" href="./standalone/hatch_test.html">
+ <h3>Hatch Test</h3>
+ <p>Exercises hatch angles, spacing, rand/continuous/gradient options, cross-hatching, shape variety, and combined hatch settings.</p>
+ <span class="meta">Coverage</span>
+ <span class="path">test/standalone/hatch_test.html</span>
+ </a>
+
<a class="card" href="./standalone/fill_circle_explorer.html">
- <h3>Standalone Fill Circle Explorer</h3>
+ <h3>Fill Circle Explorer</h3>
<p>Seeded single-shape page for inspecting watercolor fill bleed, opacity, texture, border, and palette color in the standalone build.</p>
<span class="meta">Explorer</span>
<span class="path">test/standalone/fill_circle_explorer.html</span>
</a>
- <a class="card" href="./standalone/hatch_test.html">
- <h3>Standalone Hatch Test</h3>
- <p>Exercises hatch angles, spacing, rand/continuous/gradient options, cross-hatching, shape variety, and combined hatch settings.</p>
+ <a class="card" href="./standalone/wash_test.html">
+ <h3>Wash Test</h3>
+ <p>Standalone wash page with seeded PRNG drawing rect and circle polygons with palette colors at full opacity.</p>
<span class="meta">Coverage</span>
- <span class="path">test/standalone/hatch_test.html</span>
+ <span class="path">test/standalone/wash_test.html</span>
</a>
<a class="card" href="./standalone/field_explorer.html">
- <h3>Standalone Flow Field Explorer</h3>
+ <h3>Flow Field Explorer</h3>
<p>Interactive field inspector for comparing built-in fields with adjustable density and line length in the standalone build.</p>
<span class="meta">Explorer</span>
<span class="path">test/standalone/field_explorer.html</span>
</a>
- <a class="card" href="./standalone/transform_alignment.html">
- <h3>Standalone Transform Alignment</h3>
- <p>Native 2D references are overlaid on standalone brush marks to verify translate, rotate, scale, stroke, and fill alignment.</p>
- <span class="meta">Standalone</span>
- <span class="path">test/standalone/transform_alignment.html</span>
+ <a class="card" href="./standalone/angle_mode_test.html">
+ <h3>Angle Mode Test</h3>
+ <p>Standalone angle mode coverage with canvas2D reference overlays for degrees, radians, hatch, flow lines, and custom fields.</p>
+ <span class="meta">Behavior</span>
+ <span class="path">test/standalone/angle_mode_test.html</span>
+ </a>
+
+ <a class="card" href="./standalone/transform_test.html">
+ <h3>Transform Alignment</h3>
+ <p>Native 2D references overlaid on standalone brush marks to verify translate, rotate, scale, stroke, and fill alignment.</p>
+ <span class="meta">Geometry</span>
+ <span class="path">test/standalone/transform_test.html</span>
</a>
- <a class="card" href="./standalone/pushpop.html">
- <h3>Standalone Push / Pop</h3>
+ <a class="card" href="./standalone/pushpop_test.html">
+ <h3>Push / Pop State</h3>
<p>Checks that standalone push/pop restores stroke color, weight, brush type, and fill state.</p>
- <span class="meta">Standalone</span>
- <span class="path">test/standalone/pushpop.html</span>
+ <span class="meta">State</span>
+ <span class="path">test/standalone/pushpop_test.html</span>
</a>
- <a class="card" href="./standalone/offscreen.html">
- <h3>Standalone Offscreen</h3>
- <p>Checks drawing into an OffscreenCanvas target and presenting the result to a visible canvas.</p>
- <span class="meta">Standalone</span>
- <span class="path">test/standalone/offscreen.html</span>
+ <a class="card" href="./standalone/pastel_hatching_test.html">
+ <h3>Pastel Hatching Test</h3>
+ <p>Interactive standalone version with brush selector, precision, strength, gradient, and outline controls.</p>
+ <span class="meta">Experiment</span>
+ <span class="path">test/standalone/pastel_hatching_test.html</span>
+ </a>
+ </div>
+ </section>
+
+ <section class="band">
+ <div class="band-head">
+ <h2>p5-Specific Tests</h2>
+ <p>Tests for p5-only features: instance mode, multi-instance startup, and offscreen targets.</p>
+ </div>
+ <div class="grid">
+ <a class="card" href="./p5_specific/instance_mode_test.html">
+ <h3>Instance Mode</h3>
+ <p>Checks brush.instance(p) on the instance canvas, an instance p5.Graphics target, and an instance-owned main framebuffer.</p>
+ <span class="meta">Instances</span>
+ <span class="path">test/p5_specific/instance_mode_test.html</span>
+ </a>
+
+ <a class="card" href="./p5_specific/multi_instance_async_test.html">
+ <h3>Async Multi-Instance</h3>
+ <p>Stress-tests the old multi-instance startup race with many instance-mode sketches and repeated canvas ownership checks.</p>
+ <span class="meta">Regression</span>
+ <span class="path">test/p5_specific/multi_instance_async_test.html</span>
+ </a>
+
+ <a class="card" href="./p5_specific/offscreen_target_test.html">
+ <h3>Offscreen Targets</h3>
+ <p>Checks brush.load() on p5.Graphics and custom-sized main framebuffers, with pixel-count diagnostics.</p>
+ <span class="meta">Targets</span>
+ <span class="path">test/p5_specific/offscreen_target_test.html</span>
</a>
</div>
</section>
diff --git a/test/instance_mode_test.html b/test/p5_specific/instance_mode_test.html
similarity index 87%
rename from test/instance_mode_test.html
rename to test/p5_specific/instance_mode_test.html
index d06a6db..740ebe3 100644
--- a/test/instance_mode_test.html
+++ b/test/p5_specific/instance_mode_test.html
@@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>p5.brush - Instance Mode Test</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>
- <script src="../dist/p5.brush.js"></script>
- <script src="./p5_first_frame_profiler.js"></script>
+ <script src="../../dist/p5.brush.js"></script>
+ <script src="../p5_first_frame_profiler.js"></script>
<style>
* {
box-sizing: border-box;
@@ -34,6 +34,8 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a {
@@ -45,6 +47,8 @@
text-decoration: underline;
}
+ .nav .sep { color: #8a9aa8; }
+
h1 {
margin: 0 0 8px;
font-size: clamp(24px, 3.6vw, 34px);
@@ -81,7 +85,11 @@
</head>
<body>
<main>
- <div class="nav"><a href="./index.html">All tests</a></div>
+ <div class="nav">
+ <a href="../index.html">All tests</a>
+ <span class="sep">·</span>
+ <span style="color:#8a9aa8;">p5 specific</span>
+ </div>
<h1>Instance Mode Test</h1>
<p>
This page is rendered entirely by a <b>new p5((p) =&gt; {})</b> sketch and checks that
diff --git a/test/instance_mode_test.js b/test/p5_specific/instance_mode_test.js
similarity index 100%
rename from test/instance_mode_test.js
rename to test/p5_specific/instance_mode_test.js
diff --git a/test/multi_instance_async_test.html b/test/p5_specific/multi_instance_async_test.html
similarity index 94%
rename from test/multi_instance_async_test.html
rename to test/p5_specific/multi_instance_async_test.html
index f6ab59e..e972bf5 100644
--- a/test/multi_instance_async_test.html
+++ b/test/p5_specific/multi_instance_async_test.html
@@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>p5.brush - Async Multi-Instance Test</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>
- <script src="../dist/p5.brush.js"></script>
- <script src="./p5_first_frame_profiler.js"></script>
+ <script src="../../dist/p5.brush.js"></script>
+ <script src="../p5_first_frame_profiler.js"></script>
<style>
:root {
--bg: #f4efe6;
@@ -47,6 +47,8 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a {
@@ -58,6 +60,8 @@
text-decoration: underline;
}
+ .nav .sep { color: #8a9aa8; }
+
h1 {
margin: 0 0 8px;
font-size: clamp(24px, 3.6vw, 34px);
@@ -219,7 +223,11 @@
</head>
<body>
<main>
- <div class="nav"><a href="./index.html">All tests</a></div>
+ <div class="nav">
+ <a href="../index.html">All tests</a>
+ <span class="sep">·</span>
+ <span style="color:#8a9aa8;">p5 specific</span>
+ </div>
<h1>Async Multi-Instance Test</h1>
<p>
This page stress-tests the old report about multiple instance-mode sketches racing on
diff --git a/test/multi_instance_async_test.js b/test/p5_specific/multi_instance_async_test.js
similarity index 100%
rename from test/multi_instance_async_test.js
rename to test/p5_specific/multi_instance_async_test.js
diff --git a/test/offscreen_target_test.html b/test/p5_specific/offscreen_target_test.html
similarity index 87%
rename from test/offscreen_target_test.html
rename to test/p5_specific/offscreen_target_test.html
index 181aa4e..0acef69 100644
--- a/test/offscreen_target_test.html
+++ b/test/p5_specific/offscreen_target_test.html
@@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>p5.brush - Offscreen Target Test</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>
- <script src="../dist/p5.brush.js"></script>
- <script src="./p5_first_frame_profiler.js"></script>
+ <script src="../../dist/p5.brush.js"></script>
+ <script src="../p5_first_frame_profiler.js"></script>
<style>
* {
box-sizing: border-box;
@@ -34,6 +34,8 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a {
@@ -45,6 +47,8 @@
text-decoration: underline;
}
+ .nav .sep { color: #8a9aa8; }
+
h1 {
margin: 0 0 8px;
font-size: clamp(24px, 3.6vw, 34px);
@@ -86,7 +90,11 @@
</head>
<body>
<main>
- <div class="nav"><a href="./index.html">All tests</a></div>
+ <div class="nav">
+ <a href="../index.html">All tests</a>
+ <span class="sep">·</span>
+ <span style="color:#8a9aa8;">p5 specific</span>
+ </div>
<h1>Offscreen Target Test</h1>
<p>
This page checks that p5.brush can target offscreen drawing surfaces and still composite them back correctly.
diff --git a/test/offscreen_target_test.js b/test/p5_specific/offscreen_target_test.js
similarity index 100%
rename from test/offscreen_target_test.js
rename to test/p5_specific/offscreen_target_test.js
diff --git a/test/pastel_hatching_test.html b/test/pastel_hatching_test.html
index a6edd75..340ff3a 100644
--- a/test/pastel_hatching_test.html
+++ b/test/pastel_hatching_test.html
@@ -41,6 +41,8 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a {
@@ -49,6 +51,7 @@
}
.nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
h1 {
margin: 0 0 8px;
@@ -189,7 +192,11 @@
</head>
<body>
<main>
- <div class="nav"><a href="./index.html">All tests</a></div>
+ <div class="nav">
+ <a href="./index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="./standalone/pastel_hatching_test.html">Standalone →</a>
+ </div>
<h1>Pastel Hatching Test</h1>
<p>
Minimal global-mode sketch with a custom crayon brush, scaled built-in brushes, and a single centered rectangle for trying pastel hatching ideas.
diff --git a/test/pushpop_test.html b/test/pushpop_test.html
index 3b5dea7..7205ee1 100644
--- a/test/pushpop_test.html
+++ b/test/pushpop_test.html
@@ -32,10 +32,13 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a { color: #153e5c; text-decoration: none; }
.nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
h1 {
margin: 0 0 8px;
@@ -68,7 +71,11 @@
</head>
<body>
<main>
- <div class="nav"><a href="./index.html">All tests</a></div>
+ <div class="nav">
+ <a href="./index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="./standalone/pushpop_test.html">Standalone →</a>
+ </div>
<h1>Push / Pop State Test</h1>
<p>
Each column proves that p5’s <b>push()</b> and <b>pop()</b> automatically save and restore brush state.
diff --git a/test/standalone/pushpop.html b/test/standalone/angle_mode_test.html
similarity index 60%
rename from test/standalone/pushpop.html
rename to test/standalone/angle_mode_test.html
index a38a9b1..a9799db 100644
--- a/test/standalone/pushpop.html
+++ b/test/standalone/angle_mode_test.html
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>brush.js - Standalone Push/Pop Test</title>
+ <title>Angle Mode Test — Standalone</title>
<style>
* { box-sizing: border-box; }
@@ -17,7 +17,7 @@
}
main {
- width: min(920px, calc(100vw - 24px));
+ width: min(1240px, calc(100vw - 24px));
margin: 0 auto;
padding: 18px 0 24px;
display: grid;
@@ -29,10 +29,13 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a { color: #153e5c; text-decoration: none; }
.nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
h1 {
margin: 0 0 8px;
@@ -41,7 +44,7 @@
}
p {
- max-width: 760px;
+ max-width: 860px;
margin: 0 0 8px;
color: #52616e;
line-height: 1.45;
@@ -53,28 +56,34 @@
display: grid;
justify-content: center;
width: 100%;
+ overflow: hidden;
}
- canvas {
+ #canvas-host canvas {
+ grid-area: 1 / 1;
display: block;
max-width: 100%;
height: auto !important;
}
+
+ #label-canvas { pointer-events: none; }
</style>
</head>
<body>
<main>
- <div class="nav"><a href="../index.html">All tests</a></div>
- <h1>Standalone Push / Pop State Test</h1>
- <p>
- Each column proves that standalone <b>push()</b> and <b>pop()</b> restore both transform and brush state.
- </p>
+ <div class="nav">
+ <a href="../index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="../angle_mode_test.html">← p5 version</a>
+ </div>
+ <h1>Angle Mode Test <small style="font-size:0.55em;color:#8a9aa8;">standalone</small></h1>
<p>
- Column 1 checks stroke color, column 2 checks stroke weight and brush type, and column 3 checks fill color and opacity. The “after pop” row should match the “before” row exactly.
+ Compares degrees, radians, mixed mode changes, stored hatch angles, low-level Position movement, and custom fields.
+ Red dashed lines are mathematical references; matching panels confirm correct angle interpretation.
</p>
<div id="canvas-host"></div>
-
- <script type="module" src="./pushpop.js"></script>
+ <script src="./standalone_profiler.js"></script>
+ <script type="module" src="./angle_mode_test.js"></script>
</main>
</body>
</html>
diff --git a/test/standalone/angle_mode_test.js b/test/standalone/angle_mode_test.js
new file mode 100644
index 0000000..98f3b69
--- /dev/null
+++ b/test/standalone/angle_mode_test.js
@@ -0,0 +1,531 @@
+// ============================================================
+// p5.brush Standalone Angle Mode Test
+//
+// Standalone equivalent of test/angle_mode_test.html.
+// Reference geometry is drawn on a 2D label canvas overlay;
+// brush strokes are drawn on the brush (WebGL) canvas.
+// ============================================================
+
+import * as brush from "../../dist/brush.esm.js";
+
+const CANVAS_W = 1360;
+const CANVAS_H = 1260;
+const MARGIN = 36;
+const LABEL_W = 190;
+const PANEL_GAP = 18;
+const ROW_H = 170;
+
+const INK = "#183a59";
+const ALT = "#21695f";
+const FRAME = "#cdbfae";
+const PANEL_BG = "#fcf7ef";
+const REF_ALPHA = 110 / 255;
+const REF_WEIGHT = 0.9;
+const REF_POINT = 3;
+
+// ---- Canvas setup ----
+
+const pixelDensity = window.devicePixelRatio || 1;
+brush.createCanvas(CANVAS_W, CANVAS_H, {
+ id: "brush-canvas",
+ parent: "#canvas-host",
+ pixelDensity,
+});
+
+const labelCanvas = document.createElement("canvas");
+labelCanvas.id = "label-canvas";
+labelCanvas.width = Math.round(CANVAS_W * pixelDensity);
+labelCanvas.height = Math.round(CANVAS_H * pixelDensity);
+labelCanvas.style.width = CANVAS_W + "px";
+labelCanvas.style.height = CANVAS_H + "px";
+document.getElementById("canvas-host").appendChild(labelCanvas);
+
+const lc = labelCanvas.getContext("2d");
+lc.setTransform(pixelDensity, 0, 0, pixelDensity, 0, 0);
+lc.textBaseline = "top";
+
+let currentY = MARGIN;
+
+// ---- Geometry helpers ----
+
+function toRadians(deg) { return (deg * Math.PI) / 180; }
+
+function projectPoint(x, y, angleDeg, length) {
+ const rad = toRadians(angleDeg);
+ return { x: x + length * Math.cos(rad), y: y - length * Math.sin(rad) };
+}
+
+function buildPolyline(x, y, steps) {
+ const points = [{ x, y }];
+ let cursor = { x, y };
+ for (const step of steps) {
+ cursor = projectPoint(cursor.x, cursor.y, step.angle, step.length);
+ points.push(cursor);
+ }
+ return points;
+}
+
+function maxLineLengthInBox(x, y, angleDeg, bounds) {
+ const rad = toRadians(angleDeg);
+ const dx = Math.cos(rad), dy = -Math.sin(rad);
+ const candidates = [];
+ if (dx > 0) candidates.push((bounds.maxX - x) / dx);
+ else if (dx < 0) candidates.push((bounds.minX - x) / dx);
+ if (dy > 0) candidates.push((bounds.maxY - y) / dy);
+ else if (dy < 0) candidates.push((bounds.minY - y) / dy);
+ const valid = candidates.filter((v) => Number.isFinite(v) && v >= 0);
+ return valid.length ? Math.min(...valid) : 0;
+}
+
+// ---- Reference drawing helpers (on label canvas 2D) ----
+
+function refLine(x1, y1, x2, y2) {
+ lc.strokeStyle = `rgba(199,74,61,${REF_ALPHA})`;
+ lc.lineWidth = REF_WEIGHT;
+ lc.beginPath();
+ lc.moveTo(x1, y1);
+ lc.lineTo(x2, y2);
+ lc.stroke();
+}
+
+function refDot(x, y) {
+ lc.fillStyle = `rgba(199,74,61,${REF_ALPHA})`;
+ lc.beginPath();
+ lc.arc(x, y, REF_POINT / 2, 0, Math.PI * 2);
+ lc.fill();
+}
+
+function drawCenteredReferenceLine(bounds, angleDeg, padding = 10) {
+ const cx = (bounds.minX + bounds.maxX) / 2;
+ const cy = (bounds.minY + bounds.maxY) / 2;
+ const forward = Math.max(0, maxLineLengthInBox(cx, cy, angleDeg, bounds) - padding);
+ const backward = Math.max(0, maxLineLengthInBox(cx, cy, angleDeg + 180, bounds) - padding);
+ const start = projectPoint(cx, cy, angleDeg + 180, backward);
+ const end = projectPoint(cx, cy, angleDeg, forward);
+ refLine(start.x, start.y, end.x, end.y);
+ refDot(start.x, start.y);
+ refDot(end.x, end.y);
+}
+
+function drawReferenceLine(x, y, length, angleDeg) {
+ const end = projectPoint(x, y, angleDeg, length);
+ refLine(x, y, end.x, end.y);
+ refDot(x, y);
+ refDot(end.x, end.y);
+}
+
+function drawReferencePolyline(x, y, steps, options = {}) {
+ const { dashed = false, showPoints = true, alpha = REF_ALPHA, pointSize = REF_POINT, dash = 7, gap = 5 } = options;
+ const points = buildPolyline(x, y, steps);
+
+ lc.strokeStyle = `rgba(199,74,61,${alpha})`;
+ lc.lineWidth = REF_WEIGHT;
+
+ if (dashed) {
+ for (let i = 0; i < points.length - 1; i++) {
+ const p0 = points[i], p1 = points[i + 1];
+ const dx = p1.x - p0.x, dy = p1.y - p0.y;
+ const len = Math.hypot(dx, dy);
+ if (!len) continue;
+ const ux = dx / len, uy = dy / len;
+ lc.beginPath();
+ for (let d = 0; d < len; d += dash + gap) {
+ const to = Math.min(d + dash, len);
+ lc.moveTo(p0.x + ux * d, p0.y + uy * d);
+ lc.lineTo(p0.x + ux * to, p0.y + uy * to);
+ }
+ lc.stroke();
+ }
+ } else {
+ lc.beginPath();
+ points.forEach((pt, i) => i === 0 ? lc.moveTo(pt.x, pt.y) : lc.lineTo(pt.x, pt.y));
+ lc.stroke();
+ }
+
+ if (showPoints) {
+ lc.fillStyle = `rgba(199,74,61,${alpha})`;
+ for (const pt of points) {
+ lc.beginPath();
+ lc.arc(pt.x, pt.y, pointSize / 2, 0, Math.PI * 2);
+ lc.fill();
+ }
+ }
+}
+
+function drawReferenceArc(cx, cy, radius, startDeg, endDeg) {
+ lc.strokeStyle = `rgba(199,74,61,${REF_ALPHA})`;
+ lc.lineWidth = REF_WEIGHT;
+ lc.beginPath();
+ for (let i = 0; i <= 36; i++) {
+ const t = i / 36;
+ const angle = startDeg + (endDeg - startDeg) * t;
+ const pt = projectPoint(cx, cy, angle, radius);
+ i === 0 ? lc.moveTo(pt.x, pt.y) : lc.lineTo(pt.x, pt.y);
+ }
+ lc.stroke();
+}
+
+// ---- Layout helpers ----
+
+function lcRoundRect(x, y, w, h, r) {
+ lc.beginPath();
+ lc.moveTo(x + r, y); lc.lineTo(x + w - r, y);
+ lc.arcTo(x + w, y, x + w, y + r, r); lc.lineTo(x + w, y + h - r);
+ lc.arcTo(x + w, y + h, x + w - r, y + h, r); lc.lineTo(x + r, y + h);
+ lc.arcTo(x, y + h, x, y + h - r, r); lc.lineTo(x, y + r);
+ lc.arcTo(x, y, x + r, y, r); lc.closePath();
+}
+
+function section(title, note = "") {
+ lc.fillStyle = "#1d1d1d";
+ lc.font = "bold 13px monospace";
+ lc.fillText(title, MARGIN, currentY + 2);
+ if (note) {
+ lc.fillStyle = "#5c5c5c";
+ lc.font = "10px monospace";
+ lc.fillText(note, MARGIN, currentY + 18);
+ }
+ lc.strokeStyle = "#d7cdbf";
+ lc.lineWidth = 1;
+ lc.beginPath();
+ lc.moveTo(MARGIN, currentY + 40);
+ lc.lineTo(CANVAS_W - MARGIN, currentY + 40);
+ lc.stroke();
+ currentY += 58;
+}
+
+function drawRow(label, panels) {
+ const available = CANVAS_W - 2 * MARGIN - LABEL_W;
+ const panelW = (available - PANEL_GAP * (panels.length - 1)) / panels.length;
+
+ lc.fillStyle = "rgba(251,247,239,0.94)";
+ lcRoundRect(MARGIN - 2, currentY + 6, LABEL_W - 10, ROW_H - 18, 10);
+ lc.fill();
+ lc.fillStyle = "#2e2e2e";
+ lc.font = "bold 11px monospace";
+ lc.fillText(label, MARGIN, currentY + 18);
+
+ panels.forEach((panel, index) => {
+ const x = MARGIN + LABEL_W + index * (panelW + PANEL_GAP);
+ const y = currentY;
+
+ // Panel background via brush.wash
+ brush.wash(PANEL_BG, 255);
+ new brush.Polygon([[x, y], [x + panelW, y], [x + panelW, y + ROW_H - 8], [x, y + ROW_H - 8]]).wash();
+ brush.noWash();
+
+ // Panel frame + title on label canvas
+ lc.strokeStyle = FRAME;
+ lc.lineWidth = 1;
+ lcRoundRect(x, y, panelW, ROW_H - 8, 14);
+ lc.stroke();
+
+ lc.fillStyle = "rgba(255,255,255,0.86)";
+ lcRoundRect(x + 10, y + 10, panelW - 20, 20, 9);
+ lc.fill();
+ lc.fillStyle = "#4a4a4a";
+ lc.font = "10px monospace";
+ lc.fillText(panel.title, x + 16, y + 15);
+
+ panel.render(x + 14, y + 40, panelW - 28, ROW_H - 56);
+ });
+
+ currentY += ROW_H;
+}
+
+// ---- Panel renderers ----
+
+function renderFlowLinePanel(x, y, w, h, mode, angleValue) {
+ const angleDeg = 28;
+ const startX = x + 16, startY = y + h - 14;
+ const len = Math.max(12, maxLineLengthInBox(startX, startY, angleDeg, {
+ minX: x + 8, minY: y + 8, maxX: x + w - 8, maxY: y + h - 8,
+ }) - 4);
+
+ drawReferenceLine(startX, startY, len, angleDeg);
+
+ brush.angleMode(mode);
+ brush.noField();
+ brush.set("pen", INK, 1.8);
+ brush.flowLine(startX, startY, len, angleValue);
+ brush.angleMode(brush.DEGREES);
+}
+
+function renderArcPanel(x, y, w, h, mode, startValue, endValue) {
+ const cx = x + w / 2, cy = y + h / 2 + 10;
+ const radius = Math.min(w, h) * 0.3;
+
+ drawReferenceArc(cx, cy, radius, 20, 145);
+
+ brush.angleMode(mode);
+ brush.noField();
+ brush.set("pen", ALT, 1.8);
+ brush.arc(cx, cy, radius, startValue, endValue);
+ brush.angleMode(brush.DEGREES);
+}
+
+function renderManualStrokePanel(x, y, w, h, runner) {
+ const startX = x + 20, startY = y + h - 16;
+ const steps = [
+ { angle: 24, length: 64, pressure: 1 },
+ { angle: 112, length: 52, pressure: 0.9 },
+ { angle: -18, length: 70, pressure: 1.05 },
+ ];
+ drawReferencePolyline(startX, startY, steps);
+ brush.set("2B", INK, 1.7);
+ runner(startX, startY, steps);
+ brush.angleMode(brush.DEGREES);
+}
+
+function renderPositionPanel(x, y, w, h, runner) {
+ const startX = x + 20, startY = y + h - 16;
+ const steps = [
+ { angle: 18, length: 58 },
+ { angle: 104, length: 50 },
+ { angle: -24, length: 68 },
+ ];
+
+ brush.noField();
+ const pts = runner(startX, startY, steps);
+
+ brush.set("marker", INK, 1.05);
+ for (let i = 0; i < pts.length - 1; i++) {
+ brush.line(pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y);
+ }
+
+ drawReferencePolyline(startX, startY, steps, {
+ dashed: true, showPoints: true, pointSize: 2.4, alpha: REF_ALPHA, dash: 4, gap: 9,
+ });
+
+ // Draw brush position dots on label canvas
+ lc.fillStyle = "rgb(24,58,89)";
+ for (const pt of pts) {
+ lc.beginPath();
+ lc.arc(pt.x, pt.y, 2, 0, Math.PI * 2);
+ lc.fill();
+ }
+}
+
+function renderHatchPanel(x, y, w, h, setupHatch, referenceAngleDeg = 45) {
+ const rx = x + 14, ry = y + 10;
+ const rw = w - 28, rh = h - 20;
+ const bounds = { minX: rx, minY: ry, maxX: rx + rw, maxY: ry + rh };
+
+ // Background and frame on label canvas (below hatch via wash)
+ brush.wash("#f5efe5", 255);
+ new brush.Polygon([[rx, ry], [rx + rw, ry], [rx + rw, ry + rh], [rx, ry + rh]]).wash();
+ brush.noWash();
+
+ lc.strokeStyle = "#d6c9ba";
+ lc.lineWidth = 1;
+ lc.strokeRect(rx, ry, rw, rh);
+
+ drawCenteredReferenceLine(bounds, referenceAngleDeg);
+
+ brush.noField();
+ brush.noStroke();
+ brush.noFill();
+ brush.hatchStyle("pen", INK, 1.35);
+ setupHatch();
+ brush.rect(rx, ry, rw, rh, "corner");
+ brush.noHatch();
+ brush.angleMode(brush.DEGREES);
+}
+
+function renderFieldPanel(x, y, w, h, mode, fieldName) {
+ const lines = 6, startX = x + 16, len = w - 32;
+ brush.angleMode(mode);
+ brush.field(fieldName);
+ brush.set("pen", ALT, 1.45);
+ for (let i = 0; i < lines; i++) {
+ const sy = y + 12 + (i / (lines - 1)) * (h - 24);
+ brush.flowLine(startX, sy, len, 0);
+ }
+ brush.noField();
+ brush.angleMode(brush.DEGREES);
+}
+
+function runPositionSequence(startX, startY, steps, moveRunner) {
+ const pos = new brush.Position(startX + CANVAS_W / 2, startY + CANVAS_H / 2);
+ const pts = [{ x: startX, y: startY }];
+ moveRunner(pos, steps, pts);
+ return pts;
+}
+
+// ================================================================
+// Draw
+// ================================================================
+
+brush.seed(42);
+brush.noiseSeed(42);
+brush.scaleBrushes(2.4);
+brush.angleMode(brush.DEGREES);
+brush.clear("#f4ede0");
+brush.push();
+brush.translate(-CANVAS_W / 2, -CANVAS_H / 2);
+
+brush.addField("diagDegreesTest", (_t, field) => {
+ for (let col = 0; col < field.length; col++)
+ for (let row = 0; row < field[col].length; row++)
+ field[col][row] = 32;
+ return field;
+});
+
+brush.addField("diagRadiansTest", (_t, field) => {
+ for (let col = 0; col < field.length; col++)
+ for (let row = 0; row < field[col].length; row++)
+ field[col][row] = toRadians(32);
+ return field;
+}, { angleMode: "radians" });
+
+// ---- DIRECT ANGLE ARGUMENTS ----
+
+section(
+ "DIRECT ANGLE ARGUMENTS",
+ "Matching panels mean the function interprets degrees and radians equivalently under the current angleMode().",
+);
+
+drawRow("flowLine(dir)", [
+ {
+ title: "angleMode(DEGREES) + 28",
+ render: (x, y, w, h) => renderFlowLinePanel(x, y, w, h, brush.DEGREES, 28),
+ },
+ {
+ title: "angleMode(RADIANS) + PI/180*28",
+ render: (x, y, w, h) => renderFlowLinePanel(x, y, w, h, brush.RADIANS, toRadians(28)),
+ },
+]);
+
+drawRow("arc(start, end)", [
+ {
+ title: "DEGREES input",
+ render: (x, y, w, h) => renderArcPanel(x, y, w, h, brush.DEGREES, 20, 145),
+ },
+ {
+ title: "RADIANS input",
+ render: (x, y, w, h) => renderArcPanel(x, y, w, h, brush.RADIANS, toRadians(20), toRadians(145)),
+ },
+]);
+
+drawRow("beginStroke / move / endStroke", [
+ {
+ title: "all degrees",
+ render: (x, y, w, h) => renderManualStrokePanel(x, y, w, h, (sx, sy, steps) => {
+ brush.angleMode(brush.DEGREES);
+ brush.beginStroke("segments", sx, sy);
+ for (const s of steps) brush.move(s.angle, s.length, s.pressure);
+ brush.endStroke(steps[steps.length - 1].angle, 1);
+ }),
+ },
+ {
+ title: "all radians",
+ render: (x, y, w, h) => renderManualStrokePanel(x, y, w, h, (sx, sy, steps) => {
+ brush.angleMode(brush.RADIANS);
+ brush.beginStroke("segments", sx, sy);
+ for (const s of steps) brush.move(toRadians(s.angle), s.length, s.pressure);
+ brush.endStroke(toRadians(steps[steps.length - 1].angle), 1);
+ }),
+ },
+ {
+ title: "mixed angleMode() per call",
+ render: (x, y, w, h) => renderManualStrokePanel(x, y, w, h, (sx, sy, steps) => {
+ brush.beginStroke("segments", sx, sy);
+ brush.angleMode(brush.DEGREES); brush.move(steps[0].angle, steps[0].length, steps[0].pressure);
+ brush.angleMode(brush.RADIANS); brush.move(toRadians(steps[1].angle), steps[1].length, steps[1].pressure);
+ brush.angleMode(brush.DEGREES); brush.move(steps[2].angle, steps[2].length, steps[2].pressure);
+ brush.angleMode(brush.RADIANS); brush.endStroke(toRadians(steps[steps.length - 1].angle), 1);
+ }),
+ },
+]);
+
+drawRow("Position.moveTo(dir, length, step)", [
+ {
+ title: "all degrees",
+ render: (x, y, w, h) => renderPositionPanel(x, y, w, h, (sx, sy, steps) =>
+ runPositionSequence(sx, sy, steps, (pos, steps, pts) => {
+ brush.angleMode(brush.DEGREES);
+ for (const s of steps) {
+ pos.moveTo(s.angle, s.length, s.length);
+ pts.push({ x: pos.x - CANVAS_W / 2, y: pos.y - CANVAS_H / 2 });
+ }
+ })),
+ },
+ {
+ title: "all radians",
+ render: (x, y, w, h) => renderPositionPanel(x, y, w, h, (sx, sy, steps) =>
+ runPositionSequence(sx, sy, steps, (pos, steps, pts) => {
+ brush.angleMode(brush.RADIANS);
+ for (const s of steps) {
+ pos.moveTo(toRadians(s.angle), s.length, s.length);
+ pts.push({ x: pos.x - CANVAS_W / 2, y: pos.y - CANVAS_H / 2 });
+ }
+ })),
+ },
+ {
+ title: "mixed angleMode() per segment",
+ render: (x, y, w, h) => renderPositionPanel(x, y, w, h, (sx, sy, steps) =>
+ runPositionSequence(sx, sy, steps, (pos, steps, pts) => {
+ brush.angleMode(brush.DEGREES);
+ pos.moveTo(steps[0].angle, steps[0].length, steps[0].length);
+ pts.push({ x: pos.x - CANVAS_W / 2, y: pos.y - CANVAS_H / 2 });
+ brush.angleMode(brush.RADIANS);
+ pos.moveTo(toRadians(steps[1].angle), steps[1].length, steps[1].length);
+ pts.push({ x: pos.x - CANVAS_W / 2, y: pos.y - CANVAS_H / 2 });
+ brush.angleMode(brush.DEGREES);
+ pos.moveTo(steps[2].angle, steps[2].length, steps[2].length);
+ pts.push({ x: pos.x - CANVAS_W / 2, y: pos.y - CANVAS_H / 2 });
+ })),
+ },
+]);
+
+// ---- STORED AND CUSTOM ANGLE STATE ----
+
+section(
+ "STORED AND CUSTOM ANGLE STATE",
+ "These rows check places where angles are stored and used later, or where custom generators provide their own angle convention.",
+);
+
+drawRow("hatch(angle)", [
+ {
+ title: "set in degrees, draw in degrees",
+ render: (x, y, w, h) => renderHatchPanel(x, y, w, h, () => {
+ brush.angleMode(brush.DEGREES);
+ brush.hatch(10, 45, { rand: 0 });
+ }, 45),
+ },
+ {
+ title: "set in radians, draw in radians",
+ render: (x, y, w, h) => renderHatchPanel(x, y, w, h, () => {
+ brush.angleMode(brush.RADIANS);
+ brush.hatch(10, toRadians(45), { rand: 0 });
+ }, 45),
+ },
+ {
+ title: "set degrees, switch to radians, then draw",
+ render: (x, y, w, h) => renderHatchPanel(x, y, w, h, () => {
+ brush.angleMode(brush.DEGREES);
+ brush.hatch(10, 45, { rand: 0 });
+ brush.angleMode(brush.RADIANS);
+ }, 45),
+ },
+]);
+
+drawRow("addField(name, fn, { angleMode })", [
+ {
+ title: "generator writes degrees",
+ render: (x, y, w, h) => renderFieldPanel(x, y, w, h, brush.DEGREES, "diagDegreesTest"),
+ },
+ {
+ title: "generator writes radians",
+ render: (x, y, w, h) => renderFieldPanel(x, y, w, h, brush.RADIANS, "diagRadiansTest"),
+ },
+ {
+ title: "degree field while global mode is radians",
+ render: (x, y, w, h) => renderFieldPanel(x, y, w, h, brush.RADIANS, "diagDegreesTest"),
+ },
+]);
+
+brush.pop();
+brush.render();
+window.reportStandaloneFirstFrame?.("angle_mode_test");
+console.log("Standalone angle mode test complete");
diff --git a/test/standalone/angle_transform.html b/test/standalone/angle_transform.html
deleted file mode 100644
index 5a67cad..0000000
--- a/test/standalone/angle_transform.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>brush.js Standalone Angle / Transform Test</title>
- <style>
- body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f6f0e4; font-family: "Iowan Old Style", Palatino, serif; }
- main { width: min(760px, calc(100vw - 32px)); display: grid; gap: 14px; justify-items: center; }
- h1, p { margin: 0; text-align: center; }
- p { max-width: 620px; line-height: 1.45; }
- canvas { width: 600px; height: 600px; border: 1px solid rgba(31,44,51,.16); background: white; }
- code { font-family: Menlo, Monaco, "Courier New", monospace; font-size: 12px; }
- </style>
- </head>
- <body>
- <main>
- <h1>Standalone Angle / Transform Test</h1>
- <p>Checks degrees, radians, and the standalone transform stack on a plain canvas.</p>
- <div id="canvas-host"></div>
- </main>
- <script type="module" src="./angle_transform.js"></script>
- </body>
- </html>
diff --git a/test/standalone/angle_transform.js b/test/standalone/angle_transform.js
deleted file mode 100644
index 6a64067..0000000
--- a/test/standalone/angle_transform.js
+++ /dev/null
@@ -1,29 +0,0 @@
-import * as brush from "../../dist/brush.esm.js";
-
-brush.createCanvas(600, 600, {
- id: "brush-canvas",
- parent: "#canvas-host",
- pixelDensity: globalThis.devicePixelRatio || 1,
-});
-brush.clear("#fffceb");
-brush.scaleBrushes(3);
-
-brush.angleMode(brush.DEGREES);
-brush.set("HB", "#183a52", 1);
-brush.push();
-brush.translate(-120, -80);
-brush.rotate(25);
-brush.line(-80, 0, 80, 0);
-brush.pop();
-
-brush.angleMode(brush.RADIANS);
-brush.set("HB", "#8f3a2f", 1);
-brush.push();
-brush.translate(120, 80);
-brush.rotate(Math.PI / 6);
-brush.line(-80, 0, 80, 0);
-brush.pop();
-
-brush.render();
-
-console.log("standalone angle/transform test executed");
diff --git a/test/standalone/custom.html b/test/standalone/custom.html
deleted file mode 100644
index d620f12..0000000
--- a/test/standalone/custom.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>brush.js Standalone Custom Brush Test</title>
- <style>
- body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f6f0e4; font-family: "Iowan Old Style", Palatino, serif; }
- main { width: min(760px, calc(100vw - 32px)); display: grid; gap: 14px; justify-items: center; }
- h1, p { margin: 0; text-align: center; }
- p { max-width: 620px; line-height: 1.45; }
- canvas { width: 600px; height: 600px; border: 1px solid rgba(31,44,51,.16); background: white; }
- code { font-family: Menlo, Monaco, "Courier New", monospace; font-size: 12px; }
- </style>
- </head>
- <body>
- <main>
- <h1>Standalone Custom Brush Test</h1>
- <p>Checks standalone custom tip rasterization on a plain canvas using a small 2D tip surface API.</p>
- <div id="canvas-host"></div>
- </main>
- <script type="module" src="./custom.js"></script>
- </body>
- </html>
diff --git a/test/standalone/custom.js b/test/standalone/custom.js
deleted file mode 100644
index 73e42de..0000000
--- a/test/standalone/custom.js
+++ /dev/null
@@ -1,44 +0,0 @@
-import * as brush from "../../dist/brush.esm.js";
-
-brush.createCanvas(600, 600, {
- id: "brush-canvas",
- parent: "#canvas-host",
- pixelDensity: globalThis.devicePixelRatio || 1,
-});
-brush.clear("#fffceb");
-brush.scaleBrushes(3);
-brush.angleMode(brush.DEGREES);
-
-brush.add("standalone-star", {
- type: "custom",
- weight: 0.7,
- scatter: 0.8,
- sharpness: 1,
- grain: 40,
- opacity: 180,
- spacing: 0.2,
- noise: 0.2,
- rotate: "natural",
- markerTip: false,
- pressure: [1, 1],
- tip(g) {
- g.noStroke();
- g.fill("black");
- g.beginShape();
- g.vertex(0, -14);
- g.vertex(4, -4);
- g.vertex(14, 0);
- g.vertex(4, 4);
- g.vertex(0, 14);
- g.vertex(-4, 4);
- g.vertex(-14, 0);
- g.vertex(-4, -4);
- g.endShape(true);
- },
-});
-
-brush.set("standalone-star", "#8f3a2f", 1);
-brush.line(-200, -120, 200, 120);
-brush.render();
-
-console.log("standalone custom brush test executed");
diff --git a/test/standalone/field_explorer.html b/test/standalone/field_explorer.html
index 135e7fe..bb15660 100644
--- a/test/standalone/field_explorer.html
+++ b/test/standalone/field_explorer.html
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>Standalone Flow Field Explorer</title>
+ <title>Flow Field Explorer — Standalone</title>
<style>
:root {
--paper: #f3eee2;
@@ -38,10 +38,13 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a { color: var(--accent); text-decoration: none; }
.nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
h1 {
margin: 0 0 8px;
@@ -75,11 +78,7 @@
label { display: flex; align-items: center; gap: 8px; }
- select,
- input[type=range] {
- font: inherit;
- }
-
+ select, input[type=range] { font: inherit; }
select { padding: 5px 8px; }
input[type=range] { width: 120px; }
span.val { width: 28px; display: inline-block; color: var(--accent); }
@@ -105,7 +104,7 @@
overflow: hidden;
}
- canvas {
+ #canvas-host canvas {
display: block;
border-radius: 6px;
max-width: 100%;
@@ -115,13 +114,14 @@
</head>
<body>
<main>
- <div class="nav"><a href="../index.html">All tests</a></div>
- <h1>Standalone Flow Field Explorer</h1>
- <p>
- Interactive browser page for comparing built-in vector fields with adjustable density and flow-line length.
- </p>
+ <div class="nav">
+ <a href="../index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="../field_explorer.html">← p5 version</a>
+ </div>
+ <h1>Flow Field Explorer <small style="font-size:0.55em;color:#8a9aa8;">standalone</small></h1>
<p>
- Controls update the field live. The current seed stays in the URL so the same view remains reproducible.
+ Interactive standalone page for comparing built-in vector fields with adjustable density and flow-line length.
</p>
<div id="controls" class="panel">
@@ -140,15 +140,127 @@
<span class="val" id="lineLenVal">55</span>
</label>
<label>
- Seed:
- <span class="val" id="seedVal" style="width:auto; min-width:56px;">42</span>
+ Seed: <span class="val" id="seedVal" style="width:auto;min-width:56px;">42</span>
</label>
<button id="refreshSeed" type="button">Refresh seed</button>
</div>
<div id="canvas-host" class="panel"></div>
-
- <script type="module" src="./field_explorer.js"></script>
</main>
+
+ <script src="./standalone_profiler.js"></script>
+ <script type="module">
+ import * as brush from "../../dist/brush.esm.js";
+
+ const FIELDS = ["curved", "zigzag", "waves", "seabed", "spiral", "columns", "hand"];
+ const CW = 800, CH = 800;
+
+ const params = new URLSearchParams(location.search);
+ let currentField = params.get("field") || "curved";
+ let currentDensity = parseInt(params.get("density") || "18");
+ let currentLen = parseInt(params.get("len") || "55");
+ let currentSeed = params.has("seed")
+ ? parseInt(params.get("seed"), 10)
+ : Math.floor(Math.random() * 1000000);
+
+ // Populate select
+ const sel = document.getElementById("fieldSel");
+ FIELDS.forEach((f) => {
+ const opt = document.createElement("option");
+ opt.value = f;
+ opt.textContent = f;
+ if (f === currentField) opt.selected = true;
+ sel.appendChild(opt);
+ });
+
+ const densityEl = document.getElementById("density");
+ const densityVal = document.getElementById("densityVal");
+ const lineLenEl = document.getElementById("lineLen");
+ const lineLenVal = document.getElementById("lineLenVal");
+ const seedVal = document.getElementById("seedVal");
+ const refreshSeedBtn = document.getElementById("refreshSeed");
+
+ densityEl.value = currentDensity;
+ densityVal.textContent = currentDensity;
+ lineLenEl.value = currentLen;
+ lineLenVal.textContent = currentLen;
+ seedVal.textContent = currentSeed;
+
+ function syncUrl() {
+ const qs = new URLSearchParams({
+ field: currentField, density: currentDensity,
+ len: currentLen, seed: currentSeed,
+ });
+ history.replaceState(null, "", `?${qs}`);
+ }
+ syncUrl();
+
+ const pixelDensity = window.devicePixelRatio || 1;
+ brush.createCanvas(CW, CH, { id: "brush-canvas", parent: "#canvas-host", pixelDensity });
+ brush.scaleBrushes(3);
+
+ let renderQueued = false;
+ function queueRender() {
+ if (renderQueued) return;
+ renderQueued = true;
+ requestAnimationFrame(() => { renderQueued = false; renderScene(); });
+ }
+
+ function renderScene() {
+ brush.seed(currentSeed);
+ brush.noiseSeed(currentSeed);
+ seedVal.textContent = currentSeed;
+
+ brush.clear("#f5f5f5");
+ brush.push();
+ brush.translate(-CW / 2, -CH / 2);
+
+ if (currentField === "hand") {
+ brush.wiggle(5);
+ } else {
+ brush.field(currentField);
+ }
+ brush.refreshField(0);
+ brush.set("HB", "#1a2a5a", 1);
+
+ const n = currentDensity;
+ for (let r = 0; r < n; r++) {
+ for (let c = 0; c < n; c++) {
+ const x = 40 + (c / (n - 1)) * 720;
+ const y = 40 + (r / (n - 1)) * 720;
+ brush.flowLine(x, y, currentLen, 0);
+ }
+ }
+
+ brush.noField();
+ brush.pop();
+ brush.render();
+ window.reportStandaloneFirstFrame?.("field_explorer");
+ }
+
+ function handleInput() {
+ currentField = sel.value;
+ currentDensity = parseInt(densityEl.value);
+ currentLen = parseInt(lineLenEl.value);
+ densityVal.textContent = currentDensity;
+ lineLenVal.textContent = currentLen;
+ syncUrl();
+ queueRender();
+ }
+
+ densityEl.addEventListener("input", handleInput);
+ lineLenEl.addEventListener("input", handleInput);
+ sel.addEventListener("input", handleInput);
+ sel.addEventListener("change", handleInput);
+
+ refreshSeedBtn.addEventListener("click", () => {
+ currentSeed = Math.floor(Math.random() * 1000000);
+ seedVal.textContent = currentSeed;
+ syncUrl();
+ queueRender();
+ });
+
+ renderScene();
+ </script>
</body>
</html>
diff --git a/test/standalone/field_explorer.js b/test/standalone/field_explorer.js
deleted file mode 100644
index 3309c79..0000000
--- a/test/standalone/field_explorer.js
+++ /dev/null
@@ -1,118 +0,0 @@
-import * as brush from "../../dist/brush.esm.js";
-
-const FIELDS = ["curved", "zigzag", "waves", "seabed", "spiral", "columns", "hand"];
-const SIZE = 800;
-
-const params = new URLSearchParams(location.search);
-let currentField = params.get("field") || "curved";
-let currentDensity = parseInt(params.get("density") || "18", 10);
-let currentLen = parseInt(params.get("len") || "55", 10);
-let currentSeed = params.has("seed")
- ? parseInt(params.get("seed"), 10)
- : Math.floor(Math.random() * 1000000);
-
-const sel = document.getElementById("fieldSel");
-FIELDS.forEach((fieldName) => {
- const opt = document.createElement("option");
- opt.value = fieldName;
- opt.textContent = fieldName;
- if (fieldName === currentField) opt.selected = true;
- sel.appendChild(opt);
-});
-
-const densityEl = document.getElementById("density");
-const densityVal = document.getElementById("densityVal");
-const lineLenEl = document.getElementById("lineLen");
-const lineLenVal = document.getElementById("lineLenVal");
-const seedVal = document.getElementById("seedVal");
-const refreshSeedBtn = document.getElementById("refreshSeed");
-
-densityEl.value = currentDensity;
-densityVal.textContent = currentDensity;
-lineLenEl.value = currentLen;
-lineLenVal.textContent = currentLen;
-seedVal.textContent = currentSeed;
-
-let renderQueued = false;
-
-function syncUrl() {
- const qs = new URLSearchParams({
- field: currentField,
- density: String(currentDensity),
- len: String(currentLen),
- seed: String(currentSeed),
- });
- history.replaceState(null, "", `?${qs.toString()}`);
-}
-
-function queueRender() {
- if (renderQueued) return;
- renderQueued = true;
- requestAnimationFrame(() => {
- renderQueued = false;
- renderExplorer();
- });
-}
-
-function handleControlInput() {
- currentField = sel.value;
- currentDensity = parseInt(densityEl.value, 10);
- currentLen = parseInt(lineLenEl.value, 10);
- densityVal.textContent = currentDensity;
- lineLenVal.textContent = currentLen;
- syncUrl();
- queueRender();
-}
-
-densityEl.addEventListener("input", handleControlInput);
-lineLenEl.addEventListener("input", handleControlInput);
-sel.addEventListener("input", handleControlInput);
-sel.addEventListener("change", handleControlInput);
-
-refreshSeedBtn.addEventListener("click", () => {
- currentSeed = Math.floor(Math.random() * 1000000);
- seedVal.textContent = currentSeed;
- syncUrl();
- queueRender();
-});
-
-syncUrl();
-brush.createCanvas(SIZE, SIZE, {
- id: "brush-canvas",
- parent: "#canvas-host",
- pixelDensity: globalThis.devicePixelRatio || 1,
-});
-brush.scaleBrushes(3);
-
-function renderExplorer() {
- brush.seed(currentSeed);
- brush.noiseSeed(currentSeed);
- seedVal.textContent = currentSeed;
-
- brush.clear("#f5f5f5");
- brush.push();
- brush.translate(-SIZE / 2, -SIZE / 2);
-
- if (currentField === "hand") {
- brush.wiggle(5);
- } else {
- brush.field(currentField);
- }
- brush.refreshField(0);
- brush.set("HB", "#1a2a5a", 1);
-
- const n = currentDensity;
- for (let r = 0; r < n; r++) {
- for (let c = 0; c < n; c++) {
- const x = 40 + (c / (n - 1)) * 720;
- const y = 40 + (r / (n - 1)) * 720;
- brush.flowLine(x, y, currentLen, 0);
- }
- }
-
- brush.noField();
- brush.pop();
- brush.render();
-}
-
-renderExplorer();
diff --git a/test/standalone/fill.html b/test/standalone/fill.html
deleted file mode 100644
index 9ad7070..0000000
--- a/test/standalone/fill.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>brush.js Standalone Fill Test</title>
- <style>
- body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f6f0e4; font-family: "Iowan Old Style", Palatino, serif; }
- main { width: min(760px, calc(100vw - 32px)); display: grid; gap: 14px; justify-items: center; }
- h1, p { margin: 0; text-align: center; }
- p { max-width: 620px; line-height: 1.45; }
- canvas { width: 600px; height: 600px; border: 1px solid rgba(31,44,51,.16); background: white; }
- code { font-family: Menlo, Monaco, "Courier New", monospace; font-size: 12px; }
- </style>
- </head>
- <body>
- <main>
- <h1>Standalone Fill Test</h1>
- <p>Minimal standalone fill check using <code>brush.fill()</code>, bleed, texture, and one rotated rectangle.</p>
- <div id="canvas-host"></div>
- </main>
- <script type="module" src="./fill.js"></script>
- </body>
- </html>
diff --git a/test/standalone/fill.js b/test/standalone/fill.js
deleted file mode 100644
index 9483eea..0000000
--- a/test/standalone/fill.js
+++ /dev/null
@@ -1,19 +0,0 @@
-import * as brush from "../../dist/brush.esm.js";
-
-brush.createCanvas(600, 600, {
- id: "brush-canvas",
- parent: "#canvas-host",
- pixelDensity: globalThis.devicePixelRatio || 1,
-});
-brush.clear("#fffceb");
-brush.angleMode(brush.DEGREES);
-brush.fill("#3f76b5", 220);
-brush.fillBleed(0.2, "out");
-brush.fillTexture(0.55, 0.35);
-brush.push();
-brush.rotate(10);
-brush.rect(0, 0, 220, 160, "center");
-brush.pop();
-brush.render();
-
-console.log("standalone fill test executed");
diff --git a/test/standalone/fill_circle_explorer.html b/test/standalone/fill_circle_explorer.html
index 7fd7c75..ba22a9d 100644
--- a/test/standalone/fill_circle_explorer.html
+++ b/test/standalone/fill_circle_explorer.html
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>Standalone Fill Circle Explorer</title>
+ <title>Fill Circle Explorer — Standalone</title>
<style>
:root {
--paper: #f3eee2;
@@ -38,10 +38,13 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a { color: var(--accent); text-decoration: none; }
.nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
h1 {
margin: 0 0 8px;
@@ -80,6 +83,7 @@
.control-grid {
display: grid;
+ grid-template-columns: 1fr;
gap: 10px;
font: 11px/1.4 Menlo, Monaco, "Courier New", monospace;
}
@@ -92,16 +96,11 @@
gap: 8px;
}
- input[type=range] {
- flex: 1;
- min-width: 0;
- }
+ input[type=range] { flex: 1; min-width: 0; }
- .val {
- min-width: 34px;
- color: var(--accent);
- text-align: right;
- }
+ .val { min-width: 34px; color: var(--accent); text-align: right; }
+
+ .perf { color: var(--accent); }
.top-row {
display: flex;
@@ -112,20 +111,8 @@
font: 11px/1.4 Menlo, Monaco, "Courier New", monospace;
}
- .perf {
- color: var(--accent);
- }
-
- .seed {
- display: flex;
- align-items: center;
- gap: 8px;
- }
-
- .seed strong {
- color: var(--accent);
- font-weight: 600;
- }
+ .seed { display: flex; align-items: center; gap: 8px; }
+ .seed strong { color: var(--accent); font-weight: 600; }
button {
border: 1px solid var(--line);
@@ -139,12 +126,7 @@
button:hover { background: #f4eee2; }
- .swatches {
- display: flex;
- align-items: center;
- gap: 8px;
- flex-wrap: wrap;
- }
+ .swatches { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.swatch {
width: 22px;
@@ -169,7 +151,8 @@
min-width: 0;
}
- canvas {
+ #canvas-host canvas {
+ grid-area: 1 / 1;
display: block;
border-radius: 6px;
max-width: 100%;
@@ -177,22 +160,23 @@
height: auto !important;
}
+ #label-canvas { pointer-events: none; }
+
@media (max-width: 820px) {
- .workspace {
- grid-template-columns: 1fr;
- }
+ .workspace { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<main>
- <div class="nav"><a href="../index.html">All tests</a></div>
- <h1>Standalone Fill Circle Explorer</h1>
- <p>
- Seeded browser page for checking watercolor fill behavior on a single centered circle with a fine HB stroke.
- </p>
+ <div class="nav">
+ <a href="../index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="../fill_circle_explorer.html">← p5 version</a>
+ </div>
+ <h1>Fill Circle Explorer <small style="font-size:0.55em;color:#8a9aa8;">standalone</small></h1>
<p>
- Use the sliders and palette below to inspect bleed, opacity, texture, and border behavior without changing the seed unless you refresh it.
+ Seeded standalone page for checking watercolor fill on a single centered circle with a fine HB stroke.
</p>
<div class="workspace">
@@ -202,10 +186,7 @@
<span>Seed</span>
<strong id="seedVal">000000</strong>
</div>
- <div class="perf">
- First load
- <strong id="firstLoadVal">-</strong>
- </div>
+ <div class="perf">First load <strong id="firstLoadVal">-</strong></div>
<button id="refreshSeed" type="button">Refresh seed</button>
</div>
@@ -217,7 +198,6 @@
<span class="val" id="bleedVal">0.3</span>
</div>
</label>
-
<label>
Opacity
<div class="slider-row">
@@ -225,7 +205,6 @@
<span class="val" id="opacityVal">92</span>
</div>
</label>
-
<label>
Texture
<div class="slider-row">
@@ -233,7 +212,6 @@
<span class="val" id="textureVal">0.5</span>
</div>
</label>
-
<label>
Border
<div class="slider-row">
@@ -251,8 +229,170 @@
<div id="canvas-host" class="panel"></div>
</div>
-
- <script type="module" src="./fill_circle_explorer.js"></script>
</main>
+
+ <script src="./standalone_profiler.js"></script>
+ <script type="module">
+ import * as brush from "../../dist/brush.esm.js";
+
+ const PALETTE = ["#002185", "#003c32", "#fcd300", "#ff2702", "#6b9404"];
+ const PAPER = "#fffceb";
+ const STROKE = "#111111";
+ const CW = 800, CH = 800;
+
+ const state = {
+ bleed: 0.3,
+ opacity: 92,
+ texture: 0.5,
+ border: 0.4,
+ color: PALETTE[0],
+ seed: 100000 + Math.floor(Math.random() * 900000),
+ };
+
+ const urlParams = new URLSearchParams(location.search);
+ const controls = {
+ bleed: document.getElementById("bleed"),
+ opacity: document.getElementById("opacity"),
+ texture: document.getElementById("texture"),
+ border: document.getElementById("border"),
+ bleedVal: document.getElementById("bleedVal"),
+ opacityVal: document.getElementById("opacityVal"),
+ textureVal: document.getElementById("textureVal"),
+ borderVal: document.getElementById("borderVal"),
+ seedVal: document.getElementById("seedVal"),
+ refreshSeed: document.getElementById("refreshSeed"),
+ palette: document.getElementById("palette"),
+ };
+
+ function fmt(v) {
+ return Number.isInteger(v) ? String(v) : v.toFixed(2).replace(/0$/, "").replace(/\.$/, "");
+ }
+
+ function readUrl(key, def, min, max, dec = null) {
+ if (!urlParams.has(key)) return def;
+ const v = Number(urlParams.get(key));
+ if (!Number.isFinite(v)) return def;
+ const c = Math.min(max, Math.max(min, v));
+ return dec === null ? c : Number(c.toFixed(dec));
+ }
+
+ state.bleed = readUrl("bleed", state.bleed, 0, 1, 2);
+ state.opacity = Math.round(readUrl("opacity", state.opacity, 0, 255));
+ state.texture = readUrl("texture", state.texture, 0, 1, 2);
+ state.border = readUrl("border", state.border, 0, 1, 2);
+ state.seed = Math.round(readUrl("seed", state.seed, 100000, 999999));
+ if (urlParams.has("color") && PALETTE.includes(urlParams.get("color"))) {
+ state.color = urlParams.get("color");
+ }
+
+ controls.bleed.value = state.bleed;
+ controls.opacity.value = state.opacity;
+ controls.texture.value = state.texture;
+ controls.border.value = state.border;
+
+ function syncReadouts() {
+ controls.bleedVal.textContent = fmt(state.bleed);
+ controls.opacityVal.textContent = fmt(state.opacity);
+ controls.textureVal.textContent = fmt(state.texture);
+ controls.borderVal.textContent = fmt(state.border);
+ controls.seedVal.textContent = String(state.seed).padStart(6, "0");
+ }
+
+ function syncPalette() {
+ for (const btn of controls.palette.querySelectorAll(".swatch")) {
+ btn.classList.toggle("active", btn.dataset.color === state.color);
+ }
+ }
+
+ function syncUrl() {
+ const qs = new URLSearchParams({
+ bleed: state.bleed, opacity: state.opacity,
+ texture: state.texture, border: state.border,
+ color: state.color, seed: state.seed,
+ });
+ history.replaceState(null, "", `?${qs}`);
+ }
+
+ // Canvas setup
+ const pixelDensity = window.devicePixelRatio || 1;
+ brush.createCanvas(CW, CH, { id: "brush-canvas", parent: "#canvas-host", pixelDensity });
+ brush.angleMode(brush.DEGREES);
+
+ let renderQueued = false;
+ function queueRender() {
+ if (renderQueued) return;
+ renderQueued = true;
+ requestAnimationFrame(() => {
+ renderQueued = false;
+ renderScene();
+ });
+ }
+
+ function renderScene() {
+ brush.seed(state.seed);
+ brush.noiseSeed(state.seed);
+ syncReadouts();
+
+ brush.clear(PAPER);
+ brush.push();
+ brush.translate(-CW / 2, -CH / 2);
+
+ brush.noField();
+ brush.noHatch();
+ brush.fill(state.color, state.opacity);
+ brush.fillBleed(state.bleed, "out");
+ brush.fillTexture(state.texture, state.border);
+ brush.set("HB", STROKE, 0.5);
+ brush.circle(CW * 0.5, CH * 0.5, CW * 0.25);
+ brush.noFill();
+
+ brush.pop();
+ brush.render();
+ window.reportStandaloneFirstFrame?.("fill_circle_explorer");
+ }
+
+ // Palette buttons
+ for (const color of PALETTE) {
+ const btn = document.createElement("button");
+ btn.type = "button";
+ btn.className = "swatch";
+ btn.dataset.color = color;
+ btn.style.background = color;
+ btn.title = color;
+ btn.addEventListener("click", () => {
+ state.color = color;
+ syncPalette();
+ syncUrl();
+ queueRender();
+ });
+ controls.palette.appendChild(btn);
+ }
+
+ function bindSlider(key, input, readout) {
+ input.addEventListener("input", () => {
+ state[key] = Number(input.value);
+ readout.textContent = fmt(state[key]);
+ syncUrl();
+ queueRender();
+ });
+ }
+
+ bindSlider("bleed", controls.bleed, controls.bleedVal);
+ bindSlider("opacity", controls.opacity, controls.opacityVal);
+ bindSlider("texture", controls.texture, controls.textureVal);
+ bindSlider("border", controls.border, controls.borderVal);
+
+ controls.refreshSeed.addEventListener("click", () => {
+ state.seed = 100000 + Math.floor(Math.random() * 900000);
+ syncReadouts();
+ syncUrl();
+ queueRender();
+ });
+
+ syncPalette();
+ syncReadouts();
+ syncUrl();
+ renderScene();
+ </script>
</body>
</html>
diff --git a/test/standalone/fill_circle_explorer.js b/test/standalone/fill_circle_explorer.js
deleted file mode 100644
index bf8033d..0000000
--- a/test/standalone/fill_circle_explorer.js
+++ /dev/null
@@ -1,203 +0,0 @@
-import * as brush from "../../dist/brush.esm.js";
-
-const PALETTE = ["#002185", "#003c32", "#fcd300", "#ff2702", "#6b9404"];
-const PAPER = "#fffceb";
-const STROKE = "#111111";
-const SIZE = 800;
-
-const state = {
- bleed: 0.3,
- opacity: 92,
- texture: 0.5,
- border: 0.4,
- color: PALETTE[0],
- seed: 100000 + Math.floor(Math.random() * 900000),
-};
-
-const urlParams = new URLSearchParams(location.search);
-const controls = {
- bleed: document.getElementById("bleed"),
- opacity: document.getElementById("opacity"),
- texture: document.getElementById("texture"),
- border: document.getElementById("border"),
- bleedVal: document.getElementById("bleedVal"),
- opacityVal: document.getElementById("opacityVal"),
- textureVal: document.getElementById("textureVal"),
- borderVal: document.getElementById("borderVal"),
- seedVal: document.getElementById("seedVal"),
- firstLoadVal: document.getElementById("firstLoadVal"),
- refreshSeed: document.getElementById("refreshSeed"),
- palette: document.getElementById("palette"),
-};
-
-let renderQueued = false;
-let urlSyncQueued = false;
-let firstLoadReported = false;
-const firstLoadStart =
- performance.getEntriesByType("navigation")[0]?.domContentLoadedEventEnd ??
- performance.now();
-
-function formatValue(value) {
- return Number.isInteger(value)
- ? String(value)
- : value.toFixed(2).replace(/0$/, "").replace(/\.$/, "");
-}
-
-function clampValue(value, min, max) {
- return Math.min(max, Math.max(min, value));
-}
-
-function readUrlNumber(key, fallback, min, max, decimals = null) {
- if (!urlParams.has(key)) return fallback;
- const value = Number(urlParams.get(key));
- if (!Number.isFinite(value)) return fallback;
- const clamped = clampValue(value, min, max);
- return decimals === null ? clamped : Number(clamped.toFixed(decimals));
-}
-
-function syncUrl() {
- const qs = new URLSearchParams({
- bleed: String(state.bleed),
- opacity: String(state.opacity),
- texture: String(state.texture),
- border: String(state.border),
- color: state.color,
- seed: String(state.seed),
- });
- const nextSearch = `?${qs.toString()}`;
- if (location.search === nextSearch) return;
- history.replaceState(null, "", nextSearch);
-}
-
-function queueUrlSync() {
- if (urlSyncQueued) return;
- urlSyncQueued = true;
- requestAnimationFrame(() => {
- urlSyncQueued = false;
- syncUrl();
- });
-}
-
-function syncReadouts() {
- controls.bleedVal.textContent = formatValue(state.bleed);
- controls.opacityVal.textContent = formatValue(state.opacity);
- controls.textureVal.textContent = formatValue(state.texture);
- controls.borderVal.textContent = formatValue(state.border);
- controls.seedVal.textContent = String(state.seed).padStart(6, "0");
-}
-
-function syncPalette() {
- for (const btn of controls.palette.querySelectorAll(".swatch")) {
- btn.classList.toggle("active", btn.dataset.color === state.color);
- }
-}
-
-function queueRender() {
- if (renderQueued) return;
- renderQueued = true;
- requestAnimationFrame(() => {
- renderQueued = false;
- renderScene();
- });
-}
-
-function reportFirstLoad() {
- if (firstLoadReported) return;
- firstLoadReported = true;
- requestAnimationFrame(() => {
- const total = performance.now() - firstLoadStart;
- const text = `${total.toFixed(1)} ms`;
- controls.firstLoadVal.textContent = text;
- console.log(`standalone fill_circle_explorer first load: ${text}`);
- });
-}
-
-function setupPalette() {
- for (const color of PALETTE) {
- const btn = document.createElement("button");
- btn.type = "button";
- btn.className = "swatch";
- btn.dataset.color = color;
- btn.style.background = color;
- btn.title = color;
- btn.addEventListener("click", () => {
- state.color = color;
- syncPalette();
- queueUrlSync();
- queueRender();
- });
- controls.palette.appendChild(btn);
- }
- syncPalette();
-}
-
-function bindSlider(key, input, readout) {
- input.addEventListener("input", () => {
- state[key] = Number(input.value);
- readout.textContent = formatValue(state[key]);
- queueUrlSync();
- queueRender();
- });
-}
-
-state.bleed = readUrlNumber("bleed", state.bleed, 0, 1, 2);
-state.opacity = Math.round(readUrlNumber("opacity", state.opacity, 0, 255));
-state.texture = readUrlNumber("texture", state.texture, 0, 1, 2);
-state.border = readUrlNumber("border", state.border, 0, 1, 2);
-state.seed = Math.round(readUrlNumber("seed", state.seed, 100000, 999999));
-if (urlParams.has("color") && PALETTE.includes(urlParams.get("color"))) {
- state.color = urlParams.get("color");
-}
-
-controls.bleed.value = state.bleed;
-controls.opacity.value = state.opacity;
-controls.texture.value = state.texture;
-controls.border.value = state.border;
-
-bindSlider("bleed", controls.bleed, controls.bleedVal);
-bindSlider("opacity", controls.opacity, controls.opacityVal);
-bindSlider("texture", controls.texture, controls.textureVal);
-bindSlider("border", controls.border, controls.borderVal);
-
-controls.refreshSeed.addEventListener("click", () => {
- state.seed = 100000 + Math.floor(Math.random() * 900000);
- syncReadouts();
- queueUrlSync();
- queueRender();
-});
-
-setupPalette();
-syncReadouts();
-syncUrl();
-
-brush.createCanvas(SIZE, SIZE, {
- id: "brush-canvas",
- parent: "#canvas-host",
- pixelDensity: globalThis.devicePixelRatio || 1,
-});
-brush.angleMode(brush.DEGREES);
-
-function renderScene() {
- brush.seed(state.seed);
- brush.noiseSeed(state.seed);
- syncReadouts();
-
- brush.clear(PAPER);
- brush.push();
- brush.translate(-SIZE / 2, -SIZE / 2);
-
- brush.noField();
- brush.noHatch();
- brush.fill(state.color, state.opacity);
- brush.fillBleed(state.bleed, "out");
- brush.fillTexture(state.texture, state.border);
- brush.set("HB", STROKE, 0.5);
- brush.circle(SIZE * 0.5, SIZE * 0.5, SIZE * 0.25);
- brush.noFill();
-
- brush.pop();
- brush.render();
- reportFirstLoad();
-}
-
-renderScene();
diff --git a/test/standalone/hatch.html b/test/standalone/hatch.html
deleted file mode 100644
index 65802f0..0000000
--- a/test/standalone/hatch.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>brush.js Standalone Hatch Test</title>
- <style>
- body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f6f0e4; font-family: "Iowan Old Style", Palatino, serif; }
- main { width: min(760px, calc(100vw - 32px)); display: grid; gap: 14px; justify-items: center; }
- h1, p { margin: 0; text-align: center; }
- p { max-width: 620px; line-height: 1.45; }
- canvas { width: 600px; height: 600px; border: 1px solid rgba(31,44,51,.16); background: white; }
- code { font-family: Menlo, Monaco, "Courier New", monospace; font-size: 12px; }
- </style>
- </head>
- <body>
- <main>
- <h1>Standalone Hatch Test</h1>
- <p>Minimal standalone hatch check with a hatch brush override and one rotated rectangle.</p>
- <div id="canvas-host"></div>
- </main>
- <script type="module" src="./hatch.js"></script>
- </body>
- </html>
diff --git a/test/standalone/hatch.js b/test/standalone/hatch.js
deleted file mode 100644
index fd91840..0000000
--- a/test/standalone/hatch.js
+++ /dev/null
@@ -1,20 +0,0 @@
-import * as brush from "../../dist/brush.esm.js";
-
-brush.createCanvas(600, 600, {
- id: "brush-canvas",
- parent: "#canvas-host",
- pixelDensity: globalThis.devicePixelRatio || 1,
-});
-brush.clear("#fffceb");
-brush.scaleBrushes(3);
-brush.angleMode(brush.DEGREES);
-brush.hatch(10, 25, { rand: 0.4, continuous: true, gradient: 0.6 });
-brush.hatchStyle("HB", "#264a67", 1);
-brush.push();
-brush.rotate(9);
-brush.rect(0, 0, 240, 170, "center");
-brush.pop();
-brush.noHatch();
-brush.render();
-
-console.log("standalone hatch test executed");
diff --git a/test/standalone/hatch_test.html b/test/standalone/hatch_test.html
index 14594c9..a6a9c5d 100644
--- a/test/standalone/hatch_test.html
+++ b/test/standalone/hatch_test.html
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>Hatch Test</title>
+ <title>p5.brush Standalone Hatch Test</title>
<style>
* { box-sizing: border-box; }
@@ -29,10 +29,13 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a { color: #153e5c; text-decoration: none; }
.nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
h1 {
margin: 0 0 8px;
@@ -50,36 +53,38 @@
#canvas-host {
margin-top: 18px;
- position: relative;
- width: 1360px;
- height: 1800px;
- max-width: 100%;
+ display: grid;
+ justify-content: center;
+ width: 100%;
+ overflow: hidden;
}
- canvas {
- position: absolute;
- inset: 0;
+ #canvas-host canvas {
+ grid-area: 1 / 1;
display: block;
- width: 100%;
- height: 100%;
+ max-width: 100%;
+ height: auto !important;
}
- #label-canvas {
- pointer-events: none;
- }
+ #label-canvas { pointer-events: none; }
</style>
</head>
<body>
<main>
- <div class="nav"><a href="../index.html">All tests</a></div>
- <h1>Hatch Test</h1>
+ <div class="nav">
+ <a href="../index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="../hatch_test.html">← p5 version</a>
+ </div>
+ <h1>Hatch Test <small style="font-size:0.55em;color:#8a9aa8;">standalone</small></h1>
<p>
- Coverage page for hatch angle, spacing, randomization, gradients, continuity, cross-hatching, brush styles, and multi-polygon inputs.
+ Coverage page for hatch angle, spacing, randomization, gradients, continuity, cross-hatching, brush styles, and shape variety.
</p>
<p>
Panels should show stable hatch geometry and predictable option changes without clipping or ordering glitches.
</p>
<div id="canvas-host"></div>
+ <script src="./standalone_profiler.js"></script>
<script type="module" src="./hatch_test.js"></script>
</main>
</body>
diff --git a/test/standalone/hatch_test.js b/test/standalone/hatch_test.js
index 994bb95..ab00022 100644
--- a/test/standalone/hatch_test.js
+++ b/test/standalone/hatch_test.js
@@ -1,3 +1,11 @@
+// ============================================================
+// p5.brush Standalone Hatch Test
+//
+// Standalone equivalent of test/hatch_test.html.
+// Exercises angle sweep, spacing, rand, gradient, continuous,
+// shapes, cross-hatching, large polygons, and combined options.
+// ============================================================
+
import * as brush from "../../dist/brush.esm.js";
const CANVAS_W = 1360;
@@ -14,9 +22,9 @@ const PANEL_BG = "#fcf7ef";
const palette = ["#002185", "#c0392b", "#27ae60", "#8e44ad", "#e67e22", "#16a085", "#d35400"];
const col = (i) => palette[i % palette.length];
-let currentY = MARGIN;
-const pixelDensity = globalThis.devicePixelRatio || 1;
+// ---- Canvas setup ----
+const pixelDensity = window.devicePixelRatio || 1;
brush.createCanvas(CANVAS_W, CANVAS_H, {
id: "brush-canvas",
parent: "#canvas-host",
@@ -27,27 +35,49 @@ const labelCanvas = document.createElement("canvas");
labelCanvas.id = "label-canvas";
labelCanvas.width = Math.round(CANVAS_W * pixelDensity);
labelCanvas.height = Math.round(CANVAS_H * pixelDensity);
-labelCanvas.style.width = `${CANVAS_W}px`;
-labelCanvas.style.height = `${CANVAS_H}px`;
+labelCanvas.style.width = CANVAS_W + "px";
+labelCanvas.style.height = CANVAS_H + "px";
document.getElementById("canvas-host").appendChild(labelCanvas);
-const labelCtx = labelCanvas.getContext("2d");
-labelCtx.setTransform(pixelDensity, 0, 0, pixelDensity, 0, 0);
+
+const lc = labelCanvas.getContext("2d");
+lc.setTransform(pixelDensity, 0, 0, pixelDensity, 0, 0);
+lc.textBaseline = "top";
+
+let currentY = MARGIN;
+
+// ---- Canvas2D rounded rect helper ----
+
+function lcRoundRect(x, y, w, h, r) {
+ lc.beginPath();
+ lc.moveTo(x + r, y);
+ lc.lineTo(x + w - r, y);
+ lc.arcTo(x + w, y, x + w, y + r, r);
+ lc.lineTo(x + w, y + h - r);
+ lc.arcTo(x + w, y + h, x + w - r, y + h, r);
+ lc.lineTo(x + r, y + h);
+ lc.arcTo(x, y + h, x, y + h - r, r);
+ lc.lineTo(x, y + r);
+ lc.arcTo(x, y, x + r, y, r);
+ lc.closePath();
+}
+
+// ---- Layout helpers ----
function section(title, note) {
- labelCtx.fillStyle = "#1d1d1d";
- labelCtx.font = "700 13px Menlo, Monaco, monospace";
- labelCtx.fillText(title, MARGIN, currentY + 14);
+ lc.fillStyle = "#1d1d1d";
+ lc.font = "bold 13px monospace";
+ lc.fillText(title, MARGIN, currentY + 2);
if (note) {
- labelCtx.fillStyle = "#5c5c5c";
- labelCtx.font = "10px Menlo, Monaco, monospace";
- labelCtx.fillText(note, MARGIN, currentY + 30);
+ lc.fillStyle = "#5c5c5c";
+ lc.font = "10px monospace";
+ lc.fillText(note, MARGIN, currentY + 18);
}
- labelCtx.strokeStyle = "#d7cdbf";
- labelCtx.lineWidth = 1;
- labelCtx.beginPath();
- labelCtx.moveTo(MARGIN, currentY + 40);
- labelCtx.lineTo(CANVAS_W - MARGIN, currentY + 40);
- labelCtx.stroke();
+ lc.strokeStyle = "#d7cdbf";
+ lc.lineWidth = 1;
+ lc.beginPath();
+ lc.moveTo(MARGIN, currentY + 40);
+ lc.lineTo(CANVAS_W - MARGIN, currentY + 40);
+ lc.stroke();
currentY += 58;
}
@@ -55,32 +85,46 @@ function drawRow(label, panels) {
const available = CANVAS_W - 2 * MARGIN - LABEL_W;
const panelW = (available - PANEL_GAP * (panels.length - 1)) / panels.length;
- labelCtx.fillStyle = "rgba(251,247,239,0.94)";
- labelCtx.fillRect(MARGIN - 2, currentY + 6, LABEL_W - 10, ROW_H - 18);
- labelCtx.fillStyle = "#2e2e2e";
- labelCtx.font = "700 11px Menlo, Monaco, monospace";
- labelCtx.fillText(label, MARGIN, currentY + 20);
+ // Row label background + text
+ lc.fillStyle = "rgba(251,247,239,0.94)";
+ lcRoundRect(MARGIN - 2, currentY + 6, LABEL_W - 10, ROW_H - 18, 10);
+ lc.fill();
+ lc.fillStyle = "#2e2e2e";
+ lc.font = "bold 11px monospace";
+ lc.fillText(label, MARGIN, currentY + 18);
panels.forEach((panel, index) => {
const x = MARGIN + LABEL_W + index * (panelW + PANEL_GAP);
const y = currentY;
- labelCtx.strokeStyle = FRAME;
- labelCtx.lineWidth = 1;
- labelCtx.beginPath();
- labelCtx.rect(x, y, panelW, ROW_H - 8);
- labelCtx.stroke();
-
- labelCtx.fillStyle = "#4a4a4a";
- labelCtx.font = "9px Menlo, Monaco, monospace";
- labelCtx.fillText(panel.title, x + 14, y + 21);
-
+ // Panel background via brush.wash (drawn on brush canvas, below label canvas)
+ brush.wash(PANEL_BG, 255);
+ new brush.Polygon([[x, y], [x + panelW, y], [x + panelW, y + ROW_H - 8], [x, y + ROW_H - 8]]).wash();
+ brush.noWash();
+
+ // Panel frame on label canvas
+ lc.strokeStyle = FRAME;
+ lc.lineWidth = 1;
+ lcRoundRect(x, y, panelW, ROW_H - 8, 14);
+ lc.stroke();
+
+ // Panel title on label canvas
+ lc.fillStyle = "rgba(255,255,255,0.86)";
+ lcRoundRect(x + 8, y + 8, panelW - 16, 18, 9);
+ lc.fill();
+ lc.fillStyle = "#4a4a4a";
+ lc.font = "9px monospace";
+ lc.fillText(panel.title, x + 14, y + 13);
+
+ // Hatch content
panel.render(x + 10, y + 32, panelW - 20, ROW_H - 48);
});
currentY += ROW_H;
}
+// ---- Hatch-in-panel helper ----
+
function hatchInPanel(x, y, w, h, polyFn, hatchSetup, brushName, brushColor) {
const poly = polyFn(x, y, w, h);
brush.noField();
@@ -92,6 +136,8 @@ function hatchInPanel(x, y, w, h, polyFn, hatchSetup, brushName, brushColor) {
brush.noHatch();
}
+// ---- Polygon factories ----
+
function makeRect(x, y, w, h) {
return new brush.Polygon([[x, y], [x + w, y], [x + w, y + h], [x, y + h]]);
}
@@ -109,16 +155,15 @@ function makeIrregular(x, y, w, h) {
[x + w * 0.1, y + h * 0.2],
[x + w * 0.4, y],
[x + w * 0.8, y + h * 0.1],
- [x + w, y + h * 0.5],
+ [x + w, y + h * 0.5],
[x + w * 0.7, y + h],
[x + w * 0.3, y + h * 0.9],
- [x, y + h * 0.6],
+ [x, y + h * 0.6],
]);
}
function makeStar(x, y, w, h) {
- const cx = x + w / 2;
- const cy = y + h / 2;
+ const cx = x + w / 2, cy = y + h / 2;
const outerR = Math.min(w, h) * 0.48;
const innerR = outerR * 0.4;
const verts = [];
@@ -131,10 +176,8 @@ function makeStar(x, y, w, h) {
}
function makeCircleApprox(x, y, w, h, n) {
- const cx = x + w / 2;
- const cy = y + h / 2;
- const rx = w * 0.45;
- const ry = h * 0.45;
+ const cx = x + w / 2, cy = y + h / 2;
+ const rx = w * 0.45, ry = h * 0.45;
const verts = [];
for (let i = 0; i < n; i++) {
const a = (i / n) * Math.PI * 2;
@@ -143,41 +186,55 @@ function makeCircleApprox(x, y, w, h, n) {
return new brush.Polygon(verts);
}
+// ================================================================
+// Draw
+// ================================================================
+
brush.scaleBrushes(2.4);
brush.angleMode(brush.DEGREES);
brush.clear("#f4ede0");
brush.push();
brush.translate(-CANVAS_W / 2, -CANVAS_H / 2);
+// ---- 1 — Angle sweep ----
section("ANGLE SWEEP", "Same rectangle, angle from 0 to 170 degrees");
+
const angles = [0, 30, 45, 60, 90, 135, 170];
drawRow("angle variations", angles.map((a, i) => ({
title: `${a}°`,
render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect, () => brush.hatch(6, a), "HB", col(i)),
})));
+// ---- 2 — Spacing ----
section("SPACING", "Same angle (45°), varying dist");
+
const spacings = [3, 6, 10, 18, 30];
drawRow("dist variations", spacings.map((d, i) => ({
title: `dist=${d}`,
render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect, () => brush.hatch(d, 45), "HB", col(i)),
})));
+// ---- 3 — Rand option ----
section("RAND OPTION", "Increasing randomness displaces line endpoints");
+
const rands = [0, 0.3, 0.6, 1.0, 1.5];
drawRow("rand values", rands.map((r, i) => ({
title: `rand=${r}`,
render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect, () => brush.hatch(7, 45, { rand: r }), "HB", col(i)),
})));
+// ---- 4 — Gradient option ----
section("GRADIENT OPTION", "Line spacing grows multiplicatively per line");
+
const grads = [0, 0.3, 0.6, 0.8, 1.0];
drawRow("gradient values", grads.map((g, i) => ({
title: `grad=${g}`,
render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect, () => brush.hatch(5, 30, { gradient: g }), "HB", col(i)),
})));
+// ---- 5 — Continuous ----
section("CONTINUOUS OPTION", "Connected lines vs independent segments");
+
drawRow("continuous", [
{
title: "continuous: false",
@@ -189,77 +246,99 @@ drawRow("continuous", [
},
]);
+// ---- 6 — Polygon shapes ----
section("POLYGON SHAPES", "Same hatch (45°, dist=6) on different shapes");
+
const shapeFns = [
{ title: "Rectangle", fn: makeRect },
- { title: "Triangle", fn: makeTriangle },
- { title: "Diamond", fn: makeDiamond },
+ { title: "Triangle", fn: makeTriangle },
+ { title: "Diamond", fn: makeDiamond },
{ title: "Irregular", fn: makeIrregular },
- { title: "Star", fn: makeStar },
+ { title: "Star", fn: makeStar },
];
-drawRow("shape variety", shapeFns.map((shape, i) => ({
- title: shape.title,
- render: (x, y, w, h) => hatchInPanel(x, y, w, h, shape.fn, () => brush.hatch(6, 45), "HB", col(i)),
+drawRow("shape variety", shapeFns.map((s, i) => ({
+ title: s.title,
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, s.fn, () => brush.hatch(6, 45), "HB", col(i)),
})));
+// ---- 7 — Cross-hatching ----
section("CROSS-HATCHING", "Two hatch passes at different angles");
+
const crossPairs = [
- { a1: 45, a2: -45, label: "45 / -45" },
- { a1: 0, a2: 90, label: "0 / 90" },
- { a1: 30, a2: 120, label: "30 / 120" },
+ { a1: 45, a2: -45, label: "45 / -45" },
+ { a1: 0, a2: 90, label: "0 / 90" },
+ { a1: 30, a2: 120, label: "30 / 120" },
];
-drawRow("cross-hatch", crossPairs.map((pair, i) => ({
- title: pair.label,
+drawRow("cross-hatch", crossPairs.map((cp, i) => ({
+ title: cp.label,
render: (x, y, w, h) => {
const poly = makeRect(x, y, w, h);
- brush.noField();
- brush.noStroke();
- brush.noFill();
+ brush.noField(); brush.noStroke(); brush.noFill();
- brush.hatch(8, pair.a1);
+ brush.hatch(8, cp.a1);
brush.hatchStyle("HB", col(i * 2), 1);
poly.hatch();
brush.noHatch();
- brush.hatch(8, pair.a2);
+ brush.hatch(8, cp.a2);
brush.hatchStyle("HB", col(i * 2 + 1), 1);
poly.hatch();
brush.noHatch();
},
})));
+// ---- 8 — Large polygon ----
section("LARGE POLYGON", "64-vertex circle approximation with fine spacing");
+
drawRow("64-vert circle", [
{
title: "dist=4, angle=30",
- render: (x, y, w, h) => hatchInPanel(x, y, w, h, (px, py, pw, ph) => makeCircleApprox(px, py, pw, ph, 64), () => brush.hatch(4, 30), "HB", col(0)),
+ render: (x, y, w, h) => hatchInPanel(
+ x, y, w, h,
+ (px, py, pw, ph) => makeCircleApprox(px, py, pw, ph, 64),
+ () => brush.hatch(4, 30), "HB", col(0),
+ ),
},
{
title: "dist=4, angle=75",
- render: (x, y, w, h) => hatchInPanel(x, y, w, h, (px, py, pw, ph) => makeCircleApprox(px, py, pw, ph, 64), () => brush.hatch(4, 75), "HB", col(3)),
+ render: (x, y, w, h) => hatchInPanel(
+ x, y, w, h,
+ (px, py, pw, ph) => makeCircleApprox(px, py, pw, ph, 64),
+ () => brush.hatch(4, 75), "HB", col(3),
+ ),
},
{
title: "dist=3, angle=45, rand=0.3",
- render: (x, y, w, h) => hatchInPanel(x, y, w, h, (px, py, pw, ph) => makeCircleApprox(px, py, pw, ph, 64), () => brush.hatch(3, 45, { rand: 0.3 }), "HB", col(5)),
+ render: (x, y, w, h) => hatchInPanel(
+ x, y, w, h,
+ (px, py, pw, ph) => makeCircleApprox(px, py, pw, ph, 64),
+ () => brush.hatch(3, 45, { rand: 0.3 }), "HB", col(5),
+ ),
},
]);
+// ---- 9 — Combined options ----
section("COMBINED OPTIONS", "Mixing rand, gradient, and continuous");
+
drawRow("combos", [
{
title: "rand + gradient",
- render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect, () => brush.hatch(6, 45, { rand: 0.4, gradient: 0.5 }), "HB", col(0)),
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect,
+ () => brush.hatch(6, 45, { rand: 0.4, gradient: 0.5 }), "HB", col(0)),
},
{
title: "rand + continuous",
- render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect, () => brush.hatch(8, 45, { rand: 0.3, continuous: true }), "HB", col(1)),
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect,
+ () => brush.hatch(8, 45, { rand: 0.3, continuous: true }), "HB", col(1)),
},
{
title: "all three",
- render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect, () => brush.hatch(6, 45, { rand: 0.3, gradient: 0.3, continuous: true }), "HB", col(2)),
+ render: (x, y, w, h) => hatchInPanel(x, y, w, h, makeRect,
+ () => brush.hatch(6, 45, { rand: 0.3, gradient: 0.3, continuous: true }), "HB", col(2)),
},
]);
brush.pop();
brush.render();
+window.reportStandaloneFirstFrame?.("hatch_test");
console.log("Standalone hatch test complete");
diff --git a/test/standalone/image.html b/test/standalone/image.html
deleted file mode 100644
index 3d675b5..0000000
--- a/test/standalone/image.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>brush.js Standalone Image Brush Test</title>
- <style>
- body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f6f0e4; font-family: "Iowan Old Style", Palatino, serif; }
- main { width: min(760px, calc(100vw - 32px)); display: grid; gap: 14px; justify-items: center; }
- h1, p { margin: 0; text-align: center; }
- p { max-width: 620px; line-height: 1.45; }
- canvas { width: 600px; height: 600px; border: 1px solid rgba(31,44,51,.16); background: white; }
- code { font-family: Menlo, Monaco, "Courier New", monospace; font-size: 12px; }
- </style>
- </head>
- <body>
- <main>
- <h1>Standalone Image Brush Test</h1>
- <p>Checks standalone image-tip loading using an inline SVG data URL.</p>
- <div id="canvas-host"></div>
- </main>
- <script type="module" src="./image.js"></script>
- </body>
- </html>
diff --git a/test/standalone/image.js b/test/standalone/image.js
deleted file mode 100644
index 44932d8..0000000
--- a/test/standalone/image.js
+++ /dev/null
@@ -1,39 +0,0 @@
-import * as brush from "../../dist/brush.esm.js";
-
-const svg = encodeURIComponent(`
- <svg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 80 80">
- <circle cx="40" cy="40" r="24" fill="black"/>
- <rect x="35" y="8" width="10" height="64" fill="black"/>
- <rect x="8" y="35" width="64" height="10" fill="black"/>
- </svg>
-`);
-
-brush.createCanvas(600, 600, {
- id: "brush-canvas",
- parent: "#canvas-host",
- pixelDensity: globalThis.devicePixelRatio || 1,
-});
-brush.clear("#fffceb");
-brush.scaleBrushes(3);
-brush.angleMode(brush.DEGREES);
-
-await brush.add("standalone-image", {
- type: "image",
- image: { src: `data:image/svg+xml;charset=utf-8,${svg}` },
- weight: 0.8,
- scatter: 0.5,
- sharpness: 1,
- grain: 24,
- opacity: 200,
- spacing: 0.18,
- noise: 0.1,
- rotate: "natural",
- markerTip: false,
- pressure: [1, 1],
-});
-
-brush.set("standalone-image", "#305f8a", 1);
-brush.line(-200, 120, 200, -120);
-brush.render();
-
-console.log("standalone image brush test executed");
diff --git a/test/standalone/mass.html b/test/standalone/mass.html
deleted file mode 100644
index d3768a9..0000000
--- a/test/standalone/mass.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>brush.js Standalone Mass Test</title>
- <style>
- body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f6f0e4; font-family: "Iowan Old Style", Palatino, serif; }
- main { width: min(760px, calc(100vw - 32px)); display: grid; gap: 14px; justify-items: center; }
- h1, p { margin: 0; text-align: center; }
- p { max-width: 620px; line-height: 1.45; }
- canvas { width: 600px; height: 600px; border: 1px solid rgba(31,44,51,.16); background: white; }
- code { font-family: Menlo, Monaco, "Courier New", monospace; font-size: 12px; }
- </style>
- </head>
- <body>
- <main>
- <h1>Standalone Mass Test</h1>
- <p>Minimal standalone mass check using the built-in <code>pastel</code> brush on a single rectangle.</p>
- <div id="canvas-host"></div>
- </main>
- <script type="module" src="./mass.js"></script>
- </body>
- </html>
diff --git a/test/standalone/mass.js b/test/standalone/mass.js
deleted file mode 100644
index a26c2e4..0000000
--- a/test/standalone/mass.js
+++ /dev/null
@@ -1,24 +0,0 @@
-import * as brush from "../../dist/brush.esm.js";
-
-brush.createCanvas(600, 600, {
- id: "brush-canvas",
- parent: "#canvas-host",
- pixelDensity: globalThis.devicePixelRatio || 1,
-});
-brush.clear("#fffceb");
-brush.scaleBrushes(3);
-brush.angleMode(brush.DEGREES);
-brush.mass("pastel", "#4b6cb7", {
- precision: 0.75,
- strength: 1,
- gradient: 0.65,
- outline: true,
-});
-brush.push();
-brush.rotate(-7);
-brush.rect(0, 0, 220, 160, "center");
-brush.pop();
-brush.noMass();
-brush.render();
-
-console.log("standalone mass test executed");
diff --git a/test/standalone/offscreen.html b/test/standalone/offscreen.html
deleted file mode 100644
index 405d21c..0000000
--- a/test/standalone/offscreen.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>brush.js Standalone Offscreen Test</title>
- <style>
- body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f6f0e4; font-family: "Iowan Old Style", Palatino, serif; }
- main { width: min(760px, calc(100vw - 32px)); display: grid; gap: 14px; justify-items: center; }
- h1, p { margin: 0; text-align: center; }
- p { max-width: 620px; line-height: 1.45; }
- canvas { width: 600px; height: 600px; border: 1px solid rgba(31,44,51,.16); background: white; }
- code { font-family: Menlo, Monaco, "Courier New", monospace; font-size: 12px; }
- </style>
- </head>
- <body>
- <main>
- <h1>Standalone Offscreen Test</h1>
- <p>Checks drawing into an <code>OffscreenCanvas</code> target and presenting it on a visible canvas.</p>
- <div id="canvas-host"></div>
- </main>
- <script type="module" src="./offscreen.js"></script>
- </body>
- </html>
diff --git a/test/standalone/offscreen.js b/test/standalone/offscreen.js
deleted file mode 100644
index 70d6179..0000000
--- a/test/standalone/offscreen.js
+++ /dev/null
@@ -1,33 +0,0 @@
-import * as brush from "../../dist/brush.esm.js";
-
-const host = document.getElementById("canvas-host");
-const canvas = document.createElement("canvas");
-const pixelDensity = globalThis.devicePixelRatio || 1;
-
-canvas.id = "brush-canvas";
-canvas.width = Math.round(600 * pixelDensity);
-canvas.height = Math.round(600 * pixelDensity);
-canvas.style.width = "600px";
-canvas.style.height = "600px";
-host.appendChild(canvas);
-
-if (typeof OffscreenCanvas === "undefined") {
- console.warn("OffscreenCanvas is not available in this browser.");
-} else {
- const offscreen = new OffscreenCanvas(600, 600);
-
- brush.load(offscreen);
- brush.clear("#fffceb");
- brush.scaleBrushes(3);
- brush.angleMode(brush.DEGREES);
- brush.set("HB", "#183a52", 1);
- brush.line(-200, -140, 200, 140);
- brush.render();
-
- const ctx = canvas.getContext("2d");
- ctx.setTransform(1, 0, 0, 1, 0, 0);
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.drawImage(offscreen, 0, 0, canvas.width, canvas.height);
-}
-
-console.log("standalone offscreen test executed");
diff --git a/test/standalone/pastel_hatching_test.html b/test/standalone/pastel_hatching_test.html
new file mode 100644
index 0000000..8ea3bbf
--- /dev/null
+++ b/test/standalone/pastel_hatching_test.html
@@ -0,0 +1,324 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Pastel Hatching — Standalone</title>
+ <style>
+ :root {
+ --paper: #f3eee2;
+ --ink: #22313f;
+ --muted: #52616e;
+ --line: #d4c8b8;
+ --panel: rgba(255, 252, 245, 0.86);
+ --accent: #153e5c;
+ }
+
+ * { box-sizing: border-box; }
+
+ body {
+ margin: 0;
+ color: var(--ink);
+ background:
+ radial-gradient(circle at top left, rgba(21, 62, 92, 0.08), transparent 24%),
+ linear-gradient(180deg, #f7f2e7 0%, #ece3d3 100%);
+ font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, serif;
+ }
+
+ main {
+ width: min(920px, calc(100vw - 24px));
+ margin: 0 auto;
+ padding: 18px 0 24px;
+ display: grid;
+ justify-items: center;
+ }
+
+ main > * { width: 100%; }
+
+ .nav {
+ margin-bottom: 14px;
+ font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
+ }
+
+ .nav a { color: var(--accent); text-decoration: none; }
+ .nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
+
+ h1 { margin: 0 0 8px; font-size: clamp(24px, 3.6vw, 34px); letter-spacing: -0.04em; }
+
+ p { margin: 0 0 8px; max-width: 760px; color: var(--muted); line-height: 1.45; font-size: 13px; }
+
+ .workspace {
+ margin-top: 18px;
+ display: grid;
+ grid-template-columns: 260px minmax(0, 1fr);
+ gap: 18px;
+ align-items: start;
+ }
+
+ .panel { border: 1px solid var(--line); border-radius: 8px; background: var(--panel); }
+
+ #controls {
+ padding: 14px 16px;
+ display: grid;
+ gap: 12px;
+ align-self: start;
+ }
+
+ .top-row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ flex-wrap: wrap;
+ justify-content: space-between;
+ font: 11px/1.4 Menlo, Monaco, "Courier New", monospace;
+ }
+
+ .seed { display: flex; align-items: center; gap: 8px; }
+ .seed strong { color: var(--accent); font-weight: 600; }
+
+ .control-grid { display: grid; gap: 10px; font: 11px/1.4 Menlo, Monaco, "Courier New", monospace; }
+
+ label { display: grid; gap: 6px; }
+
+ .slider-row { display: flex; align-items: center; gap: 8px; }
+ input[type=range] { flex: 1; min-width: 0; }
+ .val { min-width: 34px; color: var(--accent); text-align: right; }
+
+ select {
+ border: 1px solid var(--line); border-radius: 6px;
+ background: #fbf8f0; color: var(--ink); font: inherit; padding: 6px 8px;
+ }
+
+ button {
+ border: 1px solid var(--line); border-radius: 999px;
+ padding: 7px 12px; background: rgba(255,252,245,0.95);
+ color: var(--accent); font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ cursor: pointer;
+ }
+
+ button:hover { background: #fff; }
+
+ .checkbox-row { display: flex; align-items: center; gap: 8px; }
+
+ #canvas-host {
+ padding: 10px;
+ display: grid;
+ justify-content: center;
+ width: 100%;
+ overflow: hidden;
+ }
+
+ #canvas-host canvas {
+ display: block;
+ border-radius: 6px;
+ max-width: 100%;
+ max-height: min(78vh, 760px);
+ height: auto !important;
+ }
+
+ @media (max-width: 820px) {
+ .workspace { grid-template-columns: 1fr; }
+ }
+ </style>
+ </head>
+ <body>
+ <main>
+ <div class="nav">
+ <a href="../index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="../pastel_hatching_test.html">← p5 version</a>
+ </div>
+ <h1>Pastel Hatching <small style="font-size:0.55em;color:#8a9aa8;">standalone</small></h1>
+ <p>
+ Three random circles drawn with brush.mass() from a fixed palette, reseeded on each render.
+ Controls adjust brush type, precision, strength, gradient, and outline.
+ </p>
+
+ <div class="workspace">
+ <div id="controls" class="panel">
+ <div class="top-row">
+ <div class="seed">
+ <span>Seed</span>
+ <strong id="seedVal">000000</strong>
+ </div>
+ <button id="refresh-seed" type="button">Refresh Seed</button>
+ </div>
+
+ <div class="control-grid">
+ <label>
+ Brush
+ <select id="brushType">
+ <option value="pastel">pastel</option>
+ <option value="crayon">crayon</option>
+ <option value="HB">HB</option>
+ <option value="pen">pen</option>
+ </select>
+ </label>
+
+ <label>
+ Precision
+ <div class="slider-row">
+ <input type="range" id="precision" min="0" max="1" step="0.01" value="0.3" />
+ <span class="val" id="precisionVal">0.3</span>
+ </div>
+ </label>
+
+ <label>
+ Strength
+ <div class="slider-row">
+ <input type="range" id="strength" min="0" max="1" step="0.01" value="0.6" />
+ <span class="val" id="strengthVal">0.6</span>
+ </div>
+ </label>
+
+ <label>
+ Gradient
+ <div class="slider-row">
+ <input type="range" id="gradient" min="0" max="1" step="0.01" value="0.1" />
+ <span class="val" id="gradientVal">0.1</span>
+ </div>
+ </label>
+
+ <label class="checkbox-row">
+ <input type="checkbox" id="outline" />
+ Outline
+ </label>
+ </div>
+ </div>
+
+ <div id="canvas-host" class="panel"></div>
+ </div>
+ </main>
+
+ <script src="./standalone_profiler.js"></script>
+ <script type="module">
+ import * as brush from "../../dist/brush.esm.js";
+
+ const PAPER = "#fffceb";
+ const PALETTE = ["#002185", "#003c32", "#fcd300", "#ff2702", "#6b9404"];
+ const CW = 600, CH = 600;
+
+ const pixelDensity = window.devicePixelRatio || 1;
+ brush.createCanvas(CW, CH, { id: "brush-canvas", parent: "#canvas-host", pixelDensity });
+ brush.scaleBrushes(3);
+
+ let currentSeed = Math.floor(Math.random() * 900000) + 100000;
+
+ const state = {
+ brushType: "pastel",
+ precision: 0.3,
+ strength: 0.6,
+ gradient: 0.1,
+ outline: false,
+ };
+
+ const controls = {
+ seedVal: document.getElementById("seedVal"),
+ refreshSeed: document.getElementById("refresh-seed"),
+ brushType: document.getElementById("brushType"),
+ precision: document.getElementById("precision"),
+ precisionVal: document.getElementById("precisionVal"),
+ strength: document.getElementById("strength"),
+ strengthVal: document.getElementById("strengthVal"),
+ gradient: document.getElementById("gradient"),
+ gradientVal: document.getElementById("gradientVal"),
+ outline: document.getElementById("outline"),
+ };
+
+ // Mulberry32 seeded PRNG — mirrors p5's randomSeed behavior
+ function mkRng(seed) {
+ let s = seed >>> 0;
+ return function () {
+ s += 0x6d2b79f5;
+ let t = Math.imul(s ^ (s >>> 15), 1 | s);
+ t ^= t + Math.imul(t ^ (t >>> 7), 61 | t);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+ }
+
+ function formatValue(v) {
+ return Number.isInteger(v) ? String(v) : v.toFixed(2).replace(/0$/, "").replace(/\.$/, "");
+ }
+
+ function syncReadouts() {
+ controls.seedVal.textContent = String(currentSeed).padStart(6, "0");
+ controls.precisionVal.textContent = formatValue(state.precision);
+ controls.strengthVal.textContent = formatValue(state.strength);
+ controls.gradientVal.textContent = formatValue(state.gradient);
+ }
+
+ let renderQueued = false;
+ function queueRender() {
+ if (renderQueued) return;
+ renderQueued = true;
+ requestAnimationFrame(() => { renderQueued = false; renderScene(); });
+ }
+
+ function renderScene() {
+ syncReadouts();
+
+ const rng = mkRng(currentSeed);
+ brush.seed(currentSeed);
+ brush.noiseSeed(currentSeed);
+
+ brush.clear(PAPER);
+ brush.push();
+ brush.translate(-CW / 2, -CH / 2);
+ brush.wiggle();
+
+ for (let i = 0; i < 3; i++) {
+ const color = PALETTE[Math.floor(rng() * PALETTE.length)];
+ const x = rng() * CW;
+ const y = rng() * CH;
+ const r = CW * (0.2 + rng() * 0.2);
+
+ brush.mass(state.brushType, color, {
+ precision: state.precision,
+ strength: state.strength,
+ gradient: state.gradient,
+ outline: state.outline,
+ });
+ brush.set("pen", "black", 1);
+ brush.circle(x, y, r);
+ brush.noMass();
+ }
+
+ brush.pop();
+ brush.render();
+ window.reportStandaloneFirstFrame?.("pastel_hatching_test");
+ }
+
+ function bindSlider(id, key) {
+ document.getElementById(id).addEventListener("input", (e) => {
+ state[key] = Number(e.target.value);
+ syncReadouts();
+ queueRender();
+ });
+ }
+
+ bindSlider("precision", "precision");
+ bindSlider("strength", "strength");
+ bindSlider("gradient", "gradient");
+
+ controls.brushType.addEventListener("change", () => {
+ state.brushType = controls.brushType.value;
+ queueRender();
+ });
+
+ controls.outline.addEventListener("change", () => {
+ state.outline = controls.outline.checked;
+ queueRender();
+ });
+
+ controls.refreshSeed.addEventListener("click", () => {
+ currentSeed = Math.floor(Math.random() * 900000) + 100000;
+ queueRender();
+ });
+
+ renderScene();
+ </script>
+ </body>
+</html>
diff --git a/test/standalone/pushpop.js b/test/standalone/pushpop.js
deleted file mode 100644
index 7c7318a..0000000
--- a/test/standalone/pushpop.js
+++ /dev/null
@@ -1,91 +0,0 @@
-import * as brush from "../../dist/brush.esm.js";
-
-const CW = 760;
-const CH = 500;
-const COLS = 3;
-const CellW = CW / COLS;
-const cx = (c) => -CW / 2 + c * CellW + CellW / 2;
-
-const Y_BEFORE = -150;
-const Y_INSIDE = 0;
-const Y_AFTER = 150;
-
-brush.createCanvas(CW, CH, {
- id: "brush-canvas",
- parent: "#canvas-host",
- pixelDensity: globalThis.devicePixelRatio || 1,
-});
-brush.clear("#f8f6ee");
-brush.scaleBrushes(1.5);
-
-brush.pick("marker");
-brush.stroke("#1a3a6a");
-brush.strokeWeight(3);
-
-brush.push();
-brush.translate(cx(0), Y_BEFORE);
-brush.line(-60, 0, 60, 0);
-brush.line(0, -30, 0, 30);
-brush.pop();
-
-brush.push();
-brush.translate(cx(0), Y_INSIDE);
-brush.stroke("#c0392b");
-brush.line(-60, 0, 60, 0);
-brush.line(0, -30, 0, 30);
-brush.pop();
-
-brush.push();
-brush.translate(cx(0), Y_AFTER);
-brush.line(-60, 0, 60, 0);
-brush.line(0, -30, 0, 30);
-brush.pop();
-
-brush.pick("HB");
-brush.stroke("#1a3a6a");
-brush.strokeWeight(1);
-brush.noFill();
-
-brush.push();
-brush.translate(cx(1), Y_BEFORE);
-brush.line(-60, 0, 60, 0);
-brush.line(0, -30, 0, 30);
-brush.pop();
-
-brush.push();
-brush.translate(cx(1), Y_INSIDE);
-brush.pick("charcoal");
-brush.stroke("#c0392b");
-brush.strokeWeight(6);
-brush.line(-60, 0, 60, 0);
-brush.line(0, -30, 0, 30);
-brush.pop();
-
-brush.push();
-brush.translate(cx(1), Y_AFTER);
-brush.line(-60, 0, 60, 0);
-brush.line(0, -30, 0, 30);
-brush.pop();
-
-brush.noStroke();
-brush.fill("#1a3a6a", 70);
-brush.fillBleed(0.2);
-brush.fillTexture(0.4, 0.3);
-
-brush.push();
-brush.translate(cx(2), Y_BEFORE);
-brush.rect(-55, -35, 110, 70, "corner");
-brush.pop();
-
-brush.push();
-brush.translate(cx(2), Y_INSIDE);
-brush.fill("#c0392b", 120);
-brush.rect(-55, -35, 110, 70, "corner");
-brush.pop();
-
-brush.push();
-brush.translate(cx(2), Y_AFTER);
-brush.rect(-55, -35, 110, 70, "corner");
-brush.pop();
-
-brush.render();
diff --git a/test/standalone/pushpop_test.html b/test/standalone/pushpop_test.html
new file mode 100644
index 0000000..b4f5071
--- /dev/null
+++ b/test/standalone/pushpop_test.html
@@ -0,0 +1,203 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Push / Pop State — Standalone</title>
+ <style>
+ * { box-sizing: border-box; }
+
+ body {
+ margin: 0;
+ color: #22313f;
+ background:
+ radial-gradient(circle at top left, rgba(20, 48, 73, 0.08), transparent 24%),
+ linear-gradient(180deg, #f7f2e7 0%, #ece3d3 100%);
+ font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, serif;
+ }
+
+ main {
+ width: min(920px, calc(100vw - 24px));
+ margin: 0 auto;
+ padding: 18px 0 24px;
+ display: grid;
+ justify-items: center;
+ }
+
+ main > * { width: 100%; }
+
+ .nav {
+ margin-bottom: 14px;
+ font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
+ }
+
+ .nav a { color: #153e5c; text-decoration: none; }
+ .nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
+
+ h1 {
+ margin: 0 0 8px;
+ font-size: clamp(24px, 3.6vw, 34px);
+ letter-spacing: -0.04em;
+ }
+
+ p {
+ max-width: 760px;
+ margin: 0 0 8px;
+ color: #52616e;
+ line-height: 1.45;
+ font-size: 13px;
+ }
+
+ #canvas-host {
+ margin-top: 18px;
+ display: grid;
+ justify-content: center;
+ width: 100%;
+ overflow: hidden;
+ }
+
+ #canvas-host canvas {
+ grid-area: 1 / 1;
+ display: block;
+ max-width: 100%;
+ height: auto !important;
+ }
+
+ #label-canvas { pointer-events: none; }
+ </style>
+ </head>
+ <body>
+ <main>
+ <div class="nav">
+ <a href="../index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="../pushpop_test.html">← p5 version</a>
+ </div>
+ <h1>Push / Pop State <small style="font-size:0.55em;color:#8a9aa8;">standalone</small></h1>
+ <p>
+ Each column proves that standalone <b>brush.push()</b> and <b>brush.pop()</b> save and restore brush state.
+ </p>
+ <p>
+ Column 1 checks stroke color, column 2 checks stroke weight and brush type, column 3 checks fill color and opacity.
+ The "after pop" row must match the "before" row exactly.
+ </p>
+ <div id="canvas-host"></div>
+ </main>
+
+ <script src="./standalone_profiler.js"></script>
+ <script type="module">
+ import * as brush from "../../dist/brush.esm.js";
+
+ const CW = 760, CH = 500;
+ const COLS = 3;
+ const CellW = CW / COLS;
+ const cxFn = (c) => c * CellW + CellW / 2;
+
+ const Y_BEFORE = 100, Y_INSIDE = 250, Y_AFTER = 400;
+
+ const pixelDensity = window.devicePixelRatio || 1;
+ brush.createCanvas(CW, CH, { id: "brush-canvas", parent: "#canvas-host", pixelDensity });
+ brush.scaleBrushes(1.5);
+
+ // Label canvas for grid lines and row labels
+ const labelCanvas = document.createElement("canvas");
+ labelCanvas.id = "label-canvas";
+ labelCanvas.width = Math.round(CW * pixelDensity);
+ labelCanvas.height = Math.round(CH * pixelDensity);
+ labelCanvas.style.width = CW + "px";
+ labelCanvas.style.height = CH + "px";
+ document.getElementById("canvas-host").appendChild(labelCanvas);
+ const lc = labelCanvas.getContext("2d");
+ lc.setTransform(pixelDensity, 0, 0, pixelDensity, 0, 0);
+ lc.textBaseline = "middle";
+
+ // Grid dividers
+ lc.strokeStyle = "rgba(190,190,190,0.8)";
+ lc.lineWidth = 1;
+ for (let c = 1; c < COLS; c++) {
+ lc.beginPath(); lc.moveTo(c * CellW, 0); lc.lineTo(c * CellW, CH); lc.stroke();
+ }
+
+ // Row separator lines
+ lc.strokeStyle = "rgba(200,200,200,0.5)";
+ lc.lineWidth = 0.5;
+ for (const y of [Y_BEFORE - 50, Y_INSIDE - 50, Y_AFTER - 50]) {
+ lc.beginPath(); lc.moveTo(0, y); lc.lineTo(CW, y); lc.stroke();
+ }
+
+ // Row labels
+ lc.fillStyle = "rgba(80,80,80,0.7)";
+ lc.font = "10px monospace";
+ for (const [label, y] of [["before", Y_BEFORE - 35], ["inside push", Y_INSIDE - 35], ["after pop", Y_AFTER - 35]]) {
+ lc.fillText(label, 8, y);
+ }
+
+ brush.clear("#f8f6ee");
+ brush.push();
+ brush.translate(-CW / 2, -CH / 2);
+
+ // ---- COL 0 — stroke COLOR ----
+ brush.pick("marker");
+ brush.stroke("#1a3a6a");
+ brush.strokeWeight(3);
+
+ brush.push(); brush.translate(cxFn(0), Y_BEFORE);
+ brush.line(-60, 0, 60, 0); brush.line(0, -30, 0, 30);
+ brush.pop();
+
+ brush.push(); brush.translate(cxFn(0), Y_INSIDE);
+ brush.stroke("#c0392b");
+ brush.line(-60, 0, 60, 0); brush.line(0, -30, 0, 30);
+ brush.pop();
+
+ brush.push(); brush.translate(cxFn(0), Y_AFTER);
+ brush.line(-60, 0, 60, 0); brush.line(0, -30, 0, 30);
+ brush.pop();
+
+ // ---- COL 1 — stroke WEIGHT + brush TYPE ----
+ brush.pick("HB");
+ brush.stroke("#1a3a6a");
+ brush.strokeWeight(1);
+ brush.noFill();
+
+ brush.push(); brush.translate(cxFn(1), Y_BEFORE);
+ brush.line(-60, 0, 60, 0); brush.line(0, -30, 0, 30);
+ brush.pop();
+
+ brush.push(); brush.translate(cxFn(1), Y_INSIDE);
+ brush.pick("charcoal"); brush.stroke("#c0392b"); brush.strokeWeight(6);
+ brush.line(-60, 0, 60, 0); brush.line(0, -30, 0, 30);
+ brush.pop();
+
+ brush.push(); brush.translate(cxFn(1), Y_AFTER);
+ brush.line(-60, 0, 60, 0); brush.line(0, -30, 0, 30);
+ brush.pop();
+
+ // ---- COL 2 — FILL color + opacity ----
+ brush.noStroke();
+ brush.fill("#1a3a6a", 70);
+ brush.fillBleed(0.2);
+ brush.fillTexture(0.4, 0.3);
+
+ brush.push(); brush.translate(cxFn(2), Y_BEFORE);
+ brush.rect(-55, -35, 110, 70, "corner");
+ brush.pop();
+
+ brush.push(); brush.translate(cxFn(2), Y_INSIDE);
+ brush.fill("#c0392b", 120);
+ brush.rect(-55, -35, 110, 70, "corner");
+ brush.pop();
+
+ brush.push(); brush.translate(cxFn(2), Y_AFTER);
+ brush.rect(-55, -35, 110, 70, "corner");
+ brush.pop();
+
+ brush.pop();
+ brush.render();
+ window.reportStandaloneFirstFrame?.("pushpop_test");
+ </script>
+ </body>
+</html>
diff --git a/test/standalone/smoke.html b/test/standalone/smoke.html
deleted file mode 100644
index fba6cbb..0000000
--- a/test/standalone/smoke.html
+++ /dev/null
@@ -1,64 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>brush.js Standalone Smoke Test</title>
- <style>
- body {
- margin: 0;
- min-height: 100vh;
- display: grid;
- place-items: center;
- background: #f6f0e4;
- color: #1f2c33;
- font-family: "Iowan Old Style", "Palatino Linotype", Palatino, serif;
- }
-
- main {
- width: min(760px, calc(100vw - 32px));
- display: grid;
- gap: 14px;
- justify-items: center;
- }
-
- h1 {
- margin: 0;
- font-size: 28px;
- letter-spacing: -0.03em;
- }
-
- p {
- margin: 0;
- max-width: 620px;
- text-align: center;
- line-height: 1.45;
- }
-
- canvas {
- width: 600px;
- height: 600px;
- border: 1px solid rgba(31, 44, 51, 0.16);
- background: white;
- }
-
- code {
- font-family: Menlo, Monaco, "Courier New", monospace;
- font-size: 12px;
- }
- </style>
- </head>
- <body>
- <main>
- <h1>Standalone Smoke Test</h1>
- <p>
- Minimal browser test for the standalone build. It loads a plain
- <code>canvas</code>, applies a transform stack, and draws one line plus
- one rectangle.
- </p>
- <div id="canvas-host"></div>
- </main>
-
- <script type="module" src="./smoke.js"></script>
- </body>
- </html>
diff --git a/test/standalone/smoke.js b/test/standalone/smoke.js
deleted file mode 100644
index cf5c9f2..0000000
--- a/test/standalone/smoke.js
+++ /dev/null
@@ -1,23 +0,0 @@
-import * as brush from "../../dist/brush.esm.js";
-
-brush.createCanvas(600, 600, {
- id: "brush-canvas",
- parent: "#canvas-host",
- pixelDensity: globalThis.devicePixelRatio || 1,
-});
-brush.scaleBrushes(3);
-brush.angleMode(brush.DEGREES);
-
-brush.set("HB", "#183a52", 1);
-brush.line(-180, -160, 180, 160);
-
-brush.push();
-brush.translate(0, 40);
-brush.rotate(12);
-brush.set("HB", "#b1542f", 1);
-brush.rect(0, 0, 180, 110, "center");
-brush.pop();
-
-brush.render();
-
-console.log("standalone smoke test executed");
diff --git a/test/standalone/standalone_profiler.js b/test/standalone/standalone_profiler.js
new file mode 100644
index 0000000..c3a9500
--- /dev/null
+++ b/test/standalone/standalone_profiler.js
@@ -0,0 +1,56 @@
+(() => {
+ const start =
+ performance.getEntriesByType("navigation")[0]?.domContentLoadedEventEnd ??
+ performance.now();
+
+ let reported = false;
+ let badge = null;
+
+ function ensureBadge() {
+ if (document.getElementById("firstLoadVal")) return null;
+ if (badge) return badge;
+ if (!document.body) return null;
+
+ badge = document.createElement("div");
+ badge.id = "standalone-first-load-badge";
+ badge.style.position = "fixed";
+ badge.style.top = "12px";
+ badge.style.right = "12px";
+ badge.style.zIndex = "9999";
+ badge.style.padding = "8px 10px";
+ badge.style.border = "1px solid rgba(48, 41, 30, 0.14)";
+ badge.style.borderRadius = "8px";
+ badge.style.background = "rgba(255, 252, 245, 0.9)";
+ badge.style.color = "#153e5c";
+ badge.style.font = '11px/1.4 Menlo, Monaco, "Courier New", monospace';
+ badge.style.boxShadow = "0 2px 10px rgba(0, 0, 0, 0.06)";
+ badge.textContent = "First load -";
+ document.body.appendChild(badge);
+ return badge;
+ }
+
+ function setText(text) {
+ const valueEl = document.getElementById("firstLoadVal");
+ if (valueEl) {
+ valueEl.textContent = text;
+ return;
+ }
+ const el = ensureBadge();
+ if (el) el.textContent = `First load ${text}`;
+ }
+
+ document.addEventListener("DOMContentLoaded", () => {
+ ensureBadge();
+ });
+
+ window.reportStandaloneFirstFrame = (label = document.title || "standalone test") => {
+ if (reported) return;
+ reported = true;
+ requestAnimationFrame(() => {
+ const total = performance.now() - start;
+ const text = `${total.toFixed(1)} ms`;
+ setText(text);
+ console.log(`${label} first load: ${text}`);
+ });
+ };
+})();
diff --git a/test/standalone/transform_alignment.html b/test/standalone/transform_alignment.html
deleted file mode 100644
index 0c882c8..0000000
--- a/test/standalone/transform_alignment.html
+++ /dev/null
@@ -1,87 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>brush.js - Standalone Transform Alignment</title>
- <style>
- * { box-sizing: border-box; }
-
- body {
- margin: 0;
- color: #22313f;
- background:
- radial-gradient(circle at top left, rgba(20, 48, 73, 0.08), transparent 24%),
- linear-gradient(180deg, #f7f2e7 0%, #ece3d3 100%);
- font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, serif;
- }
-
- main {
- width: min(920px, calc(100vw - 24px));
- margin: 0 auto;
- padding: 18px 0 24px;
- display: grid;
- justify-items: center;
- }
-
- main > * { width: 100%; }
-
- .nav {
- margin-bottom: 14px;
- font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
- }
-
- .nav a { color: #153e5c; text-decoration: none; }
- .nav a:hover { text-decoration: underline; }
-
- h1 {
- margin: 0 0 8px;
- font-size: clamp(24px, 3.6vw, 34px);
- letter-spacing: -0.04em;
- }
-
- p {
- max-width: 760px;
- margin: 0 0 8px;
- color: #52616e;
- line-height: 1.45;
- font-size: 13px;
- }
-
- #canvas-host {
- margin-top: 18px;
- position: relative;
- width: 760px;
- height: 600px;
- max-width: 100%;
- }
-
- canvas {
- position: absolute;
- inset: 0;
- display: block;
- width: 100%;
- height: 100%;
- }
-
- #ref-canvas {
- pointer-events: none;
- }
- </style>
- </head>
- <body>
- <main>
- <div class="nav"><a href="../index.html">All tests</a></div>
- <h1>Standalone Transform Alignment</h1>
- <p>
- Red native canvas references are drawn at the exact same coordinates as the standalone brush marks, so they should align precisely.
- </p>
- <p>
- Columns cover <b>translate(+80, -40)</b>, <b>rotate(25deg)</b>, and <b>scale(1.8)</b>. Row 1 checks strokes and row 2 checks fills.
- </p>
- <div id="canvas-host"></div>
-
- <script type="module" src="./transform_alignment.js"></script>
- </main>
- </body>
-</html>
diff --git a/test/standalone/transform_alignment.js b/test/standalone/transform_alignment.js
deleted file mode 100644
index 2bdf47f..0000000
--- a/test/standalone/transform_alignment.js
+++ /dev/null
@@ -1,207 +0,0 @@
-import * as brush from "../../dist/brush.esm.js";
-
-const CW = 760;
-const CH = 600;
-const COLS = 3;
-const ROWS = 2;
-const CellW = CW / COLS;
-const CellH = CH / ROWS;
-const cx = (c) => -CW / 2 + c * CellW + CellW / 2;
-const cy = (r) => -CH / 2 + r * CellH + CellH / 2;
-
-const BLUE = "#1a3a6a";
-const RED = "#c0392b";
-const OLIVE = "#4a6a1a";
-
-const pixelDensity = globalThis.devicePixelRatio || 1;
-brush.createCanvas(CW, CH, {
- id: "brush-canvas",
- parent: "#canvas-host",
- pixelDensity,
-});
-const refCanvas = document.createElement("canvas");
-refCanvas.id = "ref-canvas";
-refCanvas.width = Math.round(CW * pixelDensity);
-refCanvas.height = Math.round(CH * pixelDensity);
-refCanvas.style.width = `${CW}px`;
-refCanvas.style.height = `${CH}px`;
-document.getElementById("canvas-host").appendChild(refCanvas);
-const ref = refCanvas.getContext("2d");
-ref.setTransform(pixelDensity, 0, 0, pixelDensity, 0, 0);
-
-brush.clear("#f8f6ee");
-brush.scaleBrushes(2);
-
-function withRefTransform(drawFn) {
- ref.save();
- ref.translate(CW / 2, CH / 2);
- drawFn();
- ref.restore();
-}
-
-function drawGrid() {
- ref.save();
- ref.strokeStyle = "rgba(120, 112, 100, 0.35)";
- ref.lineWidth = 1;
- ref.translate(CW / 2, CH / 2);
- for (let c = 1; c < COLS; c++) {
- const x = -CW / 2 + c * CellW;
- ref.beginPath();
- ref.moveTo(x, -CH / 2);
- ref.lineTo(x, CH / 2);
- ref.stroke();
- }
- ref.beginPath();
- ref.moveTo(-CW / 2, 0);
- ref.lineTo(CW / 2, 0);
- ref.stroke();
- ref.restore();
-}
-
-function drawAxisDashes(x, y) {
- const dashLen = 3;
- const gapLen = 4;
- const unit = dashLen + gapLen;
- ref.save();
- ref.translate(x, y);
- ref.strokeStyle = "rgba(120, 112, 100, 0.45)";
- ref.lineWidth = 1;
- for (let d = -70; d < 70; d += unit) {
- ref.beginPath();
- ref.moveTo(d, 0);
- ref.lineTo(Math.min(d + dashLen, 70), 0);
- ref.stroke();
- }
- for (let d = -60; d < 60; d += unit) {
- ref.beginPath();
- ref.moveTo(0, d);
- ref.lineTo(0, Math.min(d + dashLen, 60));
- ref.stroke();
- }
- ref.restore();
-}
-
-function refLines() {
- ref.strokeStyle = "rgba(220, 30, 30, 0.9)";
- ref.lineWidth = 1;
- ref.beginPath();
- ref.moveTo(-60, 0);
- ref.lineTo(60, 0);
- ref.moveTo(0, -40);
- ref.lineTo(0, 40);
- ref.moveTo(-50, -20);
- ref.lineTo(50, 20);
- ref.stroke();
-}
-
-function refRect(color) {
- ref.fillStyle = `${color}50`;
- ref.strokeStyle = "rgba(220, 30, 30, 0.9)";
- ref.lineWidth = 2;
- ref.beginPath();
- ref.rect(-55, -40, 110, 80);
- ref.fill();
- ref.stroke();
-}
-
-function brushLines(color) {
- brush.set("HB", color, 1.2);
- brush.line(-60, 0, 60, 0);
- brush.line(0, -40, 0, 40);
- brush.set("2B", color, 0.8);
- brush.line(-50, -20, 50, 20);
-}
-
-function brushFill(color) {
- brush.noStroke();
- brush.fill(color, 200);
- brush.fillBleed(0.3);
- brush.fillTexture(0.5, 0.4);
- brush.rect(-55, -40, 110, 80, "corner");
- brush.noFill();
-}
-
-drawGrid();
-
-brush.push();
-brush.translate(cx(0), cy(0));
-drawAxisDashes(cx(0), cy(0));
-brush.push();
-brush.translate(80, -40);
-withRefTransform(() => {
- ref.translate(cx(0), cy(0));
- ref.translate(80, -40);
- refLines();
-});
-brushLines(BLUE);
-brush.pop();
-brush.pop();
-
-brush.push();
-brush.translate(cx(1), cy(0));
-drawAxisDashes(cx(1), cy(0));
-brush.push();
-brush.rotate(25);
-withRefTransform(() => {
- ref.translate(cx(1), cy(0));
- ref.rotate((25 * Math.PI) / 180);
- refLines();
-});
-brushLines(RED);
-brush.pop();
-brush.pop();
-
-brush.push();
-brush.translate(cx(2), cy(0));
-drawAxisDashes(cx(2), cy(0));
-brush.push();
-brush.scale(1.8);
-withRefTransform(() => {
- ref.translate(cx(2), cy(0));
- ref.scale(1.8, 1.8);
- refLines();
-});
-brushLines(OLIVE);
-brush.pop();
-brush.pop();
-
-brush.push();
-brush.translate(cx(0), cy(1));
-brush.push();
-brush.translate(80, -40);
-withRefTransform(() => {
- ref.translate(cx(0), cy(1));
- ref.translate(80, -40);
- refRect(BLUE);
-});
-brushFill(BLUE);
-brush.pop();
-brush.pop();
-
-brush.push();
-brush.translate(cx(1), cy(1));
-brush.push();
-brush.rotate(25);
-withRefTransform(() => {
- ref.translate(cx(1), cy(1));
- ref.rotate((25 * Math.PI) / 180);
- refRect(RED);
-});
-brushFill(RED);
-brush.pop();
-brush.pop();
-
-brush.push();
-brush.translate(cx(2), cy(1));
-brush.push();
-brush.scale(1.8);
-withRefTransform(() => {
- ref.translate(cx(2), cy(1));
- ref.scale(1.8, 1.8);
- refRect(OLIVE);
-});
-brushFill(OLIVE);
-brush.pop();
-brush.pop();
-
-brush.render();
diff --git a/test/standalone/transform_test.html b/test/standalone/transform_test.html
new file mode 100644
index 0000000..5e61d71
--- /dev/null
+++ b/test/standalone/transform_test.html
@@ -0,0 +1,226 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Transform Alignment — Standalone</title>
+ <style>
+ * { box-sizing: border-box; }
+
+ body {
+ margin: 0;
+ color: #22313f;
+ background:
+ radial-gradient(circle at top left, rgba(20, 48, 73, 0.08), transparent 24%),
+ linear-gradient(180deg, #f7f2e7 0%, #ece3d3 100%);
+ font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, serif;
+ }
+
+ main {
+ width: min(920px, calc(100vw - 24px));
+ margin: 0 auto;
+ padding: 18px 0 24px;
+ display: grid;
+ justify-items: center;
+ }
+
+ main > * { width: 100%; }
+
+ .nav {
+ margin-bottom: 14px;
+ font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
+ }
+
+ .nav a { color: #153e5c; text-decoration: none; }
+ .nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
+
+ h1 {
+ margin: 0 0 8px;
+ font-size: clamp(24px, 3.6vw, 34px);
+ letter-spacing: -0.04em;
+ }
+
+ p {
+ max-width: 760px;
+ margin: 0 0 8px;
+ color: #52616e;
+ line-height: 1.45;
+ font-size: 13px;
+ }
+
+ #canvas-host {
+ margin-top: 18px;
+ display: grid;
+ justify-content: center;
+ width: 100%;
+ overflow: hidden;
+ }
+
+ #canvas-host canvas {
+ grid-area: 1 / 1;
+ display: block;
+ max-width: 100%;
+ height: auto !important;
+ }
+
+ #ref-canvas { pointer-events: none; }
+ </style>
+ </head>
+ <body>
+ <main>
+ <div class="nav">
+ <a href="../index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="../transform_test.html">← p5 version</a>
+ </div>
+ <h1>Transform Alignment <small style="font-size:0.55em;color:#8a9aa8;">standalone</small></h1>
+ <p>
+ Red canvas2D references are drawn at the same coordinates as standalone brush marks using matching transforms,
+ so they should align precisely.
+ </p>
+ <p>
+ Columns cover <b>translate(+80, -40)</b>, <b>rotate(PI/5)</b>, and <b>scale(1.8)</b>. Row 1 checks strokes and row 2 checks fills.
+ </p>
+ <div id="canvas-host"></div>
+ </main>
+
+ <script src="./standalone_profiler.js"></script>
+ <script type="module">
+ import * as brush from "../../dist/brush.esm.js";
+
+ const CW = 760, CH = 600;
+ const COLS = 3, ROWS = 2;
+ const CellW = CW / COLS, CellH = CH / ROWS;
+ const cx = (c) => c * CellW + CellW / 2;
+ const cy = (r) => r * CellH + CellH / 2;
+
+ const BLUE = "#1a3a6a";
+ const RED = "#c0392b";
+ const OLIVE = "#4a6a1a";
+ const SEED = 12345;
+
+ const pixelDensity = window.devicePixelRatio || 1;
+ brush.createCanvas(CW, CH, { id: "brush-canvas", parent: "#canvas-host", pixelDensity });
+ brush.scaleBrushes(2);
+ brush.seed(SEED);
+ brush.noiseSeed(SEED);
+
+ // Reference canvas (2D, overlaid)
+ const refCanvas = document.createElement("canvas");
+ refCanvas.id = "ref-canvas";
+ refCanvas.width = Math.round(CW * pixelDensity);
+ refCanvas.height = Math.round(CH * pixelDensity);
+ refCanvas.style.width = CW + "px";
+ refCanvas.style.height = CH + "px";
+ document.getElementById("canvas-host").appendChild(refCanvas);
+ const rc = refCanvas.getContext("2d");
+ rc.setTransform(pixelDensity, 0, 0, pixelDensity, 0, 0);
+
+ // ---- Reference helpers ----
+
+ function rcLines() {
+ rc.strokeStyle = "rgba(220,30,30,0.7)";
+ rc.lineWidth = 0.5;
+ rc.beginPath();
+ rc.moveTo(-60, 0); rc.lineTo(60, 0);
+ rc.moveTo(0, -40); rc.lineTo(0, 40);
+ rc.moveTo(-50, -20); rc.lineTo(50, 20);
+ rc.stroke();
+ }
+
+ function rcRect(hex) {
+ const [r, g, b] = hexToRgb(hex);
+ rc.fillStyle = `rgba(${r},${g},${b},0.31)`;
+ rc.strokeStyle = "rgba(220,30,30,0.8)";
+ rc.lineWidth = 2;
+ rc.fillRect(-55, -40, 110, 80);
+ rc.strokeRect(-55, -40, 110, 80);
+ }
+
+ function hexToRgb(hex) {
+ const r = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
+ return r ? [parseInt(r[1],16), parseInt(r[2],16), parseInt(r[3],16)] : [0,0,0];
+ }
+
+ // ---- Grid lines on ref canvas ----
+ rc.strokeStyle = "rgba(190,190,190,0.6)";
+ rc.lineWidth = 1;
+ for (let c = 1; c < COLS; c++) { rc.beginPath(); rc.moveTo(c * CellW, 0); rc.lineTo(c * CellW, CH); rc.stroke(); }
+ rc.beginPath(); rc.moveTo(0, CellH); rc.lineTo(CW, CellH); rc.stroke();
+
+ // ---- Dash pattern helper ----
+ function rcDashes(x, y, w, h) {
+ rc.strokeStyle = "rgba(180,180,180,0.5)";
+ rc.lineWidth = 0.5;
+ const dash = 3, gap = 4, unit = dash + gap;
+ rc.beginPath();
+ for (let d = x - 70; d < x + 70; d += unit) { rc.moveTo(d, y); rc.lineTo(Math.min(d + dash, x + 70), y); }
+ for (let d = y - 60; d < y + 60; d += unit) { rc.moveTo(x, d); rc.lineTo(x, Math.min(d + dash, y + 60)); }
+ rc.stroke();
+ }
+
+ // ================================================================
+ // Brush setup
+ // ================================================================
+
+ brush.clear("#f8f6ee");
+ brush.push();
+ brush.translate(-CW / 2, -CH / 2);
+
+ function brushLines(color) {
+ brush.set("HB", color, 1.2);
+ brush.line(-60, 0, 60, 0);
+ brush.line(0, -40, 0, 40);
+ brush.set("2B", color, 0.8);
+ brush.line(-50, -20, 50, 20);
+ }
+
+ function brushFill(color) {
+ brush.noStroke();
+ brush.fill(color, 200);
+ brush.fillBleed(0.3);
+ brush.fillTexture(0.5, 0.4);
+ brush.rect(-55, -40, 110, 80, "corner");
+ brush.noFill();
+ }
+
+ // ---- ROW 0 — Strokes ----
+
+ // Col 0 — translate
+ rcDashes(cx(0), cy(0), CellW, CellH);
+ rc.save(); rc.translate(cx(0), cy(0)); rc.translate(80, -40); rcLines(); rc.restore();
+ brush.push(); brush.translate(cx(0), cy(0)); brush.push(); brush.translate(80, -40); brushLines(BLUE); brush.pop(); brush.pop();
+
+ // Col 1 — rotate
+ rcDashes(cx(1), cy(0), CellW, CellH);
+ rc.save(); rc.translate(cx(1), cy(0)); rc.rotate(Math.PI / 5); rcLines(); rc.restore();
+ brush.push(); brush.translate(cx(1), cy(0)); brush.push(); brush.rotate(Math.PI / 5); brushLines(RED); brush.pop(); brush.pop();
+
+ // Col 2 — scale
+ rcDashes(cx(2), cy(0), CellW, CellH);
+ rc.save(); rc.translate(cx(2), cy(0)); rc.scale(1.8, 1.8); rcLines(); rc.restore();
+ brush.push(); brush.translate(cx(2), cy(0)); brush.push(); brush.scale(1.8); brushLines(OLIVE); brush.pop(); brush.pop();
+
+ // ---- ROW 1 — Fills ----
+
+ // Col 0 — translate
+ rc.save(); rc.translate(cx(0), cy(1)); rc.translate(80, -40); rcRect(BLUE); rc.restore();
+ brush.push(); brush.translate(cx(0), cy(1)); brush.push(); brush.translate(80, -40); brushFill(BLUE); brush.pop(); brush.pop();
+
+ // Col 1 — rotate
+ rc.save(); rc.translate(cx(1), cy(1)); rc.rotate(Math.PI / 5); rcRect(RED); rc.restore();
+ brush.push(); brush.translate(cx(1), cy(1)); brush.push(); brush.rotate(Math.PI / 5); brushFill(RED); brush.pop(); brush.pop();
+
+ // Col 2 — scale
+ rc.save(); rc.translate(cx(2), cy(1)); rc.scale(1.8, 1.8); rcRect(OLIVE); rc.restore();
+ brush.push(); brush.translate(cx(2), cy(1)); brush.push(); brush.scale(1.8); brushFill(OLIVE); brush.pop(); brush.pop();
+
+ brush.pop();
+ brush.render();
+ window.reportStandaloneFirstFrame?.("transform_test");
+ </script>
+ </body>
+</html>
diff --git a/test/standalone/visual_suite.html b/test/standalone/visual_suite.html
index 5bc26f4..d5f2e97 100644
--- a/test/standalone/visual_suite.html
+++ b/test/standalone/visual_suite.html
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>Visual API Suite</title>
+ <title>p5.brush Standalone Visual Suite</title>
<style>
* { box-sizing: border-box; }
@@ -29,14 +29,13 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
- .nav a {
- color: #153e5c;
- text-decoration: none;
- }
-
+ .nav a { color: #153e5c; text-decoration: none; }
.nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
h1 {
margin: 0 0 8px;
@@ -54,36 +53,38 @@
#canvas-host {
margin-top: 18px;
- position: relative;
- width: 1400px;
- height: 5200px;
- max-width: 100%;
+ display: grid;
+ justify-content: center;
+ width: 100%;
+ overflow: hidden;
}
- canvas {
- position: absolute;
- inset: 0;
+ #canvas-host canvas {
+ grid-area: 1 / 1;
display: block;
- width: 100%;
- height: 100%;
+ max-width: 100%;
+ height: auto !important;
}
- #label-canvas {
- pointer-events: none;
- }
+ #label-canvas { pointer-events: none; }
</style>
</head>
<body>
<main>
- <div class="nav"><a href="../index.html">All tests</a></div>
- <h1>Visual API Suite</h1>
+ <div class="nav">
+ <a href="../index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="../visual_suite.html">← p5 version</a>
+ </div>
+ <h1>Visual API Suite <small style="font-size:0.55em;color:#8a9aa8;">standalone</small></h1>
<p>
- Broad browser coverage page for the public API, intended for quick visual sweeps after larger rendering or state-management changes.
+ Broad standalone coverage page for the public API, intended for quick visual sweeps after rendering or state-management changes.
</p>
<p>
- The browser console still receives the error-message checks, but the canvas itself is the main verification surface.
+ The browser console receives the error-message checks; the canvas is the main verification surface.
</p>
<div id="canvas-host"></div>
+ <script src="./standalone_profiler.js"></script>
<script type="module" src="./visual_suite.js"></script>
</main>
</body>
diff --git a/test/standalone/visual_suite.js b/test/standalone/visual_suite.js
index 7782c7a..94529dc 100644
--- a/test/standalone/visual_suite.js
+++ b/test/standalone/visual_suite.js
@@ -1,72 +1,145 @@
+// ============================================================
+// p5.brush Standalone Visual Suite
+//
+// Standalone (no p5) equivalent of test/visual_suite.html.
+// ============================================================
+
import * as brush from "../../dist/brush.esm.js";
const CANVAS_W = 1400;
const CANVAS_H = 5200;
const MARGIN = 50;
const LABEL_W = 175;
-const ROW_H = 56;
+const ROW_H = 52;
const CONTENT_X = MARGIN + LABEL_W;
const CONTENT_W = CANVAS_W - MARGIN - LABEL_W - 40;
-let currentY = MARGIN;
-
const palette = ["#002185", "#c0392b", "#27ae60", "#8e44ad", "#e67e22"];
-const col = (i) => palette[i % palette.length];
+const query = new URLSearchParams(window.location.search);
+const nativeDebugStage = query.get("nativeDebug");
+
+function col(i) { return palette[i % palette.length]; }
-const pixelDensity = globalThis.devicePixelRatio || 1;
+// ---- Canvas setup ----
+const pixelDensity = window.devicePixelRatio || 1;
brush.createCanvas(CANVAS_W, CANVAS_H, {
id: "brush-canvas",
parent: "#canvas-host",
pixelDensity,
});
+// Label overlay (2D canvas stacked above brush canvas via CSS grid-area)
const labelCanvas = document.createElement("canvas");
labelCanvas.id = "label-canvas";
labelCanvas.width = Math.round(CANVAS_W * pixelDensity);
labelCanvas.height = Math.round(CANVAS_H * pixelDensity);
-labelCanvas.style.width = `${CANVAS_W}px`;
-labelCanvas.style.height = `${CANVAS_H}px`;
+labelCanvas.style.width = CANVAS_W + "px";
+labelCanvas.style.height = CANVAS_H + "px";
document.getElementById("canvas-host").appendChild(labelCanvas);
-const labelCtx = labelCanvas.getContext("2d");
-labelCtx.setTransform(pixelDensity, 0, 0, pixelDensity, 0, 0);
+
+const lc = labelCanvas.getContext("2d");
+lc.setTransform(pixelDensity, 0, 0, pixelDensity, 0, 0);
+lc.textBaseline = "top";
+
+let currentY = MARGIN;
+
+// ---- Label helpers ----
+
+function lcText(text, x, y, maxW) {
+ if (!maxW) { lc.fillText(text, x, y); return; }
+ const words = text.split(" ");
+ let line = "";
+ let dy = y;
+ const lh = 13;
+ for (const word of words) {
+ const test = line + word + " ";
+ if (lc.measureText(test).width > maxW && line) {
+ lc.fillText(line.trim(), x, dy);
+ line = word + " ";
+ dy += lh;
+ } else {
+ line = test;
+ }
+ }
+ lc.fillText(line.trim(), x, dy);
+}
function header(title) {
- labelCtx.fillStyle = "#111111";
- labelCtx.font = "700 12px Menlo, Monaco, monospace";
- labelCtx.fillText(title, MARGIN, currentY + 15);
- labelCtx.strokeStyle = "#b4b4b4";
- labelCtx.lineWidth = 0.7;
- labelCtx.beginPath();
- labelCtx.moveTo(MARGIN, currentY + 20);
- labelCtx.lineTo(CANVAS_W - MARGIN, currentY + 20);
- labelCtx.stroke();
+ lc.fillStyle = "#0f0f0f";
+ lc.font = "bold 12px monospace";
+ lc.fillText(title, MARGIN, currentY + 4);
+ lc.strokeStyle = "rgb(180,180,180)";
+ lc.lineWidth = 0.7;
+ lc.beginPath();
+ lc.moveTo(MARGIN, currentY + 20);
+ lc.lineTo(CANVAS_W - MARGIN, currentY + 20);
+ lc.stroke();
currentY += 30;
}
function rowLabel(text) {
- labelCtx.fillStyle = "#f5f5f5";
- labelCtx.fillRect(MARGIN - 2, currentY + 2, LABEL_W - 3, ROW_H - 4);
- labelCtx.fillStyle = "#464646";
- labelCtx.font = "10px Menlo, Monaco, monospace";
- labelCtx.fillText(text, MARGIN, currentY + ROW_H / 2);
+ lc.fillStyle = "rgb(245,245,245)";
+ lc.fillRect(MARGIN - 2, currentY + 2, LABEL_W - 3, ROW_H - 4);
+ lc.fillStyle = "rgb(70,70,70)";
+ lc.font = "10px monospace";
+ lcText(text, MARGIN, currentY + ROW_H / 2 - 12, LABEL_W - 8);
}
-function nextRow() {
- currentY += ROW_H;
-}
+function nextRow() { currentY += ROW_H; }
+function gap(px = 12) { currentY += px; }
+
+// ---- Error tests ----
+
+function runErrorTests() {
+ const tests = [
+ ["pick() with unknown brush name", () => brush.pick("__DOES_NOT_EXIST__")],
+ ["line() without brush/color set", () => { brush.noStroke(); brush.line(0, 0, 10, 10); }],
+ ["flowLine() without brush/color set", () => { brush.noStroke(); brush.flowLine(0, 0, 100, 0); }],
+ ["vertex() called before beginShape()", () => brush.vertex(0, 0)],
+ ["endShape() called before beginShape()", () => brush.endShape()],
+ ["move() called before beginStroke()", () => brush.move(0, 100, 1)],
+ ["endStroke() called before beginStroke()", () => brush.endStroke(0, 1)],
+ ['beginStroke() with invalid type', () => brush.beginStroke("INVALID_TYPE", 0, 0)],
+ ["spline() with fewer than 2 points", () => brush.spline([[0, 0, 1]])],
+ ["field() with unknown field name", () => brush.field("__DOES_NOT_EXIST__")],
+ ["refreshField() when no field is active", () => { brush.noField(); brush.refreshField(); }],
+ ];
-function gap(px = 12) {
- currentY += px;
+ let passed = 0;
+ console.group("%cp5.brush - Error Message Tests", "font-weight:bold;font-size:14px");
+ for (const [desc, fn] of tests) {
+ try {
+ fn();
+ console.error(`[FAIL] ${desc}\n (no error was thrown)`);
+ } catch (e) {
+ console.log(
+ `%c[PASS]%c ${desc}\n > "${e.message}"`,
+ "color:green;font-weight:bold", "color:inherit",
+ );
+ passed++;
+ }
+ }
+ const all = passed === tests.length;
+ console.log(
+ `\n%c${passed} / ${tests.length} passed`,
+ all ? "color:green;font-weight:bold;font-size:13px" : "color:red;font-weight:bold;font-size:13px",
+ );
+ console.groupEnd();
+ return { passed, total: tests.length };
}
-async function main() {
- brush.scaleBrushes(5);
- brush.angleMode(brush.DEGREES);
+// ================================================================
+// MAIN
+// ================================================================
+
+(async () => {
brush.seed(42);
brush.noiseSeed(42);
- brush.clear("#ffffff");
+ brush.scaleBrushes(5);
+ brush.angleMode(brush.DEGREES);
+ // Image brush (async) — must be awaited before drawing starts
await brush.add("imageTip", {
type: "image",
weight: 40,
@@ -78,6 +151,7 @@ async function main() {
image: { src: "../../example/brush_tips/brush.jpg" },
});
+ // Custom tip brush
brush.add("diamondTip", {
type: "custom",
weight: 0.6,
@@ -88,42 +162,94 @@ async function main() {
spacing: 0.8,
pressure: [1, 1],
rotate: "natural",
- tip: (m) => {
- m.rotate(45);
- m.rect(-4, -4, 8, 8);
- m.rect(1, 1, 2, 2);
+ tip: (_m) => {
+ _m.rotate(45);
+ _m.rect(-4, -4, 8, 8);
+ _m.rect(1, 1, 2, 2);
},
});
+ // Error tests (before drawing state changes)
+ brush.set("HB", "#000000", 1);
+ const { passed, total } = runErrorTests();
+ brush.set("HB", "#000000", 1);
+
+ // Clear and set up transform now — after all awaits so the WebGL buffer
+ // isn't discarded by the browser between the clear and brush.render().
+ brush.clear("#f5f5f5");
brush.push();
brush.translate(-CANVAS_W / 2, -CANVAS_H / 2);
+ if (passed !== total) {
+ lc.fillStyle = "#b03030";
+ lc.font = "10px monospace";
+ lc.fillText(`Error tests: ${passed}/${total} passed. See browser console.`, MARGIN, currentY + 2);
+ currentY += 20;
+ gap(6);
+ }
+
+ // ================================================================
+ // SECTION 1 — STANDARD BRUSHES
+ // ================================================================
header("STANDARD BRUSHES");
+
const customNames = new Set(["imageTip", "diamondTip", "_pt"]);
- for (const name of brush.box().filter((n) => !customNames.has(n))) {
- brush.set(name, col(brush.box().indexOf(name)), 1);
- rowLabel(name);
+ for (const b of brush.box().filter((n) => !customNames.has(n))) {
+ brush.set(b, col(brush.box().indexOf(b)), 1);
+ rowLabel(b);
brush.flowLine(CONTENT_X, currentY + ROW_H / 2, CONTENT_W, 0);
nextRow();
}
gap();
+ // ================================================================
+ // SECTION 2 — PRESSURE CURVES
+ // ================================================================
+ header("PRESSURE CURVES (type: default, brush: pen weight)");
+
+ const pressureCases = [
+ { label: "[2, 0.3] heavy -> thin", p: [2, 0.3] },
+ { label: "[0.3, 2] thin -> heavy", p: [0.3, 2] },
+ { label: "[1.5, 0.3, 1.5] U-curve", p: [1.5, 0.3, 1.5] },
+ { label: "[0.3, 1.5, 0.3] hill", p: [0.3, 1.5, 0.3] },
+ { label: "[1, 1] flat", p: [1, 1] },
+ ];
+ for (const { label, p } of pressureCases) {
+ brush.add("_pt", {
+ type: "default", weight: 0.3, scatter: 3, sharpness: 0.3,
+ grain: 8, opacity: 140, spacing: 0.1, pressure: p,
+ });
+ brush.set("_pt", "#1a1a1a", 1);
+ rowLabel(label);
+ brush.flowLine(CONTENT_X, currentY + ROW_H / 2, CONTENT_W, 0);
+ nextRow();
+ }
+ gap();
+
+ // ================================================================
+ // SECTION 3 — BRUSH TYPES
+ // ================================================================
header("BRUSH TYPES");
+
const typeTests = [
- { label: "custom tip (diamondTip)", name: "diamondTip", color: col(0) },
- { label: "image tip (imageTip)", name: "imageTip", color: col(1) },
- { label: "marker", name: "marker", color: col(2) },
- { label: "spray", name: "spray", color: col(3) },
+ { label: "custom tip (diamondTip)", name: "diamondTip", color: col(0) },
+ { label: "image tip (imageTip)", name: "imageTip", color: col(0) },
+ { label: "marker", name: "marker", color: col(1) },
+ { label: "spray", name: "spray", color: col(2) },
];
- for (const test of typeTests) {
- brush.set(test.name, test.color, 1);
- rowLabel(test.label);
+ for (const t of typeTests) {
+ brush.set(t.name, t.color, 1);
+ rowLabel(t.label);
brush.flowLine(CONTENT_X, currentY + ROW_H / 2, CONTENT_W, 0);
nextRow();
}
gap();
- header("FLOW FIELDS");
+ // ================================================================
+ // SECTION 4 — FLOW FIELDS
+ // ================================================================
+ header("FLOW FIELDS (hatching reveals distortion per field)");
+
const FIELD_GAP = 20;
const FIELD_CELL_W = Math.floor((CONTENT_W - FIELD_GAP) / 2);
const FIELD_CELL_H = 140;
@@ -135,32 +261,37 @@ async function main() {
const name = allFields[fi + side];
const cellX = CONTENT_X + side * (FIELD_CELL_W + FIELD_GAP);
const cellY = currentY;
- const lineColor = col(fi + side);
if (name === "hand") {
brush.wiggle(5);
} else {
brush.field(name);
}
- brush.set("HB", lineColor, 1);
+ brush.set("HB", col(fi + side), 1);
for (let li = 0; li < FIELD_LINES; li++) {
const ly = cellY + 22 + (li / (FIELD_LINES - 1)) * (FIELD_CELL_H - 32);
brush.flowLine(cellX, ly, FIELD_CELL_W, 0);
}
- labelCtx.fillStyle = "#f5f5f5";
- labelCtx.fillRect(cellX, cellY, 140, 18);
- labelCtx.fillStyle = "#1e1e1e";
- labelCtx.font = "700 10px Menlo, Monaco, monospace";
- labelCtx.fillText(name === "hand" ? "hand [wiggle(5)]" : name, cellX + 4, cellY + 13);
+ lc.fillStyle = "rgb(245,245,245)";
+ lc.fillRect(cellX, cellY, 130, 18);
+ lc.fillStyle = "rgb(30,30,30)";
+ lc.font = "bold 10px monospace";
+ lc.fillText(name === "hand" ? "hand [wiggle(5)]" : name, cellX + 4, cellY + 4);
}
currentY += FIELD_CELL_H + 8;
}
brush.noField();
gap();
+ // ================================================================
+ // SECTION 5 — PRIMITIVES
+ // ================================================================
header("PRIMITIVES");
+
+ const toRad = (d) => (d * Math.PI) / 180;
+
brush.set("pen", col(0), 1);
rowLabel("line()");
brush.line(CONTENT_X, currentY + ROW_H / 2, CONTENT_X + 500, currentY + ROW_H / 2);
@@ -188,31 +319,36 @@ async function main() {
brush.set("2B", col(0), 1);
rowLabel("spline()");
- brush.spline([
- [CONTENT_X, currentY + ROW_H - 10, 1],
- [CONTENT_X + 110, currentY + 10, 1],
- [CONTENT_X + 220, currentY + ROW_H - 10, 1],
- [CONTENT_X + 330, currentY + 10, 1],
- [CONTENT_X + 440, currentY + ROW_H - 10, 1],
- ], 0.5);
+ brush.spline(
+ [
+ [CONTENT_X, currentY + ROW_H - 10, 1],
+ [CONTENT_X + 110, currentY + 10, 1],
+ [CONTENT_X + 220, currentY + ROW_H - 10, 1],
+ [CONTENT_X + 330, currentY + 10, 1],
+ [CONTENT_X + 440, currentY + ROW_H - 10, 1],
+ ],
+ 0.5,
+ );
nextRow();
brush.set("pen", col(2), 1);
rowLabel("polygon()");
- const px = CONTENT_X + 70;
- const py = currentY + ROW_H / 2;
- const pr = 22;
+ const px = CONTENT_X + 70, py = currentY + ROW_H / 2, pr = 22;
brush.polygon([
- [px + pr * Math.cos(0), py + pr * Math.sin(0), 1],
- [px + pr * Math.cos((72 * Math.PI) / 180), py + pr * Math.sin((72 * Math.PI) / 180), 1],
- [px + pr * Math.cos((144 * Math.PI) / 180), py + pr * Math.sin((144 * Math.PI) / 180), 1],
- [px + pr * Math.cos((216 * Math.PI) / 180), py + pr * Math.sin((216 * Math.PI) / 180), 1],
- [px + pr * Math.cos((288 * Math.PI) / 180), py + pr * Math.sin((288 * Math.PI) / 180), 1],
+ [px + pr * Math.cos(toRad(0)), py + pr * Math.sin(toRad(0)), 1],
+ [px + pr * Math.cos(toRad(72)), py + pr * Math.sin(toRad(72)), 1],
+ [px + pr * Math.cos(toRad(144)), py + pr * Math.sin(toRad(144)), 1],
+ [px + pr * Math.cos(toRad(216)), py + pr * Math.sin(toRad(216)), 1],
+ [px + pr * Math.cos(toRad(288)), py + pr * Math.sin(toRad(288)), 1],
]);
nextRow();
gap();
+ // ================================================================
+ // SECTION 6 — beginShape / vertex / endShape
+ // ================================================================
header("beginShape / vertex / endShape");
+
brush.set("2B", col(0), 1);
rowLabel("open shape (curvature 0.5)");
brush.beginShape(0.5);
@@ -225,8 +361,8 @@ async function main() {
brush.set("HB", col(1), 1);
rowLabel("closed shape (curvature 0.3)");
brush.beginShape(0.3);
- brush.vertex(CONTENT_X + 40, currentY + ROW_H - 8);
- brush.vertex(CONTENT_X + 90, currentY + 8);
+ brush.vertex(CONTENT_X + 40, currentY + ROW_H - 8);
+ brush.vertex(CONTENT_X + 90, currentY + 8);
brush.vertex(CONTENT_X + 140, currentY + ROW_H - 8);
brush.vertex(CONTENT_X + 190, currentY + 8);
brush.vertex(CONTENT_X + 240, currentY + ROW_H - 8);
@@ -234,7 +370,11 @@ async function main() {
nextRow();
gap();
+ // ================================================================
+ // SECTION 7 — beginStroke / move / endStroke
+ // ================================================================
header("beginStroke / move / endStroke");
+
brush.set("cpencil", col(0), 1);
rowLabel('type: "curve"');
brush.beginStroke("curve", CONTENT_X, currentY + ROW_H / 2);
@@ -249,62 +389,117 @@ async function main() {
brush.set("pen", col(3), 1);
rowLabel('type: "segments"');
brush.beginStroke("segments", CONTENT_X, currentY + ROW_H / 2);
- brush.move(20, 90, 1.0);
+ brush.move(20, 90, 1.0);
brush.move(-20, 90, 1.5);
- brush.move(35, 90, 0.7);
+ brush.move(35, 90, 0.7);
brush.move(-35, 90, 1.2);
- brush.move(0, 90, 1.0);
+ brush.move(0, 90, 1.0);
brush.endStroke(0, 1);
nextRow();
gap();
- header("HATCH / WASH / MASS");
- brush.hatch(9, 45);
- brush.hatchStyle("HB", col(0), 1);
- rowLabel("hatch");
- new brush.Polygon([
- [CONTENT_X, currentY + 5],
- [CONTENT_X + 260, currentY + 5],
- [CONTENT_X + 260, currentY + ROW_H - 6],
- [CONTENT_X, currentY + ROW_H - 6],
- ]).hatch();
- brush.noHatch();
- nextRow();
+ // ================================================================
+ // SECTION 8 — HATCH
+ // ================================================================
+ header("HATCH");
- brush.wash("#fffceb", 255);
- rowLabel("wash");
- brush.rect(CONTENT_X, currentY + 6, 260, ROW_H - 14);
- brush.noWash();
- nextRow();
+ const hatchTests = [
+ { label: "45deg basic", angle: 45, dist: 9, opts: {} },
+ { label: "0deg horizontal", angle: 0, dist: 9, opts: {} },
+ { label: "rand + continuous", angle: 30, dist: 8, opts: { rand: 0.2, continuous: true } },
+ { label: "gradient (0.6)", angle: 60, dist: 6, opts: { gradient: 0.6 } },
+ ];
- brush.mass("pastel", col(2), { precision: 0.5, strength: 0.7, outline: true });
- rowLabel("mass");
- brush.rect(CONTENT_X, currentY + 6, 260, ROW_H - 14);
- brush.noMass();
- nextRow();
+ for (let hi = 0; hi < hatchTests.length; hi++) {
+ const h = hatchTests[hi];
+ brush.hatch(h.dist, h.angle, h.opts);
+ brush.hatchStyle("HB", col(hi), 1);
+ rowLabel(h.label);
+ const hp = new brush.Polygon([
+ [CONTENT_X, currentY + 5],
+ [CONTENT_X + 260, currentY + 5],
+ [CONTENT_X + 260, currentY + ROW_H - 6],
+ [CONTENT_X, currentY + ROW_H - 6],
+ ]);
+ hp.hatch();
+ brush.noHatch();
+ nextRow();
+ }
gap();
- header("FILL");
- brush.noStroke();
- brush.fill(col(4), 90);
- brush.fillBleed(0.1, "out");
- brush.fillTexture(0.4, 0.4);
- rowLabel("rect + polygon");
- brush.rect(CONTENT_X, currentY + 10, 220, 90);
- const cx = CONTENT_X + 330;
- const cy = currentY + 56;
- const n = 24;
- const r = 45;
- const pts = Array.from({ length: n }, (_, i) => {
- const a = (i / n) * Math.PI * 2;
- return [cx + r * Math.cos(a), cy + r * Math.sin(a)];
- });
- brush.polygon(pts);
- brush.noFill();
- currentY += 115;
+ // ================================================================
+ // SECTION 9 — FILL (watercolor)
+ // ================================================================
+ header("FILL (watercolor) rect + polygon per row");
+
+ const FILL_ROW_H = 115;
+ const FRECT_W = 230, FRECT_H = 90;
+ const FCIRC_R = 45;
+ const FCIRC_X = CONTENT_X + FRECT_W + 70 + FCIRC_R;
+
+ function fillSubHeader(text) {
+ lc.fillStyle = "rgb(120,120,120)";
+ lc.font = "italic 9px monospace";
+ lc.fillText(text, MARGIN, currentY + 4);
+ currentY += 18;
+ }
+
+ function fillRow(label, color, opacity, bleed, dir, texture, border) {
+ brush.noStroke();
+ brush.fill(color, opacity);
+ brush.fillBleed(bleed, dir);
+ brush.fillTexture(texture, border);
+
+ lc.fillStyle = "rgb(245,245,245)";
+ lc.fillRect(MARGIN - 2, currentY + 2, LABEL_W - 3, FILL_ROW_H - 4);
+ lc.fillStyle = "rgb(70,70,70)";
+ lc.font = "10px monospace";
+ lcText(label, MARGIN, currentY + FILL_ROW_H / 2 - 12, LABEL_W - 8);
+
+ const ry = currentY + (FILL_ROW_H - FRECT_H) / 2;
+ brush.rect(CONTENT_X, ry, FRECT_W, FRECT_H);
+
+ const cx = FCIRC_X, cy = currentY + FILL_ROW_H / 2;
+ const n = 24;
+ const pts = Array.from({ length: n }, (_, i) => {
+ const a = (i / n) * Math.PI * 2;
+ return [cx + FCIRC_R * Math.cos(a), cy + FCIRC_R * Math.sin(a)];
+ });
+ brush.polygon(pts);
+ brush.noFill();
+ currentY += FILL_ROW_H;
+ }
+
+ fillSubHeader("bleed strength (texture 0.4, border 0.4, opacity 60)");
+ fillRow("bleed 0.03 out", col(0), 60, 0.03, "out", 0.4, 0.4);
+ fillRow("bleed 0.1 out", col(0), 60, 0.1, "out", 0.4, 0.4);
+ fillRow("bleed 0.25 out", col(0), 60, 0.25, "out", 0.4, 0.4);
+ fillRow("bleed 0.5 out", col(0), 60, 0.5, "out", 0.4, 0.4);
+
+ fillSubHeader("bleed direction (bleed 0.2, texture 0.4, border 0.4, opacity 60)");
+ fillRow("direction: out", col(1), 60, 0.2, "out", 0.4, 0.4);
+ fillRow("direction: in", col(1), 60, 0.2, "in", 0.4, 0.4);
+
+ fillSubHeader("texture strength (bleed 0.1, border 0.4, opacity 60)");
+ fillRow("texture 0.05", col(2), 60, 0.1, "out", 0.05, 0.4);
+ fillRow("texture 0.3", col(2), 60, 0.1, "out", 0.3, 0.4);
+ fillRow("texture 0.7", col(2), 60, 0.1, "out", 0.7, 0.4);
+ fillRow("texture 1.0", col(2), 60, 0.1, "out", 1.0, 0.4);
+
+ fillSubHeader("border strength (bleed 0.1, texture 0.4, opacity 60)");
+ fillRow("border 0.05", col(3), 60, 0.1, "out", 0.4, 0.05);
+ fillRow("border 0.3", col(3), 60, 0.1, "out", 0.4, 0.3);
+ fillRow("border 0.7", col(3), 60, 0.1, "out", 0.4, 0.7);
+ fillRow("border 1.0", col(3), 60, 0.1, "out", 0.4, 1.0);
+
+ fillSubHeader("opacity (bleed 0.1, texture 0.4, border 0.4)");
+ fillRow("opacity 20", col(4), 20, 0.1, "out", 0.4, 0.4);
+ fillRow("opacity 50", col(4), 50, 0.1, "out", 0.4, 0.4);
+ fillRow("opacity 90", col(4), 90, 0.1, "out", 0.4, 0.4);
+ fillRow("opacity 140", col(4), 140, 0.1, "out", 0.4, 0.4);
brush.pop();
brush.render();
-}
-
-main();
+ window.reportStandaloneFirstFrame?.("visual_suite");
+ console.log("Standalone visual suite complete");
+})();
diff --git a/test/standalone/wash.html b/test/standalone/wash.html
deleted file mode 100644
index 220199b..0000000
--- a/test/standalone/wash.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>brush.js Standalone Wash Test</title>
- <style>
- body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f6f0e4; font-family: "Iowan Old Style", Palatino, serif; }
- main { width: min(760px, calc(100vw - 32px)); display: grid; gap: 14px; justify-items: center; }
- h1, p { margin: 0; text-align: center; }
- p { max-width: 620px; line-height: 1.45; }
- canvas { width: 600px; height: 600px; border: 1px solid rgba(31,44,51,.16); background: white; }
- code { font-family: Menlo, Monaco, "Courier New", monospace; font-size: 12px; }
- </style>
- </head>
- <body>
- <main>
- <h1>Standalone Wash Test</h1>
- <p>Minimal standalone wash check using one translucent polygon wash over a paper-colored background.</p>
- <div id="canvas-host"></div>
- </main>
- <script type="module" src="./wash.js"></script>
- </body>
- </html>
diff --git a/test/standalone/wash.js b/test/standalone/wash.js
deleted file mode 100644
index 47b4d82..0000000
--- a/test/standalone/wash.js
+++ /dev/null
@@ -1,18 +0,0 @@
-import * as brush from "../../dist/brush.esm.js";
-
-brush.createCanvas(600, 600, {
- id: "brush-canvas",
- parent: "#canvas-host",
- pixelDensity: globalThis.devicePixelRatio || 1,
-});
-brush.clear("#fffceb");
-brush.angleMode(brush.DEGREES);
-brush.wash("#3f76b5", 230);
-brush.push();
-brush.rotate(-8);
-brush.rect(0, 0, 240, 170, "center");
-brush.pop();
-brush.noWash();
-brush.render();
-
-console.log("standalone wash test executed");
diff --git a/test/standalone/wash_test.html b/test/standalone/wash_test.html
new file mode 100644
index 0000000..655885d
--- /dev/null
+++ b/test/standalone/wash_test.html
@@ -0,0 +1,212 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Wash Test — Standalone</title>
+ <style>
+ :root {
+ --paper: #f3eee2;
+ --ink: #22313f;
+ --muted: #52616e;
+ --line: #d4c8b8;
+ --panel: rgba(255, 252, 245, 0.86);
+ --accent: #153e5c;
+ }
+
+ * { box-sizing: border-box; }
+
+ body {
+ margin: 0;
+ color: var(--ink);
+ background:
+ radial-gradient(circle at top left, rgba(21, 62, 92, 0.08), transparent 24%),
+ linear-gradient(180deg, #f7f2e7 0%, #ece3d3 100%);
+ font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, serif;
+ }
+
+ main {
+ width: min(920px, calc(100vw - 24px));
+ margin: 0 auto;
+ padding: 18px 0 24px;
+ display: grid;
+ justify-items: center;
+ }
+
+ main > * { width: 100%; }
+
+ .nav {
+ margin-bottom: 14px;
+ font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
+ }
+
+ .nav a { color: var(--accent); text-decoration: none; }
+ .nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
+
+ h1 {
+ margin: 0 0 8px;
+ font-size: clamp(24px, 3.6vw, 34px);
+ letter-spacing: -0.04em;
+ }
+
+ p {
+ margin: 0 0 8px;
+ max-width: 760px;
+ color: var(--muted);
+ line-height: 1.45;
+ font-size: 13px;
+ }
+
+ .panel {
+ border: 1px solid var(--line);
+ border-radius: 8px;
+ background: var(--panel);
+ }
+
+ .toolbar {
+ margin-top: 18px;
+ padding: 12px 14px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+ font: 11px/1.4 Menlo, Monaco, "Courier New", monospace;
+ }
+
+ .seed { display: flex; align-items: center; gap: 8px; }
+ .seed strong { color: var(--accent); font-weight: 600; }
+
+ button {
+ border: 1px solid var(--line);
+ background: #fbf8f0;
+ color: var(--accent);
+ font: inherit;
+ padding: 6px 10px;
+ border-radius: 6px;
+ cursor: pointer;
+ }
+
+ button:hover { background: #f4eee2; }
+
+ #canvas-host {
+ margin-top: 16px;
+ padding: 10px;
+ display: grid;
+ justify-content: center;
+ width: 100%;
+ overflow: hidden;
+ }
+
+ #canvas-host canvas {
+ display: block;
+ border-radius: 6px;
+ max-width: 100%;
+ max-height: min(78vh, 760px);
+ height: auto !important;
+ }
+ </style>
+ </head>
+ <body>
+ <main>
+ <div class="nav">
+ <a href="../index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="../wash_test.html">← p5 version</a>
+ </div>
+ <h1>Wash Test <small style="font-size:0.55em;color:#8a9aa8;">standalone</small></h1>
+ <p>
+ Direct WebGL wash test that draws random rect and circle polygons with palette colors at full opacity.
+ </p>
+ <p>
+ Refresh the seed to regenerate shapes while keeping the wash path isolated from fill and stroke.
+ </p>
+
+ <div class="toolbar panel">
+ <div class="seed">
+ <span>Seed</span>
+ <strong id="seedVal">000000</strong>
+ </div>
+ <button id="refreshSeed" type="button">Refresh seed</button>
+ </div>
+
+ <div id="canvas-host" class="panel"></div>
+ </main>
+
+ <script src="./standalone_profiler.js"></script>
+ <script type="module">
+ import * as brush from "../../dist/brush.esm.js";
+
+ const PALETTE = ["#002185", "#003c32", "#fcd300", "#ff2702", "#6b9404"];
+ const PAPER = "#fffceb";
+ const CW = 840, CH = 720;
+
+ let currentSeed = 100000 + Math.floor(Math.random() * 900000);
+
+ const seedVal = document.getElementById("seedVal");
+ const refreshSeedBtn = document.getElementById("refreshSeed");
+
+ const pixelDensity = window.devicePixelRatio || 1;
+ brush.createCanvas(CW, CH, { id: "brush-canvas", parent: "#canvas-host", pixelDensity });
+ brush.scaleBrushes(3);
+
+ // Seeded RNG (simple mulberry32)
+ function mkRng(seed) {
+ let s = seed;
+ return () => {
+ s |= 0; s = s + 0x6D2B79F5 | 0;
+ let t = Math.imul(s ^ s >>> 15, 1 | s);
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
+ };
+ }
+
+ function drawScene() {
+ seedVal.textContent = String(currentSeed).padStart(6, "0");
+ brush.seed(currentSeed);
+ brush.noiseSeed(currentSeed);
+
+ brush.clear(PAPER);
+ brush.push();
+ brush.translate(-CW / 2, -CH / 2);
+
+ const rng = mkRng(currentSeed);
+ brush.wiggle(3);
+
+ for (let i = 0; i < 50; i++) {
+ const color = PALETTE[i % PALETTE.length];
+ brush.wash(color, 255);
+
+ const isCircle = rng() < 0.5;
+ if (isCircle) {
+ const radius = 100 + rng() * 100;
+ const cx = radius + 24 + rng() * (CW - 2 * (radius + 24));
+ const cy = radius + 24 + rng() * (CH - 2 * (radius + 24));
+ brush.circle(cx, cy, radius);
+ } else {
+ const rw = 190 + rng() * 60;
+ const rh = 190 + rng() * 60;
+ const rx = 24 + rng() * (CW - rw - 24);
+ const ry = 24 + rng() * (CH - rh - 24);
+ brush.rect(rx, ry, rw, rh);
+ }
+ }
+
+ brush.noWash();
+ brush.pop();
+ brush.render();
+ window.reportStandaloneFirstFrame?.("wash_test");
+ }
+
+ refreshSeedBtn.addEventListener("click", () => {
+ currentSeed = 100000 + Math.floor(Math.random() * 900000);
+ drawScene();
+ });
+
+ drawScene();
+ </script>
+ </body>
+</html>
diff --git a/test/transform_test.html b/test/transform_test.html
index 0178a63..6064c00 100644
--- a/test/transform_test.html
+++ b/test/transform_test.html
@@ -32,10 +32,13 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a { color: #153e5c; text-decoration: none; }
.nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
h1 {
margin: 0 0 8px;
@@ -68,7 +71,11 @@
</head>
<body>
<main>
- <div class="nav"><a href="./index.html">All tests</a></div>
+ <div class="nav">
+ <a href="./index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="./standalone/transform_test.html">Standalone →</a>
+ </div>
<h1>Transform Alignment Test</h1>
<p>
Red native p5 references are drawn at the exact same coordinates as p5.brush marks, so they should align precisely.
diff --git a/test/visual_suite.html b/test/visual_suite.html
index 184a6c4..4c21444 100644
--- a/test/visual_suite.html
+++ b/test/visual_suite.html
@@ -32,6 +32,8 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a {
@@ -40,6 +42,7 @@
}
.nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
h1 {
margin: 0 0 8px;
@@ -72,7 +75,11 @@
</head>
<body>
<main>
- <div class="nav"><a href="./index.html">All tests</a></div>
+ <div class="nav">
+ <a href="./index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="./standalone/visual_suite.html">Standalone →</a>
+ </div>
<h1>Visual API Suite</h1>
<p>
Broad browser coverage page for the public API, intended for quick visual sweeps after larger rendering or state-management changes.
diff --git a/test/wash_test.html b/test/wash_test.html
index 7204a4a..2ccb50f 100644
--- a/test/wash_test.html
+++ b/test/wash_test.html
@@ -41,6 +41,8 @@
.nav {
margin-bottom: 14px;
font: 11px/1.2 Menlo, Monaco, "Courier New", monospace;
+ display: flex;
+ gap: 12px;
}
.nav a {
@@ -49,6 +51,7 @@
}
.nav a:hover { text-decoration: underline; }
+ .nav .sep { color: #8a9aa8; }
h1 {
margin: 0 0 8px;
@@ -124,7 +127,11 @@
</head>
<body>
<main>
- <div class="nav"><a href="./index.html">All tests</a></div>
+ <div class="nav">
+ <a href="./index.html">All tests</a>
+ <span class="sep">·</span>
+ <a href="./standalone/wash_test.html">Standalone →</a>
+ </div>
<h1>Wash Test</h1>
<p>
Direct WEBGL wash test that draws five random rect and circle polygons with palette colors at full opacity.