@mathzetta/qblur 0.0.0-stage → 0.1.2

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.
@@ -0,0 +1,2 @@
1
+ /* qblur 0.1.2 (MathZetta not included: load mathzetta.min.js or mathzetta.glsl.min.js first) — Copyright (c) 2025-2026 Robert Wilcox — MIT licence — 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 colour 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 B="mathzetta-filter/1",P=["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:B,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!==B)throw new Error(`Unknown filter format "${e.format}" (this is ${B})`);const r={format:B};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 colour space (${t.COLOUR_SPACES.join(", ")}) or { "in": …, "out": … }`);const n={in:r.in??"srgb",out:r.out??"srgb"};for(const e of["in","out"])if(!t.COLOUR_SPACES.includes(n[e]))throw new Error(`"space": "${n[e]}" is not a colour space; they are ${t.COLOUR_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(!P.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(`Colour 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?"colour: 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:B,color:{rgb:`to${t.in}(rgb)`}}));i.push(s({...a,_space:t.in})),"srgb"!==t.out&&i.push(s({format:B,color:{rgb:`from${t.out}(rgb)`}}));const l={format:B,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:B,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=B);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 Be(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 Pe(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 Be(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 Pe(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 Pe(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 Be(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 Be(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 Be(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 Pe(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 Pe(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)"}),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}))`,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}),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 colours 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"\\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 colour 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"∉":return this.membership(e);case"random":return this.random();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.map(e=>`${n} === ${it(this.value(e))}`).join(" || ")})`:"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 colour, 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 colours (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 colour`);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.neighbourhood(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}`)}neighbourhood(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 colour is one number (grey), 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 colour is one number (grey), 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:"Colour & tone",color:"(1 - r, 1 - g, 1 - b)"},{name:"Grayscale",group:"Colour & tone",color:"gray"},{name:"Threshold",group:"Colour & tone",params:{cutoff:.5},color:"if gray > cutoff then 1 else 0"},{name:"Posterize",group:"Colour & tone",params:{levels:{default:4,min:2,max:16,step:1}},color:"min(floor(rgb * levels) / (levels - 1), 1)"},{name:"Brightness & contrast",group:"Colour & 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:"Colour & tone",params:{tint:[1,.85,.7]},color:"rgb * tint"},{name:"Sepia",group:"Colour & tone",color:"(0.393r + 0.769g + 0.189b, 0.349r + 0.686g + 0.168b, 0.272r + 0.534g + 0.131b)"},{name:"Colour circle",group:"Colour & tone",description:"Black and white, except a soft circle that keeps its colour",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 colour stays inside a circle and fades to grey 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:"Colour & 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 colour",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:"Colour & tone",description:"Replaces one colour 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 coloured by maths: 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 coloured 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 coloured 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 colour; 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:"Colour reveal brush",group:"Brushes",description:"The picture starts grey; the brush paints its colour 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 colour 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:"Colour & tone",description:"Turns every colour 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:"Colour & tone",description:"More or less colour (in HSV)",space:"hsv",params:{amount:{default:1.5,min:0,max:3}},color:"(r, clamp(g amount, 0, 1), b)"},{name:"Lightness",group:"Colour & tone",description:"Lighter or darker without changing the colours (in Lab)",space:"lab",params:{amount:{default:1.15,min:.5,max:2}},color:"(clamp(r amount, 0, 1), g, b)"},{name:"Vivid",group:"Colour & tone",description:"Colourfulness, 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:"Colour & 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 colours 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 colours, 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:"Colour spotlight",group:"Chains",description:"Grey 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=Et.find(t=>t.name.toLowerCase()===e.trim().toLowerCase());return re(t??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 Bt(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 Pt(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}function Dt(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 Lt({width:e,height:t,data:r,palette:n="auto",colours: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 `colours` colours)');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(Bt("IHDR",c),Bt("PLTE",o)),s&&l.push(Bt("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]-Dt(e>=o?s[e-o]:0,i[e],e>=o?i[e-o]:0);i.set(s)}l.push(Bt("IHDR",c))}return l.push(Bt("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)),Bt("IEND",new Uint8Array(0))),{blob:new Blob(l,{type:"image/png"}),kind:p,colours:i?i.palette.length:Pt(r),bits:f}}const Gt=e=>e&&e.data&&Number.isFinite(e.width)&&Number.isFinite(e.height)&&"function"!=typeof e.getContext;function Ht(e){if(Gt(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 Wt(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=B,e.FPS=30,e.GRAPHIC_DEFAULTS=b,e.GRAPHIC_TYPES=$,e.GROUPS=["Colour & 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 colour, [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,colours: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}=Ht(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=Wt(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=Lt,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=Ht,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 Lt({...Ht(e),palette:n});if(t)return t.blob}const o=Gt(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}(Ht(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);
@@ -0,0 +1,2 @@
1
+ /* qblur 0.1.2 (MathZetta not included: map mathzetta, mathzetta/glsl and mathzetta/formulas with an import map) — Copyright (c) 2025-2026 Robert Wilcox — MIT licence — https://qblur.com */
2
+ import{FILTER_NAMES as e,COLOUR_SPACES as t,PLACES as r,filterShader as o,filterVertexShader as n,REACH as a,FILTER_FUNCTIONS as s,FILTER_VALUES as i,filterPictureCalls as c}from"mathzetta/glsl";import{parseTree as l}from"mathzetta";import{checkGeneratedJs as h}from"mathzetta/formulas";const u=["round","soft","marker","chalk","spray"],p=["recorded","even","per-stroke"],f=["pressure","speed","none"],m=["none","inside","outside"],d=30,g={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 $(e,t){throw new Error(`Graphic "${e}": ${t}`)}function w(e,t,r,o,n){const a=Number(r);return(!Number.isFinite(a)||a<o||a>n)&&$(e,`"${t}" is a number from ${o} to ${n}`),a}function y(e,t){for(const r of Object.keys(t))r in g||$(e,`no such setting "${r}" for strokes`);const r={...g,...t},o=(t,o)=>(o.includes(r[t])||$(e,`"${t}" is ${o.join(", ")} — not "${r[t]}"`),r[t]),n={type:"strokes",brush:o("brush",u),widthFrom:o("widthFrom",f),timing:o("timing",p),clip:o("clip",m),size:w(e,"size",r.size,.001,.5),flow:w(e,"flow",r.flow,.01,1),spacing:w(e,"spacing",r.spacing,.02,2),taper:w(e,"taper",r.taper,0,.5),speed:w(e,"speed",r.speed,.05,20),gap:w(e,"gap",r.gap,0,600),start:w(e,"start",r.start,0,1e4),fit:w(e,"fit",r.fit,0,1e4),age:w(e,"age",r.age,1,1e4),buildUp:Boolean(r.buildUp),shadows:[]};Array.isArray(r.strokes)||$(e,'"strokes" is a list of { "points": [[x, y, ms, pressure], …] }');let a=0;return n.strokes=r.strokes.map((t,r)=>{const o=Array.isArray(t)?t:t?.points;return Array.isArray(o)||$(e,`stroke ${r+1} is { "points": [[x, y, ms, pressure], …] }`),a+=o.length,a>6e4&&$(e,"a drawing has at most 60000 points"),{points:o.map((t,o)=>((!Array.isArray(t)||t.length<2||!t.every(e=>Number.isFinite(Number(e))))&&$(e,`stroke ${r+1}, point ${o+1} is [x, y, ms, pressure]`),[+Number(t[0]).toFixed(4),+Number(t[1]).toFixed(4),Math.round(Number(t[2]??16*o)),+Math.min(1,Math.max(0,Number(t[3]??1))).toFixed(2)]))}}),n}function b(e,t=1){const r=[];let o=e.start;const n=30/e.speed,a=20/e.speed;for(const s of e.strokes){const i=s.points;if(!i.length)continue;const c=[0];for(let e=1;e<i.length;e++)c.push(c[e-1]+Math.hypot((i[e][0]-i[e-1][0])*t,i[e][1]-i[e-1][1]));const l=c[c.length-1]||1e-9,h=i[0][2],u=i.map((t,r)=>{let o;o="recorded"===e.timing?(t[2]-h)/1e3*30/e.speed:"even"===e.timing?c[r]*n:c[r]/l*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]),o=(c[r]-c[r-1])/e*1e3;s=Math.min(1.3,Math.max(.35,1.3-.6*o))}return e.taper>0&&(s*=Math.max(.15,Math.min(1,c[r]/l/e.taper,(1-c[r]/l)/e.taper))),{x:t[0],y:t[1],f:o,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+=o;r.push({points:u,start:o,end:o+p}),o+=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 o of r){for(const r of o.points)r.f=e.start+(r.f-e.start)*t;o.start=e.start+(o.start-e.start)*t,o.end=e.start+(o.end-e.start)*t}s=e.start+e.fit}return{strokes:r,total:s}}function x(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 _=new Map;function k(e,t,r,o=1/0,{mask:n=null}={}){const a=t*r,{alpha:s,passes:i,latest:c,cov:l,when:h,touched:u}=function(e){let t=_.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)},_.clear(),_.set(e,t)),t.alpha.fill(0),t.passes.fill(0),t.latest.fill(-1),t}(a),{strokes:p,total:f}=b(e,t/r),m=Number.isFinite(o)?o:f,d=Math.max(.5,e.size*r/2);let g=0,$=256*Math.max(a,65536);p.forEach(o=>{if(o.start>m||$<=0)return;let n=0;const a=(t,r,o,n)=>{const a=g++;if("spray"===e.brush){const e=Math.max(3,Math.round(.6*o)),s=Math.max(.6,.07*o);for(let i=0;i<e;i++){const e=x(a,2*i)*Math.PI*2,c=Math.sqrt(x(a,2*i+1))*o;p(t+Math.cos(e)*c,r+Math.sin(e)*c,s,n,"round")}}else p(t,r,o,n,e.brush)},p=(o,a,s,i,c)=>{const p="marker"===c?s:s+1,f=Math.max(0,Math.floor(o-p)),m=Math.min(t-1,Math.ceil(o+p)),d=Math.max(0,Math.floor(a-p)),g=Math.min(r-1,Math.ceil(a+p));$-=m>=f&&g>=d?(m-f+1)*(g-d+1):16;for(let r=d;r<=g;r++)for(let p=f;p<=m;p++){const f=p+.5-o,m=r+.5-a;let d;if("soft"===c){const e=Math.hypot(f,m)/s;if(e>=1)continue;const t=1-e;d=t*t*(3-2*t)}else if("marker"===c){const e=(f+m)*Math.SQRT1_2,t=(m-f)*Math.SQRT1_2,r=Math.hypot(e/s,t/(.33*s));d=Math.min(1,Math.max(0,(1-r)*s*.33+.5))}else d=Math.min(1,Math.max(0,s-Math.hypot(f,m)+.5)),"chalk"===c&&(d*=x(p,7919*r)>.42?1:.12);if(d<=0)continue;d*=e.flow;const g=r*t+p;d>l[g]&&(0===l[g]&&(u[n++]=g),l[g]=d),d>.02&&(h[g]=i)}},f=o.points;let w=0;const y=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]=y(f[0]);a(e,t,d*f[0].wf,f[0].f)}for(let t=1;t<f.length;t++){const r=f[t-1],o=f[t];if(r.f>m)break;const[n,s]=y(r),[i,c]=y(o);let l=1;o.f>m&&(l=(m-r.f)/Math.max(1e-9,o.f-r.f));const h=Math.hypot(i-n,c-s);let u=1===t?0:w;for(;u<=h*l&&$>0;){const t=h?u/h:0,l=d*(r.wf+(o.wf-r.wf)*t);a(n+(i-n)*t,s+(c-s)*t,l,r.f+(o.f-r.f)*t),u+=Math.max(.5,2*e.spacing*l)}if(w=u-h,l<1||$<=0)break}for(let t=0;t<n;t++){const r=u[t],o=l[r];s[r]=e.buildUp?1-(1-s[r])*(1-o):Math.max(s[r],o),i[r]+=o,o>.02&&h[r]>c[r]&&(c[r]=h[r]),l[r]=0}});const w=new Uint8ClampedArray(4*a),y="inside"===e.clip,k="outside"===e.clip;for(let t=0;t<a;t++){let r=s[t];if(0===r)continue;let o=1;n&&(y||k)&&(o=y?n[t]:1-n[t]),r*=o;const a=4*t;w[a]=Math.round(255*Math.min(1,Math.max(0,(m-c[t])/e.age))),w[a+1]=Math.round(255*Math.min(1,i[t]*o/4)),w[a+2]=Math.round(255*Math.min(1,Math.max(0,c[t]/Math.max(1e-9,f)))),w[a+3]=Math.round(255*r)}return{data:w,width:t,height:r,total:f}}function v(e,t,r,{minArea:o=40,tolerance:n=.8}={}){const a=(o,n)=>o>=0&&n>=0&&o<t&&n<r&&e[n*t+o]>.5,s=new Int32Array(t*r).fill(-1),i=[],c=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]];let l=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=l++,u=[e*t+r];s[e*t+r]=h;let p=0;for(;u.length;){const e=u.pop();p++;const r=e%t,o=(e-r)/t;for(const[e,n]of[[1,0],[-1,0],[0,1],[0,-1]]){const i=r+e,c=o+n;a(i,c)&&s[c*t+i]<0&&(s[c*t+i]=h,u.push(c*t+i))}}if(p<o)continue;const f=[[r,e]];let m=r,d=e,g=4;for(let o=0;o<4*p+16;o++){let o=!1;for(let e=1;e<=8;e++){const r=(g+e)%8,n=m+c[r][0],i=d+c[r][1];if(a(n,i)&&s[i*t+n]===h){g=(r+4)%8,m=n,d=i,o=!0;break}}if(!o||m===r&&d===e)break;f.push([m,d])}i.push(E(f,n))}return i}function E(e,t){if(e.length<4)return[...e,e[0]];const[r,o]=e[0];let n=0;return e.forEach(([t,a],s)=>{Math.hypot(t-r,a-o)>Math.hypot(e[n][0]-r,e[n][1]-o)&&(n=s)}),[...M(e.slice(0,n+1),t),...M([...e.slice(n),e[0]],t).slice(1)]}function M(e,t){if(e.length<3)return e;const r=new Uint8Array(e.length);r[0]=r[e.length-1]=1;const o=[[0,e.length-1]];for(;o.length;){const[n,a]=o.pop(),[s,i]=e[n],[c,l]=e[a],h=Math.hypot(c-s,l-i)||1e-9;let u=-1,p=-1;for(let t=n+1;t<a;t++){const r=Math.abs((c-s)*(i-e[t][1])-(s-e[t][0])*(l-i))/h;r>u&&(u=r,p=t)}u>t&&(r[p]=1,o.push([n,p],[p,a]))}return e.filter((e,t)=>r[t])}const A=["text","rect","ellipse","strokes"],O={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:[]}},T=8,j=(e,t)=>(t.shadows??[]).map((t,r)=>`${e}_shadow${r+1}`);function S(e,t){let r="rgb";for(const o of j(e,t))r=`mix(${r}, ${o}, alpha(${o}))`;return`mix(${r}, ${e}, alpha(${e}))`}const F=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d.,\s%deg/]+\)|[a-z]{3,20}|transparent)$/i,R=/^[\w\s,'"-]{1,80}$/,z=["normal","bold","100","200","300","400","500","600","700","800","900"];function I(e,t,r){if("string"!=typeof r||!F.test(r.trim()))throw new Error(`Graphic "${e}": "${t}" is a colour like "#ffcc00", "rgba(0,0,0,0.5)" or "white"`);return r.trim()}function N(e,t,r,o=-1/0,n=1/0){const a=Number(r);if(!Number.isFinite(a)||a<o||a>n)throw new Error(`Graphic "${e}": "${t}" is a number${Number.isFinite(o)?` from ${o} to ${n}`:""}`);return a}function U(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:I(e,"outline.color",t.color??"#000000"),width:N(e,"outline.width",t.width??.06,0,1)}}function B(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:I(e,"shadow.color",t.color??"rgba(0,0,0,0.6)"),blur:N(e,"shadow.blur",t.blur??.15,0,2),dx:N(e,"shadow.dx",t.dx??0,-2,2),dy:N(e,"shadow.dy",t.dy??0,-2,2)}}function C(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(!A.includes(r))throw new Error(`Graphic "${e}": "type" is text, rect, ellipse or strokes — not "${r}"`);if("strokes"===r)return y(e,t);const o=O[r];for(const n of Object.keys(t))if(!(n in o)&&"fontUrl"!==n&&"onlyShadow"!==n)throw new Error(`Graphic "${e}": no such setting "${n}" for ${r}`);const n={type:r};for(const[r,a]of Object.entries(o)){if("type"===r)continue;const o=r in t&&void 0!==t[r]?t[r]:a;if("color"===r)n.color=I(e,r,o);else if("outline"===r)n.outline=U(e,o);else if("shadow"===r)n.shadow=B(e,o);else if("shadows"===r){if(!Array.isArray(o)||o.length>8)throw new Error(`Graphic "${e}": "shadows" is a list of up to 8 { "color", "blur", "dx", "dy" }`);n.shadows=o.map((t,r)=>{if(!t||"object"!=typeof t)throw new Error(`Graphic "${e}": shadow layer ${r+1} is { "color", "blur", "dx", "dy" }`);return B(e,t)})}else if("text"===r){if("string"!=typeof o||o.length>500)throw new Error(`Graphic "${e}": "text" is up to 500 characters`);n.text=o}else if("font"===r){if("string"!=typeof o||!R.test(o))throw new Error(`Graphic "${e}": "font" is a font family, like "Georgia" or "sans-serif"`);n.font=o}else if("weight"===r){if(!z.includes(String(o)))throw new Error(`Graphic "${e}": "weight" is normal, bold or 100–900`);n.weight=String(o)}else if("style"===r){if(!["normal","italic"].includes(o))throw new Error(`Graphic "${e}": "style" is normal or italic`);n.style=o}else if("align"===r){if(!["left","center","right"].includes(o))throw new Error(`Graphic "${e}": "align" is left, center or right`);n.align=o}else"size"===r?n.size=N(e,r,o,.005,2):"w"===r||"h"===r?n[r]=N(e,r,o,0,4):"radius"===r?n.radius=N(e,r,o,0,.5):"lineHeight"===r?n.lineHeight=N(e,r,o,.5,4):n[r]=N(e,r,o)}if(void 0!==t.fontUrl&&null!==t.fontUrl&&""!==t.fontUrl){if("text"!==r)throw new Error(`Graphic "${e}": "fontUrl" is for text`);let o;try{o=new URL(t.fontUrl)}catch{o=null}if(!o||"https:"!==o.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`);n.fontUrl=o.href}return void 0!==t.onlyShadow&&(n.onlyShadow=N(e,"onlyShadow",t.onlyShadow,0,7)),n}function P(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`}function G(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 D(e,{weight:t="400",style:r="normal"}={}){const o=[...e.matchAll(/@font-face\s*{([^}]*)}/g)].map(e=>e[1]),n=(e,t)=>(new RegExp(`${t}\\s*:\\s*([^;]+);`).exec(e)?.[1]??"").trim(),a=String("bold"===t?700:"normal"===t?400:t),s=o.filter(e=>n(e,"font-weight")===a&&n(e,"font-style")===r),i=(s.length?s:o).at(-1);return i&&(/url\(([^)]+)\)/.exec(i)?.[1]??"").replace(/^['"]|['"]$/g,"")||null}function L(e,t){const r=e.fontUrl?`"${q(e.fontUrl)}", ${e.font}`:e.font;return`${e.style} ${e.weight} ${Math.max(1,e.size*t)}px ${r}`}function q(e){let t=0;for(const r of e)t=31*t+r.charCodeAt(0)>>>0;return`mz-font-${t.toString(36)}`}const W=new Map;async function X(e,t=100){if("undefined"==typeof document&&"undefined"==typeof self)return[];const r="undefined"!=typeof document?document.fonts:self.fonts;if(!r)return[];const o=[];for(const n of Object.values(e??{}))if("text"===n.type){if(n.fontUrl&&"undefined"!=typeof FontFace){const e=`${n.fontUrl} ${n.weight} ${n.style}`;W.has(e)||W.set(e,H(n,r)),await W.get(e)||o.push(n.fontUrl)}try{await r.load(L(n,t),n.text)}catch{}}return[...new Set(o)]}async function H(e,t){try{let r=e.fontUrl;if(!/\.(woff2?|ttf|otf)(\?|$)/i.test(new URL(r).pathname)||G(r)){if(r=D(await(await fetch(r,{credentials:"omit",referrerPolicy:"no-referrer"})).text(),e),!r||!r.startsWith("https://"))return null}const o=new FontFace(q(e.fontUrl),`url(${JSON.stringify(r)})`,{weight:e.weight,style:e.style});return t.add(await o.load()),o}catch{return null}}function K(e,t,r,o){e.save();const n="text"===t.type?t.size*o:o,a=void 0!==t.onlyShadow?t.shadows[t.onlyShadow]:null,s=a?2*(r+o)+1e3:0,i=a??t.shadow;if(e.translate(t.x*r-s,t.y*o),t.angle&&e.rotate(t.angle),i&&(e.shadowColor=i.color,e.shadowBlur=i.blur*n,e.shadowOffsetX=i.dx*n+s,e.shadowOffsetY=i.dy*n),e.fillStyle=a?"#000000":t.color,t.outline&&(e.strokeStyle=t.outline.color,e.lineWidth=t.outline.width*n,e.lineJoin="round"),"text"===t.type){e.font=L(t,o),e.textAlign=t.align,e.textBaseline="middle";const r=t.text.split("\n"),n=t.size*o*t.lineHeight;r.forEach((o,s)=>{const c=(s-(r.length-1)/2)*n;t.outline&&e.strokeText(o,0,c),t.outline&&i&&!a&&(e.shadowColor="transparent"),e.fillText(o,0,c),t.outline&&i&&!a&&(e.shadowColor=i.color)})}else{const n=t.w*r,s=t.h*o;if(e.beginPath(),"ellipse"===t.type)e.ellipse(0,0,n/2,s/2,0,0,2*Math.PI);else{const r=Math.min(n,s)*t.radius;e.roundRect?e.roundRect(-n/2,-s/2,n,s,r):e.rect(-n/2,-s/2,n,s)}e.fill(),t.outline&&(a||(e.shadowColor="transparent"),e.stroke())}e.restore()}async function Y(e,t,r,{t:o=1/0,mask:n=null}={}){const a=e.graphics??{},s=await X(a,r),i={};for(const[e,s]of Object.entries(a)){if("strokes"===s.type){const a=k(s,t,r,o,{mask:n});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});K(a.getContext("2d"),s,t,r),i[e]=a}return Object.defineProperty(i,"failedFonts",{value:s}),i}const J="mathzetta-filter/1",V=["r","g","b","a","rgb","rgba"],Z=/^[A-Za-z][A-Za-z0-9_]*$/,Q=new Set([...e,"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"]),ee=e=>Array.isArray(e)&&3===e.length&&e.every(e=>Number.isFinite(Number(e))),te=e=>e&&"object"==typeof e&&!Array.isArray(e),re={place:"cover",zoom:1,x:.5,y:.5,angle:0};function oe(e){if("string"==typeof e){if(!e.trim())throw new Error("The filter is empty");return{format:J,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!==J)throw new Error(`Unknown filter format "${e.format}" (this is ${J})`);const r={format:J};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(ie),void 0!==e.notes&&(r.notes=ne(e.notes,he(r))),r}if(void 0===e.color)throw new Error('A filter needs "color" (an expression, or one per channel) or "steps"');const o=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,o]of Object.entries(e)){if(!Z.test(r))throw new Error(`Parameter name "${r}" must be letters, digits and _, starting with a letter`);if(Q.has(r))throw new Error(`"${r}" is already defined in every filter; pick another parameter name`);t[r]=ce(r,o)}return t}(e.params??{});Object.keys(o).length&&(r.params=o),void 0!==e.notes&&(r.notes=ne(e.notes,o));const n=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 o={};for(const[e,n]of Object.entries(r)){if(!Z.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(Q.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`);o[e]=se(e,n)}return o}(e.images??{},o);Object.keys(n).length&&(r.images=n);const a=function(e,t,r){if(!te(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 o={};for(const[n,a]of Object.entries(e)){if(!Z.test(n)||n.startsWith("mz_"))throw new Error(`Graphic name "${n}" must be letters, digits and _, starting with a letter`);if(Q.has(n)||"source"===n||"selection"===n)throw new Error(`"${n}" is already defined in every filter; pick another graphic name`);if(Object.hasOwn(t,n)||Object.hasOwn(r,n))throw new Error(`"${n}" is both a graphic and a parameter or picture`);o[n]=C(n,a)}const n=new Set(Object.keys(o).flatMap(e=>Array.from({length:8},(t,r)=>`${e}_shadow${r+1}`)));for(const e of[...Object.keys(o),...Object.keys(t),...Object.keys(r)])if(n.has(e))throw new Error(`"${e}" is the name of a shadow layer of another graphic; pick another name`);return o}(e.graphics??{},o,n);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(!te(r))throw new Error(`"space" is a colour space (${t.join(", ")}) or { "in": …, "out": … }`);const o={in:r.in??"srgb",out:r.out??"srgb"};for(const e of["in","out"])if(!t.includes(o[e]))throw new Error(`"space": "${o[e]}" is not a colour space; they are ${t.join(", ")}`);return"srgb"===o.in&&"srgb"===o.out?null:o}(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,o]of Object.entries(e)){if(!V.includes(r))throw new Error(`"color" can set r, g, b, a, rgb or rgba — not "${r}"`);if("string"!=typeof o||!o.trim())throw new Error(`"color.${r}" must be an expression`);t[r]=o.trim()}if(!Object.keys(t).length)throw new Error('"color" sets no channels');return t}(e.color),r}function ne(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(!te(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 ae(e){if(e.color)return{...e.graphics??{}};const t={};for(const r of e.steps)for(const[e,o]of Object.entries(ae(r.filter)))Object.hasOwn(t,e)||(t[e]=o);return t}function se(e,t){if(!te(t))throw new Error(`Image "${e}": give { description, place, zoom, x, y, angle }`);const o={};if(t.description&&(o.description=String(t.description)),void 0!==t.place){if(!r.includes(t.place))throw new Error(`Image "${e}": "place" is ${r.join(", ")} — not "${t.place}"`);o.place=t.place}for(const r of["zoom","x","y","angle"]){if(void 0===t[r])continue;const n=Number(t[r]);if(!Number.isFinite(n))throw new Error(`Image "${e}": "${r}" is a number`);o[r]=n}for(const r of Object.keys(t))if(!["description","place","zoom","x","y","angle"].includes(r))throw new Error(`Image "${e}": no such setting "${r}"`);return o}function ie(e){if("string"==typeof e)return{filter:oe(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:o,skip:n,...a}=e,s={filter:oe(void 0!==t?t:a),with:{},opacity:1,skip:Boolean(n)};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!==o){const e=Number(o);if(!(e>=0&&e<=1))throw new Error('"opacity" is a number from 0 to 1');s.opacity=e}return s}function ce(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"),o={type:r};if(void 0!==t.label&&(o.label=String(t.label)),"color"===r){const r=t.default??[1,1,1];if(!ee(r))throw new Error(`Colour parameter "${e}" needs a default of three numbers, 0–1`);return o.default=r.map(Number),o}if("number"!==r)throw new Error(`Parameter "${e}": the type is "number" or "color", not "${r}"`);let n=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`);n=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??(n?n[0]:0));if(!Number.isFinite(a))throw new Error(`Parameter "${e}" needs a numeric default`);if(o.default=a,o.min=void 0!==t.min?Number(t.min):n?n.reduce((e,t)=>Math.min(e,t),a):Math.min(0,2*a),o.max=void 0!==t.max?Number(t.max):n?n.reduce((e,t)=>Math.max(e,t),a):Math.max(1,2*a),void 0!==t.step&&(o.step=Number(t.step)),n&&(o.options=n),"box"!==t.input||n||(o.input="box"),!(o.min<=a&&a<=o.max))throw new Error(`Parameter "${e}": the default ${a} is outside ${o.min} to ${o.max}`);return o}function le(e){if(e.color)return{...e.images??{}};const t={};for(const r of e.steps)for(const[e,o]of Object.entries(le(r.filter)))Object.hasOwn(t,e)||(t[e]=o);return t}function he(e){if(e.color)return{...e.params??{}};const t={};for(const r of e.steps)for(const[e,o]of Object.entries(he(r.filter)))Object.hasOwn(t,e)||(t[e]=o);return t}function ue(e){let t;try{t=oe(e)}catch(e){return[e.message]}const r=[];return pe({filter:t,with:{},opacity:1},[],r,!0),r}function pe(e,t,r,o){const{filter:n}=e,a=fe(n,t),s=he(n),i=le(n),c=ae(n);for(const[t,o]of Object.entries(e.with)){if(Object.hasOwn(c,t)){if(te(o))try{C(t,{...c[t],...o})}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{se(t,o)}catch(e){r.push(`${a}: ${e.message}`)}continue}const e=Object.hasOwn(s,t)?s[t]:null;e?("color"===e.type?ee(o):Number.isFinite(Number(o)))||r.push(`${a}: "${t}" should be a ${"color"===e.type?"colour: three numbers, 0–1":"number"}`):r.push(`${a}: "with" sets "${t}", but there is no parameter called that`)}if(n.steps)n.steps.forEach((e,n)=>pe(e,[...t,n],r,o));else if(o)try{ge(n,Object.fromEntries(Object.entries(e.with).filter(([e])=>Object.hasOwn(n.graphics??{},e))),1,t,100)}catch(e){r.push(`${a}: ${e.message}`)}}function fe(e,t){return e.name?`"${e.name}"`:t.length?`step ${t.map(e=>e+1).join(".")}`:"the filter"}function me(e,t={}){const r=oe(e),o=[];if(pe({filter:r,with:{},opacity:1},[],o,!1),o.length)throw new Error(o.join("\n"));const n={passes:[],credits:[],problems:o,version:300===t.version?300:100,top:r,graphics:{}};if(de({filter:r,with:{},opacity:1,skip:!1},[],{},n),o.length)throw new Error(o.join("\n"));return n.passes.length||n.passes.push(ge(oe("pixel(px, py)"),{},1,[],n.version)),{name:r.name??"",author:r.author??"",description:r.description??"",version:n.version,passes:n.passes,credits:n.credits,images:le(r),graphics:n.graphics}}function de(e,t,r,o){if(e.skip)return;if(o.passes.length>256){const e="A filter has at most 256 passes";return void(o.problems.includes(e)||o.problems.push(e))}const n=function(e){if(!e.space||void 0===e.color)return null;const{space:t,name:r,author:o,description:n,...a}=e,s=e=>({filter:e,with:{},opacity:1,skip:!1}),i=[];"srgb"!==t.in&&i.push(s({format:J,color:{rgb:`to${t.in}(rgb)`}}));i.push(s({...a,_space:t.in})),"srgb"!==t.out&&i.push(s({format:J,color:{rgb:`from${t.out}(rgb)`}}));const c={format:J,steps:i};for(const[e,t]of Object.entries({name:r,author:o,description:n}))t&&(c[e]=t);return c}(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:o,...n}=e,a=e=>{const r={format:J,color:`${t[1]}${e}(${t[2]})`};return n.params&&(r.params=n.params),n.images&&(r.images=n.images),n.graphics&&(r.graphics=n.graphics),{filter:r,with:{},opacity:1,skip:!1}};return{...n,steps:[a("x"),a("y")]}}(e.filter);if(n)return e.filter===o.top&&(o.top=n),void de({...e,filter:n},t,r,o);const{filter:a}=e,s={...e.with,...r};for(const t of Object.keys(r))te(r[t])&&te(e.with[t])&&(s[t]={...e.with[t],...r[t]});if(a.name&&a!==o.top&&!o.credits.some(e=>e.name===a.name&&e.author===(a.author??""))&&o.credits.push({name:a.name,author:a.author??""}),a.color){try{o.passes.push(function(e,t){e.bind={};for(const[r,o]of Object.entries(e.graphics??{})){let n=r;for(let e=2;n in t&&JSON.stringify(t[n])!==JSON.stringify(o);e++)n=`${r}~${e}`;t[n]=o,e.bind[r]=n}return e}(ge(a,s,e.opacity,t,o.version),o.graphics))}catch(e){o.problems.push(`${fe(a,t)}: ${e.message}`)}return}const i=o.passes.length;a.steps.forEach((e,r)=>de(e,[...t,r],s,o)),e.opacity<1&&(o.passes.length-i===1?o.passes[i].opacity*=e.opacity:(o.passes[i].keepInput+=1,o.passes.push(function(e,t,r){const o=300===r,n=o?"texture":"texture2D",a=[o?"#version 300 es":"","precision highp float;","uniform sampler2D image;","uniform sampler2D base;","uniform vec2 resolution;","uniform float mz_opacity;",o?"out vec4 fragColor;":"","void main() {"," vec2 uv = gl_FragCoord.xy / resolution;",` ${o?"fragColor":"gl_FragColor"} = mix(${n}(base, uv), ${n}(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,o.version))))}function ge(e,t,r,n,a){const s=e.params??{},i={};for(const[e,r]of Object.entries(s))Object.hasOwn(t,e)?i[e]="color"===r.type?t[e].map(Number):Number(t[e]):i[e]=r.default;const c={};for(const[r,o]of Object.entries(e.images??{})){const{description:e,...n}=o;c[r]={...re,...n,...te(t[r])?t[r]:{}}}const l={};for(const[r,o]of Object.entries(e.graphics??{}))l[r]=te(t[r])?C(r,{...o,...t[r]}):o,c[r]={...re,place:"stretch"},j(r,l[r]).forEach((e,t)=>{l[e]={...l[r],onlyShadow:t},c[e]={...re,place:"stretch"}});const h=function(e,t,r=null){const n=e.params??{},a={};for(const[e,t]of Object.entries(n))a[e]="color"===t.type?"vec3":"float";const s={};for(const[t,o]of Object.entries(e.images??{}))s[t]={place:r?.[t]?.place??o.place??re.place};for(const[t,o]of Object.entries(e.graphics??{})){s[t]={place:"stretch"};const e=r?Object.keys(r).filter(e=>/_shadow\d+$/.test(e)&&e.startsWith(`${t}_shadow`)):j(t,o);for(const t of e)s[t]={place:"stretch"}}return o(e.color,{version:t,uniforms:a,values:Object.keys(n),images:s,blend:!0,space:e._space??e.space?.in??"srgb"})}(e,a,c),u=Object.keys(c);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:n,color:e.color,space:e._space??"srgb",fragment:h,params:s,values:i,opacity:r,images:u,placements:c,graphics:l,keepInput:0,blendKept:!1}}function $e(e){return JSON.stringify(_e(oe(e),!0),null,2)}function we(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Not valid JSON")}return oe(t)}function ye(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(_e(oe(e),!0)))}`}function be(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 oe(r)}function xe(e){const t=String(e??"").trim();if(!t)throw new Error("Nothing to read");if(t.startsWith("{"))return we(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 be(e)}catch(e){if(t.includes("#"))throw e}}return oe(t)}function _e(e,t){const r={};t&&(r.format=J);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=_e(e.filter,!1),r=1===Object.keys(t).length&&"string"==typeof t.color?t.color:t,o={};return Object.keys(e.with).length&&(o.with=e.with),1!==e.opacity&&(o.opacity=e.opacity),e.skip&&(o.skip=!0),Object.keys(o).length?{filter:r,...o}: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 ke(e,t,r={}){if(e.isContextLost())throw new Error("The WebGL context is lost");const o=Ee(e,r.precision),a=n({version:t.version}),s=[];try{for(const r of t.passes)s.push(Me(e,a,r.fragment,r.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,c=s.map(()=>new Map),l=(t,r)=>(c[t].has(r)||c[t].set(r,e.getUniformLocation(s[t],r)),c[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),ve(e);const p=new Map,f=new Map,m=e.createTexture();e.bindTexture(e.TEXTURE_2D,m),ve(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),ve(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 $=0,w=0;const y={passes:t.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),y;let o=u.texture;if(t&&"source"!==t&&(p.has(t)||(p.set(t,e.createTexture()),e.bindTexture(e.TEXTURE_2D,p.get(t)),ve(e)),o=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,o=e instanceof Uint8ClampedArray?e:Uint8ClampedArray.from(e,t?e=>255*e:void 0);r=new ImageData(o,r.width,r.height)}return e.bindTexture(e.TEXTURE_2D,o),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]),y},draw({t:r=0}={}){if(e.drawingBufferWidth!==$||e.drawingBufferHeight!==w){$=e.drawingBufferWidth,w=e.drawingBufferHeight;for(const t of g)e.bindTexture(e.TEXTURE_2D,t.texture),e.texImage2D(e.TEXTURE_2D,0,o.internal,$,w,0,e.RGBA,o.type,null)}let n=u;const a=[];return t.passes.forEach((c,y)=>{for(let e=0;e<c.keepInput;e++)a.push(n);const b=y===t.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),ve(e,o.filter),e.texImage2D(e.TEXTURE_2D,0,o.internal,$,w,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,Ee(e,"byte")),e.bindTexture(e.TEXTURE_2D,r.texture),ve(e,o.filter),e.texImage2D(e.TEXTURE_2D,0,o.internal,$,w,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);const x=s[y];e.useProgram(x);const _=e.getAttribLocation(x,"position");e.bindBuffer(e.ARRAY_BUFFER,h),e.enableVertexAttribArray(_),e.vertexAttribPointer(_,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,n.texture),e.uniform1i(l(y,"image"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,c.blendKept?a[a.length-1].texture:null),c.blendKept&&e.uniform1i(l(y,"base"),1),c.images.forEach((t,r)=>{if(e.activeTexture(e.TEXTURE2+r),e.bindTexture(e.TEXTURE_2D,"source"===t?u.texture:p.get(i(c,t))??(c.graphics?.[t]?d:m)),e.uniform1i(l(y,`mz_img_${t}`),2+r),!c.placements[t])return;const o=f.get(i(c,t))??[1,1],n=c.placements[t];e.uniform2f(l(y,`mz_size_${t}`),o[0],o[1]),e.uniform4f(l(y,`mz_place_${t}`),Number(n.zoom),Number(n.x),Number(n.y),Number(n.angle))}),e.uniform2f(l(y,"resolution"),$,w),e.uniform1f(l(y,"t"),r),e.uniform1f(l(y,"mz_opacity"),c.opacity);for(const[t,r]of Object.entries(c.params)){const o=c.values[t];"color"===r.type?e.uniform3fv(l(y,t),o.map(Number)):e.uniform1f(l(y,t),Number(o))}e.drawArrays(e.TRIANGLES,0,3),c.blendKept&&a.pop(),n=b}),y},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 y}function ve(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 Ee(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 o=e.getExtension("OES_texture_float_linear")?e.LINEAR:e.NEAREST;return"float"===t?{name:"float",internal:e.RGBA32F,type:e.FLOAT,filter:o}:{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 o=e.getExtension("OES_texture_half_float");return o&&e.getExtension("EXT_color_buffer_half_float")?{name:"half",internal:e.RGBA,type:o.HALF_FLOAT_OES,filter:e.getExtension("OES_texture_half_float_linear")?e.LINEAR:e.NEAREST}:r}function Me(e,t,r,o){const n=e.createProgram(),a=[];let s=null;for(const[i,c]of[[e.VERTEX_SHADER,t],[e.FRAGMENT_SHADER,r]]){const t=e.createShader(i);if(a.push(t),e.shaderSource(t,c),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS)){s=`${o||"The filter"} does not compile: ${(e.getShaderInfoLog(t)??"").trim()}`;break}e.attachShader(n,t)}s||(e.linkProgram(n),e.getProgramParameter(n,e.LINK_STATUS)||(s=`${o||"The filter"} does not link: ${(e.getProgramInfoLog(n)??"").trim()}`));for(const t of a)e.deleteShader(t);if(s)throw e.deleteProgram(n),new Error(s);return n}const Ae={data:new Float32Array([1,1,1,1]),width:1,height:1},Oe={data:new Float32Array([0,0,0,0]),width:1,height:1},Te={cover:0,fit:1,stretch:2,tile:3};function je(e){return Te[e??"cover"]??0}function Se(e,t){return e-t*Math.floor(e/t)}const Fe=(e,t)=>e<0?0:e>t?t:e;function Re(e,t,r,o,n,a){const s=Math.floor(o),i=Math.floor(n),c=o-s,l=n-i,h=Fe(s,t-1),u=Fe(s+1,t-1),p=Fe(i,r-1),f=Fe(i+1,r-1),m=4*(p*t+h),d=4*(p*t+u),g=4*(f*t+h),$=4*(f*t+u);for(let t=0;t<4;t++){const r=e[m+t]+(e[d+t]-e[m+t])*c,o=e[g+t]+(e[$+t]-e[g+t])*c;a[t]=r+(o-r)*l}return a}function ze(e,t,r){const o=Math.min(Math.max(Math.ceil(e),0),t),n=[];for(let e=-o;e<=o;e++)r(e)&&n.push(e);return n}function Ie(e,t,r,o,n,a,s,i,c=0,l=o){const h=new Float32Array(r*o*3),u=a.length,p=Int32Array.from(a),f=Float64Array.from(s??a.map(()=>1)),m="x"===n?r:o,d=new Int32Array(u);for(let o=c;o<l;o++)for(let a=0;a<r;a++){const s="x"===n?a:o;for(let e=0;e<u;e++){let i=s+p[e];i=i<0?0:i>=m?m-1:i,d[e]=("x"===n?o*r+i:i*r+a)*t}let c=0,l=0,g=0;for(let t=0;t<u;t++){const r=d[t],o=f[t];c+=e[r]*o,l+=e[r+1]*o,g+=e[r+2]*o}const $=3*(o*r+a);h[$]=c/i,h[$+1]=l/i,h[$+2]=g/i}return h}function Ne(e,t,r,o,n,a,s,i=0,c=o){const l=new Float32Array(r*o*3),h="x"===n?r:o,u="x"===n?o:r,p=s-a+1,f=(e,t)=>"x"===n?e*r+t:t*r+e,m=e=>e<0?0:e>=h?h-1:e,[d,g]="x"===n?[i,c]:[0,u],[$,w]="x"===n?[0,h]:[i,c];for(let r=d;r<g;r++){let o=0,n=0,i=0;for(let c=$+a;c<=$+s;c++){const a=f(r,m(c))*t;o+=e[a],n+=e[a+1],i+=e[a+2]}for(let c=$;c<w;c++){const h=3*f(r,c);l[h]=o/p,l[h+1]=n/p,l[h+2]=i/p;const u=f(r,m(c+a))*t,d=f(r,m(c+s+1))*t;o+=e[d]-e[u],n+=e[d+1]-e[u+1],i+=e[d+2]-e[u+2]}}return l}function Ue(e,t,r,o,n,a,s,i,c=0,l=o){const h=new Float32Array(r*o*3),u="x"===n?r:o;for(let o=c;o<l;o++)for(let c=0;c<r;c++){const l="x"===n?c:o;let p=s,f=s,m=s;for(let s=0;s<a.length;s++){let h=l+a[s];h=h<0?0:h>=u?u-1:h;const d=("x"===n?o*r+h:h*r+c)*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*(o*r+c);h[d]=p,h[d+1]=f,h[d+2]=m}return h}const Be=(e,t,r)=>e+t*r,Ce=(e,t)=>t>e?t:e,Pe=(e,t)=>t<e?t:e;function Ge(e,t,r,o=0,n=r){const a=new Float32Array(t*r*3);for(let r=o*t;r<n*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 De=(e,t,r,o)=>[Math.max(0,e-r),Math.min(o,t+r)];function Le(e,t,r,o,n,a,s,i){const c=ze(a,i,e=>Math.abs(e)<=a);if(!c.length)return Ge(e,t,r,o,n);const l=c[0],h=c[c.length-1];if(1===s.length)return Ne(e,4,t,r,s[0],l,h,o,n);const[u,p]=De(o,n,h,r);return Ne(Ne(e,4,t,r,"x",l,h,u,p),3,t,r,"y",l,h,o,n)}function qe(e,t,r,o,n,a,s,i){if(!(a>0))return Ge(e,t,r,o,n);const c=3*a,l=ze(c,i,e=>Math.abs(e)<=c),h=l.map(e=>Math.exp(-e*e/(2*a*a))),u=h.reduce((e,t)=>e+t,0);if(1===s.length)return Ie(e,4,t,r,s[0],l,h,u,o,n);const[p,f]=De(o,n,l[l.length-1],r);return Ie(Ie(e,4,t,r,"x",l,h,u,p,f),3,t,r,"y",l,h,u,o,n)}function We(e,t,r,o,n,s,i,c){const l=ze(s,a.square,e=>Math.abs(e)<=s);if(!l.length)return new Float32Array(t*r*3).fill(i);const[h,u]=De(o,n,l[l.length-1],r);return Ue(Ue(e,4,t,r,"x",l,i,c,h,u),3,t,r,"y",l,i,c,o,n)}function Xe(e,t,r,o,n,a){const s=function(e,t,r){const o=new Float32Array(t*r);for(let n=0;n<t*r;n++)o[n]=.299*e[4*n]+.587*e[4*n+1]+.114*e[4*n+2];return o}(e,t,r),i=new Float32Array(t*r);for(let e=o;e<n;e++)for(let o=0;o<t;o++){const n=(n,a)=>s[Fe(e+a,r-1)*t+Fe(o+n,t-1)];i[e*t+o]=a(n)}return i}const He=e=>e(1,-1)+2*e(1,0)+e(1,1)-(e(-1,-1)+2*e(-1,0)+e(-1,1)),Ke=e=>e(-1,1)+2*e(0,1)+e(1,1)-(e(-1,-1)+2*e(0,-1)+e(1,-1)),Ye=e=>4*e(0,0)-e(-1,0)-e(1,0)-e(0,-1)-e(0,1),Je=e=>.5+e(-1,-1)-e(1,1),Ve=e=>Math.hypot(He(e),Ke(e));function Ze(e,t,r,o,n,a,s,i,c,l,h){for(let u=0;u<3;u++){let p=i,f=0;for(const i of a)for(const l of a){const a=s?s(i,l):1;p=c(p,e[4*(Fe(n+l,r-1)*t+Fe(o+i,t-1))+u],a),f+=a}l[u]=h?h(p,f):p}return l}function Qe(e,t,r,o,n,a,s,i,c){for(let l=0;l<3;l++){let h=0,u=0;for(const c of s){const s=i?i(c):1,p="x"===a?Fe(o+c,t-1):o;h+=e[4*(("y"===a?Fe(n+c,r-1):n)*t+p)+l]*s,u+=s}c[l]=h/u}return c}const et=(e,t,r,o,n)=>{const a=4*(o*t+r);return n[0]=e[a],n[1]=e[a+1],n[2]=e[a+2],n};const tt=e=>e<.04045?e/12.92:Math.pow((e+.055)/1.055,2.4),rt=e=>(e=Math.max(e,0))<.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055,ot=(e,t,r,o,n)=>{const a=o===e?(t-r)/n:o===t?2+(r-e)/n:4+(e-t)/n;return a/6-Math.floor(a/6)},nt=(e,t)=>{const r=Math.abs(6*(e+t-Math.floor(e+t))-3);return Math.min(Math.max(r-1,0),1)};const at=e=>e<.008856?7.787*e+16/116:Math.cbrt(e),st=e=>e<.206893?(e-16/116)/7.787:e*e*e;var it=Object.freeze({__proto__:null,BLANK:Ae,CLEAR:Oe,at:function(e,t,r){return Number(e[t][r])},at_blur:function(e,t,r,o,n,s,i){return Ze(e,t,r,o,n,ze(s,a.square,e=>Math.abs(e)<=s),null,0,Be,i,(e,t)=>e/t)},at_blurx:function(e,t,r,o,n,s,i){return Qe(e,t,r,o,n,"x",ze(s,a.line,e=>Math.abs(e)<=s),null,i)},at_blury:function(e,t,r,o,n,s,i){return Qe(e,t,r,o,n,"y",ze(s,a.line,e=>Math.abs(e)<=s),null,i)},at_dilate:function(e,t,r,o,n,s,i){return Ze(e,t,r,o,n,ze(s,a.square,e=>Math.abs(e)<=s),null,0,Ce,i)},at_erode:function(e,t,r,o,n,s,i){return Ze(e,t,r,o,n,ze(s,a.square,e=>Math.abs(e)<=s),null,1,Pe,i)},at_gaussian:function(e,t,r,o,n,s,i){if(!(s>0))return et(e,t,o,n,i);const c=3*s;return Ze(e,t,r,o,n,ze(c,a.square,e=>Math.abs(e)<=c),(e,t)=>Math.exp(-(e*e+t*t)/(2*s*s)),0,Be,i,(e,t)=>e/t)},at_gaussianx:function(e,t,r,o,n,s,i){if(!(s>0))return et(e,t,o,n,i);const c=3*s;return Qe(e,t,r,o,n,"x",ze(c,a.line,e=>Math.abs(e)<=c),e=>Math.exp(-e*e/(2*s*s)),i)},at_gaussiany:function(e,t,r,o,n,s,i){if(!(s>0))return et(e,t,o,n,i);const c=3*s;return Qe(e,t,r,o,n,"y",ze(c,a.line,e=>Math.abs(e)<=c),e=>Math.exp(-e*e/(2*s*s)),i)},at_sharpen:function(e,t,r,o,n,a,s){const i=(e,o)=>4*(Fe(o,r-1)*t+Fe(e,t-1)),c=i(o,n),l=i(o-1,n),h=i(o+1,n),u=i(o,n-1),p=i(o,n+1);for(let t=0;t<3;t++)s[t]=e[c+t]+a*(4*e[c+t]-e[l+t]-e[h+t]-e[u+t]-e[p+t]);return s},col_fromhsl:function(e,t,r,o){const n=(1-Math.abs(2*r-1))*t;return o[0]=r-.5*n+n*nt(e,0),o[1]=r-.5*n+n*nt(e,2/3),o[2]=r-.5*n+n*nt(e,1/3),o},col_fromhsv:function(e,t,r,o){return o[0]=r*(1+(nt(e,0)-1)*t),o[1]=r*(1+(nt(e,2/3)-1)*t),o[2]=r*(1+(nt(e,1/3)-1)*t),o},col_fromlab:function(e,t,r,o){const n=(100*e+16)/116,a=n-256*(r-.5)/200,s=.95047*st(n+256*(t-.5)/500),i=st(n),c=1.08883*st(a),l=Math.min(Math.max(3.2404542*s-1.5371385*i-.4985314*c,0),1),h=Math.min(Math.max(-.969266*s+1.8760108*i+.041556*c,0),1),u=Math.min(Math.max(.0556434*s-.2040259*i+1.0572252*c,0),1);return o[0]=rt(l),o[1]=rt(h),o[2]=rt(u),o},col_fromlinear:function(e,t,r,o){return o[0]=rt(e),o[1]=rt(t),o[2]=rt(r),o},col_fromoklab:function(e,t,r,o){let n=e+.3963377774*(t-=.5)+.2158037573*(r-=.5),a=e-.1055613458*t-.0638541728*r,s=e-.0894841775*t-1.291485548*r;n*=n*n,a*=a*a,s*=s*s;const i=Math.min(Math.max(4.0767416621*n-3.3077115913*a+.2309699292*s,0),1),c=Math.min(Math.max(-1.2684380046*n+2.6097574011*a-.3413193965*s,0),1),l=Math.min(Math.max(-.0041960863*n-.7034186147*a+1.707614701*s,0),1);return o[0]=rt(i),o[1]=rt(c),o[2]=rt(l),o},col_fromycbcr:function(e,t,r,o){return t-=.5,r-=.5,o[0]=e+1.402*r,o[1]=e-.344136*t-.714136*r,o[2]=e+1.772*t,o},col_tohsl:function(e,t,r,o){const n=Math.max(e,t,r),a=Math.min(e,t,r),s=n-a,i=.5*(n+a);return o[0]=s>0?ot(e,t,r,n,s):0,o[1]=s>0?s/(1-Math.abs(2*i-1)):0,o[2]=i,o},col_tohsv:function(e,t,r,o){const n=Math.max(e,t,r),a=n-Math.min(e,t,r);return o[0]=a>0?ot(e,t,r,n,a):0,o[1]=n>0?a/n:0,o[2]=n,o},col_tolab:function(e,t,r,o){const n=tt(e),a=tt(t),s=tt(r),i=at((.4124564*n+.3575761*a+.1804375*s)/.95047),c=at(.2126729*n+.7151522*a+.072175*s),l=at((.0193339*n+.119192*a+.9503041*s)/1.08883);return o[0]=(116*c-16)/100,o[1]=.5+500*(i-c)/256,o[2]=.5+200*(c-l)/256,o},col_tolinear:function(e,t,r,o){return o[0]=tt(e),o[1]=tt(t),o[2]=tt(r),o},col_tooklab:function(e,t,r,o){const n=tt(e),a=tt(t),s=tt(r),i=Math.cbrt(.4122214708*n+.5363325363*a+.0514459929*s),c=Math.cbrt(.2119034982*n+.6806995451*a+.1073969566*s),l=Math.cbrt(.0883024619*n+.2817188376*a+.6299787005*s);return o[0]=.2104542553*i+.793617785*c-.0040720468*l,o[1]=.5+1.9779984951*i-2.428592205*c+.4505937099*l,o[2]=.5+.0259040371*i+.7827717662*c-.808675766*l,o},col_toycbcr:function(e,t,r,o){const n=.299*e+.587*t+.114*r;return o[0]=n,o[1]=.5+.5643*(r-n),o[2]=.5+.7132*(e-n),o},convolve:function(e,t,r,o,n,a,s,i,c,l,h,u,p,f,m){const d=(e,a)=>4*(Fe(n+a,r-1)*t+Fe(o+e,t-1)),g=[[a,-1,-1],[s,0,-1],[i,1,-1],[c,-1,0],[l,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[o,n,a]of g)r+=o*e[d(n,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:Se,gcd:function(e,t){e=Math.abs(e),t=Math.abs(t);for(let r=0;r<64&&0!==t;r++){const r=Se(e,t);e=t,t=r}return e},perm:function(e,t){let r=1;for(let o=0;o<170&&!(o>=t);o++)r*=e-o;return r},picture:function(e,t,r,o,n,a,s,i,c,l,h,u,p){let f,m;0===l?f=m=Math.max(o/t,n/r):1===l?f=m=Math.min(o/t,n/r):2===l?(f=o/t,m=n/r):f=m=1,f*=a,m*=a;const d=h+.5-s*o,g=u+.5-i*n,$=Math.cos(c),w=Math.sin(c);let y=($*d+w*g)/f+.5*t,b=($*g-w*d)/m+.5*r;if(3===l)y=Se(y,t),b=Se(b,r);else if(y<0||b<0||y>t||b>r)return p[0]=p[1]=p[2]=p[3]=0,p;return Re(e,t,r,y-.5,b-.5,p)},placeCode:je,plane_blur:function(e,t,r,o,n,s){return Le(e,t,r,o,n,s,["x","y"],a.square)},plane_blurx:function(e,t,r,o,n,s){return Le(e,t,r,o,n,s,["x"],a.line)},plane_blury:function(e,t,r,o,n,s){return Le(e,t,r,o,n,s,["y"],a.line)},plane_dilate:function(e,t,r,o,n,a){return We(e,t,r,o,n,a,0,!0)},plane_emboss:function(e,t,r,o,n){return Xe(e,t,r,o,n,Je)},plane_erode:function(e,t,r,o,n,a){return We(e,t,r,o,n,a,1,!1)},plane_gaussian:function(e,t,r,o,n,s){return qe(e,t,r,o,n,s,["x","y"],a.square)},plane_gaussianx:function(e,t,r,o,n,s){return qe(e,t,r,o,n,s,["x"],a.line)},plane_gaussiany:function(e,t,r,o,n,s){return qe(e,t,r,o,n,s,["y"],a.line)},plane_laplacian:function(e,t,r,o,n){return Xe(e,t,r,o,n,Ye)},plane_sharpen:function(e,t,r,o,n,a){const s=new Float32Array(t*r*3);for(let i=o;i<n;i++)for(let o=0;o<t;o++){const n=(e,o)=>4*(Fe(o,r-1)*t+Fe(e,t-1)),c=n(o,i),l=n(o-1,i),h=n(o+1,i),u=n(o,i-1),p=n(o,i+1);for(let r=0;r<3;r++)s[3*(i*t+o)+r]=e[c+r]+a*(4*e[c+r]-e[l+r]-e[h+r]-e[u+r]-e[p+r])}return s},plane_sobel:function(e,t,r,o,n){return Xe(e,t,r,o,n,Ve)},plane_sobelx:function(e,t,r,o,n){return Xe(e,t,r,o,n,He)},plane_sobely:function(e,t,r,o,n){return Xe(e,t,r,o,n,Ke)},random:function(e,t,r,o){const n=43758.5453*Math.sin(12.9898*(e+.5)+78.233*(r-t-.5)+37.719*o);return n-Math.floor(n)},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:Re,sampleOrZero:function(e,t,r,o,n,a){const s=o+.5,i=n+.5;return s<0||i<0||s>t||i>r?(a[0]=a[1]=a[2]=a[3]=0,a):Re(e,t,r,o,n,a)},scratch:function(){return new Float64Array(4)},smoothstep:function(e,t,r){const o=Math.min(Math.max((r-e)/(t-e),0),1);return o*o*(3-2*o)}});const ct="\\:",lt=Object.keys(it).filter(e=>"function"==typeof it[e]),ht=e=>Object.assign(Object.create(null),e),ut=ht({r:"$r",g:"$g",b:"$b",a:"$a",x:"$x",y:"$y",px:"$px",py:"$py",w:"$w",h:"$h",t:"$t",gray:"$gray"}),pt=ht({pi:"Math.PI","π":"Math.PI",e:"Math.E",tau:"(2 * Math.PI)","τ":"(2 * Math.PI)","∞":"Infinity","-∞":"(-Infinity)"}),ft=ht({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}))`,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})`}),mt=ht({atan2:2,pow:2,mod:2,step:2,clamp:3,mix:3,smoothstep:3}),dt=ht({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}),gt=(e,t)=>({kind:e,c:t}),$t=e=>gt("f",[e]),wt=e=>gt("b",[e]),yt=e=>1===e.length?$t(e[0]):gt("v",e),bt=(e,t=0)=>"b"===e.kind?`(${e.c[0]} ? 1 : 0)`:"f"===e.kind?e.c[0]:e.c[t]??e.c[0],xt=e=>"v"===e.kind?e.c.length:1;class _t extends Error{}function kt(e){if(e.blendKept)return{blend:!0,source:""};const t=e.params??{},r=new Set([...Object.keys(e.placements??{}),"source","selection"]),o=new vt(t,r,e.space??"srgb");o.graphics=new Set(Object.keys(e.graphics??{})),o.bind=ht(e.bind??{});const n="string"==typeof e.color?{rgba:e.color}:e.color,a=(o,n)=>{const a=[...s,...Object.keys(e.placements??{})],h=[...i,...Object.keys(t)];return c(l(o,{names:a,values:h,blocks:null}),r,{whole:n})};for(const e of["rgba","rgb","r","g","b","a"]){if(!n[e])continue;let t;try{t=a(n[e],"rgba"===e)}catch(e){throw new _t(e.message)}o.channel(e,t)}const u=o.source();h(u,{variables:/^\$\w+$/,indexable:/^\$[A-Z]\w*$/,strings:!1});const p=new Function(...o.parameters(),u);return{source:u,uses:o.uses,pictures:[...o.pictureNames],run(e){p(...o.arguments(e))}}}class vt{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 gt(e.kind,e.c.map(e=>/^[\w$.]+$|^\(?-?[\d.e+]+\)?$/.test(e)?e:this.temp(e,t)))}fail(e){throw new _t(e)}leaf(e){if("number"===e.type)return $t(`(${e.value.replace(/\.+$/,"")})`);"string"===e.type&&this.fail("a filter has no text: numbers and colours only");const t=e.value,r=/^(-?(?:\d+\.?\d*|\.\d+))%$/.exec(t);if(r)return $t(`(${r[1]} / 100)`);if("t"===t&&this.uses.add("t"),ut[t])return $t(ut[t]);if("rgb"===t)return yt(["$r","$g","$b"]);if("unchanged"===t)return $t("$u");if("selected"===t)return $t(this.pictureHere("selection").c[0]);if(pt[t])return $t(pt[t]);if("true"===t||"false"===t)return wt(t);if(Object.prototype.hasOwnProperty.call(this.params,t)){const e=`$p_${t}`;return"color"===this.params[t].type?yt([`${e}_0`,`${e}_1`,`${e}_2`]):$t(e)}if(this.pictures.has(t)){const e=this.pictureHere(t);return yt(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 o=this.scratchArray();return"source"===e?(this.uses.add("source"),this.body.push(`$h_sample($S, $w, $h, ${t}, ${r}, ${o});`)):(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}, ${o});`)),this.space&&"selection"!==e&&this.body.push(`$h_col_to${this.space}(${o}[0], ${o}[1], ${o}[2], ${o});`),yt([0,1,2,3].map(e=>`${o}[${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,o=t.startsWith(ct)?t.slice(2):null;if(null!==o)return this.call(o,r,e);const n=()=>r.map(e=>this.value(e));switch(t){case"+":case"-":case"*":case"/":{const[e,r]=n();return this.componentwise([e,r],(e,r)=>`(${e} ${t} ${r})`)}case"neg":return this.componentwise(n(),e=>`(-${e})`);case"^":return this.power(r);case"mod":return this.componentwise(n(),ft.mod);case"<":case">":case"≤":case"≥":{const[e,r]=n(),o={"≤":"<=","≥":">="}[t]??t;return wt(`(${bt(e)} ${o} ${bt(r)})`)}case"=":case"===":case"≠":case"≠=":case"≡":{const[e,r]=n(),o=Math.max(xt(e),xt(r)),a=Array.from({length:o},(t,o)=>`${bt(e,o)} === ${bt(r,o)}`).join(" && ");return wt("≠"===t||"≠="===t?`!(${a})`:`(${a})`)}case"≈":{const[e,t]=n();return wt(`(Math.abs(${bt(e)} - ${bt(t)}) < 1e-5)`)}case"&":{const[e,t]=n();return wt(`(${this.truth(e)} && ${this.truth(t)})`)}case"|":{const[e,t]=n();return wt(`(${this.truth(e)} || ${this.truth(t)})`)}case"\\xor":{const[e,t]=n();return wt(`(${this.truth(e)} !== ${this.truth(t)})`)}case"\\nand":{const[e,t]=n();return wt(`!(${this.truth(e)} && ${this.truth(t)})`)}case"\\nor":{const[e,t]=n();return wt(`!(${this.truth(e)} || ${this.truth(t)})`)}case"\\not":{const[e]=n();return wt(`!${this.truth(e)}`)}case"?:":return this.ternary(r);case"max":case"min":return this.componentwise(n(),(...e)=>`Math.${t}(${e.join(", ")})`);case"sum":return this.componentwise(n(),(...e)=>`(${e.join(" + ")})`);case"prod":return this.componentwise(n(),(...e)=>`(${e.join(" * ")})`);case"mean":return this.componentwise(n(),(...e)=>`((${e.join(" + ")}) / ${e.length})`);case"()":case"[]":case"{}":case"(]":case"[)":{const e=n().flatMap(e=>"b"===e.kind?[bt(e)]:e.c.map((t,r)=>bt(e,r)));return e.length>4&&this.fail("a colour has at most 4 values (r, g, b, a)"),yt(e)}case"!":return this.componentwise(n(),e=>`$h_factorial(${e})`);case"perm":return this.componentwise(n(),(e,t)=>`$h_perm(${e}, ${t})`);case"comb":return this.componentwise(n(),(e,t)=>`($h_perm(${e}, ${t}) / $h_factorial(${t}))`);case"gcd":return this.componentwise(n(),(...e)=>e.reduce((e,t)=>`$h_gcd(${e}, ${t})`));case"round":{const[e,t]=n();return this.componentwise([e,t],(e,t)=>`$h_round(${e}, ${t})`)}case"log":{const[e,t]=n();return this.componentwise([e,t],(e,t)=>`(Math.log(${t}) / Math.log(${e}))`)}case"root":{const[e,t]=n();return this.componentwise([e,t],(e,t)=>`$h_root(${e}, ${t})`)}case"∈":case"∉":return this.membership(e);case"random":return this.random();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(ft[t])return this.builtin(t,n());this.fail(`"${t}" isn't available in a filter`)}truth(e){return"b"===e.kind?e.c[0]:`(${bt(e)} !== 0)`}componentwise(e,t){const r=e.map(xt),o=Math.max(...r),n=new Set(r.filter(e=>e>1));n.size>1&&this.fail(`can't combine vectors of ${[...n].join(" and ")} values`);const a=Array.from({length:o},(r,o)=>t(...e.map(e=>bt(e,o))));return this.keep(yt(a))}builtin(e,t){const r=ft[e];if(mt[e]&&t.length!==mt[e]&&this.fail(`${e}() takes ${mt[e]} values`),"function"==typeof r)return this.componentwise(t,r);const o=1===r?e:r;return this.componentwise(t,(...e)=>`Math.${o}(${e.join(", ")})`)}power([e,t]){const r="number"===t.type&&/^-?\d+$/.test(t.value)?Number(t.value):null,o=this.keep(this.value(e)),n=e=>this.componentwise([o],t=>Array(e).fill(t).join(" * "));return 0===r?this.componentwise([o],()=>"1"):null!==r&&r>=1&&r<=4?n(r):null!==r&&r<=-1&&r>=-4?this.componentwise([n(-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([o,this.value(t)],(e,t)=>`Math.pow(${e}, ${t})`)}ternary([e,t,r]){const o=this.truth(this.value(e)),n=e=>"symbol"===e.type&&"unchanged"===e.value;let a=n(t)?null:this.value(t),s=n(r)?null:this.value(r);const i=e=>"b"===e.kind?wt("($u > 0.5)"):"f"===e.kind?$t("$u"):yt(["$k0","$k1","$k2","$k3"].slice(0,4===e.c.length?4:3));if(!a&&!s)return $t("$u");if(a||(a=i(s)),s||(s=i(a)),"b"===a.kind&&"b"===s.kind)return wt(this.temp(`(${o} ? ${a.c[0]} : ${s.c[0]})`));const c=Math.max(xt(a),xt(s)),l=Array.from({length:c},(e,t)=>this.temp(`(${o} ? ${bt(a,t)} : ${bt(s,t)})`));return yt(l)}membership(e){const[t,r]=e.args,o=bt(this.value(t)),n="∉"===e.op;let a;if("op"===r.type&&["()","[]","(]","[)"].includes(r.op)&&2===r.args.length){const[e,t]=r.args.map(e=>bt(this.value(e)));a=`(${o} ${"["===r.op[0]?">=":">"} ${e} && ${o} ${"]"===r.op[1]?"<=":"<"} ${t})`}else"op"===r.type&&"{}"===r.op?a=`(${r.args.map(e=>`${o} === ${bt(this.value(e))}`).join(" || ")})`:"symbol"===r.type&&["ℝ","ℤ","ℕ"].includes(r.value)?a={"ℝ":`Number.isFinite(${o})`,"ℤ":`Number.isInteger(${o})`,"ℕ":`(Number.isInteger(${o}) && ${o} > 0)`}[r.value]:this.fail("∈ needs an interval [a, b], a set {…}, ℝ, ℤ or ℕ");return wt(n?`!${a}`:a)}random(){return this.uses.add("random"),$t(this.temp("$h_random($px, $py, $h, ++$seed)"))}call(e,t,r){const o=()=>t.map(e=>this.value(e));if(e.startsWith("mz_sample_")){const t=e.slice(10),[r,n]=o(),[a,s]=n?[bt(r),bt(n)]:[bt(r,0),bt(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),this.keep(yt([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,n]=o(),[a,s]=n?[bt(r),bt(n)]:[bt(r,0),bt(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),yt([0,1,2].map(t=>`${e}[${t}]`))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep(yt(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),$t(e.startsWith("mz_width_")?`$qw_${t}`:`$qh_${t}`)}switch(e){case"pixel":{const[e,t]=o().map(e=>bt(e)),r=this.scratchArray();return this.body.push(`$h_sample($I, $w, $h, ${e}, ${t}, ${r});`),this.keep(yt([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 colour, or a position px, py`);const o={red:0,green:1,blue:2,alpha:3}[e];return"luma"===e?$t(`(${bt(r,0)} * 0.299 + ${bt(r,1)} * 0.587 + ${bt(r,2)} * 0.114)`):"alpha"===e&&3===xt(r)?$t("1"):$t(bt(r,o))}case"length":{const[e]=o();return $t(`Math.sqrt(${e.c.map((t,r)=>`${bt(e,r)} * ${bt(e,r)}`).join(" + ")})`)}case"distance":{const[e,t]=o(),r=this.componentwise([e,t],(e,t)=>`(${e} - ${t})`);return $t(`Math.sqrt(${r.c.map(e=>`${e} * ${e}`).join(" + ")})`)}case"dot":{const[e,t]=o(),r=Math.max(xt(e),xt(t));return $t(`(${Array.from({length:r},(r,o)=>`${bt(e,o)} * ${bt(t,o)}`).join(" + ")})`)}case"normalize":{const[e]=o(),t=this.temp(`Math.sqrt(${e.c.map((t,r)=>`${bt(e,r)} * ${bt(e,r)}`).join(" + ")})`);return this.componentwise([e],e=>`(${e} / ${t})`)}case"cross":{const[e,t]=o();3===xt(e)&&3===xt(t)||this.fail("cross() takes two colours (3 values each)");const[r,n,a]=e.c,[s,i,c]=t.c;return this.keep(yt([`(${n} * ${c} - ${a} * ${i})`,`(${a} * ${s} - ${r} * ${c})`,`(${r} * ${i} - ${n} * ${s})`]))}case"convolve":{const e=o().map(e=>bt(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});`),yt([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),o().map(e=>bt(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=o(),r=3===t.length?t.map(e=>bt(e)):[0,1,2].map(e=>bt(t[0],e));1!==t.length&&3!==t.length&&this.fail(`${e}() takes a colour`);const n=this.scratchArray();return this.body.push(`$h_col_${e}(${r.join(", ")}, ${n});`),this.keep(yt([0,1,2].map(e=>`${n}[${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,o());case"asin":return this.builtin("arcsin",o());case"acos":return this.builtin("arccos",o());case"atan":return 2===t.length?this.builtin("atan2",o()):this.builtin("arctan",o());case"log":return this.builtin("ln",o());case"max":case"min":return this.componentwise(o(),(...t)=>`Math.${e}(${t.join(", ")})`)}if(dt[e])return this.neighbourhood(e,t);this.fail(`unknown function "${e}"`)}geometry(e,t){const r=(e,t)=>this.keep(yt([e,t]));switch(e){case"zoom":{const[e,o="0.5",n="0.5"]=t,a=r(`(${o} * $w - 0.5)`,`(${n} * $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,o]=t;return r(`($h_fmod($px - ${e} + 0.5, $w) - 0.5)`,`($h_fmod($py - ${o} + 0.5, $h) - 0.5)`)}case"rotate":{const[e,o="0.5",n="0.5"]=t,a=r(`(${o} * $w - 0.5)`,`(${n} * $h - 0.5)`),s=r(`($px - ${a.c[0]})`,`($py - ${a.c[1]})`),i=this.keep(yt([`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,o,n,a]=t;return r(`((${e} + (${n} - ${e}) * ($px + 0.5) / $w) * $w - 0.5)`,`((${o} + (${a} - ${o}) * ($py + 0.5) / $h) * $h - 0.5)`)}case"tile":{const[e,o=e]=t;return r(`($h_fmod(($px + 0.5) * ${e}, $w) - 0.5)`,`($h_fmod(($py + 0.5) * ${o}, $h) - 0.5)`)}case"flipx":return r("($w - 1 - $px)","$py");case"flipy":return r("$px","($h - 1 - $py)")}this.fail(`unknown geometry ${e}`)}neighbourhood(e,t){const r=dt[e];if(t.every(e=>this.isUniform(e))){const o=t.map(e=>bt(this.uniformValue(e))),n=`${e}(${o.join(",")})`;if(!this.planes.has(n)){const t=`$N${this.planes.size}`;this.pre.push(`let ${t} = $h_plane_${e}($I, $w, $h, $y0, $y1${o.map(e=>`, ${e}`).join("")});`),this.planes.set(n,t)}const a=this.planes.get(n);return 3===r?yt([0,1,2].map(e=>`${a}[$j3 + ${e}]`)):$t(`${a}[$j]`)}const o=t.map(e=>bt(this.value(e)));if(1===r)return $t(this.temp(`$h_at_${e}($I, $w, $h, $px, $py${o.map(e=>`, ${e}`).join("")})`));const n=this.scratchArray();return this.body.push(`$h_at_${e}($I, $w, $h, $px, $py${o.map(e=>`, ${e}`).join("")}, ${n});`),yt([0,1,2].map(e=>`${n}[${e}]`))}isUniform(e){return"number"===e.type||("symbol"===e.type?["w","h","t"].includes(e.value)||Boolean(pt[e.value])||Object.prototype.hasOwnProperty.call(this.params,e.value)&&"color"!==this.params[e.value].type:"op"===e.type&&!e.op.startsWith(ct)&&"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 o=this.value(t),n=xt(o),a=e=>bt(o,e);if("rgba"===e){2===n&&this.fail("a colour is one number (grey), three (r, g, b) or four (r, g, b, a) — not two");const e=1===n?[a(0),a(0),a(0),"1"]:3===n?[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===n&&this.fail("a colour is one number (grey), three (r, g, b) or four — not two");const e=1===n?[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===n?a(0):3===n&&"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}`]),...lt.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)?Oe:Ae),o=e.placements[t]??{};return[r.data,r.width,r.height,Number(o.zoom??1),Number(o.x??.5),Number(o.y??.5),Number(o.angle??0),je(o.place)]}),...lt.map(e=>it[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 Et(e,t={}){const r="float"===t.precision||"half"===t.precision?"float":"byte",o=e.passes.map(e=>kt(e)),n={};let a=null;const s=t.parallelFrom??25e4,i=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,l=null,h=new Map;const u={passes:e.passes,get precision(){return r},sources:o.map(e=>e.source),setImage(e,t){"string"!=typeof e&&(t=e,e=null);const r=At(t);return e&&"source"!==e?n[e]=r:a=r,u},draw({t:t=0,canvas:s=null}={}){if(!a)throw new Error("setImage() first");const{width:i,height:c}=a,l=i*c*4;let h=a.data;const u=[];e.passes.forEach((e,s)=>{for(let t=0;t<e.keepInput;t++)u.push(h);const p=new Float32Array(l);if(e.blendKept){const t=u.pop(),r=e.opacity;for(let e=0;e<l;e++)p[e]=t[e]+(h[e]-t[e])*r}else o[s].run({input:h,output:p,source:a.data,width:i,height:c,t:t,params:Object.keys(e.params??{}).map(t=>e.values[t]),opacity:e.opacity,pictures:n,placements:e.placements??{}});"byte"===r&&Mt(p),h=p});const p=new Uint8ClampedArray(l);for(let e=0;e<l;e++){const t=h[e];p[e]=t>0?t<1?Math.round(255*t):255:0}const f={data:p,width:i,height:c};return s&&(s.width=i,s.height=c,s.getContext("2d").putImageData(new ImageData(p,i,c),0,0)),f},async drawAsync({t:o=0,canvas:p=null}={}){if(!a)throw new Error("setImage() first");const{width:f,height:m}=a;if(i<2||f*m<s)return u.draw({t:o,canvas:p});l??=async function(e,t,r){const o=new URL(r??"./cpu-worker.js",import.meta.url);let n,a=()=>{};if("undefined"!=typeof Worker&&"undefined"!=typeof window){const e=o.origin===location.origin?o:URL.createObjectURL(new Blob([`import ${JSON.stringify(o.href)};`],{type:"text/javascript"}));e!==o&&(a=()=>URL.revokeObjectURL(e)),n=()=>{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"));n=()=>{const t=new e(o);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 s=Array.from({length:e},n);let i=1;const c=s.map(()=>new Map);s.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 l=(e,t)=>new Promise((r,o)=>{const n=i++;c[e].set(n,{resolve:r,reject:o}),s[e].send({...t,id:n})}),h={size:e,shared:Tt(),ask:l,broadcast:e=>Promise.all(s.map((t,r)=>l(r,e))),close:()=>{s.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 h.broadcast({type:"init",passes:t.map(({fragment:e,...t})=>t)})}catch(e){throw h.close(),e}finally{a()}return h}(i,e.passes,t.workerUrl).catch(()=>!1);const d=l,g=await d;if(d!==l)throw new Error("The runner was disposed of while drawing");if(c=g,!g)return u.draw({t:o,canvas:p});const $=f*m*4,w=()=>g.shared?new Float32Array(new SharedArrayBuffer(4*$)):new Float32Array($);for(const[e,t]of[["source",a],...Object.entries(n)])h.get(e)!==t&&(await g.broadcast({type:"picture",name:e,picture:g.shared?jt(t):t}),h.set(e,t));let y=g.shared?jt(a).data:a.data;const b=[];for(let t=0;t<e.passes.length;t++){const n=e.passes[t];for(let e=0;e<n.keepInput;e++)b.push(y);const a=w();if(n.blendKept){const e=b.pop();for(let t=0;t<$;t++)a[t]=e[t]+(y[t]-e[t])*n.opacity;"byte"===r&&Mt(a)}else{const e=Object.keys(n.params??{}).map(e=>n.values[e]),s=Ot(m,g.size),i=await Promise.all(s.map(([s,i],c)=>g.ask(c,{type:"run",pass:t,input:y,output:g.shared?a:null,width:f,height:m,t:o,params:e,opacity:n.opacity,placements:n.placements??{},y0:s,y1:i,quantize:"byte"===r})));g.shared||i.forEach((e,t)=>a.set(e.band,s[t][0]*f*4))}y=a}const x=new Uint8ClampedArray($);for(let e=0;e<$;e++){const t=y[e];x[e]=t>0?t<1?Math.round(255*t):255:0}const _={data:x,width:f,height:m};return p&&(p.width=f,p.height=m,p.getContext("2d").putImageData(new ImageData(x,f,m),0,0)),_},get workers(){return c?c.size:0},dispose(){a=null;for(const e of Object.keys(n))delete n[e];l&&l.then(e=>e&&e.close()),l=null,c=null,h=new Map}};return u}function Mt(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 At(e){if(e&&e.data&&e.width&&e.height){const t=e.data,r=t instanceof Float32Array||t instanceof Float64Array?1:1/255,o=new Float32Array(e.width*e.height*4);for(let e=0;e<o.length;e++)o[e]=t[e]*r;return{data:o,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 o=("undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,r):Object.assign(document.createElement("canvas"),{width:t,height:r})).getContext("2d",{willReadFrequently:!0});return o.drawImage(e,0,0,t,r),At(o.getImageData(0,0,t,r))}throw new Error("setImage: give ImageData or { data, width, height }")}function Ot(e,t){const r=[];for(let o=0;o<t;o++){const n=Math.floor(e*o/t),a=Math.floor(e*(o+1)/t);a>n&&r.push([n,a])}return r}const Tt=()=>"undefined"!=typeof SharedArrayBuffer&&("undefined"==typeof crossOriginIsolated||!0===crossOriginIsolated);function jt(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 St({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 Ft(e,t={}){const r=St({webgl:Boolean(t.gl),prefer:t.prefer});if("gpu"===r.engine)try{return{runner:ke(t.gl,e,{precision:t.precision}),...r}}catch(r){if("gpu"===t.prefer)throw r;return{runner:Et(e,t),engine:"cpu",reason:`the GPU refused the shader (${r.message.split("\n")[0]})`}}return{runner:Et(e,t),...r}}const Rt=[{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:"Colour & tone",color:"(1 - r, 1 - g, 1 - b)"},{name:"Grayscale",group:"Colour & tone",color:"gray"},{name:"Threshold",group:"Colour & tone",params:{cutoff:.5},color:"if gray > cutoff then 1 else 0"},{name:"Posterize",group:"Colour & tone",params:{levels:{default:4,min:2,max:16,step:1}},color:"min(floor(rgb * levels) / (levels - 1), 1)"},{name:"Brightness & contrast",group:"Colour & 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:"Colour & tone",params:{tint:[1,.85,.7]},color:"rgb * tint"},{name:"Sepia",group:"Colour & tone",color:"(0.393r + 0.769g + 0.189b, 0.349r + 0.686g + 0.168b, 0.272r + 0.534g + 0.131b)"},{name:"Colour circle",group:"Colour & tone",description:"Black and white, except a soft circle that keeps its colour",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 colour stays inside a circle and fades to grey 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:"Colour & 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 colour",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:"Colour & tone",description:"Replaces one colour 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 coloured by maths: 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 coloured 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 coloured 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 colour; 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:"Colour reveal brush",group:"Brushes",description:"The picture starts grey; the brush paints its colour 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 colour 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:"Colour & tone",description:"Turns every colour 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:"Colour & tone",description:"More or less colour (in HSV)",space:"hsv",params:{amount:{default:1.5,min:0,max:3}},color:"(r, clamp(g amount, 0, 1), b)"},{name:"Lightness",group:"Colour & tone",description:"Lighter or darker without changing the colours (in Lab)",space:"lab",params:{amount:{default:1.15,min:.5,max:2}},color:"(clamp(r amount, 0, 1), g, b)"},{name:"Vivid",group:"Colour & tone",description:"Colourfulness, 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:"Colour & 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))"}],zt=e=>Rt.find(t=>t.name===e);Rt.push({name:"Old film",group:"Chains",description:"Sepia, a vignette and faint scanlines — a chain of three",steps:[zt("Sepia"),{filter:zt("Vignette"),with:{strength:1.2}},{filter:zt("Scanlines"),opacity:.5}]},{name:"Comic",group:"Chains",description:"Bold flat colours with ink lines: a small blur first, so a photo's fine texture isn't inked — a chain of four",steps:[{filter:zt("Gaussian blur"),with:{sigma:1.6}},{filter:zt("Vivid"),with:{amount:1.5}},{filter:zt("Posterize"),with:{levels:4}},{filter:zt("Outline"),with:{gain:1.2}}]},{name:"Cartoon",group:"Chains",description:"Blur, then flatten the colours, then outline — a chain of three",steps:[{filter:zt("Gaussian blur"),with:{sigma:1.5}},{filter:zt("Posterize"),with:{levels:6}},{filter:zt("Outline"),with:{gain:2}}]},{name:"Dreamy",group:"Chains",description:"A soft glow mixed over the picture",steps:[{filter:zt("Bloom"),with:{amount:1.2}},{filter:zt("Gaussian blur"),with:{sigma:2},opacity:.4}]},{name:"Tilt shift",group:"Chains",description:"Blurred where the mask is light — a chain",steps:[{filter:zt("Gaussian blur"),with:{sigma:4}},zt("Through a mask")]},{name:"Title card",group:"Chains",description:"A frosted panel with a caption on it — a chain of two",steps:[zt("Frosted panel"),{filter:zt("Caption"),with:{title:{text:"A title on a panel",y:.86}}}]},{name:"Colour spotlight",group:"Chains",description:"Grey except where the mask is dark — a chain",steps:[zt("Grayscale"),zt("Through a mask")]});const It=Rt,Nt=["Colour & tone","Blur & edges","Shape & motion","Text & shapes","Brushes","Other pictures","Chains"];export{u as BRUSHES,m as CLIPS,J as FILTER_FORMAT,d as FPS,O as GRAPHIC_DEFAULTS,A as GRAPHIC_TYPES,Nt as GROUPS,It as LIBRARY,T as MAX_SHADOW_LAYERS,re as PLACEMENT,g as STROKES_DEFAULTS,p as TIMINGS,f as WIDTH_FROM,St as chooseEngine,kt as compileCpuPass,me as compileFilter,Et as createCpuRunner,ke as createFilterRunner,Ft as createRunner,L as cssFont,K as drawGraphic,q as familyFor,we as filterFromJSON,be as filterFromLink,ae as filterGraphics,le as filterImages,he as filterParams,$e as filterToJSON,ye as filterToLink,D as fontFileFromCss,G as googleFontFamily,P as googleFontUrl,S as layeredExpression,X as loadGraphicFonts,oe as normalizeFilter,C as normalizeGraphic,y as normalizeStrokes,k as rasterizeStrokes,xe as readFilter,Y as renderGraphics,j as shadowLayerNames,M as simplify,E as simplifyLoop,b as strokeTimeline,At as toPicture,v as traceContours,ue as validateFilter};