@mathzetta/qblur 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- /* qblur 0.2.0 (MathZetta not included: load mathzetta.min.js or mathzetta.glsl.min.js first) — Copyright (c) 2025-2026 Robert Wilcox — MIT license — https://qblur.com */
2
- var QBlur=function(e,t,r,n){"use strict";var o="undefined"!=typeof document?document.currentScript:null;const a=["round","soft","marker","chalk","spray"],s=["recorded","even","per-stroke"],i=["pressure","speed","none"],l=["none","inside","outside"],c={type:"strokes",strokes:[],brush:"round",size:.03,flow:1,spacing:.2,taper:0,buildUp:!1,widthFrom:"pressure",timing:"recorded",speed:1,gap:6,start:0,fit:0,age:30,clip:"none",shadows:[]};function h(e,t){throw new Error(`Graphic "${e}": ${t}`)}function u(e,t,r,n,o){const a=Number(r);return(!Number.isFinite(a)||a<n||a>o)&&h(e,`"${t}" is a number from ${n} to ${o}`),a}function p(e,t){for(const r of Object.keys(t))r in c||h(e,`no such setting "${r}" for strokes`);const r={...c,...t},n=(t,n)=>(n.includes(r[t])||h(e,`"${t}" is ${n.join(", ")} — not "${r[t]}"`),r[t]),o={type:"strokes",brush:n("brush",a),widthFrom:n("widthFrom",i),timing:n("timing",s),clip:n("clip",l),size:u(e,"size",r.size,.001,.5),flow:u(e,"flow",r.flow,.01,1),spacing:u(e,"spacing",r.spacing,.02,2),taper:u(e,"taper",r.taper,0,.5),speed:u(e,"speed",r.speed,.05,20),gap:u(e,"gap",r.gap,0,600),start:u(e,"start",r.start,0,1e4),fit:u(e,"fit",r.fit,0,1e4),age:u(e,"age",r.age,1,1e4),buildUp:Boolean(r.buildUp),shadows:[]};Array.isArray(r.strokes)||h(e,'"strokes" is a list of { "points": [[x, y, ms, pressure], …] }');let p=0;return o.strokes=r.strokes.map((t,r)=>{const n=Array.isArray(t)?t:t?.points;return Array.isArray(n)||h(e,`stroke ${r+1} is { "points": [[x, y, ms, pressure], …] }`),p+=n.length,p>6e4&&h(e,"a drawing has at most 60000 points"),{points:n.map((t,n)=>((!Array.isArray(t)||t.length<2||!t.every(e=>Number.isFinite(Number(e))))&&h(e,`stroke ${r+1}, point ${n+1} is [x, y, ms, pressure]`),[+Number(t[0]).toFixed(4),+Number(t[1]).toFixed(4),Math.round(Number(t[2]??16*n)),+Math.min(1,Math.max(0,Number(t[3]??1))).toFixed(2)]))}}),o}function f(e,t=1){const r=[];let n=e.start;const o=30/e.speed,a=20/e.speed;for(const s of e.strokes){const i=s.points;if(!i.length)continue;const l=[0];for(let e=1;e<i.length;e++)l.push(l[e-1]+Math.hypot((i[e][0]-i[e-1][0])*t,i[e][1]-i[e-1][1]));const c=l[l.length-1]||1e-9,h=i[0][2],u=i.map((t,r)=>{let n;n="recorded"===e.timing?(t[2]-h)/1e3*30/e.speed:"even"===e.timing?l[r]*o:l[r]/c*a;let s=1;if("pressure"===e.widthFrom)s=.3+.7*t[3];else if("speed"===e.widthFrom&&r>0){const e=Math.max(1,t[2]-i[r-1][2]),n=(l[r]-l[r-1])/e*1e3;s=Math.min(1.3,Math.max(.35,1.3-.6*n))}return e.taper>0&&(s*=Math.max(.15,Math.min(1,l[r]/c/e.taper,(1-l[r]/c)/e.taper))),{x:t[0],y:t[1],f:n,wf:s}});"speed"===e.widthFrom&&u.length>1&&(u[0].wf=u[1].wf);const p=u[u.length-1].f;for(const e of u)e.f+=n;r.push({points:u,start:n,end:n+p}),n+=p+e.gap}let s=r.length?r[r.length-1].end:e.start;if(e.fit>0&&s>e.start){const t=e.fit/(s-e.start);for(const n of r){for(const r of n.points)r.f=e.start+(r.f-e.start)*t;n.start=e.start+(n.start-e.start)*t,n.end=e.start+(n.end-e.start)*t}s=e.start+e.fit}return{strokes:r,total:s}}function m(e,t){let r=Math.imul(0|e,374761393)+Math.imul(0|t,668265263)|0;return r=Math.imul(r^r>>>13,1274126177),((r^r>>>16)>>>0)/4294967296}const d=new Map;function g(e,t,r,n=1/0,{mask:o=null}={}){const a=t*r,{alpha:s,passes:i,latest:l,cov:c,when:h,touched:u}=function(e){let t=d.get(e);return t||(t={alpha:new Float32Array(e),passes:new Float32Array(e),latest:new Float32Array(e),cov:new Float32Array(e),when:new Float32Array(e),touched:new Int32Array(e)},d.clear(),d.set(e,t)),t.alpha.fill(0),t.passes.fill(0),t.latest.fill(-1),t}(a),{strokes:p,total:g}=f(e,t/r),w=Number.isFinite(n)?n:g,y=Math.max(.5,e.size*r/2);let $=0,b=256*Math.max(a,65536);p.forEach(n=>{if(n.start>w||b<=0)return;let o=0;const a=(t,r,n,o)=>{const a=$++;if("spray"===e.brush){const e=Math.max(3,Math.round(.6*n)),s=Math.max(.6,.07*n);for(let i=0;i<e;i++){const e=m(a,2*i)*Math.PI*2,l=Math.sqrt(m(a,2*i+1))*n;p(t+Math.cos(e)*l,r+Math.sin(e)*l,s,o,"round")}}else p(t,r,n,o,e.brush)},p=(n,a,s,i,l)=>{const p="marker"===l?s:s+1,f=Math.max(0,Math.floor(n-p)),d=Math.min(t-1,Math.ceil(n+p)),g=Math.max(0,Math.floor(a-p)),w=Math.min(r-1,Math.ceil(a+p));b-=d>=f&&w>=g?(d-f+1)*(w-g+1):16;for(let r=g;r<=w;r++)for(let p=f;p<=d;p++){const f=p+.5-n,d=r+.5-a;let g;if("soft"===l){const e=Math.hypot(f,d)/s;if(e>=1)continue;const t=1-e;g=t*t*(3-2*t)}else if("marker"===l){const e=(f+d)*Math.SQRT1_2,t=(d-f)*Math.SQRT1_2,r=Math.hypot(e/s,t/(.33*s));g=Math.min(1,Math.max(0,(1-r)*s*.33+.5))}else g=Math.min(1,Math.max(0,s-Math.hypot(f,d)+.5)),"chalk"===l&&(g*=m(p,7919*r)>.42?1:.12);if(g<=0)continue;g*=e.flow;const w=r*t+p;g>c[w]&&(0===c[w]&&(u[o++]=w),c[w]=g),g>.02&&(h[w]=i)}},f=n.points;let d=0;const g=e=>[e.x*t,e.y*r];if(1===f.length||f.every(e=>e.x===f[0].x&&e.y===f[0].y)){const[e,t]=g(f[0]);a(e,t,y*f[0].wf,f[0].f)}for(let t=1;t<f.length;t++){const r=f[t-1],n=f[t];if(r.f>w)break;const[o,s]=g(r),[i,l]=g(n);let c=1;n.f>w&&(c=(w-r.f)/Math.max(1e-9,n.f-r.f));const h=Math.hypot(i-o,l-s);let u=1===t?0:d;for(;u<=h*c&&b>0;){const t=h?u/h:0,c=y*(r.wf+(n.wf-r.wf)*t);a(o+(i-o)*t,s+(l-s)*t,c,r.f+(n.f-r.f)*t),u+=Math.max(.5,2*e.spacing*c)}if(d=u-h,c<1||b<=0)break}for(let t=0;t<o;t++){const r=u[t],n=c[r];s[r]=e.buildUp?1-(1-s[r])*(1-n):Math.max(s[r],n),i[r]+=n,n>.02&&h[r]>l[r]&&(l[r]=h[r]),c[r]=0}});const x=new Uint8ClampedArray(4*a),E="inside"===e.clip,v="outside"===e.clip;for(let t=0;t<a;t++){let r=s[t];if(0===r)continue;let n=1;o&&(E||v)&&(n=E?o[t]:1-o[t]),r*=n;const a=4*t;x[a]=Math.round(255*Math.min(1,Math.max(0,(w-l[t])/e.age))),x[a+1]=Math.round(255*Math.min(1,i[t]*n/4)),x[a+2]=Math.round(255*Math.min(1,Math.max(0,l[t]/Math.max(1e-9,g)))),x[a+3]=Math.round(255*r)}return{data:x,width:t,height:r,total:g}}function w(e,t){if(e.length<4)return[...e,e[0]];const[r,n]=e[0];let o=0;return e.forEach(([t,a],s)=>{Math.hypot(t-r,a-n)>Math.hypot(e[o][0]-r,e[o][1]-n)&&(o=s)}),[...y(e.slice(0,o+1),t),...y([...e.slice(o),e[0]],t).slice(1)]}function y(e,t){if(e.length<3)return e;const r=new Uint8Array(e.length);r[0]=r[e.length-1]=1;const n=[[0,e.length-1]];for(;n.length;){const[o,a]=n.pop(),[s,i]=e[o],[l,c]=e[a],h=Math.hypot(l-s,c-i)||1e-9;let u=-1,p=-1;for(let t=o+1;t<a;t++){const r=Math.abs((l-s)*(i-e[t][1])-(s-e[t][0])*(c-i))/h;r>u&&(u=r,p=t)}u>t&&(r[p]=1,n.push([o,p],[p,a]))}return e.filter((e,t)=>r[t])}const $=["text","rect","ellipse","strokes"],b={text:{type:"text",text:"Text",font:"sans-serif",weight:"bold",style:"normal",size:.08,x:.5,y:.85,align:"center",angle:0,lineHeight:1.2,color:"#ffffff",outline:null,shadow:{color:"rgba(0,0,0,0.6)",blur:.15,dx:.04,dy:.06},shadows:[]},rect:{type:"rect",x:.5,y:.85,w:.8,h:.18,radius:.15,angle:0,color:"#ffffff",outline:null,shadow:null,shadows:[]},ellipse:{type:"ellipse",x:.5,y:.5,w:.4,h:.4,angle:0,color:"#ffffff",outline:null,shadow:null,shadows:[]}},x=(e,t)=>(t.shadows??[]).map((t,r)=>`${e}_shadow${r+1}`);const E=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d.,\s%deg/]+\)|[a-z]{3,20}|transparent)$/i,v=/^[\w\s,'"-]{1,80}$/,M=["normal","bold","100","200","300","400","500","600","700","800","900"];function A(e,t,r){if("string"!=typeof r||!E.test(r.trim()))throw new Error(`Graphic "${e}": "${t}" is a color like "#ffcc00", "rgba(0,0,0,0.5)" or "white"`);return r.trim()}function _(e,t,r,n=-1/0,o=1/0){const a=Number(r);if(!Number.isFinite(a)||a<n||a>o)throw new Error(`Graphic "${e}": "${t}" is a number${Number.isFinite(n)?` from ${n} to ${o}`:""}`);return a}function k(e,t){if(null===t||!1===t)return null;if("object"!=typeof t)throw new Error(`Graphic "${e}": "outline" is { "color", "width" } or null`);return{color:A(e,"outline.color",t.color??"#000000"),width:_(e,"outline.width",t.width??.06,0,1)}}function O(e,t){if(null===t||!1===t)return null;if("object"!=typeof t)throw new Error(`Graphic "${e}": "shadow" is { "color", "blur", "dx", "dy" } or null`);return{color:A(e,"shadow.color",t.color??"rgba(0,0,0,0.6)"),blur:_(e,"shadow.blur",t.blur??.15,0,2),dx:_(e,"shadow.dx",t.dx??0,-2,2),dy:_(e,"shadow.dy",t.dy??0,-2,2)}}function T(e,t){if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(`Graphic "${e}": give { "type": "text" | "rect" | "ellipse", … }`);const r=t.type??"text";if(!$.includes(r))throw new Error(`Graphic "${e}": "type" is text, rect, ellipse or strokes — not "${r}"`);if("strokes"===r)return p(e,t);const n=b[r];for(const o of Object.keys(t))if(!(o in n)&&"fontUrl"!==o&&"onlyShadow"!==o)throw new Error(`Graphic "${e}": no such setting "${o}" for ${r}`);const o={type:r};for(const[r,a]of Object.entries(n)){if("type"===r)continue;const n=r in t&&void 0!==t[r]?t[r]:a;if("color"===r)o.color=A(e,r,n);else if("outline"===r)o.outline=k(e,n);else if("shadow"===r)o.shadow=O(e,n);else if("shadows"===r){if(!Array.isArray(n)||n.length>8)throw new Error(`Graphic "${e}": "shadows" is a list of up to 8 { "color", "blur", "dx", "dy" }`);o.shadows=n.map((t,r)=>{if(!t||"object"!=typeof t)throw new Error(`Graphic "${e}": shadow layer ${r+1} is { "color", "blur", "dx", "dy" }`);return O(e,t)})}else if("text"===r){if("string"!=typeof n||n.length>500)throw new Error(`Graphic "${e}": "text" is up to 500 characters`);o.text=n}else if("font"===r){if("string"!=typeof n||!v.test(n))throw new Error(`Graphic "${e}": "font" is a font family, like "Georgia" or "sans-serif"`);o.font=n}else if("weight"===r){if(!M.includes(String(n)))throw new Error(`Graphic "${e}": "weight" is normal, bold or 100–900`);o.weight=String(n)}else if("style"===r){if(!["normal","italic"].includes(n))throw new Error(`Graphic "${e}": "style" is normal or italic`);o.style=n}else if("align"===r){if(!["left","center","right"].includes(n))throw new Error(`Graphic "${e}": "align" is left, center or right`);o.align=n}else"size"===r?o.size=_(e,r,n,.005,2):"w"===r||"h"===r?o[r]=_(e,r,n,0,4):"radius"===r?o.radius=_(e,r,n,0,.5):"lineHeight"===r?o.lineHeight=_(e,r,n,.5,4):o[r]=_(e,r,n)}if(void 0!==t.fontUrl&&null!==t.fontUrl&&""!==t.fontUrl){if("text"!==r)throw new Error(`Graphic "${e}": "fontUrl" is for text`);let n;try{n=new URL(t.fontUrl)}catch{n=null}if(!n||"https:"!==n.protocol)throw new Error(`Graphic "${e}": "fontUrl" is an https:// address of a font file (.woff2, .woff, .ttf, .otf) or of a Google Fonts stylesheet`);o.fontUrl=n.href}return void 0!==t.onlyShadow&&(o.onlyShadow=_(e,"onlyShadow",t.onlyShadow,0,7)),o}function j(e){try{const t=new URL(e);return"fonts.googleapis.com"!==t.hostname?null:(t.searchParams.get("family")??"").split(":")[0].replace(/\+/g," ")||null}catch{return null}}function S(e,{weight:t="400",style:r="normal"}={}){const n=[...e.matchAll(/@font-face\s*{([^}]*)}/g)].map(e=>e[1]),o=(e,t)=>(new RegExp(`${t}\\s*:\\s*([^;]+);`).exec(e)?.[1]??"").trim(),a=String("bold"===t?700:"normal"===t?400:t),s=n.filter(e=>o(e,"font-weight")===a&&o(e,"font-style")===r),i=(s.length?s:n).at(-1);return i&&(/url\(([^)]+)\)/.exec(i)?.[1]??"").replace(/^['"]|['"]$/g,"")||null}function F(e,t){const r=e.fontUrl?`"${C(e.fontUrl)}", ${e.font}`:e.font;return`${e.style} ${e.weight} ${Math.max(1,e.size*t)}px ${r}`}function C(e){let t=0;for(const r of e)t=31*t+r.charCodeAt(0)>>>0;return`mz-font-${t.toString(36)}`}const R=new Map;async function I(e,t=100){if("undefined"==typeof document&&"undefined"==typeof self)return[];const r="undefined"!=typeof document?document.fonts:self.fonts;if(!r)return[];const n=[];for(const o of Object.values(e??{}))if("text"===o.type){if(o.fontUrl&&"undefined"!=typeof FontFace){const e=`${o.fontUrl} ${o.weight} ${o.style}`;R.has(e)||R.set(e,U(o,r)),await R.get(e)||n.push(o.fontUrl)}try{await r.load(F(o,t),o.text)}catch{}}return[...new Set(n)]}async function U(e,t){try{let r=e.fontUrl;if(!/\.(woff2?|ttf|otf)(\?|$)/i.test(new URL(r).pathname)||j(r)){if(r=S(await(await fetch(r,{credentials:"omit",referrerPolicy:"no-referrer"})).text(),e),!r||!r.startsWith("https://"))return null}const n=new FontFace(C(e.fontUrl),`url(${JSON.stringify(r)})`,{weight:e.weight,style:e.style});return t.add(await n.load()),n}catch{return null}}function N(e,t,r,n){e.save();const o="text"===t.type?t.size*n:n,a=void 0!==t.onlyShadow?t.shadows[t.onlyShadow]:null,s=a?2*(r+n)+1e3:0,i=a??t.shadow;if(e.translate(t.x*r-s,t.y*n),t.angle&&e.rotate(t.angle),i&&(e.shadowColor=i.color,e.shadowBlur=i.blur*o,e.shadowOffsetX=i.dx*o+s,e.shadowOffsetY=i.dy*o),e.fillStyle=a?"#000000":t.color,t.outline&&(e.strokeStyle=t.outline.color,e.lineWidth=t.outline.width*o,e.lineJoin="round"),"text"===t.type){e.font=F(t,n),e.textAlign=t.align,e.textBaseline="middle";const r=t.text.split("\n"),o=t.size*n*t.lineHeight;r.forEach((n,s)=>{const l=(s-(r.length-1)/2)*o;t.outline&&e.strokeText(n,0,l),t.outline&&i&&!a&&(e.shadowColor="transparent"),e.fillText(n,0,l),t.outline&&i&&!a&&(e.shadowColor=i.color)})}else{const o=t.w*r,s=t.h*n;if(e.beginPath(),"ellipse"===t.type)e.ellipse(0,0,o/2,s/2,0,0,2*Math.PI);else{const r=Math.min(o,s)*t.radius;e.roundRect?e.roundRect(-o/2,-s/2,o,s,r):e.rect(-o/2,-s/2,o,s)}e.fill(),t.outline&&(a||(e.shadowColor="transparent"),e.stroke())}e.restore()}async function z(e,t,r,{t:n=1/0,mask:o=null}={}){const a=e.graphics??{},s=await I(a,r),i={};for(const[e,s]of Object.entries(a)){if("strokes"===s.type){const a=g(s,t,r,n,{mask:o});i[e]="undefined"!=typeof ImageData?new ImageData(a.data,t,r):a;continue}const a="undefined"!=typeof OffscreenCanvas&&"undefined"==typeof document?new OffscreenCanvas(t,r):Object.assign(document.createElement("canvas"),{width:t,height:r});N(a.getContext("2d"),s,t,r),i[e]=a}return Object.defineProperty(i,"failedFonts",{value:s}),i}const P="mathzetta-filter/1",B=["r","g","b","a","rgb","rgba"],D=/^[A-Za-z][A-Za-z0-9_]*$/,L=new Set([...t.FILTER_NAMES,"r","g","b","a","x","y","w","h","t","c","e","pi","color","image","resolution","base","position","main","in","out","inout","const","uniform","varying","attribute","void","float","int","bool","vec2","vec3","vec4","mat2","mat3","mat4","sampler2D","struct","precision","highp","mediump","lowp","if","else","for","while","do","return","break","continue","discard","true","false","texture2D","texture","mix","clamp","step","smoothstep","abs","sign","floor","ceil","fract","mod","min","max","sin","cos","tan","asin","acos","atan","pow","exp","log","exp2","log2","sqrt","inversesqrt","length","distance","dot","cross","normalize","radians","degrees"]),G=e=>Array.isArray(e)&&3===e.length&&e.every(e=>Number.isFinite(Number(e))),H=e=>e&&"object"==typeof e&&!Array.isArray(e),W={place:"cover",zoom:1,x:.5,y:.5,angle:0};function q(e){if("string"==typeof e){if(!e.trim())throw new Error("The filter is empty");return{format:P,color:e.trim()}}if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('A filter is an expression, or an object with "color" or "steps"');if(void 0!==e.format&&e.format!==P)throw new Error(`Unknown filter format "${e.format}" (this is ${P})`);const r={format:P};for(const t of["name","author","description"])void 0!==e[t]&&""!==e[t]&&(r[t]=String(e[t]));if(void 0!==e.steps){if(void 0!==e.color)throw new Error('A filter has either "color" or "steps", not both');if(!Array.isArray(e.steps)||!e.steps.length)throw new Error('"steps" must be a list with at least one step');return r.steps=e.steps.map(Y),void 0!==e.notes&&(r.notes=X(e.notes,Q(r))),r}if(void 0===e.color)throw new Error('A filter needs "color" (an expression, or one per channel) or "steps"');const n=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('"params" is an object of name → { default, min, max }');const t={};for(const[r,n]of Object.entries(e)){if(!D.test(r))throw new Error(`Parameter name "${r}" must be letters, digits and _, starting with a letter`);if(L.has(r))throw new Error(`"${r}" is already defined in every filter; pick another parameter name`);t[r]=Z(r,n)}return t}(e.params??{});Object.keys(n).length&&(r.params=n),void 0!==e.notes&&(r.notes=X(e.notes,n));const o=function(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,{}])):e;if(!r||"object"!=typeof r)throw new Error('"images" is a list of names, or an object of name → { description }');const n={};for(const[e,o]of Object.entries(r)){if(!D.test(e)||e.startsWith("mz_"))throw new Error(`Image name "${e}" must be letters, digits and _, starting with a letter`);if("source"===e)throw new Error('"source" is always available: the picture the chain started from');if(L.has(e))throw new Error(`"${e}" is already defined in every filter; pick another image name`);if(Object.hasOwn(t,e))throw new Error(`"${e}" is both a parameter and an image`);n[e]=V(e,o)}return n}(e.images??{},n);Object.keys(o).length&&(r.images=o);const a=function(e,t,r){if(!H(e))throw new Error('"graphics" is an object of name → { "type": "text" | "rect" | "ellipse", … }');if(Object.keys(e).length>64)throw new Error("A filter has at most 64 graphics");const n={};for(const[o,a]of Object.entries(e)){if(!D.test(o)||o.startsWith("mz_"))throw new Error(`Graphic name "${o}" must be letters, digits and _, starting with a letter`);if(L.has(o)||"source"===o||"selection"===o)throw new Error(`"${o}" is already defined in every filter; pick another graphic name`);if(Object.hasOwn(t,o)||Object.hasOwn(r,o))throw new Error(`"${o}" is both a graphic and a parameter or picture`);n[o]=T(o,a)}const o=new Set(Object.keys(n).flatMap(e=>Array.from({length:8},(t,r)=>`${e}_shadow${r+1}`)));for(const e of[...Object.keys(n),...Object.keys(t),...Object.keys(r)])if(o.has(e))throw new Error(`"${e}" is the name of a shadow layer of another graphic; pick another name`);return n}(e.graphics??{},n,o);Object.keys(a).length&&(r.graphics=a);const s=function(e){if(null==e)return null;const r="string"==typeof e?{in:e,out:e}:e;if(!H(r))throw new Error(`"space" is a color space (${t.COLOR_SPACES.join(", ")}) or { "in": …, "out": … }`);const n={in:r.in??"srgb",out:r.out??"srgb"};for(const e of["in","out"])if(!t.COLOR_SPACES.includes(n[e]))throw new Error(`"space": "${n[e]}" is not a color space; they are ${t.COLOR_SPACES.join(", ")}`);return"srgb"===n.in&&"srgb"===n.out?null:n}(e.space);return s&&(r.space=s),r.color=function(e){if("string"==typeof e){if(!e.trim())throw new Error('"color" is empty');return e.trim()}if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('"color" is an expression, or an object with r, g, b, a, rgb or rgba expressions');const t={};for(const[r,n]of Object.entries(e)){if(!B.includes(r))throw new Error(`"color" can set r, g, b, a, rgb or rgba — not "${r}"`);if("string"!=typeof n||!n.trim())throw new Error(`"color.${r}" must be an expression`);t[r]=n.trim()}if(!Object.keys(t).length)throw new Error('"color" sets no channels');return t}(e.color),r}function X(e,t){if(!Array.isArray(e))throw new Error('"notes" is a list of Markdown texts and { "param": name } entries');return e.map(e=>{if("string"==typeof e)return e;if(!H(e)||"string"!=typeof e.param||1!==Object.keys(e).length)throw new Error('"notes": each entry is a Markdown text or { "param": name }');if(!Object.hasOwn(t,e.param))throw new Error(`"notes" places "${e.param}", but there is no parameter called that`);return{param:e.param}})}function J(e){if(e.color)return{...e.graphics??{}};const t={};for(const r of e.steps)for(const[e,n]of Object.entries(J(r.filter)))Object.hasOwn(t,e)||(t[e]=n);return t}function V(e,r){if(!H(r))throw new Error(`Image "${e}": give { description, place, zoom, x, y, angle }`);const n={};if(r.description&&(n.description=String(r.description)),void 0!==r.place){if(!t.PLACES.includes(r.place))throw new Error(`Image "${e}": "place" is ${t.PLACES.join(", ")} — not "${r.place}"`);n.place=r.place}for(const t of["zoom","x","y","angle"]){if(void 0===r[t])continue;const o=Number(r[t]);if(!Number.isFinite(o))throw new Error(`Image "${e}": "${t}" is a number`);n[t]=o}for(const t of Object.keys(r))if(!["description","place","zoom","x","y","angle"].includes(t))throw new Error(`Image "${e}": no such setting "${t}"`);return n}function Y(e){if("string"==typeof e)return{filter:q(e),with:{},opacity:1,skip:!1};if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('A step is an expression, a filter, or { "filter": …, "with": { … }, "opacity": … }');const{filter:t,with:r,opacity:n,skip:o,...a}=e,s={filter:q(void 0!==t?t:a),with:{},opacity:1,skip:Boolean(o)};if(void 0!==r){if(!r||"object"!=typeof r||Array.isArray(r))throw new Error('"with" is an object of parameter name → value');s.with={...r}}if(void 0!==n){const e=Number(n);if(!(e>=0&&e<=1))throw new Error('"opacity" is a number from 0 to 1');s.opacity=e}return s}function Z(e,t){if("number"==typeof t)t={default:t};else if(Array.isArray(t))t={type:"color",default:t};else if(!t||"object"!=typeof t)throw new Error(`Parameter "${e}" needs a default value`);const r=t.type??(Array.isArray(t.default)?"color":"number"),n={type:r};if(void 0!==t.label&&(n.label=String(t.label)),"color"===r){const r=t.default??[1,1,1];if(!G(r))throw new Error(`Color parameter "${e}" needs a default of three numbers, 0–1`);return n.default=r.map(Number),n}if("number"!==r)throw new Error(`Parameter "${e}": the type is "number" or "color", not "${r}"`);let o=null;if(void 0!==t.options){if(!Array.isArray(t.options)||!t.options.length||!t.options.every(e=>""!==e&&Number.isFinite(Number(e))))throw new Error(`Parameter "${e}": "options" is a list of numbers`);o=t.options.map(Number)}if(void 0!==t.input&&"slider"!==t.input&&"box"!==t.input)throw new Error(`Parameter "${e}": "input" is "slider" or "box", not "${t.input}"`);const a=Number(t.default??(o?o[0]:0));if(!Number.isFinite(a))throw new Error(`Parameter "${e}" needs a numeric default`);if(n.default=a,n.min=void 0!==t.min?Number(t.min):o?o.reduce((e,t)=>Math.min(e,t),a):Math.min(0,2*a),n.max=void 0!==t.max?Number(t.max):o?o.reduce((e,t)=>Math.max(e,t),a):Math.max(1,2*a),void 0!==t.step&&(n.step=Number(t.step)),o&&(n.options=o),"box"!==t.input||o||(n.input="box"),!(n.min<=a&&a<=n.max))throw new Error(`Parameter "${e}": the default ${a} is outside ${n.min} to ${n.max}`);return n}function K(e){if(e.color)return{...e.images??{}};const t={};for(const r of e.steps)for(const[e,n]of Object.entries(K(r.filter)))Object.hasOwn(t,e)||(t[e]=n);return t}function Q(e){if(e.color)return{...e.params??{}};const t={};for(const r of e.steps)for(const[e,n]of Object.entries(Q(r.filter)))Object.hasOwn(t,e)||(t[e]=n);return t}function ee(e,t,r,n){const{filter:o}=e,a=te(o,t),s=Q(o),i=K(o),l=J(o);for(const[t,n]of Object.entries(e.with)){if(Object.hasOwn(l,t)){if(H(n))try{T(t,{...l[t],...n})}catch(e){r.push(`${a}: ${e.message}`)}else r.push(`${a}: "with" for the graphic "${t}" is an object of its settings`);continue}if(Object.hasOwn(i,t)){try{V(t,n)}catch(e){r.push(`${a}: ${e.message}`)}continue}const e=Object.hasOwn(s,t)?s[t]:null;e?("color"===e.type?G(n):Number.isFinite(Number(n)))||r.push(`${a}: "${t}" should be a ${"color"===e.type?"color: three numbers, 0–1":"number"}`):r.push(`${a}: "with" sets "${t}", but there is no parameter called that`)}if(o.steps)o.steps.forEach((e,o)=>ee(e,[...t,o],r,n));else if(n)try{oe(o,Object.fromEntries(Object.entries(e.with).filter(([e])=>Object.hasOwn(o.graphics??{},e))),1,t,100)}catch(e){r.push(`${a}: ${e.message}`)}}function te(e,t){return e.name?`"${e.name}"`:t.length?`step ${t.map(e=>e+1).join(".")}`:"the filter"}function re(e,t={}){const r=q(e),n=[];if(ee({filter:r,with:{},opacity:1},[],n,!1),n.length)throw new Error(n.join("\n"));const o={passes:[],credits:[],problems:n,version:300===t.version?300:100,top:r,graphics:{}};if(ne({filter:r,with:{},opacity:1,skip:!1},[],{},o),n.length)throw new Error(n.join("\n"));return o.passes.length||o.passes.push(oe(q("pixel(px, py)"),{},1,[],o.version)),{name:r.name??"",author:r.author??"",description:r.description??"",version:o.version,passes:o.passes,credits:o.credits,images:K(r),graphics:o.graphics}}function ne(e,t,r,n){if(e.skip)return;if(n.passes.length>256){const e="A filter has at most 256 passes";return void(n.problems.includes(e)||n.problems.push(e))}const o=function(e){if(!e.space||void 0===e.color)return null;const{space:t,name:r,author:n,description:o,...a}=e,s=e=>({filter:e,with:{},opacity:1,skip:!1}),i=[];"srgb"!==t.in&&i.push(s({format:P,color:{rgb:`to${t.in}(rgb)`}}));i.push(s({...a,_space:t.in})),"srgb"!==t.out&&i.push(s({format:P,color:{rgb:`from${t.out}(rgb)`}}));const l={format:P,steps:i};for(const[e,t]of Object.entries({name:r,author:n,description:o}))t&&(l[e]=t);return l}(e.filter)??function(e){if("string"!=typeof e.color)return null;const t=/^(gaussian|blur)\((.*)\)$/s.exec(e.color.trim());if(!t)return null;let r=0;for(const e of t[2])if("("===e)r++;else if(")"===e&&--r<0)return null;if(0!==r)return null;const{color:n,...o}=e,a=e=>{const r={format:P,color:`${t[1]}${e}(${t[2]})`};return o.params&&(r.params=o.params),o.images&&(r.images=o.images),o.graphics&&(r.graphics=o.graphics),{filter:r,with:{},opacity:1,skip:!1}};return{...o,steps:[a("x"),a("y")]}}(e.filter);if(o)return e.filter===n.top&&(n.top=o),void ne({...e,filter:o},t,r,n);const{filter:a}=e,s={...e.with,...r};for(const t of Object.keys(r))H(r[t])&&H(e.with[t])&&(s[t]={...e.with[t],...r[t]});if(a.name&&a!==n.top&&!n.credits.some(e=>e.name===a.name&&e.author===(a.author??""))&&n.credits.push({name:a.name,author:a.author??""}),a.color){try{n.passes.push(function(e,t){e.bind={};for(const[r,n]of Object.entries(e.graphics??{})){let o=r;for(let e=2;o in t&&JSON.stringify(t[o])!==JSON.stringify(n);e++)o=`${r}~${e}`;t[o]=n,e.bind[r]=o}return e}(oe(a,s,e.opacity,t,n.version),n.graphics))}catch(e){n.problems.push(`${te(a,t)}: ${e.message}`)}return}const i=n.passes.length;a.steps.forEach((e,r)=>ne(e,[...t,r],s,n)),e.opacity<1&&(n.passes.length-i===1?n.passes[i].opacity*=e.opacity:(n.passes[i].keepInput+=1,n.passes.push(function(e,t,r){const n=300===r,o=n?"texture":"texture2D",a=[n?"#version 300 es":"","precision highp float;","uniform sampler2D image;","uniform sampler2D base;","uniform vec2 resolution;","uniform float mz_opacity;",n?"out vec4 fragColor;":"","void main() {"," vec2 uv = gl_FragCoord.xy / resolution;",` ${n?"fragColor":"gl_FragColor"} = mix(${o}(base, uv), ${o}(image, uv), mz_opacity);`,"}"].filter(Boolean).join("\n");return{name:"blend",author:"",path:t,fragment:a,params:{},values:{},opacity:e,images:[],placements:{},graphics:{},keepInput:0,blendKept:!0}}(e.opacity,t,n.version))))}function oe(e,r,n,o,a){const s=e.params??{},i={};for(const[e,t]of Object.entries(s))Object.hasOwn(r,e)?i[e]="color"===t.type?r[e].map(Number):Number(r[e]):i[e]=t.default;const l={};for(const[t,n]of Object.entries(e.images??{})){const{description:e,...o}=n;l[t]={...W,...o,...H(r[t])?r[t]:{}}}const c={};for(const[t,n]of Object.entries(e.graphics??{}))c[t]=H(r[t])?T(t,{...n,...r[t]}):n,l[t]={...W,place:"stretch"},x(t,c[t]).forEach((e,r)=>{c[e]={...c[t],onlyShadow:r},l[e]={...W,place:"stretch"}});const h=function(e,r,n=null){const o=e.params??{},a={};for(const[e,t]of Object.entries(o))a[e]="color"===t.type?"vec3":"float";const s={};for(const[t,r]of Object.entries(e.images??{}))s[t]={place:n?.[t]?.place??r.place??W.place};for(const[t,r]of Object.entries(e.graphics??{})){s[t]={place:"stretch"};const e=n?Object.keys(n).filter(e=>/_shadow\d+$/.test(e)&&e.startsWith(`${t}_shadow`)):x(t,r);for(const t of e)s[t]={place:"stretch"}}return t.filterShader(e.color,{version:r,uniforms:a,values:Object.keys(o),images:s,blend:!0,space:e._space??e.space?.in??"srgb"})}(e,a,l),u=Object.keys(l);return h.includes("uniform sampler2D mz_img_source;")&&u.push("source"),h.includes("uniform sampler2D mz_img_selection;")&&u.push("selection"),{name:e.name??"",author:e.author??"",path:o,color:e.color,space:e._space??"srgb",fragment:h,params:s,values:i,opacity:n,images:u,placements:l,graphics:c,keepInput:0,blendKept:!1}}function ae(e){return JSON.stringify(ce(q(e),!0),null,2)}function se(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Not valid JSON")}return q(t)}function ie(e){const t=e.includes("#")?e.slice(e.lastIndexOf("#")+1):e;let r;try{r=JSON.parse(function(e){const t=atob(e.replace(/-/g,"+").replace(/_/g,"/"));return(new TextDecoder).decode(Uint8Array.from(t,e=>e.charCodeAt(0)))}(t.trim()))}catch{throw new Error("Not a filter link")}return q(r)}function le(e){const t=String(e??"").trim();if(!t)throw new Error("Nothing to read");if(t.startsWith("{"))return se(t);if(!/\s/.test(t)){const e=t.includes("#")?t.slice(t.lastIndexOf("#")+1):t;if(/^[A-Za-z0-9_-]{8,}$/.test(e))try{return ie(e)}catch(e){if(t.includes("#"))throw e}}return q(t)}function ce(e,t){const r={};t&&(r.format=P);for(const t of["name","author","description"])e[t]&&(r[t]=e[t]);return e.notes&&e.notes.length&&(r.notes=e.notes),e.steps?(r.steps=e.steps.map(e=>{const t=ce(e.filter,!1),r=1===Object.keys(t).length&&"string"==typeof t.color?t.color:t,n={};return Object.keys(e.with).length&&(n.with=e.with),1!==e.opacity&&(n.opacity=e.opacity),e.skip&&(n.skip=!0),Object.keys(n).length?{filter:r,...n}:r}),r):(e.params&&(r.params=e.params),e.images&&(r.images=e.images),e.graphics&&(r.graphics=e.graphics),e.space&&(r.space=e.space.in===e.space.out?e.space.in:e.space),r.color=e.color,r)}function he(e,r,n={}){if(e.isContextLost())throw new Error("The WebGL context is lost");const o=pe(e,n.precision),a=t.filterVertexShader({version:r.version}),s=[];try{for(const t of r.passes)s.push(fe(e,a,t.fragment,t.name))}catch(t){for(const t of s)e.deleteProgram(t);throw t}const i=(e,t)=>e.bind&&Object.hasOwn(e.bind,t)?e.bind[t]:t,l=s.map(()=>new Map),c=(t,r)=>(l[t].has(r)||l[t].set(r,e.getUniformLocation(s[t],r)),l[t].get(r)),h=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,h),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),e.STATIC_DRAW);const u={texture:e.createTexture(),framebuffer:null};e.bindTexture(e.TEXTURE_2D,u.texture),ue(e);const p=new Map,f=new Map,m=e.createTexture();e.bindTexture(e.TEXTURE_2D,m),ue(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([255,255,255,255]));const d=e.createTexture();e.bindTexture(e.TEXTURE_2D,d),ue(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([0,0,0,0]));const g=[];let w=0,y=0;const $={passes:r.passes,get precision(){return o.name},setImage(t,r){if("string"!=typeof t&&(r=t,t=null),t&&"source"!==t&&null==r)return p.has(t)&&e.deleteTexture(p.get(t)),p.delete(t),f.delete(t),$;let n=u.texture;if(t&&"source"!==t&&(p.has(t)||(p.set(t,e.createTexture()),e.bindTexture(e.TEXTURE_2D,p.get(t)),ue(e)),n=p.get(t)),r&&r.data&&r.width&&r.height&&"undefined"!=typeof ImageData&&!(r instanceof ImageData)){const e=r.data,t=e instanceof Float32Array||e instanceof Float64Array,n=e instanceof Uint8ClampedArray?e:Uint8ClampedArray.from(e,t?e=>255*e:void 0);r=new ImageData(n,r.width,r.height)}return e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r),t&&f.set(t,[r.naturalWidth||r.videoWidth||r.width||1,r.naturalHeight||r.videoHeight||r.height||1]),$},draw({t:t=0}={}){if(e.drawingBufferWidth!==w||e.drawingBufferHeight!==y){w=e.drawingBufferWidth,y=e.drawingBufferHeight;for(const t of g)e.bindTexture(e.TEXTURE_2D,t.texture),e.texImage2D(e.TEXTURE_2D,0,o.internal,w,y,0,e.RGBA,o.type,null)}let n=u;const a=[];return r.passes.forEach((l,$)=>{for(let e=0;e<l.keepInput;e++)a.push(n);const b=$===r.passes.length-1?null:function(t){let r=g.find(e=>!t.includes(e));return r||(r={texture:e.createTexture(),framebuffer:e.createFramebuffer()},e.bindTexture(e.TEXTURE_2D,r.texture),ue(e,o.filter),e.texImage2D(e.TEXTURE_2D,0,o.internal,w,y,0,e.RGBA,o.type,null),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r.texture,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE&&"byte"!==o.name&&(Object.assign(o,pe(e,"byte")),e.bindTexture(e.TEXTURE_2D,r.texture),ue(e,o.filter),e.texImage2D(e.TEXTURE_2D,0,o.internal,w,y,0,e.RGBA,o.type,null)),g.push(r)),r}([n,...a]);e.bindFramebuffer(e.FRAMEBUFFER,b?b.framebuffer:null),e.viewport(0,0,w,y);const x=s[$];e.useProgram(x);const E=e.getAttribLocation(x,"position");e.bindBuffer(e.ARRAY_BUFFER,h),e.enableVertexAttribArray(E),e.vertexAttribPointer(E,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,n.texture),e.uniform1i(c($,"image"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,l.blendKept?a[a.length-1].texture:null),l.blendKept&&e.uniform1i(c($,"base"),1),l.images.forEach((t,r)=>{if(e.activeTexture(e.TEXTURE2+r),e.bindTexture(e.TEXTURE_2D,"source"===t?u.texture:p.get(i(l,t))??(l.graphics?.[t]?d:m)),e.uniform1i(c($,`mz_img_${t}`),2+r),!l.placements[t])return;const n=f.get(i(l,t))??[1,1],o=l.placements[t];e.uniform2f(c($,`mz_size_${t}`),n[0],n[1]),e.uniform4f(c($,`mz_place_${t}`),Number(o.zoom),Number(o.x),Number(o.y),Number(o.angle))}),e.uniform2f(c($,"resolution"),w,y),e.uniform1f(c($,"t"),t),e.uniform1f(c($,"mz_opacity"),l.opacity);for(const[t,r]of Object.entries(l.params)){const n=l.values[t];"color"===r.type?e.uniform3fv(c($,t),n.map(Number)):e.uniform1f(c($,t),Number(n))}e.drawArrays(e.TRIANGLES,0,3),l.blendKept&&a.pop(),n=b}),$},dispose(){for(const t of s)e.deleteProgram(t);e.deleteTexture(u.texture),e.deleteTexture(m),e.deleteTexture(d);for(const t of p.values())e.deleteTexture(t);for(const t of g)e.deleteTexture(t.texture),e.deleteFramebuffer(t.framebuffer);e.deleteBuffer(h)}};return $}function ue(e,t=e.LINEAR){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t)}function pe(e,t="byte"){const r={name:"byte",internal:e.RGBA,type:e.UNSIGNED_BYTE,filter:e.LINEAR};if("half"!==t&&"float"!==t)return r;if("undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext){if(!e.getExtension("EXT_color_buffer_float"))return r;const n=e.getExtension("OES_texture_float_linear")?e.LINEAR:e.NEAREST;return"float"===t?{name:"float",internal:e.RGBA32F,type:e.FLOAT,filter:n}:{name:"half",internal:e.RGBA16F,type:e.HALF_FLOAT,filter:e.LINEAR}}if("float"===t&&e.getExtension("OES_texture_float")&&e.getExtension("WEBGL_color_buffer_float"))return{name:"float",internal:e.RGBA,type:e.FLOAT,filter:e.getExtension("OES_texture_float_linear")?e.LINEAR:e.NEAREST};const n=e.getExtension("OES_texture_half_float");return n&&e.getExtension("EXT_color_buffer_half_float")?{name:"half",internal:e.RGBA,type:n.HALF_FLOAT_OES,filter:e.getExtension("OES_texture_half_float_linear")?e.LINEAR:e.NEAREST}:r}function fe(e,t,r,n){const o=e.createProgram(),a=[];let s=null;for(const[i,l]of[[e.VERTEX_SHADER,t],[e.FRAGMENT_SHADER,r]]){const t=e.createShader(i);if(a.push(t),e.shaderSource(t,l),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS)){s=`${n||"The filter"} does not compile: ${(e.getShaderInfoLog(t)??"").trim()}`;break}e.attachShader(o,t)}s||(e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS)||(s=`${n||"The filter"} does not link: ${(e.getProgramInfoLog(o)??"").trim()}`));for(const t of a)e.deleteShader(t);if(s)throw e.deleteProgram(o),new Error(s);return o}const me={data:new Float32Array([1,1,1,1]),width:1,height:1},de={data:new Float32Array([0,0,0,0]),width:1,height:1},ge={cover:0,fit:1,stretch:2,tile:3};function we(e){return ge[e??"cover"]??0}function ye(e,t){return e-t*Math.floor(e/t)}const $e=(e,t)=>e<0?0:e>t?t:e;function be(e,t,r,n,o,a){const s=Math.floor(n),i=Math.floor(o),l=n-s,c=o-i,h=$e(s,t-1),u=$e(s+1,t-1),p=$e(i,r-1),f=$e(i+1,r-1),m=4*(p*t+h),d=4*(p*t+u),g=4*(f*t+h),w=4*(f*t+u);for(let t=0;t<4;t++){const r=e[m+t]+(e[d+t]-e[m+t])*l,n=e[g+t]+(e[w+t]-e[g+t])*l;a[t]=r+(n-r)*c}return a}function xe(e,t,r){const n=Math.min(Math.max(Math.ceil(e),0),t),o=[];for(let e=-n;e<=n;e++)r(e)&&o.push(e);return o}function Ee(e,t,r,n,o,a,s,i,l=0,c=n){const h=new Float32Array(r*n*3),u=a.length,p=Int32Array.from(a),f=Float64Array.from(s??a.map(()=>1)),m="x"===o?r:n,d=new Int32Array(u);for(let n=l;n<c;n++)for(let a=0;a<r;a++){const s="x"===o?a:n;for(let e=0;e<u;e++){let i=s+p[e];i=i<0?0:i>=m?m-1:i,d[e]=("x"===o?n*r+i:i*r+a)*t}let l=0,c=0,g=0;for(let t=0;t<u;t++){const r=d[t],n=f[t];l+=e[r]*n,c+=e[r+1]*n,g+=e[r+2]*n}const w=3*(n*r+a);h[w]=l/i,h[w+1]=c/i,h[w+2]=g/i}return h}function ve(e,t,r,n,o,a,s,i=0,l=n){const c=new Float32Array(r*n*3),h="x"===o?r:n,u="x"===o?n:r,p=s-a+1,f=(e,t)=>"x"===o?e*r+t:t*r+e,m=e=>e<0?0:e>=h?h-1:e,[d,g]="x"===o?[i,l]:[0,u],[w,y]="x"===o?[0,h]:[i,l];for(let r=d;r<g;r++){let n=0,o=0,i=0;for(let l=w+a;l<=w+s;l++){const a=f(r,m(l))*t;n+=e[a],o+=e[a+1],i+=e[a+2]}for(let l=w;l<y;l++){const h=3*f(r,l);c[h]=n/p,c[h+1]=o/p,c[h+2]=i/p;const u=f(r,m(l+a))*t,d=f(r,m(l+s+1))*t;n+=e[d]-e[u],o+=e[d+1]-e[u+1],i+=e[d+2]-e[u+2]}}return c}function Me(e,t,r,n,o,a,s,i,l=0,c=n){const h=new Float32Array(r*n*3),u="x"===o?r:n;for(let n=l;n<c;n++)for(let l=0;l<r;l++){const c="x"===o?l:n;let p=s,f=s,m=s;for(let s=0;s<a.length;s++){let h=c+a[s];h=h<0?0:h>=u?u-1:h;const d=("x"===o?n*r+h:h*r+l)*t;i?(e[d]>p&&(p=e[d]),e[d+1]>f&&(f=e[d+1]),e[d+2]>m&&(m=e[d+2])):(e[d]<p&&(p=e[d]),e[d+1]<f&&(f=e[d+1]),e[d+2]<m&&(m=e[d+2]))}const d=3*(n*r+l);h[d]=p,h[d+1]=f,h[d+2]=m}return h}const Ae=(e,t,r)=>e+t*r,_e=(e,t)=>t>e?t:e,ke=(e,t)=>t<e?t:e;function Oe(e,t,r,n=0,o=r){const a=new Float32Array(t*r*3);for(let r=n*t;r<o*t;r++)a[3*r]=e[4*r],a[3*r+1]=e[4*r+1],a[3*r+2]=e[4*r+2];return a}const Te=(e,t,r,n)=>[Math.max(0,e-r),Math.min(n,t+r)];function je(e,t,r,n,o,a,s,i){const l=xe(a,i,e=>Math.abs(e)<=a);if(!l.length)return Oe(e,t,r,n,o);const c=l[0],h=l[l.length-1];if(1===s.length)return ve(e,4,t,r,s[0],c,h,n,o);const[u,p]=Te(n,o,h,r);return ve(ve(e,4,t,r,"x",c,h,u,p),3,t,r,"y",c,h,n,o)}function Se(e,t,r,n,o,a,s,i){if(!(a>0))return Oe(e,t,r,n,o);const l=3*a,c=xe(l,i,e=>Math.abs(e)<=l),h=c.map(e=>Math.exp(-e*e/(2*a*a))),u=h.reduce((e,t)=>e+t,0);if(1===s.length)return Ee(e,4,t,r,s[0],c,h,u,n,o);const[p,f]=Te(n,o,c[c.length-1],r);return Ee(Ee(e,4,t,r,"x",c,h,u,p,f),3,t,r,"y",c,h,u,n,o)}function Fe(e,r,n,o,a,s,i,l){const c=xe(s,t.REACH.square,e=>Math.abs(e)<=s);if(!c.length)return new Float32Array(r*n*3).fill(i);const[h,u]=Te(o,a,c[c.length-1],n);return Me(Me(e,4,r,n,"x",c,i,l,h,u),3,r,n,"y",c,i,l,o,a)}function Ce(e,t,r,n,o,a){const s=function(e,t,r){const n=new Float32Array(t*r);for(let o=0;o<t*r;o++)n[o]=.299*e[4*o]+.587*e[4*o+1]+.114*e[4*o+2];return n}(e,t,r),i=new Float32Array(t*r);for(let e=n;e<o;e++)for(let n=0;n<t;n++){const o=(o,a)=>s[$e(e+a,r-1)*t+$e(n+o,t-1)];i[e*t+n]=a(o)}return i}const Re=e=>e(1,-1)+2*e(1,0)+e(1,1)-(e(-1,-1)+2*e(-1,0)+e(-1,1)),Ie=e=>e(-1,1)+2*e(0,1)+e(1,1)-(e(-1,-1)+2*e(0,-1)+e(1,-1)),Ue=e=>4*e(0,0)-e(-1,0)-e(1,0)-e(0,-1)-e(0,1),Ne=e=>.5+e(-1,-1)-e(1,1),ze=e=>Math.hypot(Re(e),Ie(e));function Pe(e,t,r,n,o,a,s,i,l,c,h){for(let u=0;u<3;u++){let p=i,f=0;for(const i of a)for(const c of a){const a=s?s(i,c):1;p=l(p,e[4*($e(o+c,r-1)*t+$e(n+i,t-1))+u],a),f+=a}c[u]=h?h(p,f):p}return c}function Be(e,t,r,n,o,a,s,i,l){for(let c=0;c<3;c++){let h=0,u=0;for(const l of s){const s=i?i(l):1,p="x"===a?$e(n+l,t-1):n;h+=e[4*(("y"===a?$e(o+l,r-1):o)*t+p)+c]*s,u+=s}l[c]=h/u}return l}const De=(e,t,r,n,o)=>{const a=4*(n*t+r);return o[0]=e[a],o[1]=e[a+1],o[2]=e[a+2],o};const Le=e=>e<.04045?e/12.92:Math.pow((e+.055)/1.055,2.4),Ge=e=>(e=Math.max(e,0))<.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055,He=(e,t,r,n,o)=>{const a=n===e?(t-r)/o:n===t?2+(r-e)/o:4+(e-t)/o;return a/6-Math.floor(a/6)},We=(e,t)=>{const r=Math.abs(6*(e+t-Math.floor(e+t))-3);return Math.min(Math.max(r-1,0),1)};const qe=e=>e<.008856?7.787*e+16/116:Math.cbrt(e),Xe=e=>e<.206893?(e-16/116)/7.787:e*e*e;var Je=Object.freeze({__proto__:null,BLANK:me,CLEAR:de,at:function(e,t,r){return Number(e[t][r])},at_blur:function(e,r,n,o,a,s,i){return Pe(e,r,n,o,a,xe(s,t.REACH.square,e=>Math.abs(e)<=s),null,0,Ae,i,(e,t)=>e/t)},at_blurx:function(e,r,n,o,a,s,i){return Be(e,r,n,o,a,"x",xe(s,t.REACH.line,e=>Math.abs(e)<=s),null,i)},at_blury:function(e,r,n,o,a,s,i){return Be(e,r,n,o,a,"y",xe(s,t.REACH.line,e=>Math.abs(e)<=s),null,i)},at_dilate:function(e,r,n,o,a,s,i){return Pe(e,r,n,o,a,xe(s,t.REACH.square,e=>Math.abs(e)<=s),null,0,_e,i)},at_erode:function(e,r,n,o,a,s,i){return Pe(e,r,n,o,a,xe(s,t.REACH.square,e=>Math.abs(e)<=s),null,1,ke,i)},at_gaussian:function(e,r,n,o,a,s,i){if(!(s>0))return De(e,r,o,a,i);const l=3*s;return Pe(e,r,n,o,a,xe(l,t.REACH.square,e=>Math.abs(e)<=l),(e,t)=>Math.exp(-(e*e+t*t)/(2*s*s)),0,Ae,i,(e,t)=>e/t)},at_gaussianx:function(e,r,n,o,a,s,i){if(!(s>0))return De(e,r,o,a,i);const l=3*s;return Be(e,r,n,o,a,"x",xe(l,t.REACH.line,e=>Math.abs(e)<=l),e=>Math.exp(-e*e/(2*s*s)),i)},at_gaussiany:function(e,r,n,o,a,s,i){if(!(s>0))return De(e,r,o,a,i);const l=3*s;return Be(e,r,n,o,a,"y",xe(l,t.REACH.line,e=>Math.abs(e)<=l),e=>Math.exp(-e*e/(2*s*s)),i)},at_sharpen:function(e,t,r,n,o,a,s){const i=(e,n)=>4*($e(n,r-1)*t+$e(e,t-1)),l=i(n,o),c=i(n-1,o),h=i(n+1,o),u=i(n,o-1),p=i(n,o+1);for(let t=0;t<3;t++)s[t]=e[l+t]+a*(4*e[l+t]-e[c+t]-e[h+t]-e[u+t]-e[p+t]);return s},col_fromhsl:function(e,t,r,n){const o=(1-Math.abs(2*r-1))*t;return n[0]=r-.5*o+o*We(e,0),n[1]=r-.5*o+o*We(e,2/3),n[2]=r-.5*o+o*We(e,1/3),n},col_fromhsv:function(e,t,r,n){return n[0]=r*(1+(We(e,0)-1)*t),n[1]=r*(1+(We(e,2/3)-1)*t),n[2]=r*(1+(We(e,1/3)-1)*t),n},col_fromlab:function(e,t,r,n){const o=(100*e+16)/116,a=o-256*(r-.5)/200,s=.95047*Xe(o+256*(t-.5)/500),i=Xe(o),l=1.08883*Xe(a),c=Math.min(Math.max(3.2404542*s-1.5371385*i-.4985314*l,0),1),h=Math.min(Math.max(-.969266*s+1.8760108*i+.041556*l,0),1),u=Math.min(Math.max(.0556434*s-.2040259*i+1.0572252*l,0),1);return n[0]=Ge(c),n[1]=Ge(h),n[2]=Ge(u),n},col_fromlinear:function(e,t,r,n){return n[0]=Ge(e),n[1]=Ge(t),n[2]=Ge(r),n},col_fromoklab:function(e,t,r,n){let o=e+.3963377774*(t-=.5)+.2158037573*(r-=.5),a=e-.1055613458*t-.0638541728*r,s=e-.0894841775*t-1.291485548*r;o*=o*o,a*=a*a,s*=s*s;const i=Math.min(Math.max(4.0767416621*o-3.3077115913*a+.2309699292*s,0),1),l=Math.min(Math.max(-1.2684380046*o+2.6097574011*a-.3413193965*s,0),1),c=Math.min(Math.max(-.0041960863*o-.7034186147*a+1.707614701*s,0),1);return n[0]=Ge(i),n[1]=Ge(l),n[2]=Ge(c),n},col_fromycbcr:function(e,t,r,n){return t-=.5,r-=.5,n[0]=e+1.402*r,n[1]=e-.344136*t-.714136*r,n[2]=e+1.772*t,n},col_tohsl:function(e,t,r,n){const o=Math.max(e,t,r),a=Math.min(e,t,r),s=o-a,i=.5*(o+a);return n[0]=s>0?He(e,t,r,o,s):0,n[1]=s>0?s/(1-Math.abs(2*i-1)):0,n[2]=i,n},col_tohsv:function(e,t,r,n){const o=Math.max(e,t,r),a=o-Math.min(e,t,r);return n[0]=a>0?He(e,t,r,o,a):0,n[1]=o>0?a/o:0,n[2]=o,n},col_tolab:function(e,t,r,n){const o=Le(e),a=Le(t),s=Le(r),i=qe((.4124564*o+.3575761*a+.1804375*s)/.95047),l=qe(.2126729*o+.7151522*a+.072175*s),c=qe((.0193339*o+.119192*a+.9503041*s)/1.08883);return n[0]=(116*l-16)/100,n[1]=.5+500*(i-l)/256,n[2]=.5+200*(l-c)/256,n},col_tolinear:function(e,t,r,n){return n[0]=Le(e),n[1]=Le(t),n[2]=Le(r),n},col_tooklab:function(e,t,r,n){const o=Le(e),a=Le(t),s=Le(r),i=Math.cbrt(.4122214708*o+.5363325363*a+.0514459929*s),l=Math.cbrt(.2119034982*o+.6806995451*a+.1073969566*s),c=Math.cbrt(.0883024619*o+.2817188376*a+.6299787005*s);return n[0]=.2104542553*i+.793617785*l-.0040720468*c,n[1]=.5+1.9779984951*i-2.428592205*l+.4505937099*c,n[2]=.5+.0259040371*i+.7827717662*l-.808675766*c,n},col_toycbcr:function(e,t,r,n){const o=.299*e+.587*t+.114*r;return n[0]=o,n[1]=.5+.5643*(r-o),n[2]=.5+.7132*(e-o),n},convolve:function(e,t,r,n,o,a,s,i,l,c,h,u,p,f,m){const d=(e,a)=>4*($e(o+a,r-1)*t+$e(n+e,t-1)),g=[[a,-1,-1],[s,0,-1],[i,1,-1],[l,-1,0],[c,0,0],[h,1,0],[u,-1,1],[p,0,1],[f,1,1]];for(let t=0;t<3;t++){let r=0;for(const[n,o,a]of g)r+=n*e[d(o,a)+t];m[t]=r}return m},factorial:function(e){let t=1;for(let r=2;r<=170&&!(r>e);r++)t*=r;return t},fmod:ye,gcd:function(e,t){e=Math.abs(e),t=Math.abs(t);for(let r=0;r<64&&0!==t;r++){const r=ye(e,t);e=t,t=r}return e},perm:function(e,t){let r=1;for(let n=0;n<170&&!(n>=t);n++)r*=e-n;return r},picture:function(e,t,r,n,o,a,s,i,l,c,h,u,p){let f,m;0===c?f=m=Math.max(n/t,o/r):1===c?f=m=Math.min(n/t,o/r):2===c?(f=n/t,m=o/r):f=m=1,f*=a,m*=a;const d=h+.5-s*n,g=u+.5-i*o,w=Math.cos(l),y=Math.sin(l);let $=(w*d+y*g)/f+.5*t,b=(w*g-y*d)/m+.5*r;if(3===c)$=ye($,t),b=ye(b,r);else if($<0||b<0||$>t||b>r)return p[0]=p[1]=p[2]=p[3]=0,p;return be(e,t,r,$-.5,b-.5,p)},placeCode:we,plane_blur:function(e,r,n,o,a,s){return je(e,r,n,o,a,s,["x","y"],t.REACH.square)},plane_blurx:function(e,r,n,o,a,s){return je(e,r,n,o,a,s,["x"],t.REACH.line)},plane_blury:function(e,r,n,o,a,s){return je(e,r,n,o,a,s,["y"],t.REACH.line)},plane_dilate:function(e,t,r,n,o,a){return Fe(e,t,r,n,o,a,0,!0)},plane_emboss:function(e,t,r,n,o){return Ce(e,t,r,n,o,Ne)},plane_erode:function(e,t,r,n,o,a){return Fe(e,t,r,n,o,a,1,!1)},plane_gaussian:function(e,r,n,o,a,s){return Se(e,r,n,o,a,s,["x","y"],t.REACH.square)},plane_gaussianx:function(e,r,n,o,a,s){return Se(e,r,n,o,a,s,["x"],t.REACH.line)},plane_gaussiany:function(e,r,n,o,a,s){return Se(e,r,n,o,a,s,["y"],t.REACH.line)},plane_laplacian:function(e,t,r,n,o){return Ce(e,t,r,n,o,Ue)},plane_sharpen:function(e,t,r,n,o,a){const s=new Float32Array(t*r*3);for(let i=n;i<o;i++)for(let n=0;n<t;n++){const o=(e,n)=>4*($e(n,r-1)*t+$e(e,t-1)),l=o(n,i),c=o(n-1,i),h=o(n+1,i),u=o(n,i-1),p=o(n,i+1);for(let r=0;r<3;r++)s[3*(i*t+n)+r]=e[l+r]+a*(4*e[l+r]-e[c+r]-e[h+r]-e[u+r]-e[p+r])}return s},plane_sobel:function(e,t,r,n,o){return Ce(e,t,r,n,o,ze)},plane_sobelx:function(e,t,r,n,o){return Ce(e,t,r,n,o,Re)},plane_sobely:function(e,t,r,n,o){return Ce(e,t,r,n,o,Ie)},random:function(e,t,r,n){const o=43758.5453*Math.sin(12.9898*(e+.5)+78.233*(r-t-.5)+37.719*n);return o-Math.floor(o)},root:function(e,t){return 2===e?Math.sqrt(t):3===e?Math.sign(t)*Math.pow(Math.abs(t),1/3):Math.pow(t,1/e)},round:function(e,t){const r=Math.pow(10,t);return Math.sign(e)*Math.floor(Math.abs(e)*r+.5)/r},sample:be,sampleOrZero:function(e,t,r,n,o,a){const s=n+.5,i=o+.5;return s<0||i<0||s>t||i>r?(a[0]=a[1]=a[2]=a[3]=0,a):be(e,t,r,n,o,a)},scratch:function(){return new Float64Array(4)},smoothstep:function(e,t,r){const n=Math.min(Math.max((r-e)/(t-e),0),1);return n*n*(3-2*n)}});const Ve="\\:",Ye=Object.keys(Je).filter(e=>"function"==typeof Je[e]),Ze=e=>Object.assign(Object.create(null),e),Ke=Ze({r:"$r",g:"$g",b:"$b",a:"$a",x:"$x",y:"$y",px:"$px",py:"$py",w:"$w",h:"$h",t:"$t",gray:"$gray"}),Qe=Ze({pi:"Math.PI","π":"Math.PI",e:"Math.E",tau:"(2 * Math.PI)","τ":"(2 * Math.PI)","∞":"Infinity","-∞":"(-Infinity)","°":"(Math.PI / 180)"}),et=Ze({sqrt:1,abs:1,floor:1,ceil:1,ln:"log",sin:1,cos:1,tan:1,arcsin:"asin",arccos:"acos",arctan:"atan",sinh:1,cosh:1,tanh:1,arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",sign:1,exp:1,exp2:e=>`Math.pow(2, ${e})`,log2:1,expm1:e=>`(Math.exp(${e}) - 1)`,loglog:e=>`Math.log(Math.log(${e}))`,logloglog:e=>`Math.log(Math.log(Math.log(${e})))`,csc:e=>`(1 / Math.sin(${e}))`,sec:e=>`(1 / Math.cos(${e}))`,cot:e=>`(1 / Math.tan(${e}))`,fract:e=>`(${e} - Math.floor(${e}))`,radians:e=>`(${e} * 0.017453292519943295)`,degrees:e=>`(${e} * 57.29577951308232)`,inversesqrt:e=>`(1 / Math.sqrt(${e}))`,arcsec:e=>`Math.acos(1 / ${e})`,arccsc:e=>`Math.asin(1 / ${e})`,arccot:e=>`(Math.PI / 2 - Math.atan(${e}))`,atan2:(e,t)=>`Math.atan2(${e}, ${t})`,pow:(e,t)=>`Math.pow(${e}, ${t})`,mod:(e,t)=>`(${e} - ${t} * Math.floor(${e} / ${t}))`,step:(e,t)=>`(${t} < ${e} ? 0 : 1)`,clamp:(e,t,r)=>`Math.min(Math.max(${e}, ${t}), ${r})`,mix:(e,t,r)=>`(${e} + (${t} - ${e}) * ${r})`,smoothstep:(e,t,r)=>`$h_smoothstep(${e}, ${t}, ${r})`}),tt=Ze({atan2:2,pow:2,mod:2,step:2,clamp:3,mix:3,smoothstep:3});const rt=Ze({blur:3,blurx:3,blury:3,gaussian:3,gaussianx:3,gaussiany:3,dilate:3,erode:3,sharpen:3,sobel:1,sobelx:1,sobely:1,laplacian:1,emboss:1}),nt=(e,t)=>({kind:e,c:t}),ot=e=>nt("f",[e]),at=e=>nt("b",[e]),st=e=>1===e.length?ot(e[0]):nt("v",e),it=(e,t=0)=>"b"===e.kind?`(${e.c[0]} ? 1 : 0)`:"f"===e.kind?e.c[0]:e.c[t]??e.c[0],lt=e=>"v"===e.kind?e.c.length:1;class ct extends Error{}function ht(e){if(e.blendKept)return{blend:!0,source:""};const o=e.params??{},a=new Set([...Object.keys(e.placements??{}),"source","selection"]),s=new ut(o,a,e.space??"srgb");s.graphics=new Set(Object.keys(e.graphics??{})),s.bind=Ze(e.bind??{});const i="string"==typeof e.color?{rgba:e.color}:e.color,l=(n,s)=>{const i=[...t.FILTER_FUNCTIONS,...Object.keys(e.placements??{})],l=[...t.FILTER_VALUES,...Object.keys(o)];return t.filterPictureCalls(r.parseTree(n,{names:i,values:l,blocks:null}),a,{whole:s})};for(const e of["rgba","rgb","r","g","b","a"]){if(!i[e])continue;let t;try{t=l(i[e],"rgba"===e)}catch(e){throw new ct(e.message)}s.channel(e,t)}const c=s.source();n.checkGeneratedJs(c,{variables:/^\$\w+$/,indexable:/^\$[A-Z]\w*$/,strings:!1});const h=new Function(...s.parameters(),c);return{source:c,uses:s.uses,pictures:[...s.pictureNames],run(e){h(...s.arguments(e))}}}class ut{constructor(e,t,r="srgb"){this.params=e,this.pictures=t,this.space="srgb"===r?null:r,this.pre=[],this.body=[],this.n=0,this.uses=new Set,this.pictureNames=new Set,this.perPixel=new Map,this.planes=new Map,this.scratch=0}temp(e,t=this.body){const r="$v"+this.n++;return t.push(`let ${r} = ${e};`),r}keep(e,t=this.body){return nt(e.kind,e.c.map(e=>/^[\w$.]+$|^\(?-?[\d.e+]+\)?$/.test(e)?e:this.temp(e,t)))}fail(e){throw new ct(e)}leaf(e){if("number"===e.type)return ot(`(${e.value.replace(/\.+$/,"")})`);"string"===e.type&&this.fail("a filter has no text: numbers and colors only");const t=e.value,r=/^(-?(?:\d+\.?\d*|\.\d+))%$/.exec(t);if(r)return ot(`(${r[1]} / 100)`);if("t"===t&&this.uses.add("t"),Ke[t])return ot(Ke[t]);if("rgb"===t)return st(["$r","$g","$b"]);if("unchanged"===t)return ot("$u");if("selected"===t)return ot(this.pictureHere("selection").c[0]);if(Qe[t])return ot(Qe[t]);if("true"===t||"false"===t)return at(t);if(Object.prototype.hasOwnProperty.call(this.params,t)){const e=`$p_${t}`;return"color"===this.params[t].type?st([`${e}_0`,`${e}_1`,`${e}_2`]):ot(e)}if(this.pictures.has(t)){const e=this.pictureHere(t);return st(e.c.slice(0,3))}if(t.startsWith("mz_px_")&&this.pictures.has(t.slice(6)))return this.pictureHere(t.slice(6));this.fail(`unknown name "${t}"`)}pictureHere(e){if(!this.perPixel.has(e)){const t=this.sampler(e,"$px","$py");this.perPixel.set(e,this.keep(t))}return this.perPixel.get(e)}sampler(e,t,r){const n=this.scratchArray();return"source"===e?(this.uses.add("source"),this.body.push(`$h_sample($S, $w, $h, ${t}, ${r}, ${n});`)):(this.pictureNames.add(e),this.body.push(`$h_picture($Q_${e}, $qw_${e}, $qh_${e}, $w, $h, $qz_${e}, $qx_${e}, $qy_${e}, $qa_${e}, $qm_${e}, ${t}, ${r}, ${n});`)),this.space&&"selection"!==e&&this.body.push(`$h_col_to${this.space}(${n}[0], ${n}[1], ${n}[2], ${n});`),st([0,1,2,3].map(e=>`${n}[${e}]`))}scratchArray(){const e="$T"+this.scratch++;return this.pre.push(`let ${e} = $h_scratch();`),e}value(e){return"op"===e.type?this.op(e):this.leaf(e)}op(e){const{op:t,args:r}=e,n=t.startsWith(Ve)?t.slice(2):null;if(null!==n)return this.call(n,r,e);const o=()=>r.map(e=>this.value(e));switch(t){case"+":case"-":case"*":case"/":{const[e,r]=o();return this.componentwise([e,r],(e,r)=>`(${e} ${t} ${r})`)}case"neg":return this.componentwise(o(),e=>`(-${e})`);case"^":return this.power(r);case"mod":return this.componentwise(o(),et.mod);case"<":case">":case"≤":case"≥":{const[e,r]=o(),n={"≤":"<=","≥":">="}[t]??t;return at(`(${it(e)} ${n} ${it(r)})`)}case"=":case"===":case"≠":case"≠=":case"≡":{const[e,r]=o(),n=Math.max(lt(e),lt(r)),a=Array.from({length:n},(t,n)=>`${it(e,n)} === ${it(r,n)}`).join(" && ");return at("≠"===t||"≠="===t?`!(${a})`:`(${a})`)}case"≈":{const[e,t]=o();return at(`(Math.abs(${it(e)} - ${it(t)}) < 1e-5)`)}case"&":{const[e,t]=o();return at(`(${this.truth(e)} && ${this.truth(t)})`)}case"|":{const[e,t]=o();return at(`(${this.truth(e)} || ${this.truth(t)})`)}case"\\xor":{const[e,t]=o();return at(`(${this.truth(e)} !== ${this.truth(t)})`)}case"\\nand":{const[e,t]=o();return at(`!(${this.truth(e)} && ${this.truth(t)})`)}case"\\nor":{const[e,t]=o();return at(`!(${this.truth(e)} || ${this.truth(t)})`)}case"\\implies":{const[e,t]=o();return at(`(!${this.truth(e)} || ${this.truth(t)})`)}case"\\iff":{const[e,t]=o();return at(`(${this.truth(e)} === ${this.truth(t)})`)}case"\\not":{const[e]=o();return at(`!${this.truth(e)}`)}case"?:":return this.ternary(r);case"max":case"min":return this.componentwise(o(),(...e)=>`Math.${t}(${e.join(", ")})`);case"sum":return this.componentwise(o(),(...e)=>`(${e.join(" + ")})`);case"prod":return this.componentwise(o(),(...e)=>`(${e.join(" * ")})`);case"mean":return this.componentwise(o(),(...e)=>`((${e.join(" + ")}) / ${e.length})`);case"()":case"[]":case"{}":case"(]":case"[)":{const e=o().flatMap(e=>"b"===e.kind?[it(e)]:e.c.map((t,r)=>it(e,r)));return e.length>4&&this.fail("a color has at most 4 values (r, g, b, a)"),st(e)}case"!":return this.componentwise(o(),e=>`$h_factorial(${e})`);case"perm":return this.componentwise(o(),(e,t)=>`$h_perm(${e}, ${t})`);case"comb":return this.componentwise(o(),(e,t)=>`($h_perm(${e}, ${t}) / $h_factorial(${t}))`);case"gcd":return this.componentwise(o(),(...e)=>e.reduce((e,t)=>`$h_gcd(${e}, ${t})`));case"round":{const[e,t]=o();return this.componentwise([e,t],(e,t)=>`$h_round(${e}, ${t})`)}case"log":{const[e,t]=o();return this.componentwise([e,t],(e,t)=>`(Math.log(${t}) / Math.log(${e}))`)}case"root":{const[e,t]=o();return this.componentwise([e,t],(e,t)=>`$h_root(${e}, ${t})`)}case"∈":case"∉":{const t=function(e){const[t,r]=e.args;if("op"!==r.type||"setbuilder"!==r.op)return null;let[n,o]=r.args,a=null;"op"===n.type&&"∈"===n.op&&([n,a]=n.args);const s=e=>"symbol"===e.type&&e.value===n.value?t:"op"===e.type?{...e,args:e.args.map(s)}:e,i=a?{type:"op",op:"&",args:[{type:"op",op:"∈",args:[t,a]},s(o)]}:s(o);return"∉"===e.op?{type:"op",op:"\\not",args:[i]}:i}(e);return t?this.value(t):this.membership(e)}case"random":return this.random();case"evaluated":return this.value(function(e){const[t,r,n,o]=e.args,a=(e,t)=>"symbol"===e.type&&e.value===r.value?t:"op"===e.type?{...e,args:e.args.map(e=>a(e,t))}:e;return{type:"op",op:"-",args:[a(t,o),a(t,n)]}}(e));case"_":{const[e,t]=r;if("symbol"===e.type&&("number"===t.type||"symbol"===t.type))return this.leaf({type:"symbol",value:`${e.value}_${t.value}`});break}}if(et[t])return this.builtin(t,o());this.fail(`"${t}" isn't available in a filter`)}truth(e){return"b"===e.kind?e.c[0]:`(${it(e)} !== 0)`}componentwise(e,t){const r=e.map(lt),n=Math.max(...r),o=new Set(r.filter(e=>e>1));o.size>1&&this.fail(`can't combine vectors of ${[...o].join(" and ")} values`);const a=Array.from({length:n},(r,n)=>t(...e.map(e=>it(e,n))));return this.keep(st(a))}builtin(e,t){const r=et[e];if(tt[e]&&t.length!==tt[e]&&this.fail(`${e}() takes ${tt[e]} values`),"function"==typeof r)return this.componentwise(t,r);const n=1===r?e:r;return this.componentwise(t,(...e)=>`Math.${n}(${e.join(", ")})`)}power([e,t]){const r="number"===t.type&&/^-?\d+$/.test(t.value)?Number(t.value):null,n=this.keep(this.value(e)),o=e=>this.componentwise([n],t=>Array(e).fill(t).join(" * "));return 0===r?this.componentwise([n],()=>"1"):null!==r&&r>=1&&r<=4?o(r):null!==r&&r<=-1&&r>=-4?this.componentwise([o(-r)],e=>`(1 / ${e})`):"symbol"===e.type&&"e"===e.value?this.componentwise([this.value(t)],e=>`Math.exp(${e})`):"number"===e.type&&"2"===e.value?this.componentwise([this.value(t)],e=>`Math.pow(2, ${e})`):this.componentwise([n,this.value(t)],(e,t)=>`Math.pow(${e}, ${t})`)}ternary([e,t,r]){const n=this.truth(this.value(e)),o=e=>"symbol"===e.type&&"unchanged"===e.value;let a=o(t)?null:this.value(t),s=o(r)?null:this.value(r);const i=e=>"b"===e.kind?at("($u > 0.5)"):"f"===e.kind?ot("$u"):st(["$k0","$k1","$k2","$k3"].slice(0,4===e.c.length?4:3));if(!a&&!s)return ot("$u");if(a||(a=i(s)),s||(s=i(a)),"b"===a.kind&&"b"===s.kind)return at(this.temp(`(${n} ? ${a.c[0]} : ${s.c[0]})`));const l=Math.max(lt(a),lt(s)),c=Array.from({length:l},(e,t)=>this.temp(`(${n} ? ${it(a,t)} : ${it(s,t)})`));return st(c)}membership(e){const[t,r]=e.args,n=it(this.value(t)),o="∉"===e.op;let a;if("op"===r.type&&["()","[]","(]","[)"].includes(r.op)&&2===r.args.length){const[e,t]=r.args.map(e=>it(this.value(e)));a=`(${n} ${"["===r.op[0]?">=":">"} ${e} && ${n} ${"]"===r.op[1]?"<=":"<"} ${t})`}else"op"===r.type&&"{}"===r.op?a=r.args.length?`(${r.args.map(e=>`${n} === ${it(this.value(e))}`).join(" || ")})`:"false":"symbol"===r.type&&["ℝ","ℤ","ℕ"].includes(r.value)?a={"ℝ":`Number.isFinite(${n})`,"ℤ":`Number.isInteger(${n})`,"ℕ":`(Number.isInteger(${n}) && ${n} > 0)`}[r.value]:this.fail("∈ needs an interval [a, b], a set {…}, ℝ, ℤ or ℕ");return at(o?`!${a}`:a)}random(){return this.uses.add("random"),ot(this.temp("$h_random($px, $py, $h, ++$seed)"))}call(e,t,r){const n=()=>t.map(e=>this.value(e));if(e.startsWith("mz_sample_")){const t=e.slice(10),[r,o]=n(),[a,s]=o?[it(r),it(o)]:[it(r,0),it(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),this.keep(st([0,1,2,3].map(t=>`${e}[${t}]`)))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep(this.sampler(t,a,s))}if(e.startsWith("mz_at_")){const t=e.slice(6),[r,o]=n(),[a,s]=o?[it(r),it(o)]:[it(r,0),it(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),st([0,1,2].map(t=>`${e}[${t}]`))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep(st(this.sampler(t,a,s).c.slice(0,3)))}if(e.startsWith("mz_width_")||e.startsWith("mz_height_")){const t=e.replace(/^mz_(width|height)_/,"");return this.pictureNames.add(t),ot(e.startsWith("mz_width_")?`$qw_${t}`:`$qh_${t}`)}switch(e){case"pixel":{const[e,t]=n().map(e=>it(e)),r=this.scratchArray();return this.body.push(`$h_sample($I, $w, $h, ${e}, ${t}, ${r});`),this.keep(st([0,1,2,3].map(e=>`${r}[${e}]`)))}case"red":case"green":case"blue":case"alpha":case"luma":{let r;2===t.length?r=this.call("pixel",t):1===t.length?r=this.value(t[0]):this.fail(`${e}() takes a color, or a position px, py`);const n={red:0,green:1,blue:2,alpha:3}[e];return"luma"===e?ot(`(${it(r,0)} * 0.299 + ${it(r,1)} * 0.587 + ${it(r,2)} * 0.114)`):"alpha"===e&&3===lt(r)?ot("1"):ot(it(r,n))}case"length":{const[e]=n();return ot(`Math.sqrt(${e.c.map((t,r)=>`${it(e,r)} * ${it(e,r)}`).join(" + ")})`)}case"distance":{const[e,t]=n(),r=this.componentwise([e,t],(e,t)=>`(${e} - ${t})`);return ot(`Math.sqrt(${r.c.map(e=>`${e} * ${e}`).join(" + ")})`)}case"dot":{const[e,t]=n(),r=Math.max(lt(e),lt(t));return ot(`(${Array.from({length:r},(r,n)=>`${it(e,n)} * ${it(t,n)}`).join(" + ")})`)}case"normalize":{const[e]=n(),t=this.temp(`Math.sqrt(${e.c.map((t,r)=>`${it(e,r)} * ${it(e,r)}`).join(" + ")})`);return this.componentwise([e],e=>`(${e} / ${t})`)}case"cross":{const[e,t]=n();3===lt(e)&&3===lt(t)||this.fail("cross() takes two colors (3 values each)");const[r,o,a]=e.c,[s,i,l]=t.c;return this.keep(st([`(${o} * ${l} - ${a} * ${i})`,`(${a} * ${s} - ${r} * ${l})`,`(${r} * ${i} - ${o} * ${s})`]))}case"convolve":{const e=n().map(e=>it(e));9!==e.length&&this.fail("convolve() takes 9 numbers: the 3×3 kernel, row by row");const t=this.scratchArray();return this.body.push(`$h_convolve($I, $w, $h, $px, $py, ${e.join(", ")}, ${t});`),st([0,1,2].map(e=>`${t}[${e}]`))}case"mz_zoom":case"mz_shift":case"mz_rotate":case"mz_crop":case"mz_tile":case"mz_flipx":case"mz_flipy":return this.geometry(e.slice(3),n().map(e=>it(e)));case"tolinear":case"fromlinear":case"tohsv":case"fromhsv":case"tohsl":case"fromhsl":case"tolab":case"fromlab":case"tooklab":case"fromoklab":case"toycbcr":case"fromycbcr":{const t=n(),r=3===t.length?t.map(e=>it(e)):[0,1,2].map(e=>it(t[0],e));1!==t.length&&3!==t.length&&this.fail(`${e}() takes a color`);const o=this.scratchArray();return this.body.push(`$h_col_${e}(${r.join(", ")}, ${o});`),this.keep(st([0,1,2].map(e=>`${o}[${e}]`)))}case"random":return this.random();case"exp":case"exp2":case"log2":case"sign":case"fract":case"radians":case"degrees":case"inversesqrt":case"pow":case"mod":case"step":case"clamp":case"mix":case"smoothstep":case"abs":case"floor":case"ceil":case"sqrt":case"sin":case"cos":case"tan":return this.builtin(e,n());case"asin":return this.builtin("arcsin",n());case"acos":return this.builtin("arccos",n());case"atan":return 2===t.length?this.builtin("atan2",n()):this.builtin("arctan",n());case"log":return this.builtin("ln",n());case"max":case"min":return this.componentwise(n(),(...t)=>`Math.${e}(${t.join(", ")})`)}if(rt[e])return this.neighborhood(e,t);this.fail(`unknown function "${e}"`)}geometry(e,t){const r=(e,t)=>this.keep(st([e,t]));switch(e){case"zoom":{const[e,n="0.5",o="0.5"]=t,a=r(`(${n} * $w - 0.5)`,`(${o} * $h - 0.5)`);return r(`(${a.c[0]} + ($px - ${a.c[0]}) / ${e})`,`(${a.c[1]} + ($py - ${a.c[1]}) / ${e})`)}case"shift":{const[e,n]=t;return r(`($h_fmod($px - ${e} + 0.5, $w) - 0.5)`,`($h_fmod($py - ${n} + 0.5, $h) - 0.5)`)}case"rotate":{const[e,n="0.5",o="0.5"]=t,a=r(`(${n} * $w - 0.5)`,`(${o} * $h - 0.5)`),s=r(`($px - ${a.c[0]})`,`($py - ${a.c[1]})`),i=this.keep(st([`Math.cos(${e})`,`Math.sin(${e})`]));return r(`(${a.c[0]} + ${i.c[0]} * ${s.c[0]} + ${i.c[1]} * ${s.c[1]})`,`(${a.c[1]} + ${i.c[0]} * ${s.c[1]} - ${i.c[1]} * ${s.c[0]})`)}case"crop":{const[e,n,o,a]=t;return r(`((${e} + (${o} - ${e}) * ($px + 0.5) / $w) * $w - 0.5)`,`((${n} + (${a} - ${n}) * ($py + 0.5) / $h) * $h - 0.5)`)}case"tile":{const[e,n=e]=t;return r(`($h_fmod(($px + 0.5) * ${e}, $w) - 0.5)`,`($h_fmod(($py + 0.5) * ${n}, $h) - 0.5)`)}case"flipx":return r("($w - 1 - $px)","$py");case"flipy":return r("$px","($h - 1 - $py)")}this.fail(`unknown geometry ${e}`)}neighborhood(e,t){const r=rt[e];if(t.every(e=>this.isUniform(e))){const n=t.map(e=>it(this.uniformValue(e))),o=`${e}(${n.join(",")})`;if(!this.planes.has(o)){const t=`$N${this.planes.size}`;this.pre.push(`let ${t} = $h_plane_${e}($I, $w, $h, $y0, $y1${n.map(e=>`, ${e}`).join("")});`),this.planes.set(o,t)}const a=this.planes.get(o);return 3===r?st([0,1,2].map(e=>`${a}[$j3 + ${e}]`)):ot(`${a}[$j]`)}const n=t.map(e=>it(this.value(e)));if(1===r)return ot(this.temp(`$h_at_${e}($I, $w, $h, $px, $py${n.map(e=>`, ${e}`).join("")})`));const o=this.scratchArray();return this.body.push(`$h_at_${e}($I, $w, $h, $px, $py${n.map(e=>`, ${e}`).join("")}, ${o});`),st([0,1,2].map(e=>`${o}[${e}]`))}isUniform(e){return"number"===e.type||("symbol"===e.type?["w","h","t"].includes(e.value)||Boolean(Qe[e.value])||Object.prototype.hasOwnProperty.call(this.params,e.value)&&"color"!==this.params[e.value].type:"op"===e.type&&!e.op.startsWith(Ve)&&"random"!==e.op&&e.args.every(e=>this.isUniform(e)))}uniformValue(e){const t=this.body;this.body=this.pre;try{return this.value(e)}finally{this.body=t}}channel(e,t){const r="rgba"===e||"rgb"===e?"$gray":`$c${"rgba".indexOf(e)}`;this.body.push(`$u = ${r}; $k0 = $c0; $k1 = $c1; $k2 = $c2; $k3 = $c3;`);const n=this.value(t),o=lt(n),a=e=>it(n,e);if("rgba"===e){2===o&&this.fail("a color is one number (gray), three (r, g, b) or four (r, g, b, a) — not two");const e=1===o?[a(0),a(0),a(0),"1"]:3===o?[a(0),a(1),a(2),"1"]:[0,1,2,3].map(a);this.body.push(`$c0 = ${e[0]}; $c1 = ${e[1]}; $c2 = ${e[2]}; $c3 = ${e[3]};`)}else if("rgb"===e){2===o&&this.fail("a color is one number (gray), three (r, g, b) or four — not two");const e=1===o?[a(0),a(0),a(0)]:[a(0),a(1),a(2)];this.body.push(`$c0 = ${e[0]}; $c1 = ${e[1]}; $c2 = ${e[2]};`)}else{const t="rgba".indexOf(e),r=1===o?a(0):3===o&&"a"===e?"1":a(t);this.body.push(`$c${t} = ${r};`)}}parameters(){return["$I","$O","$S","$w","$h","$t","$P","$op","$y0","$y1",...[...this.pictureNames].flatMap(e=>[`$Q_${e}`,`$qw_${e}`,`$qh_${e}`,`$qz_${e}`,`$qx_${e}`,`$qy_${e}`,`$qa_${e}`,`$qm_${e}`]),...Ye.map(e=>`$h_${e}`)]}arguments(e){const t=[...this.pictureNames];return[e.input,e.output,e.source,e.width,e.height,e.t,e.params,e.opacity,e.y0??0,e.y1??e.height,...t.flatMap(t=>{const r=e.pictures[this.bind?.[t]??t]??(this.graphics?.has(t)?de:me),n=e.placements[t]??{};return[r.data,r.width,r.height,Number(n.zoom??1),Number(n.x??.5),Number(n.y??.5),Number(n.angle??0),we(n.place)]}),...Ye.map(e=>Je[e])]}source(){return[...Object.entries(this.params).map(([e,t],r)=>"color"===t.type?`let $p_${e}_0 = $P[${r}][0], $p_${e}_1 = $P[${r}][1], $p_${e}_2 = $P[${r}][2];`:`let $p_${e} = $P[${r}];`).map(e=>e.replace(/\$P\[(\d+)\]\[(\d)\]/g,"$h_at($P, $1, $2)")),"let $u = 0, $k0 = 0, $k1 = 0, $k2 = 0, $k3 = 0, $seed = 0, $CS = $h_scratch();",...this.pre,"for (let $py = $y0; $py < $y1; $py++) {"," for (let $px = 0; $px < $w; $px++) {"," let $j = $py * $w + $px, $j3 = $j * 3, $j4 = $j * 4;"," let $r = $I[$j4], $g = $I[$j4 + 1], $b = $I[$j4 + 2], $a = $I[$j4 + 3];"," let $c0 = $r, $c1 = $g, $c2 = $b, $c3 = $a;"," let $x = ($px + 0.5) / $w, $y = ($py + 0.5) / $h;",this.space?` $h_col_from${this.space}($r, $g, $b, $CS); let $gray = $CS[0] * 0.299 + $CS[1] * 0.587 + $CS[2] * 0.114;`:" let $gray = $r * 0.299 + $g * 0.587 + $b * 0.114;"," $seed = $t;",...this.body.map(e=>` ${e}`)," $O[$j4] = $r + ($c0 - $r) * $op;"," $O[$j4 + 1] = $g + ($c1 - $g) * $op;"," $O[$j4 + 2] = $b + ($c2 - $b) * $op;"," $O[$j4 + 3] = $a + ($c3 - $a) * $op;"," }","}"].join("\n")}}function pt(e,t={}){const r="float"===t.precision||"half"===t.precision?"float":"byte",n=e.passes.map(e=>ht(e)),a={};let s=null;const i=t.parallelFrom??25e4,l=void 0===t.workers||"auto"===t.workers?function(){const e="undefined"!=typeof navigator&&navigator.hardwareConcurrency?navigator.hardwareConcurrency:4;return Math.max(0,Math.min(8,e-1))}():Number(t.workers);let c=null,h=null,u=new Map;const p={passes:e.passes,get precision(){return r},sources:n.map(e=>e.source),setImage(e,t){"string"!=typeof e&&(t=e,e=null);const r=mt(t);return e&&"source"!==e?a[e]=r:s=r,p},draw({t:t=0,canvas:o=null}={}){if(!s)throw new Error("setImage() first");const{width:i,height:l}=s,c=i*l*4;let h=s.data;const u=[];e.passes.forEach((e,o)=>{for(let t=0;t<e.keepInput;t++)u.push(h);const p=new Float32Array(c);if(e.blendKept){const t=u.pop(),r=e.opacity;for(let e=0;e<c;e++)p[e]=t[e]+(h[e]-t[e])*r}else n[o].run({input:h,output:p,source:s.data,width:i,height:l,t:t,params:Object.keys(e.params??{}).map(t=>e.values[t]),opacity:e.opacity,pictures:a,placements:e.placements??{}});"byte"===r&&ft(p),h=p});const p=new Uint8ClampedArray(c);for(let e=0;e<c;e++){const t=h[e];p[e]=t>0?t<1?Math.round(255*t):255:0}const f={data:p,width:i,height:l};return o&&(o.width=i,o.height=l,o.getContext("2d").putImageData(new ImageData(p,i,l),0,0)),f},async drawAsync({t:n=0,canvas:f=null}={}){if(!s)throw new Error("setImage() first");const{width:m,height:d}=s;if(l<2||m*d<i)return p.draw({t:n,canvas:f});h??=async function(e,t,r){const n=new URL(r??"./cpu-worker.js",o&&"SCRIPT"===o.tagName.toUpperCase()&&o.src||new URL("qblur.external.global.min.js",document.baseURI).href);let a,s=()=>{};if("undefined"!=typeof Worker&&"undefined"!=typeof window){const e=n.origin===location.origin?n:URL.createObjectURL(new Blob([`import ${JSON.stringify(n.href)};`],{type:"text/javascript"}));e!==n&&(s=()=>URL.revokeObjectURL(e)),a=()=>{const t=new Worker(e,{type:"module"});return{send:e=>t.postMessage(e),on:e=>{t.onmessage=t=>e(t.data),t.onerror=t=>e({id:-1,ok:!1,error:t.message})},close:()=>t.terminate()}}}else try{const{Worker:e}=await(import("node:worker_threads"));a=()=>{const t=new e(n);return{send:e=>t.postMessage(e),on:e=>{t.on("message",e),t.on("error",t=>e({id:-1,ok:!1,error:t.message}))},close:()=>t.terminate()}}}catch{return null}const i=Array.from({length:e},a);let l=1;const c=i.map(()=>new Map);i.forEach((e,t)=>e.on(e=>{if(-1===e.id){for(const[,r]of c[t])r.reject(new Error(e.error));return void c[t].clear()}const r=c[t].get(e.id);r&&(c[t].delete(e.id),e.ok?r.resolve(e):r.reject(new Error(e.error)))}));const h=(e,t)=>new Promise((r,n)=>{const o=l++;c[e].set(o,{resolve:r,reject:n}),i[e].send({...t,id:o})}),u={size:e,shared:gt(),ask:h,broadcast:e=>Promise.all(i.map((t,r)=>h(r,e))),close:()=>{i.forEach(e=>e.close());for(const e of c){for(const[,t]of e)t.reject(new Error("The runner was disposed of while drawing"));e.clear()}}};try{await u.broadcast({type:"init",passes:t.map(({fragment:e,...t})=>t)})}catch(e){throw u.close(),e}finally{s()}return u}(l,e.passes,t.workerUrl).catch(()=>!1);const g=h,w=await g;if(g!==h)throw new Error("The runner was disposed of while drawing");if(c=w,!w)return p.draw({t:n,canvas:f});const y=m*d*4,$=()=>w.shared?new Float32Array(new SharedArrayBuffer(4*y)):new Float32Array(y);for(const[e,t]of[["source",s],...Object.entries(a)])u.get(e)!==t&&(await w.broadcast({type:"picture",name:e,picture:w.shared?wt(t):t}),u.set(e,t));let b=w.shared?wt(s).data:s.data;const x=[];for(let t=0;t<e.passes.length;t++){const o=e.passes[t];for(let e=0;e<o.keepInput;e++)x.push(b);const a=$();if(o.blendKept){const e=x.pop();for(let t=0;t<y;t++)a[t]=e[t]+(b[t]-e[t])*o.opacity;"byte"===r&&ft(a)}else{const e=Object.keys(o.params??{}).map(e=>o.values[e]),s=dt(d,w.size),i=await Promise.all(s.map(([s,i],l)=>w.ask(l,{type:"run",pass:t,input:b,output:w.shared?a:null,width:m,height:d,t:n,params:e,opacity:o.opacity,placements:o.placements??{},y0:s,y1:i,quantize:"byte"===r})));w.shared||i.forEach((e,t)=>a.set(e.band,s[t][0]*m*4))}b=a}const E=new Uint8ClampedArray(y);for(let e=0;e<y;e++){const t=b[e];E[e]=t>0?t<1?Math.round(255*t):255:0}const v={data:E,width:m,height:d};return f&&(f.width=m,f.height=d,f.getContext("2d").putImageData(new ImageData(E,m,d),0,0)),v},get workers(){return c?c.size:0},dispose(){s=null;for(const e of Object.keys(a))delete a[e];h&&h.then(e=>e&&e.close()),h=null,c=null,u=new Map}};return p}function ft(e){for(let t=0;t<e.length;t++){const r=e[t];e[t]=r>0?r<1?Math.round(255*r)/255:1:0}}function mt(e){if(e&&e.data&&e.width&&e.height){const t=e.data,r=t instanceof Float32Array||t instanceof Float64Array?1:1/255,n=new Float32Array(e.width*e.height*4);for(let e=0;e<n.length;e++)n[e]=t[e]*r;return{data:n,width:e.width,height:e.height}}if("undefined"!=typeof document||"undefined"!=typeof OffscreenCanvas){const t=e.naturalWidth||e.videoWidth||e.width,r=e.naturalHeight||e.videoHeight||e.height;if(!t||!r)throw new Error("setImage: the picture has no size yet (not loaded?)");const n=("undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,r):Object.assign(document.createElement("canvas"),{width:t,height:r})).getContext("2d",{willReadFrequently:!0});return n.drawImage(e,0,0,t,r),mt(n.getImageData(0,0,t,r))}throw new Error("setImage: give ImageData or { data, width, height }")}function dt(e,t){const r=[];for(let n=0;n<t;n++){const o=Math.floor(e*n/t),a=Math.floor(e*(n+1)/t);a>o&&r.push([o,a])}return r}const gt=()=>"undefined"!=typeof SharedArrayBuffer&&("undefined"==typeof crossOriginIsolated||!0===crossOriginIsolated);function wt(e){if(e.data.buffer instanceof(globalThis.SharedArrayBuffer??Object))return e;if(e.shared)return e.shared;const t=new Float32Array(new SharedArrayBuffer(e.data.byteLength));return t.set(e.data),e.shared={data:t,width:e.width,height:e.height},e.shared}function yt({webgl:e=!1,prefer:t="auto"}={}){return"cpu"===t?{engine:"cpu",reason:"asked for the CPU"}:e?{engine:"gpu",reason:"gpu"===t?"asked for the GPU":"WebGL is here"}:{engine:"cpu",reason:"no WebGL here"}}function $t(e,t={}){const r=yt({webgl:Boolean(t.gl),prefer:t.prefer});if("gpu"===r.engine)try{return{runner:he(t.gl,e,{precision:t.precision}),...r}}catch(r){if("gpu"===t.prefer)throw r;return{runner:pt(e,t),engine:"cpu",reason:`the GPU refused the shader (${r.message.split("\n")[0]})`}}return{runner:pt(e,t),...r}}const bt=[{name:"Wave",group:"Shape & motion",description:"Rows slide back and forth as t advances",params:{amplitude:{default:8,min:0,max:40},wavelength:{default:10,min:1,max:60},speed:{default:5,min:1,max:30}},color:"pixel(px + amplitude sin(py / wavelength + t / speed), py)"},{name:"Invert",group:"Color & tone",color:"(1 - r, 1 - g, 1 - b)"},{name:"Grayscale",group:"Color & tone",color:"gray"},{name:"Threshold",group:"Color & tone",params:{cutoff:.5},color:"if gray > cutoff then 1 else 0"},{name:"Posterize",group:"Color & tone",params:{levels:{default:4,min:2,max:16,step:1}},color:"min(floor(rgb * levels) / (levels - 1), 1)"},{name:"Brightness & contrast",group:"Color & tone",params:{brightness:{default:0,min:-.5,max:.5},contrast:{default:1,min:0,max:3}},color:"(rgb - 0.5) contrast + 0.5 + brightness"},{name:"Tint",group:"Color & tone",params:{tint:[1,.85,.7]},color:"rgb * tint"},{name:"Sepia",group:"Color & tone",color:"(0.393r + 0.769g + 0.189b, 0.349r + 0.686g + 0.168b, 0.272r + 0.534g + 0.131b)"},{name:"Color circle",group:"Color & tone",description:"Black and white, except a soft circle that keeps its color",params:{across:{default:.5,min:0,max:1,label:"where, across"},down:{default:.5,min:0,max:1,label:"where, down"},radius:{default:.3,min:0,max:1},softness:{default:.08,min:0,max:.5}},notes:["The color stays inside a circle and fades to gray over the softness. Sizes are parts of the picture's shorter side, so it stays round.",{param:"across"},{param:"down"},{param:"radius"},{param:"softness"}],color:"mix((gray, gray, gray), rgb, 1 - smoothstep(radius, radius + softness, distance((px, py), (across w, down h)) / min(w, h)))"},{name:"Vignette",group:"Color & tone",params:{strength:{default:1.6,min:0,max:4}},color:"rgb * (1 - strength ((x - 0.5)^2 + (y - 0.5)^2))"},{name:"Sobel edges",group:"Blur & edges",description:"How fast the brightness changes",params:{gain:{default:2,min:.2,max:10}},color:"gain sobel()"},{name:"Edge map",group:"Blur & edges",description:"White where an edge is stronger than the cutoff",params:{cutoff:{default:.3,min:0,max:2}},color:"if sobel() > cutoff then 1 else 0"},{name:"Outline",group:"Blur & edges",description:"Ink lines over the color",params:{gain:{default:3,min:0,max:10}},color:"rgb (1 - gain sobel())"},{name:"Box blur",group:"Blur & edges",params:{radius:{default:2,min:0,max:8,step:1}},color:"blur(radius)"},{name:"Gaussian blur",group:"Blur & edges",description:"Computed in two passes, across then down, so it can be wide",params:{sigma:{default:3,min:0,max:8}},color:"gaussian(sigma)"},{name:"Canny edges",group:"Blur & edges",description:"Thin, clean edge lines: smooth, gradient, thinning, two thresholds, hysteresis — a chain",steps:[{params:{sigma:{default:1.4,min:.5,max:4}},color:"gaussian(sigma)"},{color:"(min(sobel() / 4, 1), floor(fract((atan2(sobely(), sobelx()) + π/8) / π) 4) / 4, 0)"},{color:"if green(px, py) < 0.125 then (if r >= red(px - 1, py) & r >= red(px + 1, py) then r else 0) else if green(px, py) < 0.375 then (if r >= red(px + 1, py + 1) & r >= red(px - 1, py - 1) then r else 0) else if green(px, py) < 0.625 then (if r >= red(px, py - 1) & r >= red(px, py + 1) then r else 0) else (if r >= red(px - 1, py + 1) & r >= red(px + 1, py - 1) then r else 0)"},{params:{low:{default:.08,min:0,max:.5},high:{default:.2,min:0,max:1}},color:"if r > high then 1 else if r > low then 0.5 else 0"},"if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else 0"]},{name:"Sharpen",group:"Blur & edges",params:{amount:{default:.6,min:0,max:3}},color:"sharpen(amount)"},{name:"Unsharp mask",group:"Blur & edges",description:"The picture plus what a blur removes",params:{amount:{default:1.5,min:0,max:5},sigma:{default:2,min:.5,max:4}},color:"rgb + amount (rgb - gaussian(sigma))"},{name:"Bloom",group:"Blur & edges",description:"Bright parts glow",params:{amount:{default:.8,min:0,max:3},sigma:{default:3,min:.5,max:4},cutoff:{default:.6,min:0,max:1}},color:"rgb + amount max(gaussian(sigma) - cutoff, 0)"},{name:"Emboss",group:"Blur & edges",color:"emboss()"},{name:"Dilate",group:"Blur & edges",description:"Light areas grow",params:{radius:{default:2,min:0,max:8,step:1}},color:"dilate(radius)"},{name:"Erode",group:"Blur & edges",description:"Dark areas grow",params:{radius:{default:2,min:0,max:8,step:1}},color:"erode(radius)"},{name:"3×3 kernel",group:"Blur & edges",description:"Your own convolution; the default is a sharpen",params:{k1:{default:0,min:-8,max:8},k2:{default:-1,min:-8,max:8},k3:{default:0,min:-8,max:8},k4:{default:-1,min:-8,max:8},k5:{default:5,min:-8,max:8},k6:{default:-1,min:-8,max:8},k7:{default:0,min:-8,max:8},k8:{default:-1,min:-8,max:8},k9:{default:0,min:-8,max:8}},color:"convolve(k1, k2, k3, k4, k5, k6, k7, k8, k9)"},{name:"Pixelate",group:"Shape & motion",params:{size:{default:8,min:1,max:32,step:1}},color:"pixel(floor(px / size) size, floor(py / size) size)"},{name:"Mirror",group:"Shape & motion",color:"pixel(w - px, py)"},{name:"Scanlines",group:"Shape & motion",params:{period:{default:4,min:2,max:16,step:1}},color:"if py mod period < period / 2 then rgb else rgb * 0.6"},{name:"Pulse",group:"Shape & motion",description:"Brightness breathes with t",params:{speed:{default:6,min:1,max:30},depth:{default:.25,min:0,max:1}},color:"rgb (1 - depth + depth sin(t / speed))"},{name:"Chroma key",group:"Color & tone",description:"Replaces one color with another",params:{key:[.22,.71,.29],tolerance:{default:.35,min:0,max:1},background:[.1,.1,.4]},color:"if distance(rgb, key) < tolerance then background else rgb"},{name:"Through a mask",group:"Other pictures",description:"Put this last: the steps above show only where the mask is light",images:{mask:{description:"light where the effect shows"}},color:"mix(source, rgb, luma(mask))"},{name:"Mix",group:"Other pictures",description:"Fade towards another picture",images:["overlay"],params:{amount:.5},color:"mix(rgb, overlay, amount)"},{name:"Masked mix",group:"Other pictures",images:{overlay:{},mask:{description:"light where the overlay shows"}},color:"mix(rgb, overlay, luma(mask))"},{name:"Multiply",group:"Other pictures",images:["overlay"],color:"rgb * overlay"},{name:"Screen",group:"Other pictures",images:["overlay"],color:"1 - (1 - rgb)(1 - overlay)"},{name:"Overlay blend",group:"Other pictures",images:["overlay"],color:"if gray < 0.5 then 2 rgb overlay else 1 - 2 (1 - rgb)(1 - overlay)"},{name:"Difference",group:"Other pictures",images:["overlay"],color:"abs(rgb - overlay)"},{name:"Alpha over",group:"Other pictures",description:"A picture with transparency laid on top",images:["overlay"],color:"mix(rgb, overlay, alpha(overlay))"},{name:"Chroma key onto a picture",group:"Other pictures",images:{background:{}},params:{key:[.22,.71,.29],tolerance:{default:.35,min:0,max:1}},color:"if distance(rgb, key) < tolerance then background else rgb"},{name:"Only inside the selection",group:"Other pictures",description:"Put this last: the steps above show only inside what you selected on the picture (everywhere, without a selection)",color:"mix(source, rgb, selected)"},{name:"Only outside the selection",group:"Other pictures",description:"Put this last: the steps above show only outside what you selected",color:"mix(rgb, source, selected)"},{name:"Caption",group:"Text & shapes",description:"Words along the bottom, with a soft shadow; change them under the step",graphics:{title:{text:"Your caption here",y:.88}},color:"mix(rgb, title, alpha(title))"},{name:"Poster title",group:"Text & shapes",description:"Big outlined letters across the top",graphics:{title:{text:"BIG TITLE",font:"Impact, Haettenschweiler, sans-serif",weight:"normal",size:.16,y:.14,outline:{color:"#000000",width:.08},shadow:null}},color:"mix(rgb, title, alpha(title))"},{name:"Gradient text",group:"Text & shapes",description:"The letters colored by math: a sunset from left to right",graphics:{title:{text:"Golden hour",font:"Georgia, serif",size:.13,y:.5,shadow:{color:"rgba(0,0,0,0.5)",blur:.2,dx:0,dy:.05}}},color:"mix(rgb, mix((1, 0.35, 0.3), (1, 0.85, 0.25), x), alpha(title))"},{name:"Neon sign",group:"Text & shapes",description:"White letters with a colored glow",graphics:{title:{text:"OPEN",font:"Trebuchet MS, sans-serif",size:.18,y:.5,shadow:{color:"#00e5ff",blur:.45,dx:0,dy:0}}},color:"mix(rgb * 0.6, title, alpha(title))"},{name:"Layered shadow",group:"Text & shapes",description:"Two shadow layers, each with its own filter: a soft glow that darkens and breathes with t, and a hard offset colored by a gradient",graphics:{title:{text:"LAYERS",font:"Impact, Haettenschweiler, sans-serif",weight:"normal",size:.17,y:.5,shadow:null,shadows:[{color:"#000000",blur:.7,dx:0,dy:.08},{color:"#000000",blur:0,dx:.07,dy:.07}]}},color:"mix(mix(mix(rgb, rgb * 0.25, alpha(title_shadow1) (0.7 + 0.3 sin(t / 10))), mix((1, 0.2, 0.6), (0.2, 0.6, 1), x), alpha(title_shadow2)), title, alpha(title))"},{name:"Ink brush",group:"Brushes",description:'Paint in a color; draw on the picture with "draw" under the step',graphics:{brush:{type:"strokes",brush:"round",size:.025}},params:{ink:[.95,.2,.25]},color:"mix(rgb, ink, alpha(brush))"},{name:"Blur brush",group:"Brushes",description:"Paint a blur in — stronger every time a stroke goes over the same place",graphics:{brush:{type:"strokes",brush:"soft",size:.08}},color:"mix(rgb, gaussian(2 + 3 min(4 green(brush), 3)), alpha(brush))"},{name:"Darken brush",group:"Brushes",description:"Each pass darkens a little more, like layers of a wash",graphics:{brush:{type:"strokes",brush:"soft",size:.07,flow:.7}},color:"rgb (1 - 0.22 min(4 green(brush), 4))"},{name:"Color reveal brush",group:"Brushes",description:"The picture starts gray; the brush paints its color back",graphics:{brush:{type:"strokes",brush:"soft",size:.1}},color:"mix((gray, gray, gray), rgb, alpha(brush))"},{name:"Fuse brush",group:"Brushes",description:"Paint glows as it goes down, then cools to charcoal (red(brush) is its age)",graphics:{brush:{type:"strokes",brush:"round",size:.02,age:40}},color:"mix(rgb, mix((1, 0.9, 0.5), (0.1, 0.07, 0.06), red(brush)), alpha(brush)) + (1, 0.5, 0.1) alpha(brush) max(0, 1 - 3 red(brush)) 0.6"},{name:"Rainbow brush",group:"Brushes",description:"The color runs round the wheel along the drawing (blue(brush) is how far through it)",graphics:{brush:{type:"strokes",brush:"marker",size:.035}},color:"mix(rgb, fromhsv(blue(brush), 0.85, 1), alpha(brush))"},{name:"Chalk outline",group:"Brushes",description:'Chalk round an object: select it, then "outline the selection" under the step',graphics:{brush:{type:"strokes",brush:"chalk",size:.018,timing:"even",speed:2}},color:"mix(rgb, (0.97, 0.97, 0.92), alpha(brush))"},{name:"Frosted panel",group:"Text & shapes",description:"A rounded panel that blurs and darkens what is behind it — a shape with its own filter",graphics:{panel:{type:"rect",y:.86,w:.9,h:.2,radius:.25}},color:"mix(rgb, gaussian(5) * 0.7, alpha(panel))"},{name:"Spotlight oval",group:"Text & shapes",description:"Darkens everything but a soft oval",graphics:{spot:{type:"ellipse",x:.5,y:.45,w:.45,h:.55,shadow:{color:"#ffffff",blur:.12,dx:0,dy:0}}},color:"mix(rgb * 0.3, rgb, alpha(spot))"},{name:"Scrolling banner",group:"Text & shapes",description:"Text that slides across and wraps round (animated with t)",graphics:{title:{text:"Breaking news · scrolling text · ",size:.07,y:.92}},params:{speed:{default:3,min:-10,max:10}},color:"mix(rgb, shift(title, -speed t, 0), alpha(shift(title, -speed t, 0)))"},{name:"Pulsing title",group:"Text & shapes",description:"Text that grows and shrinks a little (animated with t)",graphics:{title:{text:"Hello!",size:.14,y:.5}},params:{amount:{default:.06,min:0,max:.3}},color:"mix(rgb, zoom(title, 1 + amount sin(t / 8)), alpha(zoom(title, 1 + amount sin(t / 8))))"},{name:"Fade-in title",group:"Text & shapes",description:"Text that fades in over the first frames (animated with t)",graphics:{title:{text:"Once upon a time",font:"Georgia, serif",style:"italic",weight:"normal",size:.09,y:.5}},params:{frames:{default:40,min:1,max:200}},color:"mix(rgb, title, alpha(title) clamp(t / frames, 0, 1))"},{name:"Zoom",group:"Shape & motion",params:{scale:{default:1.5,min:.25,max:4},cx:.5,cy:.5},color:"zoom(scale, cx, cy)"},{name:"Ken Burns",group:"Shape & motion",description:"A slow zoom that drifts across — a still picture that moves",params:{speed:{default:.002,min:0,max:.01},drift:{default:3e-4,min:-.001,max:.001}},color:"zoom(1 + speed t, 0.5 + drift t, 0.45)"},{name:"Scroll",group:"Shape & motion",description:"Slides and wraps around",params:{dx:{default:1,min:-5,max:5},dy:{default:0,min:-5,max:5}},color:"shift(dx t, dy t)"},{name:"Spin",group:"Shape & motion",params:{speed:{default:.01,min:-.05,max:.05}},color:"rotate(speed t)"},{name:"Tile",group:"Shape & motion",params:{n:{default:2,min:1,max:8,step:1}},color:"tile(n)"},{name:"Crop",group:"Shape & motion",description:"A part of the picture, filling the frame",params:{left:.1,top:.1,right:.9,bottom:.9},color:"crop(left, top, right, bottom)"},{name:"Flip",group:"Shape & motion",color:"flipx()"},{name:"Picture in picture",group:"Other pictures",description:"Another picture, fitted small in a corner",images:{inset:{description:"any size: it is fitted whole",place:"fit",zoom:.35,x:.8,y:.78}},color:"mix(rgb, inset, alpha(inset))"},{name:"Moving overlay",group:"Other pictures",description:"Another picture scrolling across at half strength",images:["overlay"],params:{speed:{default:2,min:-10,max:10}},color:"mix(rgb, shift(overlay, speed t, 0), 0.5)"},{name:"Hue shift",group:"Color & tone",description:"Turns every color around the hue wheel (in HSV)",space:"hsv",params:{amount:{default:.1,min:-.5,max:.5}},color:"(fract(r + amount), g, b)"},{name:"Saturation",group:"Color & tone",description:"More or less color (in HSV)",space:"hsv",params:{amount:{default:1.5,min:0,max:3}},color:"(r, clamp(g amount, 0, 1), b)"},{name:"Lightness",group:"Color & tone",description:"Lighter or darker without changing the colors (in Lab)",space:"lab",params:{amount:{default:1.15,min:.5,max:2}},color:"(clamp(r amount, 0, 1), g, b)"},{name:"Vivid",group:"Color & tone",description:"Colorfulness, perceptually even (in OKLab)",space:"oklab",params:{amount:{default:1.6,min:0,max:3}},color:"(r, 0.5 + (g - 0.5) amount, 0.5 + (b - 0.5) amount)"},{name:"Linear-light blur",group:"Blur & edges",description:"A Gaussian in linear light: bright spots stay bright, as a lens does",space:"linear",params:{sigma:{default:3,min:0,max:8}},color:"gaussian(sigma)"},{name:"Film grain",group:"Color & tone",description:"Noise that changes every frame",params:{amount:{default:.15,min:0,max:.6}},color:"rgb + amount (random() - 0.5)"},{name:"Swirl",group:"Shape & motion",params:{strength:{default:.02,min:0,max:.1}},color:"pixel(w/2 + (px - w/2) cos(strength t gray) - (py - h/2) sin(strength t gray), h/2 + (px - w/2) sin(strength t gray) + (py - h/2) cos(strength t gray))"}],xt=e=>bt.find(t=>t.name===e);bt.push({name:"Old film",group:"Chains",description:"Sepia, a vignette and faint scanlines — a chain of three",steps:[xt("Sepia"),{filter:xt("Vignette"),with:{strength:1.2}},{filter:xt("Scanlines"),opacity:.5}]},{name:"Comic",group:"Chains",description:"Bold flat colors with ink lines: a small blur first, so a photo's fine texture isn't inked — a chain of four",steps:[{filter:xt("Gaussian blur"),with:{sigma:1.6}},{filter:xt("Vivid"),with:{amount:1.5}},{filter:xt("Posterize"),with:{levels:4}},{filter:xt("Outline"),with:{gain:1.2}}]},{name:"Cartoon",group:"Chains",description:"Blur, then flatten the colors, then outline — a chain of three",steps:[{filter:xt("Gaussian blur"),with:{sigma:1.5}},{filter:xt("Posterize"),with:{levels:6}},{filter:xt("Outline"),with:{gain:2}}]},{name:"Dreamy",group:"Chains",description:"A soft glow mixed over the picture",steps:[{filter:xt("Bloom"),with:{amount:1.2}},{filter:xt("Gaussian blur"),with:{sigma:2},opacity:.4}]},{name:"Tilt shift",group:"Chains",description:"Blurred where the mask is light — a chain",steps:[{filter:xt("Gaussian blur"),with:{sigma:4}},xt("Through a mask")]},{name:"Title card",group:"Chains",description:"A frosted panel with a caption on it — a chain of two",steps:[xt("Frosted panel"),{filter:xt("Caption"),with:{title:{text:"A title on a panel",y:.86}}}]},{name:"Color spotlight",group:"Chains",description:"Gray except where the mask is dark — a chain",steps:[xt("Grayscale"),xt("Through a mask")]});const Et=bt,vt=()=>"undefined"!=typeof document||"undefined"!=typeof OffscreenCanvas,Mt=(e,t)=>"undefined"!=typeof document?Object.assign(document.createElement("canvas"),{width:e,height:t}):new OffscreenCanvas(e,t);function At(e){if(e&&"object"==typeof e&&Array.isArray(e.passes))return e;if("string"==typeof e){const t=e.trim().toLowerCase(),r=Et.find(e=>e.name.toLowerCase()===t);return re(r??le(e))}return re(e)}const _t=4096,kt=2048;function Ot(e,t,r,n){const o=Math.min(1,n/Math.max(t,r));if(o>=1)return{image:e,width:t,height:r};const a=Math.max(1,Math.round(t*o)),s=Math.max(1,Math.round(r*o));if(vt()){let n=e;((e=>Boolean(e&&e.data&&e.width&&e.height)&&!("undefined"!=typeof ImageData&&e instanceof ImageData))(e)||"undefined"!=typeof ImageData&&e instanceof ImageData)&&(n=Mt(t,r),n.getContext("2d").putImageData((i=e,"undefined"!=typeof ImageData&&i instanceof ImageData?i:new ImageData(i.data instanceof Uint8ClampedArray?i.data:Uint8ClampedArray.from(i.data,i.data instanceof Float32Array||i.data instanceof Float64Array?e=>255*e:void 0),i.width,i.height)),0,0));const o=Mt(a,s),l=o.getContext("2d");return l.imageSmoothingEnabled=!0,l.imageSmoothingQuality="high",l.drawImage(n,0,0,a,s),{image:o,width:a,height:s}}var i;const l=e.data,c=new l.constructor(a*s*4);for(let e=0;e<s;e++){const n=Math.floor(e*r/s),o=Math.max(n+1,Math.floor((e+1)*r/s));for(let r=0;r<a;r++){const s=Math.floor(r*t/a),i=Math.max(s+1,Math.floor((r+1)*t/a)),h=[0,0,0,0];for(let e=n;e<o;e++)for(let r=s;r<i;r++)for(let n=0;n<4;n++)h[n]+=l[4*(e*t+r)+n];const u=(o-n)*(i-s);for(let t=0;t<4;t++)c[4*(e*a+r)+t]=h[t]/u}}return{image:{data:c,width:a,height:s},width:a,height:s}}const Tt=e=>!(e=>"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)(e)||e.complete&&e.naturalWidth?[e.naturalWidth||e.videoWidth||e.displayWidth||e.width||0,e.naturalHeight||e.videoHeight||e.displayHeight||e.height||0]:[0,0],jt=e=>Boolean(e)&&"object"==typeof e&&Array.isArray(e.passes),St=e=>(Array.isArray(e)||ArrayBuffer.isView(e))&&3===e.length&&[...e].every(e=>Number.isFinite(Number(e)));let Ft=null;const Ct=new WeakMap;let Rt=0;function It(e){if("string"==typeof e)return`s:${e}`;if(jt(e))return Ct.has(e)||Ct.set(e,"c:"+Rt++),Ct.get(e);if(e&&"object"==typeof e)try{return`d:${ae(e)}`}catch{return null}return null}const Ut=e=>({...e,passes:e.passes.map(e=>({...e,values:{...e.values}}))});let Nt=Promise.resolve();const zt=new Int32Array(256);for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=1&t?3988292384^t>>>1:t>>>1;zt[e]=t}function Pt(e,t){const r=new Uint8Array(12+t.length),n=new DataView(r.buffer);n.setUint32(0,t.length);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);return r.set(t,8),n.setUint32(8+t.length,function(e){let t=-1;for(let r=0;r<e.length;r++)t=zt[255&(t^e[r])]^t>>>8;return(-1^t)>>>0}(r.subarray(4,8+t.length))),r}function Bt(e,t,r){const n=e+t-r,o=Math.abs(n-e),a=Math.abs(n-t),s=Math.abs(n-r);return o<=a&&o<=s?e:a<=s?t:r}async function Dt({width:e,height:t,data:r,palette:n="auto",colors:o=256,dither:a=!0,quantize:s=null}){if("undefined"==typeof CompressionStream)return null;if(!Number.isInteger(e)||!Number.isInteger(t)||e<1||t<1||!r||r.length<e*t*4)throw new Error("encodePng: width and height are whole numbers of pixels, and data holds 4 bytes for each");let i=null;if(("auto"===n||"force"===n)&&(i=function(e){const t=new Map,r=[],n=new Uint8Array(e.length/4);for(let o=0,a=0;o<e.length;o+=4,a++){const s=(e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])>>>0;let i=t.get(s);if(void 0===i){if(256===r.length)return null;i=r.length,t.set(s,i),r.push([e[o],e[o+1],e[o+2],e[o+3]])}n[a]=i}return{palette:r,indices:n}}(r),i&&i.palette.length>o&&(i=null),!i&&"force"===n)){if(!s)throw new Error('encodePng: palette "force" needs a quantize function (the picture has more than `colors` colors)');i=s(r,Math.min(256,Math.max(2,o)),{dither:a,width:e})}const l=[new Uint8Array([137,80,78,71,13,10,26,10])],c=new Uint8Array(13),h=new DataView(c.buffer);let u,p,f;if(h.setUint32(0,e),h.setUint32(4,t),i){const r=i.palette.length;f=r<=2?1:r<=4?2:r<=16?4:8,p="palette",c[8]=f,c[9]=3;const n=Math.ceil(e*f/8);u=new Uint8Array(t*(1+n));for(let r=0;r<t;r++){const t=r*(1+n)+1;for(let n=0;n<e;n++){const o=i.indices[r*e+n];8===f?u[t+n]=o:u[t+(n*f>>3)]|=o<<8-f-n*f%8}}const o=new Uint8Array(3*r),a=new Uint8Array(r);let s=!1;i.palette.forEach(([e,t,r,n],i)=>{o.set([e,t,r],3*i),a[i]=n,n<255&&(s=!0)}),l.push(Pt("IHDR",c),Pt("PLTE",o)),s&&l.push(Pt("tRNS",a))}else{let n=!0;for(let e=3;e<r.length;e+=4)if(r[e]<255){n=!1;break}const o=n?3:4;p=n?"rgb":"rgba",f=8,c[8]=8,c[9]=n?2:6;const a=e*o;u=new Uint8Array(t*(1+a));const s=new Uint8Array(a),i=new Uint8Array(a);for(let l=0;l<t;l++){for(let t=0,a=l*e*4,i=0;t<e;t++,a+=4,i+=o)s[i]=r[a],s[i+1]=r[a+1],s[i+2]=r[a+2],n||(s[i+3]=r[a+3]);const t=l*(1+a);u[t]=4;for(let e=0;e<a;e++)u[t+1+e]=s[e]-Bt(e>=o?s[e-o]:0,i[e],e>=o?i[e-o]:0);i.set(s)}l.push(Pt("IHDR",c))}l.push(Pt("IDAT",await async function(e){if("undefined"==typeof CompressionStream)return null;const t=new CompressionStream("deflate"),r=t.writable.getWriter();return r.write(e),r.close(),new Uint8Array(await new Response(t.readable).arrayBuffer())}(u)),Pt("IEND",new Uint8Array(0)));const m=i?i.palette.length:function(e,t=257){const r=new Set;for(let n=0;n<e.length;n+=4)if(r.add((e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0),r.size>=t)return r.size;return r.size}(r);return{blob:new Blob(l,{type:"image/png"}),kind:p,colors:m,bits:f}}const Lt=e=>e&&e.data&&Number.isFinite(e.width)&&Number.isFinite(e.height)&&"function"!=typeof e.getContext;function Gt(e){if(Lt(e)){const{data:t,width:r,height:n}=e;if(t instanceof Uint8ClampedArray||t instanceof Uint8Array)return{data:t,width:r,height:n};const o=new Uint8ClampedArray(r*n*4),a=t instanceof Float32Array||t instanceof Float64Array?255:1;for(let e=0;e<o.length;e++)o[e]=Math.round(t[e]*a);return{data:o,width:r,height:n}}if(e&&"function"==typeof e.getContext){const t=e.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("This canvas has a WebGL context: pass the 2D canvas applyFilter() returned, or copy it onto one first");return t.getImageData(0,0,e.width,e.height)}throw new Error("Give a canvas or a picture ({ data, width, height })")}function Ht(e){for(let t=3;t<e.length;t+=4)if(e[t]<255)return!0;return!1}return e.BRUSHES=a,e.CLIPS=l,e.FILTER_FORMAT=P,e.FPS=30,e.GRAPHIC_DEFAULTS=b,e.GRAPHIC_TYPES=$,e.GROUPS=["Color & tone","Blur & edges","Shape & motion","Text & shapes","Brushes","Other pictures","Chains"],e.LIBRARY=Et,e.MAX_SHADOW_LAYERS=8,e.MAX_SIZE=_t,e.MAX_SIZE_CPU=kt,e.PLACEMENT=W,e.STROKES_DEFAULTS=c,e.TIMINGS=s,e.WIDTH_FROM=i,e.applyFilter=function(e,t,r={}){const n=Nt.then(()=>async function(e,t,{params:r={},t:n=0,images:o={},engine:a="auto",canvas:s=null,maxSize:i=null}={}){if(!e)throw new Error("applyFilter: no picture");const[l,c]=Tt(e);if(!l||!c)throw new Error("applyFilter: the picture has no size yet (not loaded?)");if(null!==i&&!(Number(i)>=1))throw new Error(`applyFilter: maxSize is a number of pixels, not ${JSON.stringify(i)}`);if("auto"!==a&&"gpu"!==a&&"cpu"!==a)throw new Error(`applyFilter: engine is 'auto', 'gpu' or 'cpu', not "${a}"`);const h=s?s.getContext("2d"):null;if(s&&!h)throw new Error("applyFilter: `canvas` must be a 2D canvas (this one already has another kind of context)");const u="cpu"!==a?function(){if(Ft&&!Ft.gl.isContextLost())return Ft;if(!vt())return null;const e=Mt(1,1),t=e.getContext("webgl",{preserveDrawingBuffer:!0,premultipliedAlpha:!1});return Ft=t?{canvas:e,gl:t,runners:new Map}:null,Ft}():null;if("gpu"===a&&!u)throw new Error('applyFilter: no WebGL here (use engine "auto" or "cpu")');const p=function(e,t,r){const n=It(e)&&`${t}|${It(e)}`,o=Ft?.runners;if(r&&n&&o?.has(n)){const e=o.get(n);return o.delete(n),o.set(n,e),e}const a=At(e),s=Ut(a),i=$t(s,{gl:r,prefer:t}),l={compiled:s,source:jt(e)?a:Ut(a),...i};if(r&&n&&"gpu"===i.engine&&(o.set(n,l),o.size>16)){const[e,t]=o.entries().next().value;o.delete(e),t.runner.dispose()}return l}(t,"gpu"===a?"gpu":u?"auto":"cpu",u?.gl),{compiled:f,source:m,runner:d}=p,g="gpu"===p.engine,w=g?Math.min(Number(i??_t),u.gl.getParameter(u.gl.MAX_TEXTURE_SIZE)||_t):Number(i??kt),{image:y,width:$,height:b}=Ot(e,l,c,w);try{const e=new Map(f.passes.flatMap(e=>Object.entries(e.params??{})));for(const[t,n]of Object.entries(r)){if(!e.has(t))throw new Error(`applyFilter: the filter has no knob called "${t}" (it has ${[...e.keys()].join(", ")||"none"})`);if("color"===e.get(t).type?!St(n):!Number.isFinite(Number(n))||"object"==typeof n||""===n)throw new Error(`applyFilter: the knob "${t}" needs ${"color"===e.get(t).type?"a color, [r, g, b] with each 0–1":"a number"}, not ${JSON.stringify(n)}`)}const t=Object.entries(f.graphics??{});let a={};if(t.length){const e=t.filter(([,e])=>"strokes"!==e.type).map(([e])=>e);if(!vt()&&e.length)throw new Error(`applyFilter: this filter draws ${e.join(", ")} (text or shapes), which needs a canvas — there is none here`);a=await z(f,$,b,{t:Number.isFinite(n)?n:1/0})}f.passes.forEach((e,t)=>{e.values={...m.passes[t].values},e.opacity=m.passes[t].opacity;for(const[t,n]of Object.entries(r))t in(e.params??{})&&(e.values[t]="color"===e.params[t].type?[...n].map(Number):Number(n))}),d.setImage(y);for(const e of p.given??[])e in o||d.setImage(e,null);p.given=Object.keys(o);for(const[e,t]of Object.entries(o)){const[r,n]=Tt(t);d.setImage(e,r&&n?Ot(t,r,n,w).image:t)}for(const[e,t]of Object.entries(a))d.setImage(e,t);if(g){u.canvas.width=$,u.canvas.height=b,d.draw({t:n});const e=s??Mt($,b);e.width=$,e.height=b;const t=h??e.getContext("2d");return t.clearRect(0,0,$,b),t.drawImage(u.canvas,0,0),e}const i=await d.drawAsync({t:n});if(!vt()&&!s)return i;const l=s??Mt($,b);return l.width=$,l.height=b,(h??l.getContext("2d")).putImageData(new ImageData(i.data,$,b),0,0),l}finally{g||d.dispose()}}(e,t,r));return Nt=n.catch(()=>{}),n},e.chooseEngine=yt,e.compileCpuPass=ht,e.compileFilter=re,e.createCpuRunner=pt,e.createFilterRunner=he,e.createRunner=$t,e.cssFont=F,e.drawGraphic=N,e.encodeGif=async function(e,{gifenc:t,delay:r=1e3/30,repeat:n=0,colors:o=256}={}){const a=t&&(t.GIFEncoder?t:t.default);if(!a||"function"!=typeof a.GIFEncoder)throw new Error("encodeGif needs gifenc: import * as gifenc from 'gifenc' and pass { gifenc }");const s=a.GIFEncoder();let i=null,l=0;for await(const t of e){let{data:e,width:c,height:h}=Gt(t);if((e.byteOffset||e.byteLength!==e.buffer.byteLength)&&(e=e.slice()),i&&(i[0]!==c||i[1]!==h))throw new Error(`Frame ${l+1} is ${c} × ${h}; the first was ${i[0]} × ${i[1]}`);i=[c,h];const u=Ht(e),p=u?"rgba4444":"rgb565",f=a.quantize(e,Math.max(2,Math.min(256,o)),{format:p,oneBitAlpha:u}),m=a.applyPalette(e,f,p),d={palette:f,delay:Math.round(r),repeat:n};if(u){const e=f.findIndex(e=>e.length>3&&0===e[3]);e>=0&&Object.assign(d,{transparent:!0,transparentIndex:e})}s.writeFrame(m,c,h,d),l++}if(!l)throw new Error("encodeGif: no frames");return s.finish(),new Blob([s.bytes()],{type:"image/gif"})},e.encodePng=Dt,e.familyFor=C,e.filterFromJSON=se,e.filterFromLink=ie,e.filterGraphics=J,e.filterImages=K,e.filterParams=Q,e.filterToJSON=ae,e.filterToLink=function(e,t=""){return`${t}#${function(e){let t="";for(const r of(new TextEncoder).encode(e))t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(JSON.stringify(ce(q(e),!0)))}`},e.fontFileFromCss=S,e.googleFontFamily=j,e.googleFontUrl=function(e){const t=String(e).trim().replace(/\s+/g," ");if(!/^[A-Za-z0-9 ]{1,60}$/.test(t))throw new Error('A Google Fonts name is letters, digits and spaces, like "Lobster" or "Playfair Display"');return`https://fonts.googleapis.com/css2?family=${t.replace(/ /g,"+")}:ital,wght@0,400;0,700;1,400;1,700&display=swap`},e.layeredExpression=function(e,t){let r="rgb";for(const n of x(e,t))r=`mix(${r}, ${n}, alpha(${n}))`;return`mix(${r}, ${e}, alpha(${e}))`},e.loadGraphicFonts=I,e.normalizeFilter=q,e.normalizeGraphic=T,e.normalizeStrokes=p,e.pictureData=Gt,e.rasterizeStrokes=g,e.readFilter=le,e.renderGraphics=z,e.shadowLayerNames=x,e.simplify=y,e.simplifyLoop=w,e.strokeTimeline=f,e.toBlob=async function(e,{type:t="image/png",quality:r,palette:n="auto"}={}){if("image/png"===t){const t=await Dt({...Gt(e),palette:n});if(t)return t.blob}const o=Lt(e)?function(e){const{width:t,height:r}=e;let n=null;return"undefined"!=typeof OffscreenCanvas?n=new OffscreenCanvas(t,r):"undefined"!=typeof document&&(n=Object.assign(document.createElement("canvas"),{width:t,height:r})),n?(n.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(e.data),t,r),0,0),n):null}(Gt(e)):e;if(!o)throw new Error(`Saving as ${t} needs a browser (a canvas encodes it); in Node, save as image/png`);return"function"==typeof o.convertToBlob?o.convertToBlob({type:t,quality:r}):new Promise((e,n)=>o.toBlob(r=>r?e(r):n(new Error(`The browser could not encode ${t}`)),t,r))},e.toCompiled=At,e.toPicture=mt,e.traceContours=function(e,t,r,{minArea:n=40,tolerance:o=.8}={}){const a=(n,o)=>n>=0&&o>=0&&n<t&&o<r&&e[o*t+n]>.5,s=new Int32Array(t*r).fill(-1),i=[],l=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]];let c=0;for(let e=0;e<r;e++)for(let r=0;r<t;r++){if(!a(r,e)||s[e*t+r]>=0)continue;const h=c++,u=[e*t+r];s[e*t+r]=h;let p=0;for(;u.length;){const e=u.pop();p++;const r=e%t,n=(e-r)/t;for(const[e,o]of[[1,0],[-1,0],[0,1],[0,-1]]){const i=r+e,l=n+o;a(i,l)&&s[l*t+i]<0&&(s[l*t+i]=h,u.push(l*t+i))}}if(p<n)continue;const f=[[r,e]];let m=r,d=e,g=4;for(let n=0;n<4*p+16;n++){let n=!1;for(let e=1;e<=8;e++){const r=(g+e)%8,o=m+l[r][0],i=d+l[r][1];if(a(o,i)&&s[i*t+o]===h){g=(r+4)%8,m=o,d=i,n=!0;break}}if(!n||m===r&&d===e)break;f.push([m,d])}i.push(w(f,o))}return i},e.validateFilter=function(e){let t;try{t=q(e)}catch(e){return[e.message]}const r=[];return ee({filter:t,with:{},opacity:1},[],r,!0),r},e}({},MathZetta,MathZetta,MathZetta);
1
+ /* qblur 0.3.0 (MathZetta not included: load mathzetta.min.js or mathzetta.glsl.min.js first) — Copyright (c) 2025-2026 Robert Wilcox — MIT license — https://qblur.com */
2
+ var QBlur=function(e,t,r,n){"use strict";var o="undefined"!=typeof document?document.currentScript:null;const a=["round","soft","marker","chalk","spray"],s=["recorded","even","per-stroke"],i=["pressure","speed","none"],l=["none","inside","outside"],c={type:"strokes",strokes:[],brush:"round",size:.03,flow:1,spacing:.2,taper:0,buildUp:!1,widthFrom:"pressure",timing:"recorded",speed:1,gap:6,start:0,fit:0,age:30,clip:"none",shadows:[]};function h(e,t){throw new Error(`Graphic "${e}": ${t}`)}function u(e,t,r,n,o){const a=Number(r);return(!Number.isFinite(a)||a<n||a>o)&&h(e,`"${t}" is a number from ${n} to ${o}`),a}function p(e,t){for(const r of Object.keys(t))r in c||h(e,`no such setting "${r}" for strokes`);const r={...c,...t},n=(t,n)=>(n.includes(r[t])||h(e,`"${t}" is ${n.join(", ")} — not "${r[t]}"`),r[t]),o={type:"strokes",brush:n("brush",a),widthFrom:n("widthFrom",i),timing:n("timing",s),clip:n("clip",l),size:u(e,"size",r.size,.001,.5),flow:u(e,"flow",r.flow,.01,1),spacing:u(e,"spacing",r.spacing,.02,2),taper:u(e,"taper",r.taper,0,.5),speed:u(e,"speed",r.speed,.05,20),gap:u(e,"gap",r.gap,0,600),start:u(e,"start",r.start,0,1e4),fit:u(e,"fit",r.fit,0,1e4),age:u(e,"age",r.age,1,1e4),buildUp:Boolean(r.buildUp),shadows:[]};Array.isArray(r.strokes)||h(e,'"strokes" is a list of { "points": [[x, y, ms, pressure], …] }');let p=0;return o.strokes=r.strokes.map((t,r)=>{const n=Array.isArray(t)?t:t?.points;return Array.isArray(n)||h(e,`stroke ${r+1} is { "points": [[x, y, ms, pressure], …] }`),p+=n.length,p>6e4&&h(e,"a drawing has at most 60000 points"),{points:n.map((t,n)=>((!Array.isArray(t)||t.length<2||!t.every(e=>Number.isFinite(Number(e))))&&h(e,`stroke ${r+1}, point ${n+1} is [x, y, ms, pressure]`),[+Number(t[0]).toFixed(4),+Number(t[1]).toFixed(4),Math.round(Number(t[2]??16*n)),+Math.min(1,Math.max(0,Number(t[3]??1))).toFixed(2)]))}}),o}function f(e,t=1){const r=[];let n=e.start;const o=30/e.speed,a=20/e.speed;for(const s of e.strokes){const i=s.points;if(!i.length)continue;const l=[0];for(let e=1;e<i.length;e++)l.push(l[e-1]+Math.hypot((i[e][0]-i[e-1][0])*t,i[e][1]-i[e-1][1]));const c=l[l.length-1]||1e-9,h=i[0][2],u=i.map((t,r)=>{let n;n="recorded"===e.timing?(t[2]-h)/1e3*30/e.speed:"even"===e.timing?l[r]*o:l[r]/c*a;let s=1;if("pressure"===e.widthFrom)s=.3+.7*t[3];else if("speed"===e.widthFrom&&r>0){const e=Math.max(1,t[2]-i[r-1][2]),n=(l[r]-l[r-1])/e*1e3;s=Math.min(1.3,Math.max(.35,1.3-.6*n))}return e.taper>0&&(s*=Math.max(.15,Math.min(1,l[r]/c/e.taper,(1-l[r]/c)/e.taper))),{x:t[0],y:t[1],f:n,wf:s}});"speed"===e.widthFrom&&u.length>1&&(u[0].wf=u[1].wf);const p=u[u.length-1].f;for(const e of u)e.f+=n;r.push({points:u,start:n,end:n+p}),n+=p+e.gap}let s=r.length?r[r.length-1].end:e.start;if(e.fit>0&&s>e.start){const t=e.fit/(s-e.start);for(const n of r){for(const r of n.points)r.f=e.start+(r.f-e.start)*t;n.start=e.start+(n.start-e.start)*t,n.end=e.start+(n.end-e.start)*t}s=e.start+e.fit}return{strokes:r,total:s}}function m(e,t){let r=Math.imul(0|e,374761393)+Math.imul(0|t,668265263)|0;return r=Math.imul(r^r>>>13,1274126177),((r^r>>>16)>>>0)/4294967296}const d=new Map;function g(e,t,r,n=1/0,{mask:o=null}={}){const a=t*r,{alpha:s,passes:i,latest:l,cov:c,when:h,touched:u}=function(e){let t=d.get(e);return t||(t={alpha:new Float32Array(e),passes:new Float32Array(e),latest:new Float32Array(e),cov:new Float32Array(e),when:new Float32Array(e),touched:new Int32Array(e)},d.clear(),d.set(e,t)),t.alpha.fill(0),t.passes.fill(0),t.latest.fill(-1),t}(a),{strokes:p,total:g}=f(e,t/r),w=Number.isFinite(n)?n:g,y=Math.max(.5,e.size*r/2);let $=0,b=256*Math.max(a,65536);p.forEach(n=>{if(n.start>w||b<=0)return;let o=0;const a=(t,r,n,o)=>{const a=$++;if("spray"===e.brush){const e=Math.max(3,Math.round(.6*n)),s=Math.max(.6,.07*n);for(let i=0;i<e;i++){const e=m(a,2*i)*Math.PI*2,l=Math.sqrt(m(a,2*i+1))*n;p(t+Math.cos(e)*l,r+Math.sin(e)*l,s,o,"round")}}else p(t,r,n,o,e.brush)},p=(n,a,s,i,l)=>{const p="marker"===l?s:s+1,f=Math.max(0,Math.floor(n-p)),d=Math.min(t-1,Math.ceil(n+p)),g=Math.max(0,Math.floor(a-p)),w=Math.min(r-1,Math.ceil(a+p));b-=d>=f&&w>=g?(d-f+1)*(w-g+1):16;for(let r=g;r<=w;r++)for(let p=f;p<=d;p++){const f=p+.5-n,d=r+.5-a;let g;if("soft"===l){const e=Math.hypot(f,d)/s;if(e>=1)continue;const t=1-e;g=t*t*(3-2*t)}else if("marker"===l){const e=(f+d)*Math.SQRT1_2,t=(d-f)*Math.SQRT1_2,r=Math.hypot(e/s,t/(.33*s));g=Math.min(1,Math.max(0,(1-r)*s*.33+.5))}else g=Math.min(1,Math.max(0,s-Math.hypot(f,d)+.5)),"chalk"===l&&(g*=m(p,7919*r)>.42?1:.12);if(g<=0)continue;g*=e.flow;const w=r*t+p;g>c[w]&&(0===c[w]&&(u[o++]=w),c[w]=g),g>.02&&(h[w]=i)}},f=n.points;let d=0;const g=e=>[e.x*t,e.y*r];if(1===f.length||f.every(e=>e.x===f[0].x&&e.y===f[0].y)){const[e,t]=g(f[0]);a(e,t,y*f[0].wf,f[0].f)}for(let t=1;t<f.length;t++){const r=f[t-1],n=f[t];if(r.f>w)break;const[o,s]=g(r),[i,l]=g(n);let c=1;n.f>w&&(c=(w-r.f)/Math.max(1e-9,n.f-r.f));const h=Math.hypot(i-o,l-s);let u=1===t?0:d;for(;u<=h*c&&b>0;){const t=h?u/h:0,c=y*(r.wf+(n.wf-r.wf)*t);a(o+(i-o)*t,s+(l-s)*t,c,r.f+(n.f-r.f)*t),u+=Math.max(.5,2*e.spacing*c)}if(d=u-h,c<1||b<=0)break}for(let t=0;t<o;t++){const r=u[t],n=c[r];s[r]=e.buildUp?1-(1-s[r])*(1-n):Math.max(s[r],n),i[r]+=n,n>.02&&h[r]>l[r]&&(l[r]=h[r]),c[r]=0}});const x=new Uint8ClampedArray(4*a),E="inside"===e.clip,v="outside"===e.clip;for(let t=0;t<a;t++){let r=s[t];if(0===r)continue;let n=1;o&&(E||v)&&(n=E?o[t]:1-o[t]),r*=n;const a=4*t;x[a]=Math.round(255*Math.min(1,Math.max(0,(w-l[t])/e.age))),x[a+1]=Math.round(255*Math.min(1,i[t]*n/4)),x[a+2]=Math.round(255*Math.min(1,Math.max(0,l[t]/Math.max(1e-9,g)))),x[a+3]=Math.round(255*r)}return{data:x,width:t,height:r,total:g}}function w(e,t){if(e.length<4)return[...e,e[0]];const[r,n]=e[0];let o=0;return e.forEach(([t,a],s)=>{Math.hypot(t-r,a-n)>Math.hypot(e[o][0]-r,e[o][1]-n)&&(o=s)}),[...y(e.slice(0,o+1),t),...y([...e.slice(o),e[0]],t).slice(1)]}function y(e,t){if(e.length<3)return e;const r=new Uint8Array(e.length);r[0]=r[e.length-1]=1;const n=[[0,e.length-1]];for(;n.length;){const[o,a]=n.pop(),[s,i]=e[o],[l,c]=e[a],h=Math.hypot(l-s,c-i)||1e-9;let u=-1,p=-1;for(let t=o+1;t<a;t++){const r=Math.abs((l-s)*(i-e[t][1])-(s-e[t][0])*(c-i))/h;r>u&&(u=r,p=t)}u>t&&(r[p]=1,n.push([o,p],[p,a]))}return e.filter((e,t)=>r[t])}const $=["text","rect","ellipse","strokes"],b={text:{type:"text",text:"Text",font:"sans-serif",weight:"bold",style:"normal",size:.08,x:.5,y:.85,align:"center",angle:0,lineHeight:1.2,color:"#ffffff",outline:null,shadow:{color:"rgba(0,0,0,0.6)",blur:.15,dx:.04,dy:.06},shadows:[]},rect:{type:"rect",x:.5,y:.85,w:.8,h:.18,radius:.15,angle:0,color:"#ffffff",outline:null,shadow:null,shadows:[]},ellipse:{type:"ellipse",x:.5,y:.5,w:.4,h:.4,angle:0,color:"#ffffff",outline:null,shadow:null,shadows:[]}},x=(e,t)=>(t.shadows??[]).map((t,r)=>`${e}_shadow${r+1}`);const E=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d.,\s%deg/]+\)|[a-z]{3,20}|transparent)$/i,v=/^[\w\s,'"-]{1,80}$/,M=["normal","bold","100","200","300","400","500","600","700","800","900"];function A(e,t,r){if("string"!=typeof r||!E.test(r.trim()))throw new Error(`Graphic "${e}": "${t}" is a color like "#ffcc00", "rgba(0,0,0,0.5)" or "white"`);return r.trim()}function _(e,t,r,n=-1/0,o=1/0){const a=Number(r);if(!Number.isFinite(a)||a<n||a>o)throw new Error(`Graphic "${e}": "${t}" is a number${Number.isFinite(n)?` from ${n} to ${o}`:""}`);return a}function k(e,t){if(null===t||!1===t)return null;if("object"!=typeof t)throw new Error(`Graphic "${e}": "outline" is { "color", "width" } or null`);return{color:A(e,"outline.color",t.color??"#000000"),width:_(e,"outline.width",t.width??.06,0,1)}}function O(e,t){if(null===t||!1===t)return null;if("object"!=typeof t)throw new Error(`Graphic "${e}": "shadow" is { "color", "blur", "dx", "dy" } or null`);return{color:A(e,"shadow.color",t.color??"rgba(0,0,0,0.6)"),blur:_(e,"shadow.blur",t.blur??.15,0,2),dx:_(e,"shadow.dx",t.dx??0,-2,2),dy:_(e,"shadow.dy",t.dy??0,-2,2)}}function T(e,t){if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(`Graphic "${e}": give { "type": "text" | "rect" | "ellipse", … }`);const r=t.type??"text";if(!$.includes(r))throw new Error(`Graphic "${e}": "type" is text, rect, ellipse or strokes — not "${r}"`);if("strokes"===r)return p(e,t);const n=b[r];for(const o of Object.keys(t))if(!(o in n)&&"fontUrl"!==o&&"onlyShadow"!==o)throw new Error(`Graphic "${e}": no such setting "${o}" for ${r}`);const o={type:r};for(const[r,a]of Object.entries(n)){if("type"===r)continue;const n=r in t&&void 0!==t[r]?t[r]:a;if("color"===r)o.color=A(e,r,n);else if("outline"===r)o.outline=k(e,n);else if("shadow"===r)o.shadow=O(e,n);else if("shadows"===r){if(!Array.isArray(n)||n.length>8)throw new Error(`Graphic "${e}": "shadows" is a list of up to 8 { "color", "blur", "dx", "dy" }`);o.shadows=n.map((t,r)=>{if(!t||"object"!=typeof t)throw new Error(`Graphic "${e}": shadow layer ${r+1} is { "color", "blur", "dx", "dy" }`);return O(e,t)})}else if("text"===r){if("string"!=typeof n||n.length>500)throw new Error(`Graphic "${e}": "text" is up to 500 characters`);o.text=n}else if("font"===r){if("string"!=typeof n||!v.test(n))throw new Error(`Graphic "${e}": "font" is a font family, like "Georgia" or "sans-serif"`);o.font=n}else if("weight"===r){if(!M.includes(String(n)))throw new Error(`Graphic "${e}": "weight" is normal, bold or 100–900`);o.weight=String(n)}else if("style"===r){if(!["normal","italic"].includes(n))throw new Error(`Graphic "${e}": "style" is normal or italic`);o.style=n}else if("align"===r){if(!["left","center","right"].includes(n))throw new Error(`Graphic "${e}": "align" is left, center or right`);o.align=n}else"size"===r?o.size=_(e,r,n,.005,2):"w"===r||"h"===r?o[r]=_(e,r,n,0,4):"radius"===r?o.radius=_(e,r,n,0,.5):"lineHeight"===r?o.lineHeight=_(e,r,n,.5,4):o[r]=_(e,r,n)}if(void 0!==t.fontUrl&&null!==t.fontUrl&&""!==t.fontUrl){if("text"!==r)throw new Error(`Graphic "${e}": "fontUrl" is for text`);let n;try{n=new URL(t.fontUrl)}catch{n=null}if(!n||"https:"!==n.protocol)throw new Error(`Graphic "${e}": "fontUrl" is an https:// address of a font file (.woff2, .woff, .ttf, .otf) or of a Google Fonts stylesheet`);o.fontUrl=n.href}return void 0!==t.onlyShadow&&(o.onlyShadow=_(e,"onlyShadow",t.onlyShadow,0,7)),o}function j(e){try{const t=new URL(e);return"fonts.googleapis.com"!==t.hostname?null:(t.searchParams.get("family")??"").split(":")[0].replace(/\+/g," ")||null}catch{return null}}function F(e,{weight:t="400",style:r="normal"}={}){const n=[...e.matchAll(/@font-face\s*{([^}]*)}/g)].map(e=>e[1]),o=(e,t)=>(new RegExp(`${t}\\s*:\\s*([^;]+);`).exec(e)?.[1]??"").trim(),a=String("bold"===t?700:"normal"===t?400:t),s=n.filter(e=>o(e,"font-weight")===a&&o(e,"font-style")===r),i=(s.length?s:n).at(-1);return i&&(/url\(([^)]+)\)/.exec(i)?.[1]??"").replace(/^['"]|['"]$/g,"")||null}function S(e,t){const r=e.fontUrl?`"${C(e.fontUrl)}", ${e.font}`:e.font;return`${e.style} ${e.weight} ${Math.max(1,e.size*t)}px ${r}`}function C(e){let t=0;for(const r of e)t=31*t+r.charCodeAt(0)>>>0;return`mz-font-${t.toString(36)}`}const I=new Map;async function R(e,t=100){if("undefined"==typeof document&&"undefined"==typeof self)return[];const r="undefined"!=typeof document?document.fonts:self.fonts;if(!r)return[];const n=[];for(const o of Object.values(e??{}))if("text"===o.type){if(o.fontUrl&&"undefined"!=typeof FontFace){const e=`${o.fontUrl} ${o.weight} ${o.style}`;I.has(e)||I.set(e,U(o,r)),await I.get(e)||n.push(o.fontUrl)}try{await r.load(S(o,t),o.text)}catch{}}return[...new Set(n)]}async function U(e,t){try{let r=e.fontUrl;if(!/\.(woff2?|ttf|otf)(\?|$)/i.test(new URL(r).pathname)||j(r)){if(r=F(await(await fetch(r,{credentials:"omit",referrerPolicy:"no-referrer"})).text(),e),!r||!r.startsWith("https://"))return null}const n=new FontFace(C(e.fontUrl),`url(${JSON.stringify(r)})`,{weight:e.weight,style:e.style});return t.add(await n.load()),n}catch{return null}}function N(e,t,r,n){e.save();const o="text"===t.type?t.size*n:n,a=void 0!==t.onlyShadow?t.shadows[t.onlyShadow]:null,s=a?2*(r+n)+1e3:0,i=a??t.shadow;if(e.translate(t.x*r-s,t.y*n),t.angle&&e.rotate(t.angle),i&&(e.shadowColor=i.color,e.shadowBlur=i.blur*o,e.shadowOffsetX=i.dx*o+s,e.shadowOffsetY=i.dy*o),e.fillStyle=a?"#000000":t.color,t.outline&&(e.strokeStyle=t.outline.color,e.lineWidth=t.outline.width*o,e.lineJoin="round"),"text"===t.type){e.font=S(t,n),e.textAlign=t.align,e.textBaseline="middle";const r=t.text.split("\n"),o=t.size*n*t.lineHeight;r.forEach((n,s)=>{const l=(s-(r.length-1)/2)*o;t.outline&&e.strokeText(n,0,l),t.outline&&i&&!a&&(e.shadowColor="transparent"),e.fillText(n,0,l),t.outline&&i&&!a&&(e.shadowColor=i.color)})}else{const o=t.w*r,s=t.h*n;if(e.beginPath(),"ellipse"===t.type)e.ellipse(0,0,o/2,s/2,0,0,2*Math.PI);else{const r=Math.min(o,s)*t.radius;e.roundRect?e.roundRect(-o/2,-s/2,o,s,r):e.rect(-o/2,-s/2,o,s)}e.fill(),t.outline&&(a||(e.shadowColor="transparent"),e.stroke())}e.restore()}async function z(e,t,r,{t:n=1/0,mask:o=null}={}){const a=e.graphics??{},s=await R(a,r),i={};for(const[e,s]of Object.entries(a)){if("strokes"===s.type){const a=g(s,t,r,n,{mask:o});i[e]="undefined"!=typeof ImageData?new ImageData(a.data,t,r):a;continue}const a="undefined"!=typeof OffscreenCanvas&&"undefined"==typeof document?new OffscreenCanvas(t,r):Object.assign(document.createElement("canvas"),{width:t,height:r});N(a.getContext("2d"),s,t,r),i[e]=a}return Object.defineProperty(i,"failedFonts",{value:s}),i}const P="mathzetta-filter/1",B=["r","g","b","a","rgb","rgba"],D=/^[A-Za-z][A-Za-z0-9_]*$/,L=new Set([...t.FILTER_NAMES,"r","g","b","a","x","y","w","h","t","c","e","pi","color","image","resolution","base","position","main","in","out","inout","const","uniform","varying","attribute","void","float","int","bool","vec2","vec3","vec4","mat2","mat3","mat4","sampler2D","struct","precision","highp","mediump","lowp","if","else","for","while","do","return","break","continue","discard","true","false","texture2D","texture","mix","clamp","step","smoothstep","abs","sign","floor","ceil","fract","mod","min","max","sin","cos","tan","asin","acos","atan","pow","exp","log","exp2","log2","sqrt","inversesqrt","length","distance","dot","cross","normalize","radians","degrees"]),G=e=>Array.isArray(e)&&3===e.length&&e.every(e=>Number.isFinite(Number(e))),H=e=>e&&"object"==typeof e&&!Array.isArray(e),W={place:"cover",zoom:1,x:.5,y:.5,angle:0};function q(e){if("string"==typeof e){if(!e.trim())throw new Error("The filter is empty");return{format:P,color:e.trim()}}if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('A filter is an expression, or an object with "color" or "steps"');if(void 0!==e.format&&e.format!==P)throw new Error(`Unknown filter format "${e.format}" (this is ${P})`);const r={format:P};for(const t of["name","author","description"])void 0!==e[t]&&""!==e[t]&&(r[t]=String(e[t]));if(void 0!==e.steps){if(void 0!==e.color)throw new Error('A filter has either "color" or "steps", not both');if(!Array.isArray(e.steps)||!e.steps.length)throw new Error('"steps" must be a list with at least one step');return r.steps=e.steps.map(J),void 0!==e.notes&&(r.notes=X(e.notes,Q(r))),r}if(void 0===e.color)throw new Error('A filter needs "color" (an expression, or one per channel) or "steps"');const n=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('"params" is an object of name → { default, min, max }');const t={};for(const[r,n]of Object.entries(e)){if(!D.test(r))throw new Error(`Parameter name "${r}" must be letters, digits and _, starting with a letter`);if(L.has(r))throw new Error(`"${r}" is already defined in every filter; pick another parameter name`);t[r]=V(r,n)}return t}(e.params??{});Object.keys(n).length&&(r.params=n),void 0!==e.notes&&(r.notes=X(e.notes,n));const o=function(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,{}])):e;if(!r||"object"!=typeof r)throw new Error('"images" is a list of names, or an object of name → { description }');const n={};for(const[e,o]of Object.entries(r)){if(!D.test(e)||e.startsWith("mz_"))throw new Error(`Image name "${e}" must be letters, digits and _, starting with a letter`);if("source"===e)throw new Error('"source" is always available: the picture the chain started from');if(L.has(e))throw new Error(`"${e}" is already defined in every filter; pick another image name`);if(Object.hasOwn(t,e))throw new Error(`"${e}" is both a parameter and an image`);n[e]=Z(e,o)}return n}(e.images??{},n);Object.keys(o).length&&(r.images=o);const a=function(e,t,r){if(!H(e))throw new Error('"graphics" is an object of name → { "type": "text" | "rect" | "ellipse", … }');if(Object.keys(e).length>64)throw new Error("A filter has at most 64 graphics");const n={};for(const[o,a]of Object.entries(e)){if(!D.test(o)||o.startsWith("mz_"))throw new Error(`Graphic name "${o}" must be letters, digits and _, starting with a letter`);if(L.has(o)||"source"===o||"selection"===o)throw new Error(`"${o}" is already defined in every filter; pick another graphic name`);if(Object.hasOwn(t,o)||Object.hasOwn(r,o))throw new Error(`"${o}" is both a graphic and a parameter or picture`);n[o]=T(o,a)}const o=new Set(Object.keys(n).flatMap(e=>Array.from({length:8},(t,r)=>`${e}_shadow${r+1}`)));for(const e of[...Object.keys(n),...Object.keys(t),...Object.keys(r)])if(o.has(e))throw new Error(`"${e}" is the name of a shadow layer of another graphic; pick another name`);return n}(e.graphics??{},n,o);Object.keys(a).length&&(r.graphics=a);const s=function(e){if(null==e)return null;const r="string"==typeof e?{in:e,out:e}:e;if(!H(r))throw new Error(`"space" is a color space (${t.COLOR_SPACES.join(", ")}) or { "in": …, "out": … }`);const n={in:r.in??"srgb",out:r.out??"srgb"};for(const e of["in","out"])if(!t.COLOR_SPACES.includes(n[e]))throw new Error(`"space": "${n[e]}" is not a color space; they are ${t.COLOR_SPACES.join(", ")}`);return"srgb"===n.in&&"srgb"===n.out?null:n}(e.space);return s&&(r.space=s),r.color=function(e){if("string"==typeof e){if(!e.trim())throw new Error('"color" is empty');return e.trim()}if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('"color" is an expression, or an object with r, g, b, a, rgb or rgba expressions');const t={};for(const[r,n]of Object.entries(e)){if(!B.includes(r))throw new Error(`"color" can set r, g, b, a, rgb or rgba — not "${r}"`);if("string"!=typeof n||!n.trim())throw new Error(`"color.${r}" must be an expression`);t[r]=n.trim()}if(!Object.keys(t).length)throw new Error('"color" sets no channels');return t}(e.color),r}function X(e,t){if(!Array.isArray(e))throw new Error('"notes" is a list of Markdown texts and { "param": name } entries');return e.map(e=>{if("string"==typeof e)return e;if(!H(e)||"string"!=typeof e.param||1!==Object.keys(e).length)throw new Error('"notes": each entry is a Markdown text or { "param": name }');if(!Object.hasOwn(t,e.param))throw new Error(`"notes" places "${e.param}", but there is no parameter called that`);return{param:e.param}})}function Y(e){if(e.color)return{...e.graphics??{}};const t={};for(const r of e.steps)for(const[e,n]of Object.entries(Y(r.filter)))Object.hasOwn(t,e)||(t[e]=n);return t}function Z(e,r){if(!H(r))throw new Error(`Image "${e}": give { description, place, zoom, x, y, angle }`);const n={};if(r.description&&(n.description=String(r.description)),void 0!==r.place){if(!t.PLACES.includes(r.place))throw new Error(`Image "${e}": "place" is ${t.PLACES.join(", ")} — not "${r.place}"`);n.place=r.place}for(const t of["zoom","x","y","angle"]){if(void 0===r[t])continue;const o=Number(r[t]);if(!Number.isFinite(o))throw new Error(`Image "${e}": "${t}" is a number`);n[t]=o}for(const t of Object.keys(r))if(!["description","place","zoom","x","y","angle"].includes(t))throw new Error(`Image "${e}": no such setting "${t}"`);return n}function J(e){if("string"==typeof e)return{filter:q(e),with:{},opacity:1,skip:!1};if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('A step is an expression, a filter, or { "filter": …, "with": { … }, "opacity": … }');const{filter:t,with:r,opacity:n,skip:o,...a}=e,s={filter:q(void 0!==t?t:a),with:{},opacity:1,skip:Boolean(o)};if(void 0!==r){if(!r||"object"!=typeof r||Array.isArray(r))throw new Error('"with" is an object of parameter name → value');s.with={...r}}if(void 0!==n){const e=Number(n);if(!(e>=0&&e<=1))throw new Error('"opacity" is a number from 0 to 1');s.opacity=e}return s}function V(e,t){if("number"==typeof t)t={default:t};else if(Array.isArray(t))t={type:"color",default:t};else if(!t||"object"!=typeof t)throw new Error(`Parameter "${e}" needs a default value`);const r=t.type??(Array.isArray(t.default)?"color":"number"),n={type:r};if(void 0!==t.label&&(n.label=String(t.label)),"color"===r){const r=t.default??[1,1,1];if(!G(r))throw new Error(`Color parameter "${e}" needs a default of three numbers, 0–1`);return n.default=r.map(Number),n}if("number"!==r)throw new Error(`Parameter "${e}": the type is "number" or "color", not "${r}"`);let o=null;if(void 0!==t.options){if(!Array.isArray(t.options)||!t.options.length||!t.options.every(e=>""!==e&&Number.isFinite(Number(e))))throw new Error(`Parameter "${e}": "options" is a list of numbers`);o=t.options.map(Number)}if(void 0!==t.input&&"slider"!==t.input&&"box"!==t.input)throw new Error(`Parameter "${e}": "input" is "slider" or "box", not "${t.input}"`);const a=Number(t.default??(o?o[0]:0));if(!Number.isFinite(a))throw new Error(`Parameter "${e}" needs a numeric default`);if(n.default=a,n.min=void 0!==t.min?Number(t.min):o?o.reduce((e,t)=>Math.min(e,t),a):Math.min(0,2*a),n.max=void 0!==t.max?Number(t.max):o?o.reduce((e,t)=>Math.max(e,t),a):Math.max(1,2*a),void 0!==t.step&&(n.step=Number(t.step)),o&&(n.options=o),"box"!==t.input||o||(n.input="box"),!(n.min<=a&&a<=n.max))throw new Error(`Parameter "${e}": the default ${a} is outside ${n.min} to ${n.max}`);return n}function K(e){if(e.color)return{...e.images??{}};const t={};for(const r of e.steps)for(const[e,n]of Object.entries(K(r.filter)))Object.hasOwn(t,e)||(t[e]=n);return t}function Q(e){if(e.color)return{...e.params??{}};const t={};for(const r of e.steps)for(const[e,n]of Object.entries(Q(r.filter)))Object.hasOwn(t,e)||(t[e]=n);return t}function ee(e,t,r,n){const{filter:o}=e,a=te(o,t),s=Q(o),i=K(o),l=Y(o);for(const[t,n]of Object.entries(e.with)){if(Object.hasOwn(l,t)){if(H(n))try{T(t,{...l[t],...n})}catch(e){r.push(`${a}: ${e.message}`)}else r.push(`${a}: "with" for the graphic "${t}" is an object of its settings`);continue}if(Object.hasOwn(i,t)){try{Z(t,n)}catch(e){r.push(`${a}: ${e.message}`)}continue}const e=Object.hasOwn(s,t)?s[t]:null;e?("color"===e.type?G(n):Number.isFinite(Number(n)))||r.push(`${a}: "${t}" should be a ${"color"===e.type?"color: three numbers, 0–1":"number"}`):r.push(`${a}: "with" sets "${t}", but there is no parameter called that`)}if(o.steps)o.steps.forEach((e,o)=>ee(e,[...t,o],r,n));else if(n)try{oe(o,Object.fromEntries(Object.entries(e.with).filter(([e])=>Object.hasOwn(o.graphics??{},e))),1,t,100)}catch(e){r.push(`${a}: ${e.message}`)}}function te(e,t){return e.name?`"${e.name}"`:t.length?`step ${t.map(e=>e+1).join(".")}`:"the filter"}function re(e,t={}){const r=q(e),n=[];if(ee({filter:r,with:{},opacity:1},[],n,!1),n.length)throw new Error(n.join("\n"));const o={passes:[],credits:[],problems:n,version:300===t.version?300:100,top:r,graphics:{}};if(ne({filter:r,with:{},opacity:1,skip:!1},[],{},o),n.length)throw new Error(n.join("\n"));return o.passes.length||o.passes.push(oe(q("pixel(px, py)"),{},1,[],o.version)),{name:r.name??"",author:r.author??"",description:r.description??"",version:o.version,passes:o.passes,credits:o.credits,images:K(r),graphics:o.graphics}}function ne(e,t,r,n){if(e.skip)return;if(n.passes.length>256){const e="A filter has at most 256 passes";return void(n.problems.includes(e)||n.problems.push(e))}const o=function(e){if(!e.space||void 0===e.color)return null;const{space:t,name:r,author:n,description:o,...a}=e,s=e=>({filter:e,with:{},opacity:1,skip:!1}),i=[];"srgb"!==t.in&&i.push(s({format:P,color:{rgb:`to${t.in}(rgb)`}}));i.push(s({...a,_space:t.in})),"srgb"!==t.out&&i.push(s({format:P,color:{rgb:`from${t.out}(rgb)`}}));const l={format:P,steps:i};for(const[e,t]of Object.entries({name:r,author:n,description:o}))t&&(l[e]=t);return l}(e.filter)??function(e){if("string"!=typeof e.color)return null;const t=/^(gaussian|blur)\((.*)\)$/s.exec(e.color.trim());if(!t)return null;let r=0;for(const e of t[2])if("("===e)r++;else if(")"===e&&--r<0)return null;if(0!==r)return null;const{color:n,...o}=e,a=e=>{const r={format:P,color:`${t[1]}${e}(${t[2]})`};return o.params&&(r.params=o.params),o.images&&(r.images=o.images),o.graphics&&(r.graphics=o.graphics),{filter:r,with:{},opacity:1,skip:!1}};return{...o,steps:[a("x"),a("y")]}}(e.filter);if(o)return e.filter===n.top&&(n.top=o),void ne({...e,filter:o},t,r,n);const{filter:a}=e,s={...e.with,...r};for(const t of Object.keys(r))H(r[t])&&H(e.with[t])&&(s[t]={...e.with[t],...r[t]});if(a.name&&a!==n.top&&!n.credits.some(e=>e.name===a.name&&e.author===(a.author??""))&&n.credits.push({name:a.name,author:a.author??""}),a.color){try{n.passes.push(function(e,t){e.bind={};for(const[r,n]of Object.entries(e.graphics??{})){let o=r;for(let e=2;o in t&&JSON.stringify(t[o])!==JSON.stringify(n);e++)o=`${r}~${e}`;t[o]=n,e.bind[r]=o}return e}(oe(a,s,e.opacity,t,n.version),n.graphics))}catch(e){n.problems.push(`${te(a,t)}: ${e.message}`)}return}const i=n.passes.length;a.steps.forEach((e,r)=>ne(e,[...t,r],s,n)),e.opacity<1&&(n.passes.length-i===1?n.passes[i].opacity*=e.opacity:(n.passes[i].keepInput+=1,n.passes.push(function(e,t,r){const n=300===r,o=n?"texture":"texture2D",a=[n?"#version 300 es":"","precision highp float;","uniform sampler2D image;","uniform sampler2D base;","uniform vec2 resolution;","uniform float mz_opacity;",n?"out vec4 fragColor;":"","void main() {"," vec2 uv = gl_FragCoord.xy / resolution;",` ${n?"fragColor":"gl_FragColor"} = mix(${o}(base, uv), ${o}(image, uv), mz_opacity);`,"}"].filter(Boolean).join("\n");return{name:"blend",author:"",path:t,fragment:a,params:{},values:{},opacity:e,images:[],placements:{},graphics:{},keepInput:0,blendKept:!0}}(e.opacity,t,n.version))))}function oe(e,r,n,o,a){const s=e.params??{},i={};for(const[e,t]of Object.entries(s))Object.hasOwn(r,e)?i[e]="color"===t.type?r[e].map(Number):Number(r[e]):i[e]=t.default;const l={};for(const[t,n]of Object.entries(e.images??{})){const{description:e,...o}=n;l[t]={...W,...o,...H(r[t])?r[t]:{}}}const c={};for(const[t,n]of Object.entries(e.graphics??{}))c[t]=H(r[t])?T(t,{...n,...r[t]}):n,l[t]={...W,place:"stretch"},x(t,c[t]).forEach((e,r)=>{c[e]={...c[t],onlyShadow:r},l[e]={...W,place:"stretch"}});const h=function(e,r,n=null){const o=e.params??{},a={};for(const[e,t]of Object.entries(o))a[e]="color"===t.type?"vec3":"float";const s={};for(const[t,r]of Object.entries(e.images??{}))s[t]={place:n?.[t]?.place??r.place??W.place};for(const[t,r]of Object.entries(e.graphics??{})){s[t]={place:"stretch"};const e=n?Object.keys(n).filter(e=>/_shadow\d+$/.test(e)&&e.startsWith(`${t}_shadow`)):x(t,r);for(const t of e)s[t]={place:"stretch"}}return t.filterShader(e.color,{version:r,uniforms:a,values:Object.keys(o),images:s,blend:!0,space:e._space??e.space?.in??"srgb"})}(e,a,l),u=Object.keys(l);return h.includes("uniform sampler2D mz_img_source;")&&u.push("source"),h.includes("uniform sampler2D mz_img_selection;")&&u.push("selection"),h.includes("uniform sampler2D mz_img_away;")&&u.push("away"),{name:e.name??"",author:e.author??"",path:o,color:e.color,space:e._space??"srgb",fragment:h,params:s,values:i,opacity:n,images:u,placements:l,graphics:c,keepInput:0,blendKept:!1}}function ae(e){return JSON.stringify(ce(q(e),!0),null,2)}function se(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Not valid JSON")}return q(t)}function ie(e){const t=e.includes("#")?e.slice(e.lastIndexOf("#")+1):e;let r;try{r=JSON.parse(function(e){const t=atob(e.replace(/-/g,"+").replace(/_/g,"/"));return(new TextDecoder).decode(Uint8Array.from(t,e=>e.charCodeAt(0)))}(t.trim()))}catch{throw new Error("Not a filter link")}return q(r)}function le(e){const t=String(e??"").trim();if(!t)throw new Error("Nothing to read");if(t.startsWith("{"))return se(t);if(!/\s/.test(t)){const e=t.includes("#")?t.slice(t.lastIndexOf("#")+1):t;if(/^[A-Za-z0-9_-]{8,}$/.test(e))try{return ie(e)}catch(e){if(t.includes("#"))throw e}}return q(t)}function ce(e,t){const r={};t&&(r.format=P);for(const t of["name","author","description"])e[t]&&(r[t]=e[t]);return e.notes&&e.notes.length&&(r.notes=e.notes),e.steps?(r.steps=e.steps.map(e=>{const t=ce(e.filter,!1),r=1===Object.keys(t).length&&"string"==typeof t.color?t.color:t,n={};return Object.keys(e.with).length&&(n.with=e.with),1!==e.opacity&&(n.opacity=e.opacity),e.skip&&(n.skip=!0),Object.keys(n).length?{filter:r,...n}:r}),r):(e.params&&(r.params=e.params),e.images&&(r.images=e.images),e.graphics&&(r.graphics=e.graphics),e.space&&(r.space=e.space.in===e.space.out?e.space.in:e.space),r.color=e.color,r)}const he=1e20;function ue(e,t,r,n,o){let a=0;n[0]=0,o[0]=-he,o[1]=he;for(let r=1;r<t;r++){const t=e[r]+r*r;let s=n[a],i=(t-(e[s]+s*s))/(2*(r-s));for(;i<=o[a];)a--,s=n[a],i=(t-(e[s]+s*s))/(2*(r-s));a++,n[a]=r,o[a]=i,o[a+1]=he}a=0;for(let s=0;s<t;s++){for(;o[a+1]<s;)a++;const t=n[a];r[s]=(s-t)*(s-t)+e[t]}}function pe(e,t,r){const n="function"==typeof e?e:t=>0!==e[t],o=Math.max(t,r),a=new Float64Array(o),s=new Float64Array(o),i=new Int32Array(o),l=new Float64Array(o+1),c=new Float64Array(t*r);for(let e=0;e<c.length;e++)c[e]=n(e)?0:he;for(let e=0;e<t;e++){for(let n=0;n<r;n++)a[n]=c[n*t+e];ue(a,r,s,i,l);for(let n=0;n<r;n++)c[n*t+e]=s[n]}const h=new Float32Array(t*r);for(let e=0;e<r;e++){const r=e*t;for(let e=0;e<t;e++)a[e]=c[r+e];ue(a,t,s,i,l);for(let e=0;e<t;e++)h[r+e]=s[e]>=he/2?1/0:Math.sqrt(s[e])}return h}function fe(e,t,r,{channel:n=0,scale:o=1}={}){const a=e instanceof Float32Array||e instanceof Float64Array?.5:128,s=t=>e[4*t+n]>=a,i=pe(s,t,r),l=pe(e=>!s(e),t,r),c=new Uint8ClampedArray(t*r*4);for(let e=0,t=0;e<i.length;e++,t+=4){const r=i[e]*o,n=l[e]*o;c[t]=255-Math.min(r,255),c[t+1]=255-Math.min(r,1020)/4,c[t+2]=255-Math.min(n,255),c[t+3]=255}return{data:c,width:t,height:r}}function me(e,{size:t=512}={}){if(!e)return null;const r=e.naturalWidth||e.videoWidth||e.width,n=e.naturalHeight||e.videoHeight||e.height;if(!r||!n)return null;const o=Math.min(1,t/Math.max(r,n)),a=Math.max(1,Math.round(r*o)),s=Math.max(1,Math.round(n*o));let i;if(!e.data||"undefined"!=typeof HTMLElement&&e instanceof HTMLElement){const t=("undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(a,s):Object.assign(document.createElement("canvas"),{width:a,height:s})).getContext("2d",{willReadFrequently:!0});t.drawImage(e,0,0,a,s),i=t.getImageData(0,0,a,s).data}else if(i=e.data,a!==r||s!==n){const e=new i.constructor(a*s*4);for(let t=0;t<s;t++){const o=Math.min(n-1,Math.floor((t+.5)*n/s));for(let n=0;n<a;n++){const s=4*(o*r+Math.min(r-1,Math.floor((n+.5)*r/a))),l=4*(t*a+n);for(let t=0;t<4;t++)e[l+t]=i[s+t]}}i=e}return fe(i,a,s,{scale:r/a})}const de=e=>e.passes.some(e=>e.images?.includes("away"));function ge(e,t){if(!de(t))return e;const r=e.setImage.bind(e);let n=!1,o=null;return e.setImage=(t,a)=>"away"===t?(n=null!=a,r("away",n?a:me(o))):(r(t,a),"selection"===t&&(o=a??null,n||r("away",me(o))),e),e}function we(e,r,n={}){if(e.isContextLost())throw new Error("The WebGL context is lost");const o=$e(e,n.precision),a=t.filterVertexShader({version:r.version}),s=[];try{for(const t of r.passes)s.push(be(e,a,t.fragment,t.name))}catch(t){for(const t of s)e.deleteProgram(t);throw t}const i=(e,t)=>e.bind&&Object.hasOwn(e.bind,t)?e.bind[t]:t,l=s.map(()=>new Map),c=(t,r)=>(l[t].has(r)||l[t].set(r,e.getUniformLocation(s[t],r)),l[t].get(r)),h=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,h),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),e.STATIC_DRAW);const u={texture:e.createTexture(),framebuffer:null};e.bindTexture(e.TEXTURE_2D,u.texture),ye(e);const p=new Map,f=new Map,m=e.createTexture();e.bindTexture(e.TEXTURE_2D,m),ye(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([255,255,255,255]));const d=e.createTexture();e.bindTexture(e.TEXTURE_2D,d),ye(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([0,0,0,0]));const g=[];let w=0,y=0;const $={passes:r.passes,get precision(){return o.name},setImage(t,r){if("string"!=typeof t&&(r=t,t=null),t&&"source"!==t&&null==r)return p.has(t)&&e.deleteTexture(p.get(t)),p.delete(t),f.delete(t),$;let n=u.texture;if(t&&"source"!==t&&(p.has(t)||(p.set(t,e.createTexture()),e.bindTexture(e.TEXTURE_2D,p.get(t)),ye(e)),n=p.get(t)),r&&r.data&&r.width&&r.height&&"undefined"!=typeof ImageData&&!(r instanceof ImageData)){const e=r.data,t=e instanceof Float32Array||e instanceof Float64Array,n=e instanceof Uint8ClampedArray?e:Uint8ClampedArray.from(e,t?e=>255*e:void 0);r=new ImageData(n,r.width,r.height)}return e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r),t&&f.set(t,[r.naturalWidth||r.videoWidth||r.width||1,r.naturalHeight||r.videoHeight||r.height||1]),$},draw({t:t=0}={}){if(e.drawingBufferWidth!==w||e.drawingBufferHeight!==y){w=e.drawingBufferWidth,y=e.drawingBufferHeight;for(const t of g)e.bindTexture(e.TEXTURE_2D,t.texture),e.texImage2D(e.TEXTURE_2D,0,o.internal,w,y,0,e.RGBA,o.type,null)}let n=u;const a=[];return r.passes.forEach((l,$)=>{for(let e=0;e<l.keepInput;e++)a.push(n);const b=$===r.passes.length-1?null:function(t){let r=g.find(e=>!t.includes(e));return r||(r={texture:e.createTexture(),framebuffer:e.createFramebuffer()},e.bindTexture(e.TEXTURE_2D,r.texture),ye(e,o.filter),e.texImage2D(e.TEXTURE_2D,0,o.internal,w,y,0,e.RGBA,o.type,null),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r.texture,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE&&"byte"!==o.name&&(Object.assign(o,$e(e,"byte")),e.bindTexture(e.TEXTURE_2D,r.texture),ye(e,o.filter),e.texImage2D(e.TEXTURE_2D,0,o.internal,w,y,0,e.RGBA,o.type,null)),g.push(r)),r}([n,...a]);e.bindFramebuffer(e.FRAMEBUFFER,b?b.framebuffer:null),e.viewport(0,0,w,y);const x=s[$];e.useProgram(x);const E=e.getAttribLocation(x,"position");e.bindBuffer(e.ARRAY_BUFFER,h),e.enableVertexAttribArray(E),e.vertexAttribPointer(E,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,n.texture),e.uniform1i(c($,"image"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,l.blendKept?a[a.length-1].texture:null),l.blendKept&&e.uniform1i(c($,"base"),1),l.images.forEach((t,r)=>{if(e.activeTexture(e.TEXTURE2+r),e.bindTexture(e.TEXTURE_2D,"source"===t?u.texture:p.get(i(l,t))??(l.graphics?.[t]?d:m)),e.uniform1i(c($,`mz_img_${t}`),2+r),!l.placements[t])return;const n=f.get(i(l,t))??[1,1],o=l.placements[t];e.uniform2f(c($,`mz_size_${t}`),n[0],n[1]),e.uniform4f(c($,`mz_place_${t}`),Number(o.zoom),Number(o.x),Number(o.y),Number(o.angle))}),e.uniform2f(c($,"resolution"),w,y),e.uniform1f(c($,"t"),t),e.uniform1f(c($,"mz_opacity"),l.opacity);for(const[t,r]of Object.entries(l.params)){const n=l.values[t];"color"===r.type?e.uniform3fv(c($,t),n.map(Number)):e.uniform1f(c($,t),Number(n))}e.drawArrays(e.TRIANGLES,0,3),l.blendKept&&a.pop(),n=b}),$},dispose(){for(const t of s)e.deleteProgram(t);e.deleteTexture(u.texture),e.deleteTexture(m),e.deleteTexture(d);for(const t of p.values())e.deleteTexture(t);for(const t of g)e.deleteTexture(t.texture),e.deleteFramebuffer(t.framebuffer);e.deleteBuffer(h)}};return ge($,r)}function ye(e,t=e.LINEAR){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t)}function $e(e,t="byte"){const r={name:"byte",internal:e.RGBA,type:e.UNSIGNED_BYTE,filter:e.LINEAR};if("half"!==t&&"float"!==t)return r;if("undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext){if(!e.getExtension("EXT_color_buffer_float"))return r;const n=e.getExtension("OES_texture_float_linear")?e.LINEAR:e.NEAREST;return"float"===t?{name:"float",internal:e.RGBA32F,type:e.FLOAT,filter:n}:{name:"half",internal:e.RGBA16F,type:e.HALF_FLOAT,filter:e.LINEAR}}if("float"===t&&e.getExtension("OES_texture_float")&&e.getExtension("WEBGL_color_buffer_float"))return{name:"float",internal:e.RGBA,type:e.FLOAT,filter:e.getExtension("OES_texture_float_linear")?e.LINEAR:e.NEAREST};const n=e.getExtension("OES_texture_half_float");return n&&e.getExtension("EXT_color_buffer_half_float")?{name:"half",internal:e.RGBA,type:n.HALF_FLOAT_OES,filter:e.getExtension("OES_texture_half_float_linear")?e.LINEAR:e.NEAREST}:r}function be(e,t,r,n){const o=e.createProgram(),a=[];let s=null;for(const[i,l]of[[e.VERTEX_SHADER,t],[e.FRAGMENT_SHADER,r]]){const t=e.createShader(i);if(a.push(t),e.shaderSource(t,l),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS)){s=`${n||"The filter"} does not compile: ${(e.getShaderInfoLog(t)??"").trim()}`;break}e.attachShader(o,t)}s||(e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS)||(s=`${n||"The filter"} does not link: ${(e.getProgramInfoLog(o)??"").trim()}`));for(const t of a)e.deleteShader(t);if(s)throw e.deleteProgram(o),new Error(s);return o}const xe={data:new Float32Array([1,1,1,1]),width:1,height:1},Ee={data:new Float32Array([0,0,0,0]),width:1,height:1},ve={cover:0,fit:1,stretch:2,tile:3};function Me(e){return ve[e??"cover"]??0}function Ae(e,t){return e-t*Math.floor(e/t)}const _e=(e,t)=>e<0?0:e>t?t:e;function ke(e,t,r,n,o,a){const s=Math.floor(n),i=Math.floor(o),l=n-s,c=o-i,h=_e(s,t-1),u=_e(s+1,t-1),p=_e(i,r-1),f=_e(i+1,r-1),m=4*(p*t+h),d=4*(p*t+u),g=4*(f*t+h),w=4*(f*t+u);for(let t=0;t<4;t++){const r=e[m+t]+(e[d+t]-e[m+t])*l,n=e[g+t]+(e[w+t]-e[g+t])*l;a[t]=r+(n-r)*c}return a}function Oe(e,t,r){const n=Math.min(Math.max(Math.ceil(e),0),t),o=[];for(let e=-n;e<=n;e++)r(e)&&o.push(e);return o}function Te(e,t,r,n,o,a,s,i,l=0,c=n){const h=new Float32Array(r*n*3),u=a.length,p=Int32Array.from(a),f=Float64Array.from(s??a.map(()=>1)),m="x"===o?r:n,d=new Int32Array(u);for(let n=l;n<c;n++)for(let a=0;a<r;a++){const s="x"===o?a:n;for(let e=0;e<u;e++){let i=s+p[e];i=i<0?0:i>=m?m-1:i,d[e]=("x"===o?n*r+i:i*r+a)*t}let l=0,c=0,g=0;for(let t=0;t<u;t++){const r=d[t],n=f[t];l+=e[r]*n,c+=e[r+1]*n,g+=e[r+2]*n}const w=3*(n*r+a);h[w]=l/i,h[w+1]=c/i,h[w+2]=g/i}return h}function je(e,t,r,n,o,a,s,i=0,l=n){const c=new Float32Array(r*n*3),h="x"===o?r:n,u="x"===o?n:r,p=s-a+1,f=(e,t)=>"x"===o?e*r+t:t*r+e,m=e=>e<0?0:e>=h?h-1:e,[d,g]="x"===o?[i,l]:[0,u],[w,y]="x"===o?[0,h]:[i,l];for(let r=d;r<g;r++){let n=0,o=0,i=0;for(let l=w+a;l<=w+s;l++){const a=f(r,m(l))*t;n+=e[a],o+=e[a+1],i+=e[a+2]}for(let l=w;l<y;l++){const h=3*f(r,l);c[h]=n/p,c[h+1]=o/p,c[h+2]=i/p;const u=f(r,m(l+a))*t,d=f(r,m(l+s+1))*t;n+=e[d]-e[u],o+=e[d+1]-e[u+1],i+=e[d+2]-e[u+2]}}return c}function Fe(e,t,r,n,o,a,s,i,l=0,c=n){const h=new Float32Array(r*n*3),u="x"===o?r:n;for(let n=l;n<c;n++)for(let l=0;l<r;l++){const c="x"===o?l:n;let p=s,f=s,m=s;for(let s=0;s<a.length;s++){let h=c+a[s];h=h<0?0:h>=u?u-1:h;const d=("x"===o?n*r+h:h*r+l)*t;i?(e[d]>p&&(p=e[d]),e[d+1]>f&&(f=e[d+1]),e[d+2]>m&&(m=e[d+2])):(e[d]<p&&(p=e[d]),e[d+1]<f&&(f=e[d+1]),e[d+2]<m&&(m=e[d+2]))}const d=3*(n*r+l);h[d]=p,h[d+1]=f,h[d+2]=m}return h}const Se=(e,t,r)=>e+t*r,Ce=(e,t)=>t>e?t:e,Ie=(e,t)=>t<e?t:e;function Re(e,t,r,n=0,o=r){const a=new Float32Array(t*r*3);for(let r=n*t;r<o*t;r++)a[3*r]=e[4*r],a[3*r+1]=e[4*r+1],a[3*r+2]=e[4*r+2];return a}const Ue=(e,t,r,n)=>[Math.max(0,e-r),Math.min(n,t+r)];function Ne(e,t,r,n,o,a,s,i){const l=Oe(a,i,e=>Math.abs(e)<=a);if(!l.length)return Re(e,t,r,n,o);const c=l[0],h=l[l.length-1];if(1===s.length)return je(e,4,t,r,s[0],c,h,n,o);const[u,p]=Ue(n,o,h,r);return je(je(e,4,t,r,"x",c,h,u,p),3,t,r,"y",c,h,n,o)}function ze(e,t,r,n,o,a,s,i){if(!(a>0))return Re(e,t,r,n,o);const l=3*a,c=Oe(l,i,e=>Math.abs(e)<=l),h=c.map(e=>Math.exp(-e*e/(2*a*a))),u=h.reduce((e,t)=>e+t,0);if(1===s.length)return Te(e,4,t,r,s[0],c,h,u,n,o);const[p,f]=Ue(n,o,c[c.length-1],r);return Te(Te(e,4,t,r,"x",c,h,u,p,f),3,t,r,"y",c,h,u,n,o)}function Pe(e,r,n,o,a,s,i,l){const c=Oe(s,t.REACH.square,e=>Math.abs(e)<=s);if(!c.length)return new Float32Array(r*n*3).fill(i);const[h,u]=Ue(o,a,c[c.length-1],n);return Fe(Fe(e,4,r,n,"x",c,i,l,h,u),3,r,n,"y",c,i,l,o,a)}function Be(e,t,r,n,o,a){const s=function(e,t,r){const n=new Float32Array(t*r);for(let o=0;o<t*r;o++)n[o]=.299*e[4*o]+.587*e[4*o+1]+.114*e[4*o+2];return n}(e,t,r),i=new Float32Array(t*r);for(let e=n;e<o;e++)for(let n=0;n<t;n++){const o=(o,a)=>s[_e(e+a,r-1)*t+_e(n+o,t-1)];i[e*t+n]=a(o)}return i}const De=e=>e(1,-1)+2*e(1,0)+e(1,1)-(e(-1,-1)+2*e(-1,0)+e(-1,1)),Le=e=>e(-1,1)+2*e(0,1)+e(1,1)-(e(-1,-1)+2*e(0,-1)+e(1,-1)),Ge=e=>4*e(0,0)-e(-1,0)-e(1,0)-e(0,-1)-e(0,1),He=e=>.5+e(-1,-1)-e(1,1),We=e=>Math.hypot(De(e),Le(e));function qe(e,t,r,n,o,a,s,i,l,c,h){for(let u=0;u<3;u++){let p=i,f=0;for(const i of a)for(const c of a){const a=s?s(i,c):1;p=l(p,e[4*(_e(o+c,r-1)*t+_e(n+i,t-1))+u],a),f+=a}c[u]=h?h(p,f):p}return c}function Xe(e,t,r,n,o,a,s,i,l){for(let c=0;c<3;c++){let h=0,u=0;for(const l of s){const s=i?i(l):1,p="x"===a?_e(n+l,t-1):n;h+=e[4*(("y"===a?_e(o+l,r-1):o)*t+p)+c]*s,u+=s}l[c]=h/u}return l}const Ye=(e,t,r,n,o)=>{const a=4*(n*t+r);return o[0]=e[a],o[1]=e[a+1],o[2]=e[a+2],o};const Ze=e=>e<.04045?e/12.92:Math.pow((e+.055)/1.055,2.4),Je=e=>(e=Math.max(e,0))<.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055,Ve=(e,t,r,n,o)=>{const a=n===e?(t-r)/o:n===t?2+(r-e)/o:4+(e-t)/o;return a/6-Math.floor(a/6)},Ke=(e,t)=>{const r=Math.abs(6*(e+t-Math.floor(e+t))-3);return Math.min(Math.max(r-1,0),1)};const Qe=e=>e<.008856?7.787*e+16/116:Math.cbrt(e),et=e=>e<.206893?(e-16/116)/7.787:e*e*e;var tt=Object.freeze({__proto__:null,BLANK:xe,CLEAR:Ee,at:function(e,t,r){return Number(e[t][r])},at_blur:function(e,r,n,o,a,s,i){return qe(e,r,n,o,a,Oe(s,t.REACH.square,e=>Math.abs(e)<=s),null,0,Se,i,(e,t)=>e/t)},at_blurx:function(e,r,n,o,a,s,i){return Xe(e,r,n,o,a,"x",Oe(s,t.REACH.line,e=>Math.abs(e)<=s),null,i)},at_blury:function(e,r,n,o,a,s,i){return Xe(e,r,n,o,a,"y",Oe(s,t.REACH.line,e=>Math.abs(e)<=s),null,i)},at_dilate:function(e,r,n,o,a,s,i){return qe(e,r,n,o,a,Oe(s,t.REACH.square,e=>Math.abs(e)<=s),null,0,Ce,i)},at_erode:function(e,r,n,o,a,s,i){return qe(e,r,n,o,a,Oe(s,t.REACH.square,e=>Math.abs(e)<=s),null,1,Ie,i)},at_gaussian:function(e,r,n,o,a,s,i){if(!(s>0))return Ye(e,r,o,a,i);const l=3*s;return qe(e,r,n,o,a,Oe(l,t.REACH.square,e=>Math.abs(e)<=l),(e,t)=>Math.exp(-(e*e+t*t)/(2*s*s)),0,Se,i,(e,t)=>e/t)},at_gaussianx:function(e,r,n,o,a,s,i){if(!(s>0))return Ye(e,r,o,a,i);const l=3*s;return Xe(e,r,n,o,a,"x",Oe(l,t.REACH.line,e=>Math.abs(e)<=l),e=>Math.exp(-e*e/(2*s*s)),i)},at_gaussiany:function(e,r,n,o,a,s,i){if(!(s>0))return Ye(e,r,o,a,i);const l=3*s;return Xe(e,r,n,o,a,"y",Oe(l,t.REACH.line,e=>Math.abs(e)<=l),e=>Math.exp(-e*e/(2*s*s)),i)},at_sharpen:function(e,t,r,n,o,a,s){const i=(e,n)=>4*(_e(n,r-1)*t+_e(e,t-1)),l=i(n,o),c=i(n-1,o),h=i(n+1,o),u=i(n,o-1),p=i(n,o+1);for(let t=0;t<3;t++)s[t]=e[l+t]+a*(4*e[l+t]-e[c+t]-e[h+t]-e[u+t]-e[p+t]);return s},col_fromhsl:function(e,t,r,n){const o=(1-Math.abs(2*r-1))*t;return n[0]=r-.5*o+o*Ke(e,0),n[1]=r-.5*o+o*Ke(e,2/3),n[2]=r-.5*o+o*Ke(e,1/3),n},col_fromhsv:function(e,t,r,n){return n[0]=r*(1+(Ke(e,0)-1)*t),n[1]=r*(1+(Ke(e,2/3)-1)*t),n[2]=r*(1+(Ke(e,1/3)-1)*t),n},col_fromlab:function(e,t,r,n){const o=(100*e+16)/116,a=o-256*(r-.5)/200,s=.95047*et(o+256*(t-.5)/500),i=et(o),l=1.08883*et(a),c=Math.min(Math.max(3.2404542*s-1.5371385*i-.4985314*l,0),1),h=Math.min(Math.max(-.969266*s+1.8760108*i+.041556*l,0),1),u=Math.min(Math.max(.0556434*s-.2040259*i+1.0572252*l,0),1);return n[0]=Je(c),n[1]=Je(h),n[2]=Je(u),n},col_fromlinear:function(e,t,r,n){return n[0]=Je(e),n[1]=Je(t),n[2]=Je(r),n},col_fromoklab:function(e,t,r,n){let o=e+.3963377774*(t-=.5)+.2158037573*(r-=.5),a=e-.1055613458*t-.0638541728*r,s=e-.0894841775*t-1.291485548*r;o*=o*o,a*=a*a,s*=s*s;const i=Math.min(Math.max(4.0767416621*o-3.3077115913*a+.2309699292*s,0),1),l=Math.min(Math.max(-1.2684380046*o+2.6097574011*a-.3413193965*s,0),1),c=Math.min(Math.max(-.0041960863*o-.7034186147*a+1.707614701*s,0),1);return n[0]=Je(i),n[1]=Je(l),n[2]=Je(c),n},col_fromycbcr:function(e,t,r,n){return t-=.5,r-=.5,n[0]=e+1.402*r,n[1]=e-.344136*t-.714136*r,n[2]=e+1.772*t,n},col_tohsl:function(e,t,r,n){const o=Math.max(e,t,r),a=Math.min(e,t,r),s=o-a,i=.5*(o+a);return n[0]=s>0?Ve(e,t,r,o,s):0,n[1]=s>0?s/(1-Math.abs(2*i-1)):0,n[2]=i,n},col_tohsv:function(e,t,r,n){const o=Math.max(e,t,r),a=o-Math.min(e,t,r);return n[0]=a>0?Ve(e,t,r,o,a):0,n[1]=o>0?a/o:0,n[2]=o,n},col_tolab:function(e,t,r,n){const o=Ze(e),a=Ze(t),s=Ze(r),i=Qe((.4124564*o+.3575761*a+.1804375*s)/.95047),l=Qe(.2126729*o+.7151522*a+.072175*s),c=Qe((.0193339*o+.119192*a+.9503041*s)/1.08883);return n[0]=(116*l-16)/100,n[1]=.5+500*(i-l)/256,n[2]=.5+200*(l-c)/256,n},col_tolinear:function(e,t,r,n){return n[0]=Ze(e),n[1]=Ze(t),n[2]=Ze(r),n},col_tooklab:function(e,t,r,n){const o=Ze(e),a=Ze(t),s=Ze(r),i=Math.cbrt(.4122214708*o+.5363325363*a+.0514459929*s),l=Math.cbrt(.2119034982*o+.6806995451*a+.1073969566*s),c=Math.cbrt(.0883024619*o+.2817188376*a+.6299787005*s);return n[0]=.2104542553*i+.793617785*l-.0040720468*c,n[1]=.5+1.9779984951*i-2.428592205*l+.4505937099*c,n[2]=.5+.0259040371*i+.7827717662*l-.808675766*c,n},col_toycbcr:function(e,t,r,n){const o=.299*e+.587*t+.114*r;return n[0]=o,n[1]=.5+.5643*(r-o),n[2]=.5+.7132*(e-o),n},convolve:function(e,t,r,n,o,a,s,i,l,c,h,u,p,f,m){const d=(e,a)=>4*(_e(o+a,r-1)*t+_e(n+e,t-1)),g=[[a,-1,-1],[s,0,-1],[i,1,-1],[l,-1,0],[c,0,0],[h,1,0],[u,-1,1],[p,0,1],[f,1,1]];for(let t=0;t<3;t++){let r=0;for(const[n,o,a]of g)r+=n*e[d(o,a)+t];m[t]=r}return m},factorial:function(e){let t=1;for(let r=2;r<=170&&!(r>e);r++)t*=r;return t},fmod:Ae,gcd:function(e,t){e=Math.abs(e),t=Math.abs(t);for(let r=0;r<64&&0!==t;r++){const r=Ae(e,t);e=t,t=r}return e},perm:function(e,t){let r=1;for(let n=0;n<170&&!(n>=t);n++)r*=e-n;return r},picture:function(e,t,r,n,o,a,s,i,l,c,h,u,p){let f,m;0===c?f=m=Math.max(n/t,o/r):1===c?f=m=Math.min(n/t,o/r):2===c?(f=n/t,m=o/r):f=m=1,f*=a,m*=a;const d=h+.5-s*n,g=u+.5-i*o,w=Math.cos(l),y=Math.sin(l);let $=(w*d+y*g)/f+.5*t,b=(w*g-y*d)/m+.5*r;if(3===c)$=Ae($,t),b=Ae(b,r);else if($<0||b<0||$>t||b>r)return p[0]=p[1]=p[2]=p[3]=0,p;return ke(e,t,r,$-.5,b-.5,p)},placeCode:Me,plane_blur:function(e,r,n,o,a,s){return Ne(e,r,n,o,a,s,["x","y"],t.REACH.square)},plane_blurx:function(e,r,n,o,a,s){return Ne(e,r,n,o,a,s,["x"],t.REACH.line)},plane_blury:function(e,r,n,o,a,s){return Ne(e,r,n,o,a,s,["y"],t.REACH.line)},plane_dilate:function(e,t,r,n,o,a){return Pe(e,t,r,n,o,a,0,!0)},plane_emboss:function(e,t,r,n,o){return Be(e,t,r,n,o,He)},plane_erode:function(e,t,r,n,o,a){return Pe(e,t,r,n,o,a,1,!1)},plane_gaussian:function(e,r,n,o,a,s){return ze(e,r,n,o,a,s,["x","y"],t.REACH.square)},plane_gaussianx:function(e,r,n,o,a,s){return ze(e,r,n,o,a,s,["x"],t.REACH.line)},plane_gaussiany:function(e,r,n,o,a,s){return ze(e,r,n,o,a,s,["y"],t.REACH.line)},plane_laplacian:function(e,t,r,n,o){return Be(e,t,r,n,o,Ge)},plane_sharpen:function(e,t,r,n,o,a){const s=new Float32Array(t*r*3);for(let i=n;i<o;i++)for(let n=0;n<t;n++){const o=(e,n)=>4*(_e(n,r-1)*t+_e(e,t-1)),l=o(n,i),c=o(n-1,i),h=o(n+1,i),u=o(n,i-1),p=o(n,i+1);for(let r=0;r<3;r++)s[3*(i*t+n)+r]=e[l+r]+a*(4*e[l+r]-e[c+r]-e[h+r]-e[u+r]-e[p+r])}return s},plane_sobel:function(e,t,r,n,o){return Be(e,t,r,n,o,We)},plane_sobelx:function(e,t,r,n,o){return Be(e,t,r,n,o,De)},plane_sobely:function(e,t,r,n,o){return Be(e,t,r,n,o,Le)},random:function(e,t,r,n){const o=43758.5453*Math.sin(12.9898*(e+.5)+78.233*(r-t-.5)+37.719*n);return o-Math.floor(o)},root:function(e,t){return 2===e?Math.sqrt(t):3===e?Math.sign(t)*Math.pow(Math.abs(t),1/3):Math.pow(t,1/e)},round:function(e,t){const r=Math.pow(10,t);return Math.sign(e)*Math.floor(Math.abs(e)*r+.5)/r},sample:ke,sampleOrZero:function(e,t,r,n,o,a){const s=n+.5,i=o+.5;return s<0||i<0||s>t||i>r?(a[0]=a[1]=a[2]=a[3]=0,a):ke(e,t,r,n,o,a)},scratch:function(){return new Float64Array(4)},smoothstep:function(e,t,r){const n=Math.min(Math.max((r-e)/(t-e),0),1);return n*n*(3-2*n)}});const rt="\\:",nt=Object.keys(tt).filter(e=>"function"==typeof tt[e]),ot=e=>Object.assign(Object.create(null),e),at=ot({r:"$r",g:"$g",b:"$b",a:"$a",x:"$x",y:"$y",px:"$px",py:"$py",w:"$w",h:"$h",t:"$t",gray:"$gray"}),st=ot({pi:"Math.PI","π":"Math.PI",e:"Math.E",tau:"(2 * Math.PI)","τ":"(2 * Math.PI)","∞":"Infinity","-∞":"(-Infinity)","°":"(Math.PI / 180)"}),it=ot({sqrt:1,abs:1,floor:1,ceil:1,ln:"log",sin:1,cos:1,tan:1,arcsin:"asin",arccos:"acos",arctan:"atan",sinh:1,cosh:1,tanh:1,arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",sign:1,exp:1,exp2:e=>`Math.pow(2, ${e})`,log2:1,expm1:e=>`(Math.exp(${e}) - 1)`,loglog:e=>`Math.log(Math.log(${e}))`,logloglog:e=>`Math.log(Math.log(Math.log(${e})))`,csc:e=>`(1 / Math.sin(${e}))`,sec:e=>`(1 / Math.cos(${e}))`,cot:e=>`(1 / Math.tan(${e}))`,fract:e=>`(${e} - Math.floor(${e}))`,radians:e=>`(${e} * 0.017453292519943295)`,degrees:e=>`(${e} * 57.29577951308232)`,inversesqrt:e=>`(1 / Math.sqrt(${e}))`,arcsec:e=>`Math.acos(1 / ${e})`,arccsc:e=>`Math.asin(1 / ${e})`,arccot:e=>`(Math.PI / 2 - Math.atan(${e}))`,atan2:(e,t)=>`Math.atan2(${e}, ${t})`,pow:(e,t)=>`Math.pow(${e}, ${t})`,mod:(e,t)=>`(${e} - ${t} * Math.floor(${e} / ${t}))`,step:(e,t)=>`(${t} < ${e} ? 0 : 1)`,clamp:(e,t,r)=>`Math.min(Math.max(${e}, ${t}), ${r})`,mix:(e,t,r)=>`(${e} + (${t} - ${e}) * ${r})`,smoothstep:(e,t,r)=>`$h_smoothstep(${e}, ${t}, ${r})`}),lt=ot({atan2:2,pow:2,mod:2,step:2,clamp:3,mix:3,smoothstep:3});const ct=ot({blur:3,blurx:3,blury:3,gaussian:3,gaussianx:3,gaussiany:3,dilate:3,erode:3,sharpen:3,sobel:1,sobelx:1,sobely:1,laplacian:1,emboss:1}),ht=(e,t)=>({kind:e,c:t}),ut=e=>ht("f",[e]),pt=e=>ht("b",[e]),ft=e=>1===e.length?ut(e[0]):ht("v",e),mt=(e,t=0)=>"b"===e.kind?`(${e.c[0]} ? 1 : 0)`:"f"===e.kind?e.c[0]:e.c[t]??e.c[0],dt=e=>"v"===e.kind?e.c.length:1;class gt extends Error{}function wt(e){if(e.blendKept)return{blend:!0,source:""};const o=e.params??{},a=new Set([...Object.keys(e.placements??{}),"source","selection"]),s=new yt(o,a,e.space??"srgb");s.graphics=new Set(Object.keys(e.graphics??{})),s.bind=ot(e.bind??{});const i="string"==typeof e.color?{rgba:e.color}:e.color,l=(n,s)=>{const i=[...t.FILTER_FUNCTIONS,...Object.keys(e.placements??{})],l=[...t.FILTER_VALUES,...Object.keys(o)];return t.filterPictureCalls(r.parseTree(n,{names:i,values:l,blocks:null}),a,{whole:s})};for(const e of["rgba","rgb","r","g","b","a"]){if(!i[e])continue;let t;try{t=l(i[e],"rgba"===e)}catch(e){throw new gt(e.message)}s.channel(e,t)}const c=s.source();n.checkGeneratedJs(c,{variables:/^\$\w+$/,indexable:/^\$[A-Z]\w*$/,strings:!1});const h=new Function(...s.parameters(),c);return{source:c,uses:s.uses,pictures:[...s.pictureNames],run(e){h(...s.arguments(e))}}}class yt{constructor(e,t,r="srgb"){this.params=e,this.pictures=t,this.space="srgb"===r?null:r,this.pre=[],this.body=[],this.n=0,this.uses=new Set,this.pictureNames=new Set,this.perPixel=new Map,this.planes=new Map,this.scratch=0}temp(e,t=this.body){const r="$v"+this.n++;return t.push(`let ${r} = ${e};`),r}keep(e,t=this.body){return ht(e.kind,e.c.map(e=>/^[\w$.]+$|^\(?-?[\d.e+]+\)?$/.test(e)?e:this.temp(e,t)))}fail(e){throw new gt(e)}leaf(e){if("number"===e.type)return ut(`(${e.value.replace(/\.+$/,"")})`);"string"===e.type&&this.fail("a filter has no text: numbers and colors only");const t=e.value,r=/^(-?(?:\d+\.?\d*|\.\d+))%$/.exec(t);if(r)return ut(`(${r[1]} / 100)`);if("t"===t&&this.uses.add("t"),at[t])return ut(at[t]);if("rgb"===t)return ft(["$r","$g","$b"]);if("unchanged"===t)return ut("$u");if("selected"===t)return ut(this.pictureHere("selection").c[0]);if("away"===t){const[e,t]=this.pictureHere("away").c;return ut(`(${e} > 0 ? 255 * (1 - ${e}) : 1020 * (1 - ${t}))`)}if(st[t])return ut(st[t]);if("true"===t||"false"===t)return pt(t);if(Object.prototype.hasOwnProperty.call(this.params,t)){const e=`$p_${t}`;return"color"===this.params[t].type?ft([`${e}_0`,`${e}_1`,`${e}_2`]):ut(e)}if(this.pictures.has(t)){const e=this.pictureHere(t);return ft(e.c.slice(0,3))}if(t.startsWith("mz_px_")&&this.pictures.has(t.slice(6)))return this.pictureHere(t.slice(6));this.fail(`unknown name "${t}"`)}pictureHere(e){if(!this.perPixel.has(e)){const t=this.sampler(e,"$px","$py");this.perPixel.set(e,this.keep(t))}return this.perPixel.get(e)}sampler(e,t,r){const n=this.scratchArray();return"source"===e?(this.uses.add("source"),this.body.push(`$h_sample($S, $w, $h, ${t}, ${r}, ${n});`)):(this.pictureNames.add(e),this.body.push(`$h_picture($Q_${e}, $qw_${e}, $qh_${e}, $w, $h, $qz_${e}, $qx_${e}, $qy_${e}, $qa_${e}, $qm_${e}, ${t}, ${r}, ${n});`)),this.space&&"selection"!==e&&"away"!==e&&this.body.push(`$h_col_to${this.space}(${n}[0], ${n}[1], ${n}[2], ${n});`),ft([0,1,2,3].map(e=>`${n}[${e}]`))}scratchArray(){const e="$T"+this.scratch++;return this.pre.push(`let ${e} = $h_scratch();`),e}value(e){return"op"===e.type?this.op(e):this.leaf(e)}op(e){const{op:t,args:r}=e,n=t.startsWith(rt)?t.slice(2):null;if(null!==n)return this.call(n,r,e);const o=()=>r.map(e=>this.value(e));switch(t){case"+":case"-":case"*":case"/":{const[e,r]=o();return this.componentwise([e,r],(e,r)=>`(${e} ${t} ${r})`)}case"neg":return this.componentwise(o(),e=>`(-${e})`);case"^":return this.power(r);case"mod":return this.componentwise(o(),it.mod);case"<":case">":case"≤":case"≥":{const[e,r]=o(),n={"≤":"<=","≥":">="}[t]??t;return pt(`(${mt(e)} ${n} ${mt(r)})`)}case"=":case"===":case"≠":case"≠=":case"≡":{const[e,r]=o(),n=Math.max(dt(e),dt(r)),a=Array.from({length:n},(t,n)=>`${mt(e,n)} === ${mt(r,n)}`).join(" && ");return pt("≠"===t||"≠="===t?`!(${a})`:`(${a})`)}case"≈":{const[e,t]=o();return pt(`(Math.abs(${mt(e)} - ${mt(t)}) < 1e-5)`)}case"&":{const[e,t]=o();return pt(`(${this.truth(e)} && ${this.truth(t)})`)}case"|":{const[e,t]=o();return pt(`(${this.truth(e)} || ${this.truth(t)})`)}case"\\xor":{const[e,t]=o();return pt(`(${this.truth(e)} !== ${this.truth(t)})`)}case"\\nand":{const[e,t]=o();return pt(`!(${this.truth(e)} && ${this.truth(t)})`)}case"\\nor":{const[e,t]=o();return pt(`!(${this.truth(e)} || ${this.truth(t)})`)}case"\\implies":{const[e,t]=o();return pt(`(!${this.truth(e)} || ${this.truth(t)})`)}case"\\iff":{const[e,t]=o();return pt(`(${this.truth(e)} === ${this.truth(t)})`)}case"\\not":{const[e]=o();return pt(`!${this.truth(e)}`)}case"?:":return this.ternary(r);case"max":case"min":return this.componentwise(o(),(...e)=>`Math.${t}(${e.join(", ")})`);case"sum":return this.componentwise(o(),(...e)=>`(${e.join(" + ")})`);case"prod":return this.componentwise(o(),(...e)=>`(${e.join(" * ")})`);case"mean":return this.componentwise(o(),(...e)=>`((${e.join(" + ")}) / ${e.length})`);case"()":case"[]":case"{}":case"(]":case"[)":{const e=o().flatMap(e=>"b"===e.kind?[mt(e)]:e.c.map((t,r)=>mt(e,r)));return e.length>4&&this.fail("a color has at most 4 values (r, g, b, a)"),ft(e)}case"!":return this.componentwise(o(),e=>`$h_factorial(${e})`);case"perm":return this.componentwise(o(),(e,t)=>`$h_perm(${e}, ${t})`);case"comb":return this.componentwise(o(),(e,t)=>`($h_perm(${e}, ${t}) / $h_factorial(${t}))`);case"gcd":return this.componentwise(o(),(...e)=>e.reduce((e,t)=>`$h_gcd(${e}, ${t})`));case"round":{const[e,t]=o();return this.componentwise([e,t],(e,t)=>`$h_round(${e}, ${t})`)}case"log":{const[e,t]=o();return this.componentwise([e,t],(e,t)=>`(Math.log(${t}) / Math.log(${e}))`)}case"root":{const[e,t]=o();return this.componentwise([e,t],(e,t)=>`$h_root(${e}, ${t})`)}case"∈":case"∉":{const t=function(e){const[t,r]=e.args;if("op"!==r.type||"setbuilder"!==r.op)return null;let[n,o]=r.args,a=null;"op"===n.type&&"∈"===n.op&&([n,a]=n.args);const s=e=>"symbol"===e.type&&e.value===n.value?t:"op"===e.type?{...e,args:e.args.map(s)}:e,i=a?{type:"op",op:"&",args:[{type:"op",op:"∈",args:[t,a]},s(o)]}:s(o);return"∉"===e.op?{type:"op",op:"\\not",args:[i]}:i}(e);return t?this.value(t):this.membership(e)}case"random":return this.random();case"evaluated":return this.value(function(e){const[t,r,n,o]=e.args,a=(e,t)=>"symbol"===e.type&&e.value===r.value?t:"op"===e.type?{...e,args:e.args.map(e=>a(e,t))}:e;return{type:"op",op:"-",args:[a(t,o),a(t,n)]}}(e));case"_":{const[e,t]=r;if("symbol"===e.type&&("number"===t.type||"symbol"===t.type))return this.leaf({type:"symbol",value:`${e.value}_${t.value}`});break}}if(it[t])return this.builtin(t,o());this.fail(`"${t}" isn't available in a filter`)}truth(e){return"b"===e.kind?e.c[0]:`(${mt(e)} !== 0)`}componentwise(e,t){const r=e.map(dt),n=Math.max(...r),o=new Set(r.filter(e=>e>1));o.size>1&&this.fail(`can't combine vectors of ${[...o].join(" and ")} values`);const a=Array.from({length:n},(r,n)=>t(...e.map(e=>mt(e,n))));return this.keep(ft(a))}builtin(e,t){const r=it[e];if(lt[e]&&t.length!==lt[e]&&this.fail(`${e}() takes ${lt[e]} values`),"function"==typeof r)return this.componentwise(t,r);const n=1===r?e:r;return this.componentwise(t,(...e)=>`Math.${n}(${e.join(", ")})`)}power([e,t]){const r="number"===t.type&&/^-?\d+$/.test(t.value)?Number(t.value):null,n=this.keep(this.value(e)),o=e=>this.componentwise([n],t=>Array(e).fill(t).join(" * "));return 0===r?this.componentwise([n],()=>"1"):null!==r&&r>=1&&r<=4?o(r):null!==r&&r<=-1&&r>=-4?this.componentwise([o(-r)],e=>`(1 / ${e})`):"symbol"===e.type&&"e"===e.value?this.componentwise([this.value(t)],e=>`Math.exp(${e})`):"number"===e.type&&"2"===e.value?this.componentwise([this.value(t)],e=>`Math.pow(2, ${e})`):this.componentwise([n,this.value(t)],(e,t)=>`Math.pow(${e}, ${t})`)}ternary([e,t,r]){const n=this.truth(this.value(e)),o=e=>"symbol"===e.type&&"unchanged"===e.value;let a=o(t)?null:this.value(t),s=o(r)?null:this.value(r);const i=e=>"b"===e.kind?pt("($u > 0.5)"):"f"===e.kind?ut("$u"):ft(["$k0","$k1","$k2","$k3"].slice(0,4===e.c.length?4:3));if(!a&&!s)return ut("$u");if(a||(a=i(s)),s||(s=i(a)),"b"===a.kind&&"b"===s.kind)return pt(this.temp(`(${n} ? ${a.c[0]} : ${s.c[0]})`));const l=Math.max(dt(a),dt(s)),c=Array.from({length:l},(e,t)=>this.temp(`(${n} ? ${mt(a,t)} : ${mt(s,t)})`));return ft(c)}membership(e){const[t,r]=e.args,n=mt(this.value(t)),o="∉"===e.op;let a;if("op"===r.type&&["()","[]","(]","[)"].includes(r.op)&&2===r.args.length){const[e,t]=r.args.map(e=>mt(this.value(e)));a=`(${n} ${"["===r.op[0]?">=":">"} ${e} && ${n} ${"]"===r.op[1]?"<=":"<"} ${t})`}else"op"===r.type&&"{}"===r.op?a=r.args.length?`(${r.args.map(e=>`${n} === ${mt(this.value(e))}`).join(" || ")})`:"false":"symbol"===r.type&&["ℝ","ℤ","ℕ"].includes(r.value)?a={"ℝ":`Number.isFinite(${n})`,"ℤ":`Number.isInteger(${n})`,"ℕ":`(Number.isInteger(${n}) && ${n} > 0)`}[r.value]:this.fail("∈ needs an interval [a, b], a set {…}, ℝ, ℤ or ℕ");return pt(o?`!${a}`:a)}random(){return this.uses.add("random"),ut(this.temp("$h_random($px, $py, $h, ++$seed)"))}call(e,t,r){const n=()=>t.map(e=>this.value(e));if(e.startsWith("mz_sample_")){const t=e.slice(10),[r,o]=n(),[a,s]=o?[mt(r),mt(o)]:[mt(r,0),mt(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),this.keep(ft([0,1,2,3].map(t=>`${e}[${t}]`)))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep(this.sampler(t,a,s))}if(e.startsWith("mz_at_")){const t=e.slice(6),[r,o]=n(),[a,s]=o?[mt(r),mt(o)]:[mt(r,0),mt(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),ft([0,1,2].map(t=>`${e}[${t}]`))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep(ft(this.sampler(t,a,s).c.slice(0,3)))}if(e.startsWith("mz_width_")||e.startsWith("mz_height_")){const t=e.replace(/^mz_(width|height)_/,"");return this.pictureNames.add(t),ut(e.startsWith("mz_width_")?`$qw_${t}`:`$qh_${t}`)}switch(e){case"pixel":{const[e,t]=n().map(e=>mt(e)),r=this.scratchArray();return this.body.push(`$h_sample($I, $w, $h, ${e}, ${t}, ${r});`),this.keep(ft([0,1,2,3].map(e=>`${r}[${e}]`)))}case"red":case"green":case"blue":case"alpha":case"luma":{let r;2===t.length?r=this.call("pixel",t):1===t.length?r=this.value(t[0]):this.fail(`${e}() takes a color, or a position px, py`);const n={red:0,green:1,blue:2,alpha:3}[e];return"luma"===e?ut(`(${mt(r,0)} * 0.299 + ${mt(r,1)} * 0.587 + ${mt(r,2)} * 0.114)`):"alpha"===e&&3===dt(r)?ut("1"):ut(mt(r,n))}case"length":{const[e]=n();return ut(`Math.sqrt(${e.c.map((t,r)=>`${mt(e,r)} * ${mt(e,r)}`).join(" + ")})`)}case"distance":{const[e,t]=n(),r=this.componentwise([e,t],(e,t)=>`(${e} - ${t})`);return ut(`Math.sqrt(${r.c.map(e=>`${e} * ${e}`).join(" + ")})`)}case"dot":{const[e,t]=n(),r=Math.max(dt(e),dt(t));return ut(`(${Array.from({length:r},(r,n)=>`${mt(e,n)} * ${mt(t,n)}`).join(" + ")})`)}case"normalize":{const[e]=n(),t=this.temp(`Math.sqrt(${e.c.map((t,r)=>`${mt(e,r)} * ${mt(e,r)}`).join(" + ")})`);return this.componentwise([e],e=>`(${e} / ${t})`)}case"cross":{const[e,t]=n();3===dt(e)&&3===dt(t)||this.fail("cross() takes two colors (3 values each)");const[r,o,a]=e.c,[s,i,l]=t.c;return this.keep(ft([`(${o} * ${l} - ${a} * ${i})`,`(${a} * ${s} - ${r} * ${l})`,`(${r} * ${i} - ${o} * ${s})`]))}case"convolve":{const e=n().map(e=>mt(e));9!==e.length&&this.fail("convolve() takes 9 numbers: the 3×3 kernel, row by row");const t=this.scratchArray();return this.body.push(`$h_convolve($I, $w, $h, $px, $py, ${e.join(", ")}, ${t});`),ft([0,1,2].map(e=>`${t}[${e}]`))}case"mz_zoom":case"mz_shift":case"mz_rotate":case"mz_crop":case"mz_tile":case"mz_flipx":case"mz_flipy":return this.geometry(e.slice(3),n().map(e=>mt(e)));case"tolinear":case"fromlinear":case"tohsv":case"fromhsv":case"tohsl":case"fromhsl":case"tolab":case"fromlab":case"tooklab":case"fromoklab":case"toycbcr":case"fromycbcr":{const t=n(),r=3===t.length?t.map(e=>mt(e)):[0,1,2].map(e=>mt(t[0],e));1!==t.length&&3!==t.length&&this.fail(`${e}() takes a color`);const o=this.scratchArray();return this.body.push(`$h_col_${e}(${r.join(", ")}, ${o});`),this.keep(ft([0,1,2].map(e=>`${o}[${e}]`)))}case"random":return this.random();case"exp":case"exp2":case"log2":case"sign":case"fract":case"radians":case"degrees":case"inversesqrt":case"pow":case"mod":case"step":case"clamp":case"mix":case"smoothstep":case"abs":case"floor":case"ceil":case"sqrt":case"sin":case"cos":case"tan":return this.builtin(e,n());case"asin":return this.builtin("arcsin",n());case"acos":return this.builtin("arccos",n());case"atan":return 2===t.length?this.builtin("atan2",n()):this.builtin("arctan",n());case"log":return this.builtin("ln",n());case"max":case"min":return this.componentwise(n(),(...t)=>`Math.${e}(${t.join(", ")})`)}if(ct[e])return this.neighborhood(e,t);this.fail(`unknown function "${e}"`)}geometry(e,t){const r=(e,t)=>this.keep(ft([e,t]));switch(e){case"zoom":{const[e,n="0.5",o="0.5"]=t,a=r(`(${n} * $w - 0.5)`,`(${o} * $h - 0.5)`);return r(`(${a.c[0]} + ($px - ${a.c[0]}) / ${e})`,`(${a.c[1]} + ($py - ${a.c[1]}) / ${e})`)}case"shift":{const[e,n]=t;return r(`($h_fmod($px - ${e} + 0.5, $w) - 0.5)`,`($h_fmod($py - ${n} + 0.5, $h) - 0.5)`)}case"rotate":{const[e,n="0.5",o="0.5"]=t,a=r(`(${n} * $w - 0.5)`,`(${o} * $h - 0.5)`),s=r(`($px - ${a.c[0]})`,`($py - ${a.c[1]})`),i=this.keep(ft([`Math.cos(${e})`,`Math.sin(${e})`]));return r(`(${a.c[0]} + ${i.c[0]} * ${s.c[0]} + ${i.c[1]} * ${s.c[1]})`,`(${a.c[1]} + ${i.c[0]} * ${s.c[1]} - ${i.c[1]} * ${s.c[0]})`)}case"crop":{const[e,n,o,a]=t;return r(`((${e} + (${o} - ${e}) * ($px + 0.5) / $w) * $w - 0.5)`,`((${n} + (${a} - ${n}) * ($py + 0.5) / $h) * $h - 0.5)`)}case"tile":{const[e,n=e]=t;return r(`($h_fmod(($px + 0.5) * ${e}, $w) - 0.5)`,`($h_fmod(($py + 0.5) * ${n}, $h) - 0.5)`)}case"flipx":return r("($w - 1 - $px)","$py");case"flipy":return r("$px","($h - 1 - $py)")}this.fail(`unknown geometry ${e}`)}neighborhood(e,t){const r=ct[e];if(t.every(e=>this.isUniform(e))){const n=t.map(e=>mt(this.uniformValue(e))),o=`${e}(${n.join(",")})`;if(!this.planes.has(o)){const t=`$N${this.planes.size}`;this.pre.push(`let ${t} = $h_plane_${e}($I, $w, $h, $y0, $y1${n.map(e=>`, ${e}`).join("")});`),this.planes.set(o,t)}const a=this.planes.get(o);return 3===r?ft([0,1,2].map(e=>`${a}[$j3 + ${e}]`)):ut(`${a}[$j]`)}const n=t.map(e=>mt(this.value(e)));if(1===r)return ut(this.temp(`$h_at_${e}($I, $w, $h, $px, $py${n.map(e=>`, ${e}`).join("")})`));const o=this.scratchArray();return this.body.push(`$h_at_${e}($I, $w, $h, $px, $py${n.map(e=>`, ${e}`).join("")}, ${o});`),ft([0,1,2].map(e=>`${o}[${e}]`))}isUniform(e){return"number"===e.type||("symbol"===e.type?["w","h","t"].includes(e.value)||Boolean(st[e.value])||Object.prototype.hasOwnProperty.call(this.params,e.value)&&"color"!==this.params[e.value].type:"op"===e.type&&!e.op.startsWith(rt)&&"random"!==e.op&&e.args.every(e=>this.isUniform(e)))}uniformValue(e){const t=this.body;this.body=this.pre;try{return this.value(e)}finally{this.body=t}}channel(e,t){const r="rgba"===e||"rgb"===e?"$gray":`$c${"rgba".indexOf(e)}`;this.body.push(`$u = ${r}; $k0 = $c0; $k1 = $c1; $k2 = $c2; $k3 = $c3;`);const n=this.value(t),o=dt(n),a=e=>mt(n,e);if("rgba"===e){2===o&&this.fail("a color is one number (gray), three (r, g, b) or four (r, g, b, a) — not two");const e=1===o?[a(0),a(0),a(0),"1"]:3===o?[a(0),a(1),a(2),"1"]:[0,1,2,3].map(a);this.body.push(`$c0 = ${e[0]}; $c1 = ${e[1]}; $c2 = ${e[2]}; $c3 = ${e[3]};`)}else if("rgb"===e){2===o&&this.fail("a color is one number (gray), three (r, g, b) or four — not two");const e=1===o?[a(0),a(0),a(0)]:[a(0),a(1),a(2)];this.body.push(`$c0 = ${e[0]}; $c1 = ${e[1]}; $c2 = ${e[2]};`)}else{const t="rgba".indexOf(e),r=1===o?a(0):3===o&&"a"===e?"1":a(t);this.body.push(`$c${t} = ${r};`)}}parameters(){return["$I","$O","$S","$w","$h","$t","$P","$op","$y0","$y1",...[...this.pictureNames].flatMap(e=>[`$Q_${e}`,`$qw_${e}`,`$qh_${e}`,`$qz_${e}`,`$qx_${e}`,`$qy_${e}`,`$qa_${e}`,`$qm_${e}`]),...nt.map(e=>`$h_${e}`)]}arguments(e){const t=[...this.pictureNames];return[e.input,e.output,e.source,e.width,e.height,e.t,e.params,e.opacity,e.y0??0,e.y1??e.height,...t.flatMap(t=>{const r=e.pictures[this.bind?.[t]??t]??(this.graphics?.has(t)?Ee:xe),n=e.placements[t]??{};return[r.data,r.width,r.height,Number(n.zoom??1),Number(n.x??.5),Number(n.y??.5),Number(n.angle??0),Me(n.place)]}),...nt.map(e=>tt[e])]}source(){return[...Object.entries(this.params).map(([e,t],r)=>"color"===t.type?`let $p_${e}_0 = $P[${r}][0], $p_${e}_1 = $P[${r}][1], $p_${e}_2 = $P[${r}][2];`:`let $p_${e} = $P[${r}];`).map(e=>e.replace(/\$P\[(\d+)\]\[(\d)\]/g,"$h_at($P, $1, $2)")),"let $u = 0, $k0 = 0, $k1 = 0, $k2 = 0, $k3 = 0, $seed = 0, $CS = $h_scratch();",...this.pre,"for (let $py = $y0; $py < $y1; $py++) {"," for (let $px = 0; $px < $w; $px++) {"," let $j = $py * $w + $px, $j3 = $j * 3, $j4 = $j * 4;"," let $r = $I[$j4], $g = $I[$j4 + 1], $b = $I[$j4 + 2], $a = $I[$j4 + 3];"," let $c0 = $r, $c1 = $g, $c2 = $b, $c3 = $a;"," let $x = ($px + 0.5) / $w, $y = ($py + 0.5) / $h;",this.space?` $h_col_from${this.space}($r, $g, $b, $CS); let $gray = $CS[0] * 0.299 + $CS[1] * 0.587 + $CS[2] * 0.114;`:" let $gray = $r * 0.299 + $g * 0.587 + $b * 0.114;"," $seed = $t;",...this.body.map(e=>` ${e}`)," $O[$j4] = $r + ($c0 - $r) * $op;"," $O[$j4 + 1] = $g + ($c1 - $g) * $op;"," $O[$j4 + 2] = $b + ($c2 - $b) * $op;"," $O[$j4 + 3] = $a + ($c3 - $a) * $op;"," }","}"].join("\n")}}function $t(e,t={}){const r="float"===t.precision||"half"===t.precision?"float":"byte",n=e.passes.map(e=>wt(e)),a={};let s=null;const i=t.parallelFrom??25e4,l=void 0===t.workers||"auto"===t.workers?function(){const e="undefined"!=typeof navigator&&navigator.hardwareConcurrency?navigator.hardwareConcurrency:4;return Math.max(0,Math.min(8,e-1))}():Number(t.workers);let c=null,h=null,u=new Map;const p={passes:e.passes,get precision(){return r},sources:n.map(e=>e.source),setImage(e,t){if("string"!=typeof e&&(t=e,e=null),e&&"source"!==e&&null==t)return delete a[e],p;const r=xt(t);return e&&"source"!==e?a[e]=r:s=r,p},draw({t:t=0,canvas:o=null}={}){if(!s)throw new Error("setImage() first");const{width:i,height:l}=s,c=i*l*4;let h=s.data;const u=[];e.passes.forEach((e,o)=>{for(let t=0;t<e.keepInput;t++)u.push(h);const p=new Float32Array(c);if(e.blendKept){const t=u.pop(),r=e.opacity;for(let e=0;e<c;e++)p[e]=t[e]+(h[e]-t[e])*r}else n[o].run({input:h,output:p,source:s.data,width:i,height:l,t:t,params:Object.keys(e.params??{}).map(t=>e.values[t]),opacity:e.opacity,pictures:a,placements:e.placements??{}});"byte"===r&&bt(p),h=p});const p=new Uint8ClampedArray(c);for(let e=0;e<c;e++){const t=h[e];p[e]=t>0?t<1?Math.round(255*t):255:0}const f={data:p,width:i,height:l};return o&&(o.width=i,o.height=l,o.getContext("2d").putImageData(new ImageData(p,i,l),0,0)),f},async drawAsync({t:n=0,canvas:f=null}={}){if(!s)throw new Error("setImage() first");const{width:m,height:d}=s;if(l<2||m*d<i)return p.draw({t:n,canvas:f});h??=async function(e,t,r){const n=new URL(r??"./cpu-worker.js",o&&"SCRIPT"===o.tagName.toUpperCase()&&o.src||new URL("qblur.external.global.min.js",document.baseURI).href);let a,s=()=>{};if("undefined"!=typeof Worker&&"undefined"!=typeof window){const e=n.origin===location.origin?n:URL.createObjectURL(new Blob([`import ${JSON.stringify(n.href)};`],{type:"text/javascript"}));e!==n&&(s=()=>URL.revokeObjectURL(e)),a=()=>{const t=new Worker(e,{type:"module"});return{send:e=>t.postMessage(e),on:e=>{t.onmessage=t=>e(t.data),t.onerror=t=>e({id:-1,ok:!1,error:t.message})},close:()=>t.terminate()}}}else try{const{Worker:e}=await(import("node:worker_threads"));a=()=>{const t=new e(n);return{send:e=>t.postMessage(e),on:e=>{t.on("message",e),t.on("error",t=>e({id:-1,ok:!1,error:t.message}))},close:()=>t.terminate()}}}catch{return null}const i=Array.from({length:e},a);let l=1;const c=i.map(()=>new Map);i.forEach((e,t)=>e.on(e=>{if(-1===e.id){for(const[,r]of c[t])r.reject(new Error(e.error));return void c[t].clear()}const r=c[t].get(e.id);r&&(c[t].delete(e.id),e.ok?r.resolve(e):r.reject(new Error(e.error)))}));const h=(e,t)=>new Promise((r,n)=>{const o=l++;c[e].set(o,{resolve:r,reject:n}),i[e].send({...t,id:o})}),u={size:e,shared:vt(),ask:h,broadcast:e=>Promise.all(i.map((t,r)=>h(r,e))),close:()=>{i.forEach(e=>e.close());for(const e of c){for(const[,t]of e)t.reject(new Error("The runner was disposed of while drawing"));e.clear()}}};try{await u.broadcast({type:"init",passes:t.map(({fragment:e,...t})=>t)})}catch(e){throw u.close(),e}finally{s()}return u}(l,e.passes,t.workerUrl).catch(()=>!1);const g=h,w=await g;if(g!==h)throw new Error("The runner was disposed of while drawing");if(c=w,!w)return p.draw({t:n,canvas:f});const y=m*d*4,$=()=>w.shared?new Float32Array(new SharedArrayBuffer(4*y)):new Float32Array(y);for(const[e,t]of[["source",s],...Object.entries(a)])u.get(e)!==t&&(await w.broadcast({type:"picture",name:e,picture:w.shared?Mt(t):t}),u.set(e,t));let b=w.shared?Mt(s).data:s.data;const x=[];for(let t=0;t<e.passes.length;t++){const o=e.passes[t];for(let e=0;e<o.keepInput;e++)x.push(b);const a=$();if(o.blendKept){const e=x.pop();for(let t=0;t<y;t++)a[t]=e[t]+(b[t]-e[t])*o.opacity;"byte"===r&&bt(a)}else{const e=Object.keys(o.params??{}).map(e=>o.values[e]),s=Et(d,w.size),i=await Promise.all(s.map(([s,i],l)=>w.ask(l,{type:"run",pass:t,input:b,output:w.shared?a:null,width:m,height:d,t:n,params:e,opacity:o.opacity,placements:o.placements??{},y0:s,y1:i,quantize:"byte"===r})));w.shared||i.forEach((e,t)=>a.set(e.band,s[t][0]*m*4))}b=a}const E=new Uint8ClampedArray(y);for(let e=0;e<y;e++){const t=b[e];E[e]=t>0?t<1?Math.round(255*t):255:0}const v={data:E,width:m,height:d};return f&&(f.width=m,f.height=d,f.getContext("2d").putImageData(new ImageData(E,m,d),0,0)),v},get workers(){return c?c.size:0},dispose(){s=null;for(const e of Object.keys(a))delete a[e];h&&h.then(e=>e&&e.close()),h=null,c=null,u=new Map}};return ge(p,e)}function bt(e){for(let t=0;t<e.length;t++){const r=e[t];e[t]=r>0?r<1?Math.round(255*r)/255:1:0}}function xt(e){if(e&&e.data&&e.width&&e.height){const t=e.data,r=t instanceof Float32Array||t instanceof Float64Array?1:1/255,n=new Float32Array(e.width*e.height*4);for(let e=0;e<n.length;e++)n[e]=t[e]*r;return{data:n,width:e.width,height:e.height}}if("undefined"!=typeof document||"undefined"!=typeof OffscreenCanvas){const t=e.naturalWidth||e.videoWidth||e.width,r=e.naturalHeight||e.videoHeight||e.height;if(!t||!r)throw new Error("setImage: the picture has no size yet (not loaded?)");const n=("undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,r):Object.assign(document.createElement("canvas"),{width:t,height:r})).getContext("2d",{willReadFrequently:!0});return n.drawImage(e,0,0,t,r),xt(n.getImageData(0,0,t,r))}throw new Error("setImage: give ImageData or { data, width, height }")}function Et(e,t){const r=[];for(let n=0;n<t;n++){const o=Math.floor(e*n/t),a=Math.floor(e*(n+1)/t);a>o&&r.push([o,a])}return r}const vt=()=>"undefined"!=typeof SharedArrayBuffer&&("undefined"==typeof crossOriginIsolated||!0===crossOriginIsolated);function Mt(e){if(e.data.buffer instanceof(globalThis.SharedArrayBuffer??Object))return e;if(e.shared)return e.shared;const t=new Float32Array(new SharedArrayBuffer(e.data.byteLength));return t.set(e.data),e.shared={data:t,width:e.width,height:e.height},e.shared}function At({webgl:e=!1,prefer:t="auto"}={}){return"cpu"===t?{engine:"cpu",reason:"asked for the CPU"}:e?{engine:"gpu",reason:"gpu"===t?"asked for the GPU":"WebGL is here"}:{engine:"cpu",reason:"no WebGL here"}}function _t(e,t={}){const r=At({webgl:Boolean(t.gl),prefer:t.prefer});if("gpu"===r.engine)try{return{runner:we(t.gl,e,{precision:t.precision}),...r}}catch(r){if("gpu"===t.prefer)throw r;return{runner:$t(e,t),engine:"cpu",reason:`the GPU refused the shader (${r.message.split("\n")[0]})`}}return{runner:$t(e,t),...r}}const kt=[{name:"Wave",group:"Shape & motion",description:"Rows slide back and forth as t advances",params:{amplitude:{default:8,min:0,max:40},wavelength:{default:10,min:1,max:60},speed:{default:5,min:1,max:30}},color:"pixel(px + amplitude sin(py / wavelength + t / speed), py)"},{name:"Invert",group:"Color & tone",color:"(1 - r, 1 - g, 1 - b)"},{name:"Grayscale",group:"Color & tone",color:"gray"},{name:"Threshold",group:"Color & tone",params:{cutoff:.5},color:"if gray > cutoff then 1 else 0"},{name:"Posterize",group:"Color & tone",params:{levels:{default:4,min:2,max:16,step:1}},color:"min(floor(rgb * levels) / (levels - 1), 1)"},{name:"Brightness & contrast",group:"Color & tone",params:{brightness:{default:0,min:-.5,max:.5},contrast:{default:1,min:0,max:3}},color:"(rgb - 0.5) contrast + 0.5 + brightness"},{name:"Tint",group:"Color & tone",params:{tint:[1,.85,.7]},color:"rgb * tint"},{name:"Sepia",group:"Color & tone",color:"(0.393r + 0.769g + 0.189b, 0.349r + 0.686g + 0.168b, 0.272r + 0.534g + 0.131b)"},{name:"Color circle",group:"Color & tone",description:"Black and white, except a soft circle that keeps its color",params:{across:{default:.5,min:0,max:1,label:"where, across"},down:{default:.5,min:0,max:1,label:"where, down"},radius:{default:.3,min:0,max:1},softness:{default:.08,min:0,max:.5}},notes:["The color stays inside a circle and fades to gray over the softness. Sizes are parts of the picture's shorter side, so it stays round.",{param:"across"},{param:"down"},{param:"radius"},{param:"softness"}],color:"mix((gray, gray, gray), rgb, 1 - smoothstep(radius, radius + softness, distance((px, py), (across w, down h)) / min(w, h)))"},{name:"Vignette",group:"Color & tone",params:{strength:{default:1.6,min:0,max:4}},color:"rgb * (1 - strength ((x - 0.5)^2 + (y - 0.5)^2))"},{name:"Sobel edges",group:"Blur & edges",description:"How fast the brightness changes",params:{gain:{default:2,min:.2,max:10}},color:"gain sobel()"},{name:"Edge map",group:"Blur & edges",description:"White where an edge is stronger than the cutoff",params:{cutoff:{default:.3,min:0,max:2}},color:"if sobel() > cutoff then 1 else 0"},{name:"Outline",group:"Blur & edges",description:"Ink lines over the color",params:{gain:{default:3,min:0,max:10}},color:"rgb (1 - gain sobel())"},{name:"Box blur",group:"Blur & edges",params:{radius:{default:2,min:0,max:8,step:1}},color:"blur(radius)"},{name:"Gaussian blur",group:"Blur & edges",description:"Computed in two passes, across then down, so it can be wide",params:{sigma:{default:3,min:0,max:8}},color:"gaussian(sigma)"},{name:"Canny edges",group:"Blur & edges",description:"Thin, clean edge lines: smooth, gradient, thinning, two thresholds, hysteresis — a chain",steps:[{params:{sigma:{default:1.4,min:.5,max:4}},color:"gaussian(sigma)"},{color:"(min(sobel() / 4, 1), floor(fract((atan2(sobely(), sobelx()) + π/8) / π) 4) / 4, 0)"},{color:"if green(px, py) < 0.125 then (if r >= red(px - 1, py) & r >= red(px + 1, py) then r else 0) else if green(px, py) < 0.375 then (if r >= red(px + 1, py + 1) & r >= red(px - 1, py - 1) then r else 0) else if green(px, py) < 0.625 then (if r >= red(px, py - 1) & r >= red(px, py + 1) then r else 0) else (if r >= red(px - 1, py + 1) & r >= red(px + 1, py - 1) then r else 0)"},{params:{low:{default:.08,min:0,max:.5},high:{default:.2,min:0,max:1}},color:"if r > high then 1 else if r > low then 0.5 else 0"},"if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else 0"]},{name:"Sharpen",group:"Blur & edges",params:{amount:{default:.6,min:0,max:3}},color:"sharpen(amount)"},{name:"Unsharp mask",group:"Blur & edges",description:"The picture plus what a blur removes",params:{amount:{default:1.5,min:0,max:5},sigma:{default:2,min:.5,max:4}},color:"rgb + amount (rgb - gaussian(sigma))"},{name:"Bloom",group:"Blur & edges",description:"Bright parts glow",params:{amount:{default:.8,min:0,max:3},sigma:{default:3,min:.5,max:4},cutoff:{default:.6,min:0,max:1}},color:"rgb + amount max(gaussian(sigma) - cutoff, 0)"},{name:"Emboss",group:"Blur & edges",color:"emboss()"},{name:"Dilate",group:"Blur & edges",description:"Light areas grow",params:{radius:{default:2,min:0,max:8,step:1}},color:"dilate(radius)"},{name:"Erode",group:"Blur & edges",description:"Dark areas grow",params:{radius:{default:2,min:0,max:8,step:1}},color:"erode(radius)"},{name:"3×3 kernel",group:"Blur & edges",description:"Your own convolution; the default is a sharpen",params:{k1:{default:0,min:-8,max:8},k2:{default:-1,min:-8,max:8},k3:{default:0,min:-8,max:8},k4:{default:-1,min:-8,max:8},k5:{default:5,min:-8,max:8},k6:{default:-1,min:-8,max:8},k7:{default:0,min:-8,max:8},k8:{default:-1,min:-8,max:8},k9:{default:0,min:-8,max:8}},color:"convolve(k1, k2, k3, k4, k5, k6, k7, k8, k9)"},{name:"Pixelate",group:"Shape & motion",params:{size:{default:8,min:1,max:32,step:1}},color:"pixel(floor(px / size) size, floor(py / size) size)"},{name:"Mirror",group:"Shape & motion",color:"pixel(w - px, py)"},{name:"Scanlines",group:"Shape & motion",params:{period:{default:4,min:2,max:16,step:1}},color:"if py mod period < period / 2 then rgb else rgb * 0.6"},{name:"Pulse",group:"Shape & motion",description:"Brightness breathes with t",params:{speed:{default:6,min:1,max:30},depth:{default:.25,min:0,max:1}},color:"rgb (1 - depth + depth sin(t / speed))"},{name:"Chroma key",group:"Color & tone",description:"Replaces one color with another",params:{key:[.22,.71,.29],tolerance:{default:.35,min:0,max:1},background:[.1,.1,.4]},color:"if distance(rgb, key) < tolerance then background else rgb"},{name:"Through a mask",group:"Other pictures",description:"Put this last: the steps above show only where the mask is light",images:{mask:{description:"light where the effect shows"}},color:"mix(source, rgb, luma(mask))"},{name:"Mix",group:"Other pictures",description:"Fade towards another picture",images:["overlay"],params:{amount:.5},color:"mix(rgb, overlay, amount)"},{name:"Masked mix",group:"Other pictures",images:{overlay:{},mask:{description:"light where the overlay shows"}},color:"mix(rgb, overlay, luma(mask))"},{name:"Multiply",group:"Other pictures",images:["overlay"],color:"rgb * overlay"},{name:"Screen",group:"Other pictures",images:["overlay"],color:"1 - (1 - rgb)(1 - overlay)"},{name:"Overlay blend",group:"Other pictures",images:["overlay"],color:"if gray < 0.5 then 2 rgb overlay else 1 - 2 (1 - rgb)(1 - overlay)"},{name:"Difference",group:"Other pictures",images:["overlay"],color:"abs(rgb - overlay)"},{name:"Alpha over",group:"Other pictures",description:"A picture with transparency laid on top",images:["overlay"],color:"mix(rgb, overlay, alpha(overlay))"},{name:"Chroma key onto a picture",group:"Other pictures",images:{background:{}},params:{key:[.22,.71,.29],tolerance:{default:.35,min:0,max:1}},color:"if distance(rgb, key) < tolerance then background else rgb"},{name:"Only inside the selection",group:"Other pictures",description:"Put this last: the steps above show only inside what you selected on the picture (everywhere, without a selection)",color:"mix(source, rgb, selected)"},{name:"Only outside the selection",group:"Other pictures",description:"Put this last: the steps above show only outside what you selected",color:"mix(rgb, source, selected)"},{name:"Glow round the selection",group:"Other pictures",description:"A colored halo round what you selected, fading over `reach` pixels (`away` is the distance from the selection)",params:{glow:[1,.8,.3],reach:{default:60,min:2,max:400},amount:{default:.9,min:0,max:1}},color:"mix(rgb, glow, amount (1 - smoothstep(0, reach, away)) step(0.5, away))"},{name:"Blur away from the selection",group:"Other pictures",description:"Sharp on what you selected, blurrier the farther a pixel is from it, all blurred `reach` pixels away",params:{sigma:{default:6,min:.5,max:8},reach:{default:200,min:1,max:1e3}},color:"mix(rgb, gaussian(sigma), min(1, away / reach))"},{name:"Caption",group:"Text & shapes",description:"Words along the bottom, with a soft shadow; change them under the step",graphics:{title:{text:"Your caption here",y:.88}},color:"mix(rgb, title, alpha(title))"},{name:"Poster title",group:"Text & shapes",description:"Big outlined letters across the top",graphics:{title:{text:"BIG TITLE",font:"Impact, Haettenschweiler, sans-serif",weight:"normal",size:.16,y:.14,outline:{color:"#000000",width:.08},shadow:null}},color:"mix(rgb, title, alpha(title))"},{name:"Gradient text",group:"Text & shapes",description:"The letters colored by math: a sunset from left to right",graphics:{title:{text:"Golden hour",font:"Georgia, serif",size:.13,y:.5,shadow:{color:"rgba(0,0,0,0.5)",blur:.2,dx:0,dy:.05}}},color:"mix(rgb, mix((1, 0.35, 0.3), (1, 0.85, 0.25), x), alpha(title))"},{name:"Neon sign",group:"Text & shapes",description:"White letters with a colored glow",graphics:{title:{text:"OPEN",font:"Trebuchet MS, sans-serif",size:.18,y:.5,shadow:{color:"#00e5ff",blur:.45,dx:0,dy:0}}},color:"mix(rgb * 0.6, title, alpha(title))"},{name:"Layered shadow",group:"Text & shapes",description:"Two shadow layers, each with its own filter: a soft glow that darkens and breathes with t, and a hard offset colored by a gradient",graphics:{title:{text:"LAYERS",font:"Impact, Haettenschweiler, sans-serif",weight:"normal",size:.17,y:.5,shadow:null,shadows:[{color:"#000000",blur:.7,dx:0,dy:.08},{color:"#000000",blur:0,dx:.07,dy:.07}]}},color:"mix(mix(mix(rgb, rgb * 0.25, alpha(title_shadow1) (0.7 + 0.3 sin(t / 10))), mix((1, 0.2, 0.6), (0.2, 0.6, 1), x), alpha(title_shadow2)), title, alpha(title))"},{name:"Ink brush",group:"Brushes",description:'Paint in a color; draw on the picture with "draw" under the step',graphics:{brush:{type:"strokes",brush:"round",size:.025}},params:{ink:[.95,.2,.25]},color:"mix(rgb, ink, alpha(brush))"},{name:"Blur brush",group:"Brushes",description:"Paint a blur in — stronger every time a stroke goes over the same place",graphics:{brush:{type:"strokes",brush:"soft",size:.08}},color:"mix(rgb, gaussian(2 + 3 min(4 green(brush), 3)), alpha(brush))"},{name:"Darken brush",group:"Brushes",description:"Each pass darkens a little more, like layers of a wash",graphics:{brush:{type:"strokes",brush:"soft",size:.07,flow:.7}},color:"rgb (1 - 0.22 min(4 green(brush), 4))"},{name:"Color reveal brush",group:"Brushes",description:"The picture starts gray; the brush paints its color back",graphics:{brush:{type:"strokes",brush:"soft",size:.1}},color:"mix((gray, gray, gray), rgb, alpha(brush))"},{name:"Fuse brush",group:"Brushes",description:"Paint glows as it goes down, then cools to charcoal (red(brush) is its age)",graphics:{brush:{type:"strokes",brush:"round",size:.02,age:40}},color:"mix(rgb, mix((1, 0.9, 0.5), (0.1, 0.07, 0.06), red(brush)), alpha(brush)) + (1, 0.5, 0.1) alpha(brush) max(0, 1 - 3 red(brush)) 0.6"},{name:"Rainbow brush",group:"Brushes",description:"The color runs round the wheel along the drawing (blue(brush) is how far through it)",graphics:{brush:{type:"strokes",brush:"marker",size:.035}},color:"mix(rgb, fromhsv(blue(brush), 0.85, 1), alpha(brush))"},{name:"Chalk outline",group:"Brushes",description:'Chalk round an object: select it, then "outline the selection" under the step',graphics:{brush:{type:"strokes",brush:"chalk",size:.018,timing:"even",speed:2}},color:"mix(rgb, (0.97, 0.97, 0.92), alpha(brush))"},{name:"Frosted panel",group:"Text & shapes",description:"A rounded panel that blurs and darkens what is behind it — a shape with its own filter",graphics:{panel:{type:"rect",y:.86,w:.9,h:.2,radius:.25}},color:"mix(rgb, gaussian(5) * 0.7, alpha(panel))"},{name:"Spotlight oval",group:"Text & shapes",description:"Darkens everything but a soft oval",graphics:{spot:{type:"ellipse",x:.5,y:.45,w:.45,h:.55,shadow:{color:"#ffffff",blur:.12,dx:0,dy:0}}},color:"mix(rgb * 0.3, rgb, alpha(spot))"},{name:"Scrolling banner",group:"Text & shapes",description:"Text that slides across and wraps round (animated with t)",graphics:{title:{text:"Breaking news · scrolling text · ",size:.07,y:.92}},params:{speed:{default:3,min:-10,max:10}},color:"mix(rgb, shift(title, -speed t, 0), alpha(shift(title, -speed t, 0)))"},{name:"Pulsing title",group:"Text & shapes",description:"Text that grows and shrinks a little (animated with t)",graphics:{title:{text:"Hello!",size:.14,y:.5}},params:{amount:{default:.06,min:0,max:.3}},color:"mix(rgb, zoom(title, 1 + amount sin(t / 8)), alpha(zoom(title, 1 + amount sin(t / 8))))"},{name:"Fade-in title",group:"Text & shapes",description:"Text that fades in over the first frames (animated with t)",graphics:{title:{text:"Once upon a time",font:"Georgia, serif",style:"italic",weight:"normal",size:.09,y:.5}},params:{frames:{default:40,min:1,max:200}},color:"mix(rgb, title, alpha(title) clamp(t / frames, 0, 1))"},{name:"Zoom",group:"Shape & motion",params:{scale:{default:1.5,min:.25,max:4},cx:.5,cy:.5},color:"zoom(scale, cx, cy)"},{name:"Ken Burns",group:"Shape & motion",description:"A slow zoom that drifts across — a still picture that moves",params:{speed:{default:.002,min:0,max:.01},drift:{default:3e-4,min:-.001,max:.001}},color:"zoom(1 + speed t, 0.5 + drift t, 0.45)"},{name:"Scroll",group:"Shape & motion",description:"Slides and wraps around",params:{dx:{default:1,min:-5,max:5},dy:{default:0,min:-5,max:5}},color:"shift(dx t, dy t)"},{name:"Spin",group:"Shape & motion",params:{speed:{default:.01,min:-.05,max:.05}},color:"rotate(speed t)"},{name:"Tile",group:"Shape & motion",params:{n:{default:2,min:1,max:8,step:1}},color:"tile(n)"},{name:"Crop",group:"Shape & motion",description:"A part of the picture, filling the frame",params:{left:.1,top:.1,right:.9,bottom:.9},color:"crop(left, top, right, bottom)"},{name:"Flip",group:"Shape & motion",color:"flipx()"},{name:"Picture in picture",group:"Other pictures",description:"Another picture, fitted small in a corner",images:{inset:{description:"any size: it is fitted whole",place:"fit",zoom:.35,x:.8,y:.78}},color:"mix(rgb, inset, alpha(inset))"},{name:"Moving overlay",group:"Other pictures",description:"Another picture scrolling across at half strength",images:["overlay"],params:{speed:{default:2,min:-10,max:10}},color:"mix(rgb, shift(overlay, speed t, 0), 0.5)"},{name:"Hue shift",group:"Color & tone",description:"Turns every color around the hue wheel (in HSV)",space:"hsv",params:{amount:{default:.1,min:-.5,max:.5}},color:"(fract(r + amount), g, b)"},{name:"Saturation",group:"Color & tone",description:"More or less color (in HSV)",space:"hsv",params:{amount:{default:1.5,min:0,max:3}},color:"(r, clamp(g amount, 0, 1), b)"},{name:"Lightness",group:"Color & tone",description:"Lighter or darker without changing the colors (in Lab)",space:"lab",params:{amount:{default:1.15,min:.5,max:2}},color:"(clamp(r amount, 0, 1), g, b)"},{name:"Vivid",group:"Color & tone",description:"Colorfulness, perceptually even (in OKLab)",space:"oklab",params:{amount:{default:1.6,min:0,max:3}},color:"(r, 0.5 + (g - 0.5) amount, 0.5 + (b - 0.5) amount)"},{name:"Linear-light blur",group:"Blur & edges",description:"A Gaussian in linear light: bright spots stay bright, as a lens does",space:"linear",params:{sigma:{default:3,min:0,max:8}},color:"gaussian(sigma)"},{name:"Film grain",group:"Color & tone",description:"Noise that changes every frame",params:{amount:{default:.15,min:0,max:.6}},color:"rgb + amount (random() - 0.5)"},{name:"Swirl",group:"Shape & motion",params:{strength:{default:.02,min:0,max:.1}},color:"pixel(w/2 + (px - w/2) cos(strength t gray) - (py - h/2) sin(strength t gray), h/2 + (px - w/2) sin(strength t gray) + (py - h/2) cos(strength t gray))"}],Ot=e=>kt.find(t=>t.name===e);kt.push({name:"Old film",group:"Chains",description:"Sepia, a vignette and faint scanlines — a chain of three",steps:[Ot("Sepia"),{filter:Ot("Vignette"),with:{strength:1.2}},{filter:Ot("Scanlines"),opacity:.5}]},{name:"Comic",group:"Chains",description:"Bold flat colors with ink lines: a small blur first, so a photo's fine texture isn't inked — a chain of four",steps:[{filter:Ot("Gaussian blur"),with:{sigma:1.6}},{filter:Ot("Vivid"),with:{amount:1.5}},{filter:Ot("Posterize"),with:{levels:4}},{filter:Ot("Outline"),with:{gain:1.2}}]},{name:"Cartoon",group:"Chains",description:"Blur, then flatten the colors, then outline — a chain of three",steps:[{filter:Ot("Gaussian blur"),with:{sigma:1.5}},{filter:Ot("Posterize"),with:{levels:6}},{filter:Ot("Outline"),with:{gain:2}}]},{name:"Dreamy",group:"Chains",description:"A soft glow mixed over the picture",steps:[{filter:Ot("Bloom"),with:{amount:1.2}},{filter:Ot("Gaussian blur"),with:{sigma:2},opacity:.4}]},{name:"Tilt shift",group:"Chains",description:"Blurred where the mask is light — a chain",steps:[{filter:Ot("Gaussian blur"),with:{sigma:4}},Ot("Through a mask")]},{name:"Title card",group:"Chains",description:"A frosted panel with a caption on it — a chain of two",steps:[Ot("Frosted panel"),{filter:Ot("Caption"),with:{title:{text:"A title on a panel",y:.86}}}]},{name:"Color spotlight",group:"Chains",description:"Gray except where the mask is dark — a chain",steps:[Ot("Grayscale"),Ot("Through a mask")]});const Tt=kt,jt=()=>"undefined"!=typeof document||"undefined"!=typeof OffscreenCanvas,Ft=(e,t)=>"undefined"!=typeof document?Object.assign(document.createElement("canvas"),{width:e,height:t}):new OffscreenCanvas(e,t);function St(e){if(e&&"object"==typeof e&&Array.isArray(e.passes))return e;if("string"==typeof e){const t=e.trim().toLowerCase(),r=Tt.find(e=>e.name.toLowerCase()===t);return re(r??le(e))}return re(e)}const Ct=4096,It=2048;function Rt(e,t,r,n){const o=Math.min(1,n/Math.max(t,r));if(o>=1)return{image:e,width:t,height:r};const a=Math.max(1,Math.round(t*o)),s=Math.max(1,Math.round(r*o));if(jt()){let n=e;((e=>Boolean(e&&e.data&&e.width&&e.height)&&!("undefined"!=typeof ImageData&&e instanceof ImageData))(e)||"undefined"!=typeof ImageData&&e instanceof ImageData)&&(n=Ft(t,r),n.getContext("2d").putImageData((i=e,"undefined"!=typeof ImageData&&i instanceof ImageData?i:new ImageData(i.data instanceof Uint8ClampedArray?i.data:Uint8ClampedArray.from(i.data,i.data instanceof Float32Array||i.data instanceof Float64Array?e=>255*e:void 0),i.width,i.height)),0,0));const o=Ft(a,s),l=o.getContext("2d");return l.imageSmoothingEnabled=!0,l.imageSmoothingQuality="high",l.drawImage(n,0,0,a,s),{image:o,width:a,height:s}}var i;const l=e.data,c=new l.constructor(a*s*4);for(let e=0;e<s;e++){const n=Math.floor(e*r/s),o=Math.max(n+1,Math.floor((e+1)*r/s));for(let r=0;r<a;r++){const s=Math.floor(r*t/a),i=Math.max(s+1,Math.floor((r+1)*t/a)),h=[0,0,0,0];for(let e=n;e<o;e++)for(let r=s;r<i;r++)for(let n=0;n<4;n++)h[n]+=l[4*(e*t+r)+n];const u=(o-n)*(i-s);for(let t=0;t<4;t++)c[4*(e*a+r)+t]=h[t]/u}}return{image:{data:c,width:a,height:s},width:a,height:s}}const Ut=e=>!(e=>"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)(e)||e.complete&&e.naturalWidth?[e.naturalWidth||e.videoWidth||e.displayWidth||e.width||0,e.naturalHeight||e.videoHeight||e.displayHeight||e.height||0]:[0,0],Nt=e=>Boolean(e)&&"object"==typeof e&&Array.isArray(e.passes),zt=e=>(Array.isArray(e)||ArrayBuffer.isView(e))&&3===e.length&&[...e].every(e=>Number.isFinite(Number(e)));let Pt=null;const Bt=new WeakMap;let Dt=0;function Lt(e){if("string"==typeof e)return`s:${e}`;if(Nt(e))return Bt.has(e)||Bt.set(e,"c:"+Dt++),Bt.get(e);if(e&&"object"==typeof e)try{return`d:${ae(e)}`}catch{return null}return null}const Gt=e=>({...e,passes:e.passes.map(e=>({...e,values:{...e.values}}))});let Ht=Promise.resolve();const Wt=new Int32Array(256);for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=1&t?3988292384^t>>>1:t>>>1;Wt[e]=t}function qt(e,t){const r=new Uint8Array(12+t.length),n=new DataView(r.buffer);n.setUint32(0,t.length);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);return r.set(t,8),n.setUint32(8+t.length,function(e){let t=-1;for(let r=0;r<e.length;r++)t=Wt[255&(t^e[r])]^t>>>8;return(-1^t)>>>0}(r.subarray(4,8+t.length))),r}function Xt(e,t,r){const n=e+t-r,o=Math.abs(n-e),a=Math.abs(n-t),s=Math.abs(n-r);return o<=a&&o<=s?e:a<=s?t:r}async function Yt({width:e,height:t,data:r,palette:n="auto",colors:o=256,dither:a=!0,quantize:s=null}){if("undefined"==typeof CompressionStream)return null;if(!Number.isInteger(e)||!Number.isInteger(t)||e<1||t<1||!r||r.length<e*t*4)throw new Error("encodePng: width and height are whole numbers of pixels, and data holds 4 bytes for each");let i=null;if(("auto"===n||"force"===n)&&(i=function(e){const t=new Map,r=[],n=new Uint8Array(e.length/4);for(let o=0,a=0;o<e.length;o+=4,a++){const s=(e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])>>>0;let i=t.get(s);if(void 0===i){if(256===r.length)return null;i=r.length,t.set(s,i),r.push([e[o],e[o+1],e[o+2],e[o+3]])}n[a]=i}return{palette:r,indices:n}}(r),i&&i.palette.length>o&&(i=null),!i&&"force"===n)){if(!s)throw new Error('encodePng: palette "force" needs a quantize function (the picture has more than `colors` colors)');i=s(r,Math.min(256,Math.max(2,o)),{dither:a,width:e})}const l=[new Uint8Array([137,80,78,71,13,10,26,10])],c=new Uint8Array(13),h=new DataView(c.buffer);let u,p,f;if(h.setUint32(0,e),h.setUint32(4,t),i){const r=i.palette.length;f=r<=2?1:r<=4?2:r<=16?4:8,p="palette",c[8]=f,c[9]=3;const n=Math.ceil(e*f/8);u=new Uint8Array(t*(1+n));for(let r=0;r<t;r++){const t=r*(1+n)+1;for(let n=0;n<e;n++){const o=i.indices[r*e+n];8===f?u[t+n]=o:u[t+(n*f>>3)]|=o<<8-f-n*f%8}}const o=new Uint8Array(3*r),a=new Uint8Array(r);let s=!1;i.palette.forEach(([e,t,r,n],i)=>{o.set([e,t,r],3*i),a[i]=n,n<255&&(s=!0)}),l.push(qt("IHDR",c),qt("PLTE",o)),s&&l.push(qt("tRNS",a))}else{let n=!0;for(let e=3;e<r.length;e+=4)if(r[e]<255){n=!1;break}const o=n?3:4;p=n?"rgb":"rgba",f=8,c[8]=8,c[9]=n?2:6;const a=e*o;u=new Uint8Array(t*(1+a));const s=new Uint8Array(a),i=new Uint8Array(a);for(let l=0;l<t;l++){for(let t=0,a=l*e*4,i=0;t<e;t++,a+=4,i+=o)s[i]=r[a],s[i+1]=r[a+1],s[i+2]=r[a+2],n||(s[i+3]=r[a+3]);const t=l*(1+a);u[t]=4;for(let e=0;e<a;e++)u[t+1+e]=s[e]-Xt(e>=o?s[e-o]:0,i[e],e>=o?i[e-o]:0);i.set(s)}l.push(qt("IHDR",c))}l.push(qt("IDAT",await async function(e){if("undefined"==typeof CompressionStream)return null;const t=new CompressionStream("deflate"),r=t.writable.getWriter();return r.write(e),r.close(),new Uint8Array(await new Response(t.readable).arrayBuffer())}(u)),qt("IEND",new Uint8Array(0)));const m=i?i.palette.length:function(e,t=257){const r=new Set;for(let n=0;n<e.length;n+=4)if(r.add((e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0),r.size>=t)return r.size;return r.size}(r);return{blob:new Blob(l,{type:"image/png"}),kind:p,colors:m,bits:f}}const Zt=e=>e&&e.data&&Number.isFinite(e.width)&&Number.isFinite(e.height)&&"function"!=typeof e.getContext;function Jt(e){if(Zt(e)){const{data:t,width:r,height:n}=e;if(t instanceof Uint8ClampedArray||t instanceof Uint8Array)return{data:t,width:r,height:n};const o=new Uint8ClampedArray(r*n*4),a=t instanceof Float32Array||t instanceof Float64Array?255:1;for(let e=0;e<o.length;e++)o[e]=Math.round(t[e]*a);return{data:o,width:r,height:n}}if(e&&"function"==typeof e.getContext){const t=e.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("This canvas has a WebGL context: pass the 2D canvas applyFilter() returned, or copy it onto one first");return t.getImageData(0,0,e.width,e.height)}throw new Error("Give a canvas or a picture ({ data, width, height })")}function Vt(e){for(let t=3;t<e.length;t+=4)if(e[t]<255)return!0;return!1}return e.AWAY_SIZE=512,e.BRUSHES=a,e.CLIPS=l,e.FILTER_FORMAT=P,e.FPS=30,e.GRAPHIC_DEFAULTS=b,e.GRAPHIC_TYPES=$,e.GROUPS=["Color & tone","Blur & edges","Shape & motion","Text & shapes","Brushes","Other pictures","Chains"],e.LIBRARY=Tt,e.MAX_SHADOW_LAYERS=8,e.MAX_SIZE=Ct,e.MAX_SIZE_CPU=It,e.PLACEMENT=W,e.STROKES_DEFAULTS=c,e.TIMINGS=s,e.WIDTH_FROM=i,e.applyFilter=function(e,t,r={}){const n=Ht.then(()=>async function(e,t,{params:r={},t:n=0,images:o={},engine:a="auto",canvas:s=null,maxSize:i=null}={}){if(!e)throw new Error("applyFilter: no picture");const[l,c]=Ut(e);if(!l||!c)throw new Error("applyFilter: the picture has no size yet (not loaded?)");if(null!==i&&!(Number(i)>=1))throw new Error(`applyFilter: maxSize is a number of pixels, not ${JSON.stringify(i)}`);if("auto"!==a&&"gpu"!==a&&"cpu"!==a)throw new Error(`applyFilter: engine is 'auto', 'gpu' or 'cpu', not "${a}"`);const h=s?s.getContext("2d"):null;if(s&&!h)throw new Error("applyFilter: `canvas` must be a 2D canvas (this one already has another kind of context)");const u="cpu"!==a?function(){if(Pt&&!Pt.gl.isContextLost())return Pt;if(!jt())return null;const e=Ft(1,1),t=e.getContext("webgl",{preserveDrawingBuffer:!0,premultipliedAlpha:!1});return Pt=t?{canvas:e,gl:t,runners:new Map}:null,Pt}():null;if("gpu"===a&&!u)throw new Error('applyFilter: no WebGL here (use engine "auto" or "cpu")');const p=function(e,t,r){const n=Lt(e)&&`${t}|${Lt(e)}`,o=Pt?.runners;if(r&&n&&o?.has(n)){const e=o.get(n);return o.delete(n),o.set(n,e),e}const a=St(e),s=Gt(a),i=_t(s,{gl:r,prefer:t}),l={compiled:s,source:Nt(e)?a:Gt(a),...i};if(r&&n&&"gpu"===i.engine&&(o.set(n,l),o.size>16)){const[e,t]=o.entries().next().value;o.delete(e),t.runner.dispose()}return l}(t,"gpu"===a?"gpu":u?"auto":"cpu",u?.gl),{compiled:f,source:m,runner:d}=p,g="gpu"===p.engine,w=g?Math.min(Number(i??Ct),u.gl.getParameter(u.gl.MAX_TEXTURE_SIZE)||Ct):Number(i??It),{image:y,width:$,height:b}=Rt(e,l,c,w);try{const e=new Map(f.passes.flatMap(e=>Object.entries(e.params??{})));for(const[t,n]of Object.entries(r)){if(!e.has(t))throw new Error(`applyFilter: the filter has no knob called "${t}" (it has ${[...e.keys()].join(", ")||"none"})`);if("color"===e.get(t).type?!zt(n):!Number.isFinite(Number(n))||"object"==typeof n||""===n)throw new Error(`applyFilter: the knob "${t}" needs ${"color"===e.get(t).type?"a color, [r, g, b] with each 0–1":"a number"}, not ${JSON.stringify(n)}`)}const t=Object.entries(f.graphics??{});let a={};if(t.length){const e=t.filter(([,e])=>"strokes"!==e.type).map(([e])=>e);if(!jt()&&e.length)throw new Error(`applyFilter: this filter draws ${e.join(", ")} (text or shapes), which needs a canvas — there is none here`);a=await z(f,$,b,{t:Number.isFinite(n)?n:1/0})}f.passes.forEach((e,t)=>{e.values={...m.passes[t].values},e.opacity=m.passes[t].opacity;for(const[t,n]of Object.entries(r))t in(e.params??{})&&(e.values[t]="color"===e.params[t].type?[...n].map(Number):Number(n))}),d.setImage(y);for(const e of p.given??[])e in o||d.setImage(e,null);p.given=Object.keys(o);for(const[e,t]of Object.entries(o)){const[r,n]=Ut(t);d.setImage(e,r&&n?Rt(t,r,n,w).image:t)}for(const[e,t]of Object.entries(a))d.setImage(e,t);if(g){u.canvas.width=$,u.canvas.height=b,d.draw({t:n});const e=s??Ft($,b);e.width=$,e.height=b;const t=h??e.getContext("2d");return t.clearRect(0,0,$,b),t.drawImage(u.canvas,0,0),e}const i=await d.drawAsync({t:n});if(!jt()&&!s)return i;const l=s??Ft($,b);return l.width=$,l.height=b,(h??l.getContext("2d")).putImageData(new ImageData(i.data,$,b),0,0),l}finally{g||d.dispose()}}(e,t,r));return Ht=n.catch(()=>{}),n},e.awayFromChannels=(e,t)=>e>0?255*(1-e):1020*(1-t),e.awayPicture=me,e.chooseEngine=At,e.compileCpuPass=wt,e.compileFilter=re,e.createCpuRunner=$t,e.createFilterRunner=we,e.createRunner=_t,e.cssFont=S,e.distanceTo=pe,e.drawGraphic=N,e.encodeAway=fe,e.encodeGif=async function(e,{gifenc:t,delay:r=1e3/30,repeat:n=0,colors:o=256}={}){const a=t&&(t.GIFEncoder?t:t.default);if(!a||"function"!=typeof a.GIFEncoder)throw new Error("encodeGif needs gifenc: import * as gifenc from 'gifenc' and pass { gifenc }");const s=a.GIFEncoder();let i=null,l=0;for await(const t of e){let{data:e,width:c,height:h}=Jt(t);if((e.byteOffset||e.byteLength!==e.buffer.byteLength)&&(e=e.slice()),i&&(i[0]!==c||i[1]!==h))throw new Error(`Frame ${l+1} is ${c} × ${h}; the first was ${i[0]} × ${i[1]}`);i=[c,h];const u=Vt(e),p=u?"rgba4444":"rgb565",f=a.quantize(e,Math.max(2,Math.min(256,o)),{format:p,oneBitAlpha:u}),m=a.applyPalette(e,f,p),d={palette:f,delay:Math.round(r),repeat:n};if(u){const e=f.findIndex(e=>e.length>3&&0===e[3]);e>=0&&Object.assign(d,{transparent:!0,transparentIndex:e})}s.writeFrame(m,c,h,d),l++}if(!l)throw new Error("encodeGif: no frames");return s.finish(),new Blob([s.bytes()],{type:"image/gif"})},e.encodePng=Yt,e.familyFor=C,e.filterFromJSON=se,e.filterFromLink=ie,e.filterGraphics=Y,e.filterImages=K,e.filterParams=Q,e.filterToJSON=ae,e.filterToLink=function(e,t=""){return`${t}#${function(e){let t="";for(const r of(new TextEncoder).encode(e))t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(JSON.stringify(ce(q(e),!0)))}`},e.fontFileFromCss=F,e.googleFontFamily=j,e.googleFontUrl=function(e){const t=String(e).trim().replace(/\s+/g," ");if(!/^[A-Za-z0-9 ]{1,60}$/.test(t))throw new Error('A Google Fonts name is letters, digits and spaces, like "Lobster" or "Playfair Display"');return`https://fonts.googleapis.com/css2?family=${t.replace(/ /g,"+")}:ital,wght@0,400;0,700;1,400;1,700&display=swap`},e.layeredExpression=function(e,t){let r="rgb";for(const n of x(e,t))r=`mix(${r}, ${n}, alpha(${n}))`;return`mix(${r}, ${e}, alpha(${e}))`},e.loadGraphicFonts=R,e.normalizeFilter=q,e.normalizeGraphic=T,e.normalizeStrokes=p,e.pictureData=Jt,e.rasterizeStrokes=g,e.readFilter=le,e.renderGraphics=z,e.shadowLayerNames=x,e.simplify=y,e.simplifyLoop=w,e.strokeTimeline=f,e.toBlob=async function(e,{type:t="image/png",quality:r,palette:n="auto"}={}){if("image/png"===t){const t=await Yt({...Jt(e),palette:n});if(t)return t.blob}const o=Zt(e)?function(e){const{width:t,height:r}=e;let n=null;return"undefined"!=typeof OffscreenCanvas?n=new OffscreenCanvas(t,r):"undefined"!=typeof document&&(n=Object.assign(document.createElement("canvas"),{width:t,height:r})),n?(n.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(e.data),t,r),0,0),n):null}(Jt(e)):e;if(!o)throw new Error(`Saving as ${t} needs a browser (a canvas encodes it); in Node, save as image/png`);return"function"==typeof o.convertToBlob?o.convertToBlob({type:t,quality:r}):new Promise((e,n)=>o.toBlob(r=>r?e(r):n(new Error(`The browser could not encode ${t}`)),t,r))},e.toCompiled=St,e.toPicture=xt,e.traceContours=function(e,t,r,{minArea:n=40,tolerance:o=.8}={}){const a=(n,o)=>n>=0&&o>=0&&n<t&&o<r&&e[o*t+n]>.5,s=new Int32Array(t*r).fill(-1),i=[],l=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]];let c=0;for(let e=0;e<r;e++)for(let r=0;r<t;r++){if(!a(r,e)||s[e*t+r]>=0)continue;const h=c++,u=[e*t+r];s[e*t+r]=h;let p=0;for(;u.length;){const e=u.pop();p++;const r=e%t,n=(e-r)/t;for(const[e,o]of[[1,0],[-1,0],[0,1],[0,-1]]){const i=r+e,l=n+o;a(i,l)&&s[l*t+i]<0&&(s[l*t+i]=h,u.push(l*t+i))}}if(p<n)continue;const f=[[r,e]];let m=r,d=e,g=4;for(let n=0;n<4*p+16;n++){let n=!1;for(let e=1;e<=8;e++){const r=(g+e)%8,o=m+l[r][0],i=d+l[r][1];if(a(o,i)&&s[i*t+o]===h){g=(r+4)%8,m=o,d=i,n=!0;break}}if(!n||m===r&&d===e)break;f.push([m,d])}i.push(w(f,o))}return i},e.usesAway=de,e.validateFilter=function(e){let t;try{t=q(e)}catch(e){return[e.message]}const r=[];return ee({filter:t,with:{},opacity:1},[],r,!0),r},e}({},MathZetta,MathZetta,MathZetta);