@mathzetta/qblur 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ /* qblur 0.1.0 (MathZetta not included: load mathzetta.min.js or mathzetta.glsl.min.js first) — 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 u(e,t){throw new Error(`Graphic "${e}": ${t}`)}function h(e,t,r,n,o){const a=Number(r);return(!Number.isFinite(a)||a<n||a>o)&&u(e,`"${t}" is a number from ${n} to ${o}`),a}function p(e,t){for(const r of Object.keys(t))r in c||u(e,`no such setting "${r}" for strokes`);const r={...c,...t},n=(t,n)=>(n.includes(r[t])||u(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:h(e,"size",r.size,.001,.5),flow:h(e,"flow",r.flow,.01,1),spacing:h(e,"spacing",r.spacing,.02,2),taper:h(e,"taper",r.taper,0,.5),speed:h(e,"speed",r.speed,.05,20),gap:h(e,"gap",r.gap,0,600),start:h(e,"start",r.start,0,1e4),fit:h(e,"fit",r.fit,0,1e4),age:h(e,"age",r.age,1,1e4),buildUp:Boolean(r.buildUp),shadows:[]};Array.isArray(r.strokes)||u(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)||u(e,`stroke ${r+1} is { "points": [[x, y, ms, pressure], …] }`),p+=n.length,p>6e4&&u(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))))&&u(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,u=i[0][2],h=i.map((t,r)=>{let n;n="recorded"===e.timing?(t[2]-u)/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&&h.length>1&&(h[0].wf=h[1].wf);const p=h[h.length-1].f;for(const e of h)e.f+=n;r.push({points:h,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:u,touched:h}=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),y=Number.isFinite(n)?n:g,w=Math.max(.5,e.size*r/2);let $=0;p.forEach(n=>{if(n.start>y)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)),y=Math.min(r-1,Math.ceil(a+p));for(let r=g;r<=y;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 y=r*t+p;g>c[y]&&(0===c[y]&&(h[o++]=y),c[y]=g),g>.02&&(u[y]=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,w*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>y)break;const[o,s]=g(r),[i,l]=g(n);let c=1;n.f>y&&(c=(y-r.f)/Math.max(1e-9,n.f-r.f));const u=Math.hypot(i-o,l-s);let h=1===t?0:d;for(;h<=u*c;){const t=u?h/u:0,c=w*(r.wf+(n.wf-r.wf)*t);a(o+(i-o)*t,s+(l-s)*t,c,r.f+(n.f-r.f)*t),h+=Math.max(.5,2*e.spacing*c)}if(d=h-u,c<1)break}for(let t=0;t<o;t++){const r=h[t],n=c[r];s[r]=e.buildUp?1-(1-s[r])*(1-n):Math.max(s[r],n),i[r]+=n,n>.02&&u[r]>l[r]&&(l[r]=u[r]),c[r]=0}});const b=new Uint8ClampedArray(4*a),x="inside"===e.clip,E="outside"===e.clip;for(let t=0;t<a;t++){let r=s[t];if(0===r)continue;let n=1;o&&(x||E)&&(n=x?o[t]:1-o[t]),r*=n;const a=4*t;b[a]=Math.round(255*Math.min(1,Math.max(0,(y-l[t])/e.age))),b[a+1]=Math.round(255*Math.min(1,i[t]*n/4)),b[a+2]=Math.round(255*Math.min(1,Math.max(0,l[t]/Math.max(1e-9,g)))),b[a+3]=Math.round(255*r)}return{data:b,width:t,height:r,total:g}}function y(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)}),[...w(e.slice(0,o+1),t),...w([...e.slice(o),e[0]],t).slice(1)]}function w(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],u=Math.hypot(l-s,c-i)||1e-9;let h=-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))/u;r>h&&(h=r,p=t)}h>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 T(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 O(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=T(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 T(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 S(e){try{const t=new URL(e);return"fonts.googleapis.com"!==t.hostname?null:(t.searchParams.get("family")??"").split(":")[0].replace(/\+/g," ")||null}catch{return null}}function F(e,{weight:t="400",style:r="normal"}={}){const n=[...e.matchAll(/@font-face\s*{([^}]*)}/g)].map(e=>e[1]),o=(e,t)=>(new RegExp(`${t}\\s*:\\s*([^;]+);`).exec(e)?.[1]??"").trim(),a=String("bold"===t?700:"normal"===t?400:t),s=n.filter(e=>o(e,"font-weight")===a&&o(e,"font-style")===r),i=(s.length?s:n).at(-1);return i&&(/url\(([^)]+)\)/.exec(i)?.[1]??"").replace(/^['"]|['"]$/g,"")||null}function C(e,t){const r=e.fontUrl?`"${j(e.fontUrl)}", ${e.font}`:e.font;return`${e.style} ${e.weight} ${Math.max(1,e.size*t)}px ${r}`}function j(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(C(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)||S(r)){if(r=F(await(await fetch(r)).text(),e),!r||!r.startsWith("https://"))return null}const n=new FontFace(j(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=C(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(e in t)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", … }');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(o in t||o in r)throw new Error(`"${o}" is both a graphic and a parameter or picture`);n[o]=O(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(!(e.param in t))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)))e in t||(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?Math.min(...o,a):Math.min(0,2*a),n.max=void 0!==t.max?Number(t.max):o?Math.max(...o,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)))e in t||(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)))e in t||(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(t in l){if(H(n))try{O(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(t in i){try{V(t,n)}catch(e){r.push(`${a}: ${e.message}`)}continue}const e=s[t];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])=>e in(o.graphics??{}))),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;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))i[e]=e in r?"color"===t.type?r[e].map(Number):Number(r[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])?O(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 u=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),h=Object.keys(l);return u.includes("uniform sampler2D mz_img_source;")&&h.push("source"),u.includes("uniform sampler2D mz_img_selection;")&&h.push("selection"),{name:e.name??"",author:e.author??"",path:o,color:e.color,space:e._space??"srgb",fragment:u,params:s,values:i,opacity:n,images:h,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 ue(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=r.passes.map(t=>function(e,t,r,n){const o=e.createProgram();for(const[a,s]of[[e.VERTEX_SHADER,t],[e.FRAGMENT_SHADER,r]]){const t=e.createShader(a);if(e.shaderSource(t,s),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS))throw new Error(`${n||"The filter"} does not compile: ${e.getShaderInfoLog(t).trim()}`);e.attachShader(o,t)}if(e.linkProgram(o),!e.getProgramParameter(o,e.LINK_STATUS))throw new Error(`${n||"The filter"} does not link: ${e.getProgramInfoLog(o).trim()}`);return o}(e,a,t.fragment,t.name)),i=s.map(()=>new Map),l=(t,r)=>(i[t].has(r)||i[t].set(r,e.getUniformLocation(s[t],r)),i[t].get(r)),c=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,c),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),he(e);const h=new Map,p=new Map,f=e.createTexture();e.bindTexture(e.TEXTURE_2D,f),he(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([255,255,255,255]));const m=e.createTexture();e.bindTexture(e.TEXTURE_2D,m),he(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([0,0,0,0]));const d=[];let g=0,y=0;const w={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 h.has(t)&&e.deleteTexture(h.get(t)),h.delete(t),p.delete(t),w;let n=u.texture;if(t&&"source"!==t&&(h.has(t)||(h.set(t,e.createTexture()),e.bindTexture(e.TEXTURE_2D,h.get(t)),he(e)),n=h.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&&p.set(t,[r.naturalWidth||r.videoWidth||r.width||1,r.naturalHeight||r.videoHeight||r.height||1]),w},draw({t:t=0}={}){if(e.drawingBufferWidth!==g||e.drawingBufferHeight!==y){g=e.drawingBufferWidth,y=e.drawingBufferHeight;for(const t of d)e.bindTexture(e.TEXTURE_2D,t.texture),e.texImage2D(e.TEXTURE_2D,0,o.internal,g,y,0,e.RGBA,o.type,null)}let n=u;const a=[];return r.passes.forEach((i,w)=>{for(let e=0;e<i.keepInput;e++)a.push(n);const $=w===r.passes.length-1?null:function(t){let r=d.find(e=>!t.includes(e));return r||(r={texture:e.createTexture(),framebuffer:e.createFramebuffer()},e.bindTexture(e.TEXTURE_2D,r.texture),he(e,o.filter),e.texImage2D(e.TEXTURE_2D,0,o.internal,g,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),he(e,o.filter),e.texImage2D(e.TEXTURE_2D,0,o.internal,g,y,0,e.RGBA,o.type,null)),d.push(r)),r}([n,...a]);e.bindFramebuffer(e.FRAMEBUFFER,$?$.framebuffer:null),e.viewport(0,0,g,y);const b=s[w];e.useProgram(b);const x=e.getAttribLocation(b,"position");e.bindBuffer(e.ARRAY_BUFFER,c),e.enableVertexAttribArray(x),e.vertexAttribPointer(x,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,n.texture),e.uniform1i(l(w,"image"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,i.blendKept?a[a.length-1].texture:null),i.blendKept&&e.uniform1i(l(w,"base"),1),i.images.forEach((t,r)=>{if(e.activeTexture(e.TEXTURE2+r),e.bindTexture(e.TEXTURE_2D,"source"===t?u.texture:h.get(i.bind?.[t]??t)??(i.graphics?.[t]?m:f)),e.uniform1i(l(w,`mz_img_${t}`),2+r),!i.placements[t])return;const n=p.get(i.bind?.[t]??t)??[1,1],o=i.placements[t];e.uniform2f(l(w,`mz_size_${t}`),n[0],n[1]),e.uniform4f(l(w,`mz_place_${t}`),Number(o.zoom),Number(o.x),Number(o.y),Number(o.angle))}),e.uniform2f(l(w,"resolution"),g,y),e.uniform1f(l(w,"t"),t),e.uniform1f(l(w,"mz_opacity"),i.opacity);for(const[t,r]of Object.entries(i.params)){const n=i.values[t];"color"===r.type?e.uniform3fv(l(w,t),n.map(Number)):e.uniform1f(l(w,t),Number(n))}e.drawArrays(e.TRIANGLES,0,3),i.blendKept&&a.pop(),n=$}),w},dispose(){for(const t of s)e.deleteProgram(t);e.deleteTexture(u.texture),e.deleteTexture(f),e.deleteTexture(m);for(const t of h.values())e.deleteTexture(t);for(const t of d)e.deleteTexture(t.texture),e.deleteFramebuffer(t.framebuffer);e.deleteBuffer(c)}};return w}function he(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}const fe={data:new Float32Array([1,1,1,1]),width:1,height:1},me={data:new Float32Array([0,0,0,0]),width:1,height:1},de={cover:0,fit:1,stretch:2,tile:3};function ge(e){return de[e??"cover"]??0}function ye(e,t){return e-t*Math.floor(e/t)}const we=(e,t)=>e<0?0:e>t?t:e;function $e(e,t,r,n,o,a){const s=Math.floor(n),i=Math.floor(o),l=n-s,c=o-i,u=we(s,t-1),h=we(s+1,t-1),p=we(i,r-1),f=we(i+1,r-1),m=4*(p*t+u),d=4*(p*t+h),g=4*(f*t+u),y=4*(f*t+h);for(let t=0;t<4;t++){const r=e[m+t]+(e[d+t]-e[m+t])*l,n=e[g+t]+(e[y+t]-e[g+t])*l;a[t]=r+(n-r)*c}return a}function be(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 xe(e,t,r,n,o,a,s,i,l=0,c=n){const u=new Float32Array(r*n*3),h=a.length,p=Int32Array.from(a),f=Float64Array.from(s??a.map(()=>1)),m="x"===o?r:n,d=new Int32Array(h);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<h;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<h;t++){const r=d[t],n=f[t];l+=e[r]*n,c+=e[r+1]*n,g+=e[r+2]*n}const y=3*(n*r+a);u[y]=l/i,u[y+1]=c/i,u[y+2]=g/i}return u}function Ee(e,t,r,n,o,a,s,i=0,l=n){const c=new Float32Array(r*n*3),u="x"===o?r:n,h="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>=u?u-1:e,[d,g]="x"===o?[i,l]:[0,h],[y,w]="x"===o?[0,u]:[i,l];for(let r=d;r<g;r++){let n=0,o=0,i=0;for(let l=y+a;l<=y+s;l++){const a=f(r,m(l))*t;n+=e[a],o+=e[a+1],i+=e[a+2]}for(let l=y;l<w;l++){const u=3*f(r,l);c[u]=n/p,c[u+1]=o/p,c[u+2]=i/p;const h=f(r,m(l+a))*t,d=f(r,m(l+s+1))*t;n+=e[d]-e[h],o+=e[d+1]-e[h+1],i+=e[d+2]-e[h+2]}}return c}function ve(e,t,r,n,o,a,s,i,l=0,c=n){const u=new Float32Array(r*n*3),h="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 u=c+a[s];u=u<0?0:u>=h?h-1:u;const d=("x"===o?n*r+u:u*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);u[d]=p,u[d+1]=f,u[d+2]=m}return u}const Me=(e,t,r)=>e+t*r,Ae=(e,t)=>t>e?t:e,_e=(e,t)=>t<e?t:e;function ke(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 Oe(e,t,r,n,o,a,s,i){const l=be(a,i,e=>Math.abs(e)<=a);if(!l.length)return ke(e,t,r,n,o);const c=l[0],u=l[l.length-1];if(1===s.length)return Ee(e,4,t,r,s[0],c,u,n,o);const[h,p]=Te(n,o,u,r);return Ee(Ee(e,4,t,r,"x",c,u,h,p),3,t,r,"y",c,u,n,o)}function Se(e,t,r,n,o,a,s,i){if(!(a>0))return ke(e,t,r,n,o);const l=3*a,c=be(l,i,e=>Math.abs(e)<=l),u=c.map(e=>Math.exp(-e*e/(2*a*a))),h=u.reduce((e,t)=>e+t,0);if(1===s.length)return xe(e,4,t,r,s[0],c,u,h,n,o);const[p,f]=Te(n,o,c[c.length-1],r);return xe(xe(e,4,t,r,"x",c,u,h,p,f),3,t,r,"y",c,u,h,n,o)}function Fe(e,r,n,o,a,s,i,l){const c=be(s,t.REACH.square,e=>Math.abs(e)<=s);if(!c.length)return new Float32Array(r*n*3).fill(i);const[u,h]=Te(o,a,c[c.length-1],n);return ve(ve(e,4,r,n,"x",c,i,l,u,h),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[we(e+a,r-1)*t+we(n+o,t-1)];i[e*t+n]=a(o)}return i}const je=e=>e(1,-1)+2*e(1,0)+e(1,1)-(e(-1,-1)+2*e(-1,0)+e(-1,1)),Re=e=>e(-1,1)+2*e(0,1)+e(1,1)-(e(-1,-1)+2*e(0,-1)+e(1,-1)),Ie=e=>4*e(0,0)-e(-1,0)-e(1,0)-e(0,-1)-e(0,1),Ue=e=>.5+e(-1,-1)-e(1,1),Ne=e=>Math.hypot(je(e),Re(e));function ze(e,t,r,n,o,a,s,i,l,c,u){for(let h=0;h<3;h++){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*(we(o+c,r-1)*t+we(n+i,t-1))+h],a),f+=a}c[h]=u?u(p,f):p}return c}function Be(e,t,r,n,o,a,s,i,l){for(let c=0;c<3;c++){let u=0,h=0;for(const l of s){const s=i?i(l):1,p="x"===a?we(n+l,t-1):n;u+=e[4*(("y"===a?we(o+l,r-1):o)*t+p)+c]*s,h+=s}l[c]=u/h}return l}const Pe=(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 De=e=>e<.04045?e/12.92:Math.pow((e+.055)/1.055,2.4),Le=e=>(e=Math.max(e,0))<.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055,Ge=(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)},He=(e,t)=>{const r=Math.abs(6*(e+t-Math.floor(e+t))-3);return Math.min(Math.max(r-1,0),1)};const We=e=>e<.008856?7.787*e+16/116:Math.cbrt(e),qe=e=>e<.206893?(e-16/116)/7.787:e*e*e;var Xe=Object.freeze({__proto__:null,BLANK:fe,CLEAR:me,at:function(e,t,r){return Number(e[t][r])},at_blur:function(e,r,n,o,a,s,i){return ze(e,r,n,o,a,be(s,t.REACH.square,e=>Math.abs(e)<=s),null,0,Me,i,(e,t)=>e/t)},at_blurx:function(e,r,n,o,a,s,i){return Be(e,r,n,o,a,"x",be(s,t.REACH.line,e=>Math.abs(e)<=s),null,i)},at_blury:function(e,r,n,o,a,s,i){return Be(e,r,n,o,a,"y",be(s,t.REACH.line,e=>Math.abs(e)<=s),null,i)},at_dilate:function(e,r,n,o,a,s,i){return ze(e,r,n,o,a,be(s,t.REACH.square,e=>Math.abs(e)<=s),null,0,Ae,i)},at_erode:function(e,r,n,o,a,s,i){return ze(e,r,n,o,a,be(s,t.REACH.square,e=>Math.abs(e)<=s),null,1,_e,i)},at_gaussian:function(e,r,n,o,a,s,i){if(!(s>0))return Pe(e,r,o,a,i);const l=3*s;return ze(e,r,n,o,a,be(l,t.REACH.square,e=>Math.abs(e)<=l),(e,t)=>Math.exp(-(e*e+t*t)/(2*s*s)),0,Me,i,(e,t)=>e/t)},at_gaussianx:function(e,r,n,o,a,s,i){if(!(s>0))return Pe(e,r,o,a,i);const l=3*s;return Be(e,r,n,o,a,"x",be(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 Pe(e,r,o,a,i);const l=3*s;return Be(e,r,n,o,a,"y",be(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*(we(n,r-1)*t+we(e,t-1)),l=i(n,o),c=i(n-1,o),u=i(n+1,o),h=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[u+t]-e[h+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*He(e,0),n[1]=r-.5*o+o*He(e,2/3),n[2]=r-.5*o+o*He(e,1/3),n},col_fromhsv:function(e,t,r,n){return n[0]=r*(1+(He(e,0)-1)*t),n[1]=r*(1+(He(e,2/3)-1)*t),n[2]=r*(1+(He(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*qe(o+256*(t-.5)/500),i=qe(o),l=1.08883*qe(a),c=Math.min(Math.max(3.2404542*s-1.5371385*i-.4985314*l,0),1),u=Math.min(Math.max(-.969266*s+1.8760108*i+.041556*l,0),1),h=Math.min(Math.max(.0556434*s-.2040259*i+1.0572252*l,0),1);return n[0]=Le(c),n[1]=Le(u),n[2]=Le(h),n},col_fromlinear:function(e,t,r,n){return n[0]=Le(e),n[1]=Le(t),n[2]=Le(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]=Le(i),n[1]=Le(l),n[2]=Le(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?Ge(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?Ge(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=De(e),a=De(t),s=De(r),i=We((.4124564*o+.3575761*a+.1804375*s)/.95047),l=We(.2126729*o+.7151522*a+.072175*s),c=We((.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]=De(e),n[1]=De(t),n[2]=De(r),n},col_tooklab:function(e,t,r,n){const o=De(e),a=De(t),s=De(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,u,h,p,f,m){const d=(e,a)=>4*(we(o+a,r-1)*t+we(n+e,t-1)),g=[[a,-1,-1],[s,0,-1],[i,1,-1],[l,-1,0],[c,0,0],[u,1,0],[h,-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,u,h,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=u+.5-s*n,g=h+.5-i*o,y=Math.cos(l),w=Math.sin(l);let $=(y*d+w*g)/f+.5*t,b=(y*g-w*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 $e(e,t,r,$-.5,b-.5,p)},placeCode:ge,plane_blur:function(e,r,n,o,a,s){return Oe(e,r,n,o,a,s,["x","y"],t.REACH.square)},plane_blurx:function(e,r,n,o,a,s){return Oe(e,r,n,o,a,s,["x"],t.REACH.line)},plane_blury:function(e,r,n,o,a,s){return Oe(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,Ue)},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,Ie)},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*(we(n,r-1)*t+we(e,t-1)),l=o(n,i),c=o(n-1,i),u=o(n+1,i),h=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[u+r]-e[h+r]-e[p+r])}return s},plane_sobel:function(e,t,r,n,o){return Ce(e,t,r,n,o,Ne)},plane_sobelx:function(e,t,r,n,o){return Ce(e,t,r,n,o,je)},plane_sobely:function(e,t,r,n,o){return Ce(e,t,r,n,o,Re)},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)},sample:$e,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):$e(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 Je="\\:",Ve=Object.keys(Xe).filter(e=>"function"==typeof Xe[e]),Ye={r:"$r",g:"$g",b:"$b",a:"$a",x:"$x",y:"$y",px:"$px",py:"$py",w:"$w",h:"$h",t:"$t",gray:"$gray"},Ze={pi:"Math.PI","π":"Math.PI",e:"Math.E",tau:"(2 * Math.PI)","τ":"(2 * Math.PI)","∞":"Infinity","-∞":"(-Infinity)"},Ke={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})`},Qe={atan2:2,pow:2,mod:2,step:2,clamp:3,mix:3,smoothstep:3},et={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},tt=(e,t)=>({kind:e,c:t}),rt=e=>tt("f",[e]),nt=e=>tt("b",[e]),ot=e=>1===e.length?rt(e[0]):tt("v",e),at=(e,t=0)=>"b"===e.kind?`(${e.c[0]} ? 1 : 0)`:"f"===e.kind?e.c[0]:e.c[t]??e.c[0],st=e=>"v"===e.kind?e.c.length:1;class it extends Error{}function lt(e){if(e.blendKept)return{blend:!0,source:""};const o=e.params??{},a=new Set([...Object.keys(e.placements??{}),"source","selection"]),s=new ct(o,a,e.space??"srgb");s.graphics=new Set(Object.keys(e.graphics??{})),s.bind=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 it(e.message)}s.channel(e,t)}const c=s.source();n.checkGeneratedJs(c,{variables:/^\$\w+$/,indexable:/^\$[A-Z]\w*$/,strings:!1});const u=new Function(...s.parameters(),c);return{source:c,uses:s.uses,pictures:[...s.pictureNames],run(e){u(...s.arguments(e))}}}class ct{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 tt(e.kind,e.c.map(e=>/^[\w$.]+$|^\(?-?[\d.e+]+\)?$/.test(e)?e:this.temp(e,t)))}fail(e){throw new it(e)}leaf(e){if("number"===e.type)return rt(`(${e.value.replace(/\.+$/,"")})`);"string"===e.type&&this.fail("a filter has no text: numbers and colours only");const t=e.value;if("t"===t&&this.uses.add("t"),Ye[t])return rt(Ye[t]);if("rgb"===t)return ot(["$r","$g","$b"]);if("unchanged"===t)return rt("$u");if("selected"===t)return rt(this.pictureHere("selection").c[0]);if(Ze[t])return rt(Ze[t]);if("true"===t||"false"===t)return nt(t);if(Object.prototype.hasOwnProperty.call(this.params,t)){const e=`$p_${t}`;return"color"===this.params[t].type?ot([`${e}_0`,`${e}_1`,`${e}_2`]):rt(e)}if(this.pictures.has(t)){const e=this.pictureHere(t);return ot(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});`),ot([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(Je)?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(),Ke.mod);case"<":case">":case"≤":case"≥":{const[e,r]=o(),n={"≤":"<=","≥":">="}[t]??t;return nt(`(${at(e)} ${n} ${at(r)})`)}case"=":case"===":case"≠":case"≠=":case"≡":{const[e,r]=o(),n=Math.max(st(e),st(r)),a=Array.from({length:n},(t,n)=>`${at(e,n)} === ${at(r,n)}`).join(" && ");return nt("≠"===t||"≠="===t?`!(${a})`:`(${a})`)}case"≈":{const[e,t]=o();return nt(`(Math.abs(${at(e)} - ${at(t)}) < 1e-5)`)}case"&":{const[e,t]=o();return nt(`(${this.truth(e)} && ${this.truth(t)})`)}case"|":{const[e,t]=o();return nt(`(${this.truth(e)} || ${this.truth(t)})`)}case"\\xor":{const[e,t]=o();return nt(`(${this.truth(e)} !== ${this.truth(t)})`)}case"\\nand":{const[e,t]=o();return nt(`!(${this.truth(e)} && ${this.truth(t)})`)}case"\\nor":{const[e,t]=o();return nt(`!(${this.truth(e)} || ${this.truth(t)})`)}case"\\not":{const[e]=o();return nt(`!${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?[at(e)]:e.c.map((t,r)=>at(e,r)));return e.length>4&&this.fail("a colour has at most 4 values (r, g, b, a)"),ot(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)=>`(Math.floor(${e} * Math.pow(10, ${t}) + 0.5) / Math.pow(10, ${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(Ke[t])return this.builtin(t,o());this.fail(`"${t}" isn't available in a filter`)}truth(e){return"b"===e.kind?e.c[0]:`(${at(e)} !== 0)`}componentwise(e,t){const r=e.map(st),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=>at(e,n))));return this.keep(ot(a))}builtin(e,t){const r=Ke[e];if(Qe[e]&&t.length!==Qe[e]&&this.fail(`${e}() takes ${Qe[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?nt("($u > 0.5)"):"f"===e.kind?rt("$u"):ot(["$k0","$k1","$k2","$k3"].slice(0,4===e.c.length?4:3));if(!a&&!s)return rt("$u");if(a||(a=i(s)),s||(s=i(a)),"b"===a.kind&&"b"===s.kind)return nt(this.temp(`(${n} ? ${a.c[0]} : ${s.c[0]})`));const l=Math.max(st(a),st(s)),c=Array.from({length:l},(e,t)=>this.temp(`(${n} ? ${at(a,t)} : ${at(s,t)})`));return ot(c)}membership(e){const[t,r]=e.args,n=at(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=>at(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} === ${at(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 nt(o?`!${a}`:a)}random(){return this.uses.add("random"),rt(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?[at(r),at(o)]:[at(r,0),at(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),this.keep(ot([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?[at(r),at(o)]:[at(r,0),at(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),ot([0,1,2].map(t=>`${e}[${t}]`))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep(ot(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),rt(e.startsWith("mz_width_")?`$qw_${t}`:`$qh_${t}`)}switch(e){case"pixel":{const[e,t]=n().map(e=>at(e)),r=this.scratchArray();return this.body.push(`$h_sample($I, $w, $h, ${e}, ${t}, ${r});`),this.keep(ot([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?rt(`(${at(r,0)} * 0.299 + ${at(r,1)} * 0.587 + ${at(r,2)} * 0.114)`):"alpha"===e&&3===st(r)?rt("1"):rt(at(r,n))}case"length":{const[e]=n();return rt(`Math.sqrt(${e.c.map((t,r)=>`${at(e,r)} * ${at(e,r)}`).join(" + ")})`)}case"distance":{const[e,t]=n(),r=this.componentwise([e,t],(e,t)=>`(${e} - ${t})`);return rt(`Math.sqrt(${r.c.map(e=>`${e} * ${e}`).join(" + ")})`)}case"dot":{const[e,t]=n(),r=Math.max(st(e),st(t));return rt(`(${Array.from({length:r},(r,n)=>`${at(e,n)} * ${at(t,n)}`).join(" + ")})`)}case"normalize":{const[e]=n(),t=this.temp(`Math.sqrt(${e.c.map((t,r)=>`${at(e,r)} * ${at(e,r)}`).join(" + ")})`);return this.componentwise([e],e=>`(${e} / ${t})`)}case"cross":{const[e,t]=n();3===st(e)&&3===st(t)||this.fail("cross() takes two colours (3 values each)");const[r,o,a]=e.c,[s,i,l]=t.c;return this.keep(ot([`(${o} * ${l} - ${a} * ${i})`,`(${a} * ${s} - ${r} * ${l})`,`(${r} * ${i} - ${o} * ${s})`]))}case"convolve":{const e=n().map(e=>at(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});`),ot([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=>at(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=>at(e)):[0,1,2].map(e=>at(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(ot([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(et[e])return this.neighbourhood(e,t);this.fail(`unknown function "${e}"`)}geometry(e,t){const r=(e,t)=>this.keep(ot([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(ot([`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=et[e];if(t.every(e=>this.isUniform(e))){const n=t.map(e=>at(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?ot([0,1,2].map(e=>`${a}[$j3 + ${e}]`)):rt(`${a}[$j]`)}const n=t.map(e=>at(this.value(e)));if(1===r)return rt(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});`),ot([0,1,2].map(e=>`${o}[${e}]`))}isUniform(e){return"number"===e.type||("symbol"===e.type?["w","h","t"].includes(e.value)||Boolean(Ze[e.value])||Object.prototype.hasOwnProperty.call(this.params,e.value)&&"color"!==this.params[e.value].type:"op"===e.type&&!e.op.startsWith(Je)&&"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=st(n),a=e=>at(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}`]),...Ve.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)?me:fe),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),ge(n.place)]}),...Ve.map(e=>Xe[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 ut(e,t={}){const r="float"===t.precision||"half"===t.precision?"float":"byte",n=e.passes.map(e=>lt(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,u=new Map;const h={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=pt(t);return e&&"source"!==e?a[e]=r:s=r,h},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 u=s.data;const h=[];e.passes.forEach((e,o)=>{for(let t=0;t<e.keepInput;t++)h.push(u);const p=new Float32Array(c);if(e.blendKept){const t=h.pop(),r=e.opacity;for(let e=0;e<c;e++)p[e]=t[e]+(u[e]-t[e])*r}else n[o].run({input:u,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&&ht(p),u=p});const p=new Uint8ClampedArray(c);for(let e=0;e<c;e++){const t=u[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:p=null}={}){if(!s)throw new Error("setImage() first");const{width:f,height:m}=s;if(l<2||f*m<i)return h.draw({t:n,canvas:p});if(null===c&&(c=await 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 u=(e,t)=>new Promise((r,n)=>{const o=l++;c[e].set(o,{resolve:r,reject:n}),i[e].send({...t,id:o})}),h={size:e,shared:mt(),ask:u,broadcast:e=>Promise.all(i.map((t,r)=>u(r,e))),close:()=>i.forEach(e=>e.close())};try{await h.broadcast({type:"init",passes:t.map(({fragment:e,...t})=>t)})}catch(e){throw h.close(),e}finally{s()}return h}(l,e.passes,t.workerUrl).catch(()=>!1)),!c)return h.draw({t:n,canvas:p});const d=f*m*4,g=()=>c.shared?new Float32Array(new SharedArrayBuffer(4*d)):new Float32Array(d);for(const[e,t]of[["source",s],...Object.entries(a)])u.get(e)!==t&&(await c.broadcast({type:"picture",name:e,picture:c.shared?dt(t):t}),u.set(e,t));let y=c.shared?dt(s).data:s.data;const w=[];for(let t=0;t<e.passes.length;t++){const o=e.passes[t];for(let e=0;e<o.keepInput;e++)w.push(y);const a=g();if(o.blendKept){const e=w.pop();for(let t=0;t<d;t++)a[t]=e[t]+(y[t]-e[t])*o.opacity;"byte"===r&&ht(a)}else{const e=Object.keys(o.params??{}).map(e=>o.values[e]),s=ft(m,c.size),i=await Promise.all(s.map(([s,i],l)=>c.ask(l,{type:"run",pass:t,input:y,output:c.shared?a:null,width:f,height:m,t:n,params:e,opacity:o.opacity,placements:o.placements??{},y0:s,y1:i,quantize:"byte"===r})));c.shared||i.forEach((e,t)=>a.set(e.band,s[t][0]*f*4))}y=a}const $=new Uint8ClampedArray(d);for(let e=0;e<d;e++){const t=y[e];$[e]=t>0?t<1?Math.round(255*t):255:0}const b={data:$,width:f,height:m};return p&&(p.width=f,p.height=m,p.getContext("2d").putImageData(new ImageData($,f,m),0,0)),b},get workers(){return c?c.size:0},dispose(){s=null;for(const e of Object.keys(a))delete a[e];c&&c.close(),c=null,u=new Map}};return h}function ht(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 pt(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),pt(n.getImageData(0,0,t,r))}throw new Error("setImage: give ImageData or { data, width, height }")}function ft(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 mt=()=>"undefined"!=typeof SharedArrayBuffer&&("undefined"==typeof crossOriginIsolated||!0===crossOriginIsolated);function dt(e){if(e.data.buffer instanceof(globalThis.SharedArrayBuffer??Object))return e;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 gt({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 yt(e,t={}){const r=gt({webgl:Boolean(t.gl),prefer:t.prefer});if("gpu"===r.engine)try{return{runner:ue(t.gl,e,{precision:t.precision}),...r}}catch(r){if("gpu"===t.prefer)throw r;return{runner:ut(e,t),engine:"cpu",reason:`the GPU refused the shader (${r.message.split("\n")[0]})`}}return{runner:ut(e,t),...r}}const wt=[{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))"}],$t=e=>wt.find(t=>t.name===e);wt.push({name:"Old film",group:"Chains",description:"Sepia, a vignette and faint scanlines — a chain of three",steps:[$t("Sepia"),{filter:$t("Vignette"),with:{strength:1.2}},{filter:$t("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:$t("Gaussian blur"),with:{sigma:1.6}},{filter:$t("Vivid"),with:{amount:1.5}},{filter:$t("Posterize"),with:{levels:4}},{filter:$t("Outline"),with:{gain:1.2}}]},{name:"Cartoon",group:"Chains",description:"Blur, then flatten the colours, then outline — a chain of three",steps:[{filter:$t("Gaussian blur"),with:{sigma:1.5}},{filter:$t("Posterize"),with:{levels:6}},{filter:$t("Outline"),with:{gain:2}}]},{name:"Dreamy",group:"Chains",description:"A soft glow mixed over the picture",steps:[{filter:$t("Bloom"),with:{amount:1.2}},{filter:$t("Gaussian blur"),with:{sigma:2},opacity:.4}]},{name:"Tilt shift",group:"Chains",description:"Blurred where the mask is light — a chain",steps:[{filter:$t("Gaussian blur"),with:{sigma:4}},$t("Through a mask")]},{name:"Title card",group:"Chains",description:"A frosted panel with a caption on it — a chain of two",steps:[$t("Frosted panel"),{filter:$t("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:[$t("Grayscale"),$t("Through a mask")]});const bt=wt,xt=()=>"undefined"!=typeof document||"undefined"!=typeof OffscreenCanvas,Et=(e,t)=>"undefined"!=typeof document?Object.assign(document.createElement("canvas"),{width:e,height:t}):new OffscreenCanvas(e,t);function vt(e){if(e&&"object"==typeof e&&Array.isArray(e.passes))return e;if("string"==typeof e){const t=bt.find(t=>t.name.toLowerCase()===e.trim().toLowerCase());return re(t??le(e))}return re(e)}const Mt=4096,At=2048;function _t(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(xt()){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=Et(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=Et(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)),u=[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++)u[n]+=l[4*(e*t+r)+n];const h=(o-n)*(i-s);for(let t=0;t<4;t++)c[4*(e*a+r)+t]=u[t]/h}}return{image:{data:c,width:a,height:s},width:a,height:s}}const kt=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],Tt=e=>Boolean(e)&&"object"==typeof e&&Array.isArray(e.passes),Ot=e=>(Array.isArray(e)||ArrayBuffer.isView(e))&&3===e.length&&[...e].every(e=>Number.isFinite(Number(e)));let St=null;const Ft=new WeakMap;let Ct=0;function jt(e){if("string"==typeof e)return`s:${e}`;if(Tt(e))return Ft.has(e)||Ft.set(e,"c:"+Ct++),Ft.get(e);if(e&&"object"==typeof e)try{return`d:${ae(e)}`}catch{return null}return null}const Rt=e=>({...e,passes:e.passes.map(e=>({...e,values:{...e.values}}))});let It=Promise.resolve();const Ut=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;Ut[e]=t}function Nt(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=Ut[255&(t^e[r])]^t>>>8;return(-1^t)>>>0}(r.subarray(4,8+t.length))),r}function zt(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 Bt(e,t,r){const n=e+t-r,o=Math.abs(n-e),a=Math.abs(n-t),s=Math.abs(n-r);return o<=a&&o<=s?e:a<=s?t:r}async function Pt({width:e,height:t,data:r,palette:n="auto",colours:o=256,dither:a=!0,quantize:s=null}){if("undefined"==typeof CompressionStream)return null;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),u=new DataView(c.buffer);let h,p,f;if(u.setUint32(0,e),u.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);h=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?h[t+n]=o:h[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(Nt("IHDR",c),Nt("PLTE",o)),s&&l.push(Nt("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;h=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);h[t]=4;for(let e=0;e<a;e++)h[t+1+e]=s[e]-Bt(e>=o?s[e-o]:0,i[e],e>=o?i[e-o]:0);i.set(s)}l.push(Nt("IHDR",c))}return l.push(Nt("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())}(h)),Nt("IEND",new Uint8Array(0))),{blob:new Blob(l,{type:"image/png"}),kind:p,colours:i?i.palette.length:zt(r),bits:f}}const Dt=e=>e&&e.data&&Number.isFinite(e.width)&&Number.isFinite(e.height)&&"function"!=typeof e.getContext;function Lt(e){if(Dt(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 Gt(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=bt,e.MAX_SHADOW_LAYERS=8,e.MAX_SIZE=Mt,e.MAX_SIZE_CPU=At,e.PLACEMENT=W,e.STROKES_DEFAULTS=c,e.TIMINGS=s,e.WIDTH_FROM=i,e.applyFilter=function(e,t,r={}){const n=It.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]=kt(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 u=s?s.getContext("2d"):null;if(s&&!u)throw new Error("applyFilter: `canvas` must be a 2D canvas (this one already has another kind of context)");const h="cpu"!==a?function(){if(St&&!St.gl.isContextLost())return St;if(!xt())return null;const e=Et(1,1),t=e.getContext("webgl",{preserveDrawingBuffer:!0,premultipliedAlpha:!1});return St=t?{canvas:e,gl:t,runners:new Map}:null,St}():null;if("gpu"===a&&!h)throw new Error('applyFilter: no WebGL here (use engine "auto" or "cpu")');const p=function(e,t,r){const n=jt(e)&&`${t}|${jt(e)}`,o=St?.runners;if(r&&n&&o?.has(n)){const e=o.get(n);return o.delete(n),o.set(n,e),e}const a=vt(e),s=Rt(a),i=yt(s,{gl:r,prefer:t}),l={compiled:s,source:Tt(e)?a:Rt(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":h?"auto":"cpu",h?.gl),{compiled:f,source:m,runner:d}=p,g="gpu"===p.engine,y=g?Math.min(Number(i??Mt),h.gl.getParameter(h.gl.MAX_TEXTURE_SIZE)||Mt):Number(i??At),{image:w,width:$,height:b}=_t(e,l,c,y);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?!Ot(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(!xt()&&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(w);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]=kt(t);d.setImage(e,r&&n?_t(t,r,n,y).image:t)}for(const[e,t]of Object.entries(a))d.setImage(e,t);if(g){h.canvas.width=$,h.canvas.height=b,d.draw({t:n});const e=s??Et($,b);e.width=$,e.height=b;const t=u??e.getContext("2d");return t.clearRect(0,0,$,b),t.drawImage(h.canvas,0,0),e}const i=await d.drawAsync({t:n});if(!xt()&&!s)return i;const l=s??Et($,b);return l.width=$,l.height=b,(u??l.getContext("2d")).putImageData(new ImageData(i.data,$,b),0,0),l}finally{g||d.dispose()}}(e,t,r));return It=n.catch(()=>{}),n},e.chooseEngine=gt,e.compileCpuPass=lt,e.compileFilter=re,e.createCpuRunner=ut,e.createFilterRunner=ue,e.createRunner=yt,e.cssFont=C,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:u}=Lt(t);if((e.byteOffset||e.byteLength!==e.buffer.byteLength)&&(e=e.slice()),i&&(i[0]!==c||i[1]!==u))throw new Error(`Frame ${l+1} is ${c} × ${u}; the first was ${i[0]} × ${i[1]}`);i=[c,u];const h=Gt(e),p=h?"rgba4444":"rgb565",f=a.quantize(e,Math.max(2,Math.min(256,o)),{format:p,oneBitAlpha:h}),m=a.applyPalette(e,f,p),d={palette:f,delay:Math.round(r),repeat:n};if(h){const e=f.findIndex(e=>e.length>3&&0===e[3]);e>=0&&Object.assign(d,{transparent:!0,transparentIndex:e})}s.writeFrame(m,c,u,d),l++}if(!l)throw new Error("encodeGif: no frames");return s.finish(),new Blob([s.bytes()],{type:"image/gif"})},e.encodePng=Pt,e.familyFor=j,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=F,e.googleFontFamily=S,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=O,e.normalizeStrokes=p,e.pictureData=Lt,e.rasterizeStrokes=g,e.readFilter=le,e.renderGraphics=z,e.shadowLayerNames=x,e.simplify=w,e.simplifyLoop=y,e.strokeTimeline=f,e.toBlob=async function(e,{type:t="image/png",quality:r,palette:n="auto"}={}){if("image/png"===t){const t=await Pt({...Lt(e),palette:n});if(t)return t.blob}const o=Dt(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}(Lt(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=vt,e.toPicture=pt,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 u=c++,h=[e*t+r];s[e*t+r]=u;let p=0;for(;h.length;){const e=h.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]=u,h.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]===u){g=(r+4)%8,m=o,d=i,n=!0;break}}if(!n||m===r&&d===e)break;f.push([m,d])}i.push(y(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.0 (MathZetta not included: map mathzetta, mathzetta/glsl and mathzetta/formulas with an import map) — 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 y(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 w(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:y(e,"size",r.size,.001,.5),flow:y(e,"flow",r.flow,.01,1),spacing:y(e,"spacing",r.spacing,.02,2),taper:y(e,"taper",r.taper,0,.5),speed:y(e,"speed",r.speed,.05,20),gap:y(e,"gap",r.gap,0,600),start:y(e,"start",r.start,0,1e4),fit:y(e,"fit",r.fit,0,1e4),age:y(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;p.forEach(o=>{if(o.start>m)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));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 $=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:$;for(;u<=h*l;){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($=u-h,l<1)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 $=new Uint8ClampedArray(4*a),y="inside"===e.clip,w="outside"===e.clip;for(let t=0;t<a;t++){let r=s[t];if(0===r)continue;let o=1;n&&(y||w)&&(o=y?n[t]:1-n[t]),r*=o;const a=4*t;$[a]=Math.round(255*Math.min(1,Math.max(0,(m-c[t])/e.age))),$[a+1]=Math.round(255*Math.min(1,i[t]*o/4)),$[a+2]=Math.round(255*Math.min(1,Math.max(0,c[t]/Math.max(1e-9,f)))),$[a+3]=Math.round(255*r)}return{data:$,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"],T={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:[]}},O=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 w(e,t);const o=T[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)).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(e in t)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", … }');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(n in t||n in r)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(!(e.param in t))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)))e in t||(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?Math.min(...n,a):Math.min(0,2*a),o.max=void 0!==t.max?Number(t.max):n?Math.max(...n,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)))e in t||(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)))e in t||(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(t in c){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(t in i){try{se(t,o)}catch(e){r.push(`${a}: ${e.message}`)}continue}const e=s[t];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])=>e in(n.graphics??{}))),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;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))i[e]=e in t?"color"===r.type?t[e].map(Number):Number(t[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 ye(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Not valid JSON")}return oe(t)}function we(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 ye(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=t.passes.map(t=>function(e,t,r,o){const n=e.createProgram();for(const[a,s]of[[e.VERTEX_SHADER,t],[e.FRAGMENT_SHADER,r]]){const t=e.createShader(a);if(e.shaderSource(t,s),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS))throw new Error(`${o||"The filter"} does not compile: ${e.getShaderInfoLog(t).trim()}`);e.attachShader(n,t)}if(e.linkProgram(n),!e.getProgramParameter(n,e.LINK_STATUS))throw new Error(`${o||"The filter"} does not link: ${e.getProgramInfoLog(n).trim()}`);return n}(e,a,t.fragment,t.name)),i=s.map(()=>new Map),c=(t,r)=>(i[t].has(r)||i[t].set(r,e.getUniformLocation(s[t],r)),i[t].get(r)),l=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,l),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),e.STATIC_DRAW);const h={texture:e.createTexture(),framebuffer:null};e.bindTexture(e.TEXTURE_2D,h.texture),ve(e);const u=new Map,p=new Map,f=e.createTexture();e.bindTexture(e.TEXTURE_2D,f),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 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([0,0,0,0]));const d=[];let g=0,$=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 u.has(t)&&e.deleteTexture(u.get(t)),u.delete(t),p.delete(t),y;let o=h.texture;if(t&&"source"!==t&&(u.has(t)||(u.set(t,e.createTexture()),e.bindTexture(e.TEXTURE_2D,u.get(t)),ve(e)),o=u.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&&p.set(t,[r.naturalWidth||r.videoWidth||r.width||1,r.naturalHeight||r.videoHeight||r.height||1]),y},draw({t:r=0}={}){if(e.drawingBufferWidth!==g||e.drawingBufferHeight!==$){g=e.drawingBufferWidth,$=e.drawingBufferHeight;for(const t of d)e.bindTexture(e.TEXTURE_2D,t.texture),e.texImage2D(e.TEXTURE_2D,0,o.internal,g,$,0,e.RGBA,o.type,null)}let n=h;const a=[];return t.passes.forEach((i,y)=>{for(let e=0;e<i.keepInput;e++)a.push(n);const w=y===t.passes.length-1?null:function(t){let r=d.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,g,$,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,g,$,0,e.RGBA,o.type,null)),d.push(r)),r}([n,...a]);e.bindFramebuffer(e.FRAMEBUFFER,w?w.framebuffer:null),e.viewport(0,0,g,$);const b=s[y];e.useProgram(b);const x=e.getAttribLocation(b,"position");e.bindBuffer(e.ARRAY_BUFFER,l),e.enableVertexAttribArray(x),e.vertexAttribPointer(x,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,n.texture),e.uniform1i(c(y,"image"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,i.blendKept?a[a.length-1].texture:null),i.blendKept&&e.uniform1i(c(y,"base"),1),i.images.forEach((t,r)=>{if(e.activeTexture(e.TEXTURE2+r),e.bindTexture(e.TEXTURE_2D,"source"===t?h.texture:u.get(i.bind?.[t]??t)??(i.graphics?.[t]?m:f)),e.uniform1i(c(y,`mz_img_${t}`),2+r),!i.placements[t])return;const o=p.get(i.bind?.[t]??t)??[1,1],n=i.placements[t];e.uniform2f(c(y,`mz_size_${t}`),o[0],o[1]),e.uniform4f(c(y,`mz_place_${t}`),Number(n.zoom),Number(n.x),Number(n.y),Number(n.angle))}),e.uniform2f(c(y,"resolution"),g,$),e.uniform1f(c(y,"t"),r),e.uniform1f(c(y,"mz_opacity"),i.opacity);for(const[t,r]of Object.entries(i.params)){const o=i.values[t];"color"===r.type?e.uniform3fv(c(y,t),o.map(Number)):e.uniform1f(c(y,t),Number(o))}e.drawArrays(e.TRIANGLES,0,3),i.blendKept&&a.pop(),n=w}),y},dispose(){for(const t of s)e.deleteProgram(t);e.deleteTexture(h.texture),e.deleteTexture(f),e.deleteTexture(m);for(const t of u.values())e.deleteTexture(t);for(const t of d)e.deleteTexture(t.texture),e.deleteFramebuffer(t.framebuffer);e.deleteBuffer(l)}};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}const Me={data:new Float32Array([1,1,1,1]),width:1,height:1},Ae={data:new Float32Array([0,0,0,0]),width:1,height:1},Te={cover:0,fit:1,stretch:2,tile:3};function Oe(e){return Te[e??"cover"]??0}function je(e,t){return e-t*Math.floor(e/t)}const Se=(e,t)=>e<0?0:e>t?t:e;function Fe(e,t,r,o,n,a){const s=Math.floor(o),i=Math.floor(n),c=o-s,l=n-i,h=Se(s,t-1),u=Se(s+1,t-1),p=Se(i,r-1),f=Se(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 Re(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 ze(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 Ie(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],[$,y]="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<y;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 Ne(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 Ue=(e,t,r)=>e+t*r,Be=(e,t)=>t>e?t:e,Ce=(e,t)=>t<e?t:e;function Pe(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 Ge=(e,t,r,o)=>[Math.max(0,e-r),Math.min(o,t+r)];function De(e,t,r,o,n,a,s,i){const c=Re(a,i,e=>Math.abs(e)<=a);if(!c.length)return Pe(e,t,r,o,n);const l=c[0],h=c[c.length-1];if(1===s.length)return Ie(e,4,t,r,s[0],l,h,o,n);const[u,p]=Ge(o,n,h,r);return Ie(Ie(e,4,t,r,"x",l,h,u,p),3,t,r,"y",l,h,o,n)}function Le(e,t,r,o,n,a,s,i){if(!(a>0))return Pe(e,t,r,o,n);const c=3*a,l=Re(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 ze(e,4,t,r,s[0],l,h,u,o,n);const[p,f]=Ge(o,n,l[l.length-1],r);return ze(ze(e,4,t,r,"x",l,h,u,p,f),3,t,r,"y",l,h,u,o,n)}function qe(e,t,r,o,n,s,i,c){const l=Re(s,a.square,e=>Math.abs(e)<=s);if(!l.length)return new Float32Array(t*r*3).fill(i);const[h,u]=Ge(o,n,l[l.length-1],r);return Ne(Ne(e,4,t,r,"x",l,i,c,h,u),3,t,r,"y",l,i,c,o,n)}function We(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[Se(e+a,r-1)*t+Se(o+n,t-1)];i[e*t+o]=a(n)}return i}const Xe=e=>e(1,-1)+2*e(1,0)+e(1,1)-(e(-1,-1)+2*e(-1,0)+e(-1,1)),He=e=>e(-1,1)+2*e(0,1)+e(1,1)-(e(-1,-1)+2*e(0,-1)+e(1,-1)),Ke=e=>4*e(0,0)-e(-1,0)-e(1,0)-e(0,-1)-e(0,1),Ye=e=>.5+e(-1,-1)-e(1,1),Je=e=>Math.hypot(Xe(e),He(e));function Ve(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*(Se(n+l,r-1)*t+Se(o+i,t-1))+u],a),f+=a}l[u]=h?h(p,f):p}return l}function Ze(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?Se(o+c,t-1):o;h+=e[4*(("y"===a?Se(n+c,r-1):n)*t+p)+l]*s,u+=s}c[l]=h/u}return c}const Qe=(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 et=e=>e<.04045?e/12.92:Math.pow((e+.055)/1.055,2.4),tt=e=>(e=Math.max(e,0))<.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055,rt=(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)},ot=(e,t)=>{const r=Math.abs(6*(e+t-Math.floor(e+t))-3);return Math.min(Math.max(r-1,0),1)};const nt=e=>e<.008856?7.787*e+16/116:Math.cbrt(e),at=e=>e<.206893?(e-16/116)/7.787:e*e*e;var st=Object.freeze({__proto__:null,BLANK:Me,CLEAR:Ae,at:function(e,t,r){return Number(e[t][r])},at_blur:function(e,t,r,o,n,s,i){return Ve(e,t,r,o,n,Re(s,a.square,e=>Math.abs(e)<=s),null,0,Ue,i,(e,t)=>e/t)},at_blurx:function(e,t,r,o,n,s,i){return Ze(e,t,r,o,n,"x",Re(s,a.line,e=>Math.abs(e)<=s),null,i)},at_blury:function(e,t,r,o,n,s,i){return Ze(e,t,r,o,n,"y",Re(s,a.line,e=>Math.abs(e)<=s),null,i)},at_dilate:function(e,t,r,o,n,s,i){return Ve(e,t,r,o,n,Re(s,a.square,e=>Math.abs(e)<=s),null,0,Be,i)},at_erode:function(e,t,r,o,n,s,i){return Ve(e,t,r,o,n,Re(s,a.square,e=>Math.abs(e)<=s),null,1,Ce,i)},at_gaussian:function(e,t,r,o,n,s,i){if(!(s>0))return Qe(e,t,o,n,i);const c=3*s;return Ve(e,t,r,o,n,Re(c,a.square,e=>Math.abs(e)<=c),(e,t)=>Math.exp(-(e*e+t*t)/(2*s*s)),0,Ue,i,(e,t)=>e/t)},at_gaussianx:function(e,t,r,o,n,s,i){if(!(s>0))return Qe(e,t,o,n,i);const c=3*s;return Ze(e,t,r,o,n,"x",Re(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 Qe(e,t,o,n,i);const c=3*s;return Ze(e,t,r,o,n,"y",Re(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*(Se(o,r-1)*t+Se(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*ot(e,0),o[1]=r-.5*n+n*ot(e,2/3),o[2]=r-.5*n+n*ot(e,1/3),o},col_fromhsv:function(e,t,r,o){return o[0]=r*(1+(ot(e,0)-1)*t),o[1]=r*(1+(ot(e,2/3)-1)*t),o[2]=r*(1+(ot(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*at(n+256*(t-.5)/500),i=at(n),c=1.08883*at(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]=tt(l),o[1]=tt(h),o[2]=tt(u),o},col_fromlinear:function(e,t,r,o){return o[0]=tt(e),o[1]=tt(t),o[2]=tt(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]=tt(i),o[1]=tt(c),o[2]=tt(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?rt(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?rt(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=et(e),a=et(t),s=et(r),i=nt((.4124564*n+.3575761*a+.1804375*s)/.95047),c=nt(.2126729*n+.7151522*a+.072175*s),l=nt((.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]=et(e),o[1]=et(t),o[2]=et(r),o},col_tooklab:function(e,t,r,o){const n=et(e),a=et(t),s=et(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*(Se(n+a,r-1)*t+Se(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:je,gcd:function(e,t){e=Math.abs(e),t=Math.abs(t);for(let r=0;r<64&&0!==t;r++){const r=je(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),y=Math.sin(c);let w=($*d+y*g)/f+.5*t,b=($*g-y*d)/m+.5*r;if(3===l)w=je(w,t),b=je(b,r);else if(w<0||b<0||w>t||b>r)return p[0]=p[1]=p[2]=p[3]=0,p;return Fe(e,t,r,w-.5,b-.5,p)},placeCode:Oe,plane_blur:function(e,t,r,o,n,s){return De(e,t,r,o,n,s,["x","y"],a.square)},plane_blurx:function(e,t,r,o,n,s){return De(e,t,r,o,n,s,["x"],a.line)},plane_blury:function(e,t,r,o,n,s){return De(e,t,r,o,n,s,["y"],a.line)},plane_dilate:function(e,t,r,o,n,a){return qe(e,t,r,o,n,a,0,!0)},plane_emboss:function(e,t,r,o,n){return We(e,t,r,o,n,Ye)},plane_erode:function(e,t,r,o,n,a){return qe(e,t,r,o,n,a,1,!1)},plane_gaussian:function(e,t,r,o,n,s){return Le(e,t,r,o,n,s,["x","y"],a.square)},plane_gaussianx:function(e,t,r,o,n,s){return Le(e,t,r,o,n,s,["x"],a.line)},plane_gaussiany:function(e,t,r,o,n,s){return Le(e,t,r,o,n,s,["y"],a.line)},plane_laplacian:function(e,t,r,o,n){return We(e,t,r,o,n,Ke)},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*(Se(o,r-1)*t+Se(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 We(e,t,r,o,n,Je)},plane_sobelx:function(e,t,r,o,n){return We(e,t,r,o,n,Xe)},plane_sobely:function(e,t,r,o,n){return We(e,t,r,o,n,He)},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)},sample:Fe,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):Fe(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 it="\\:",ct=Object.keys(st).filter(e=>"function"==typeof st[e]),lt={r:"$r",g:"$g",b:"$b",a:"$a",x:"$x",y:"$y",px:"$px",py:"$py",w:"$w",h:"$h",t:"$t",gray:"$gray"},ht={pi:"Math.PI","π":"Math.PI",e:"Math.E",tau:"(2 * Math.PI)","τ":"(2 * Math.PI)","∞":"Infinity","-∞":"(-Infinity)"},ut={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})`},pt={atan2:2,pow:2,mod:2,step:2,clamp:3,mix:3,smoothstep:3},ft={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},mt=(e,t)=>({kind:e,c:t}),dt=e=>mt("f",[e]),gt=e=>mt("b",[e]),$t=e=>1===e.length?dt(e[0]):mt("v",e),yt=(e,t=0)=>"b"===e.kind?`(${e.c[0]} ? 1 : 0)`:"f"===e.kind?e.c[0]:e.c[t]??e.c[0],wt=e=>"v"===e.kind?e.c.length:1;class bt extends Error{}function xt(e){if(e.blendKept)return{blend:!0,source:""};const t=e.params??{},r=new Set([...Object.keys(e.placements??{}),"source","selection"]),o=new _t(t,r,e.space??"srgb");o.graphics=new Set(Object.keys(e.graphics??{})),o.bind=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 bt(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 _t{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 mt(e.kind,e.c.map(e=>/^[\w$.]+$|^\(?-?[\d.e+]+\)?$/.test(e)?e:this.temp(e,t)))}fail(e){throw new bt(e)}leaf(e){if("number"===e.type)return dt(`(${e.value.replace(/\.+$/,"")})`);"string"===e.type&&this.fail("a filter has no text: numbers and colours only");const t=e.value;if("t"===t&&this.uses.add("t"),lt[t])return dt(lt[t]);if("rgb"===t)return $t(["$r","$g","$b"]);if("unchanged"===t)return dt("$u");if("selected"===t)return dt(this.pictureHere("selection").c[0]);if(ht[t])return dt(ht[t]);if("true"===t||"false"===t)return gt(t);if(Object.prototype.hasOwnProperty.call(this.params,t)){const e=`$p_${t}`;return"color"===this.params[t].type?$t([`${e}_0`,`${e}_1`,`${e}_2`]):dt(e)}if(this.pictures.has(t)){const e=this.pictureHere(t);return $t(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});`),$t([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(it)?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(),ut.mod);case"<":case">":case"≤":case"≥":{const[e,r]=n(),o={"≤":"<=","≥":">="}[t]??t;return gt(`(${yt(e)} ${o} ${yt(r)})`)}case"=":case"===":case"≠":case"≠=":case"≡":{const[e,r]=n(),o=Math.max(wt(e),wt(r)),a=Array.from({length:o},(t,o)=>`${yt(e,o)} === ${yt(r,o)}`).join(" && ");return gt("≠"===t||"≠="===t?`!(${a})`:`(${a})`)}case"≈":{const[e,t]=n();return gt(`(Math.abs(${yt(e)} - ${yt(t)}) < 1e-5)`)}case"&":{const[e,t]=n();return gt(`(${this.truth(e)} && ${this.truth(t)})`)}case"|":{const[e,t]=n();return gt(`(${this.truth(e)} || ${this.truth(t)})`)}case"\\xor":{const[e,t]=n();return gt(`(${this.truth(e)} !== ${this.truth(t)})`)}case"\\nand":{const[e,t]=n();return gt(`!(${this.truth(e)} && ${this.truth(t)})`)}case"\\nor":{const[e,t]=n();return gt(`!(${this.truth(e)} || ${this.truth(t)})`)}case"\\not":{const[e]=n();return gt(`!${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?[yt(e)]:e.c.map((t,r)=>yt(e,r)));return e.length>4&&this.fail("a colour has at most 4 values (r, g, b, a)"),$t(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)=>`(Math.floor(${e} * Math.pow(10, ${t}) + 0.5) / Math.pow(10, ${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(ut[t])return this.builtin(t,n());this.fail(`"${t}" isn't available in a filter`)}truth(e){return"b"===e.kind?e.c[0]:`(${yt(e)} !== 0)`}componentwise(e,t){const r=e.map(wt),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=>yt(e,o))));return this.keep($t(a))}builtin(e,t){const r=ut[e];if(pt[e]&&t.length!==pt[e]&&this.fail(`${e}() takes ${pt[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?gt("($u > 0.5)"):"f"===e.kind?dt("$u"):$t(["$k0","$k1","$k2","$k3"].slice(0,4===e.c.length?4:3));if(!a&&!s)return dt("$u");if(a||(a=i(s)),s||(s=i(a)),"b"===a.kind&&"b"===s.kind)return gt(this.temp(`(${o} ? ${a.c[0]} : ${s.c[0]})`));const c=Math.max(wt(a),wt(s)),l=Array.from({length:c},(e,t)=>this.temp(`(${o} ? ${yt(a,t)} : ${yt(s,t)})`));return $t(l)}membership(e){const[t,r]=e.args,o=yt(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=>yt(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} === ${yt(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 gt(n?`!${a}`:a)}random(){return this.uses.add("random"),dt(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?[yt(r),yt(n)]:[yt(r,0),yt(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),this.keep($t([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?[yt(r),yt(n)]:[yt(r,0),yt(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${a}, ${s}, ${e});`),$t([0,1,2].map(t=>`${e}[${t}]`))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep($t(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),dt(e.startsWith("mz_width_")?`$qw_${t}`:`$qh_${t}`)}switch(e){case"pixel":{const[e,t]=o().map(e=>yt(e)),r=this.scratchArray();return this.body.push(`$h_sample($I, $w, $h, ${e}, ${t}, ${r});`),this.keep($t([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?dt(`(${yt(r,0)} * 0.299 + ${yt(r,1)} * 0.587 + ${yt(r,2)} * 0.114)`):"alpha"===e&&3===wt(r)?dt("1"):dt(yt(r,o))}case"length":{const[e]=o();return dt(`Math.sqrt(${e.c.map((t,r)=>`${yt(e,r)} * ${yt(e,r)}`).join(" + ")})`)}case"distance":{const[e,t]=o(),r=this.componentwise([e,t],(e,t)=>`(${e} - ${t})`);return dt(`Math.sqrt(${r.c.map(e=>`${e} * ${e}`).join(" + ")})`)}case"dot":{const[e,t]=o(),r=Math.max(wt(e),wt(t));return dt(`(${Array.from({length:r},(r,o)=>`${yt(e,o)} * ${yt(t,o)}`).join(" + ")})`)}case"normalize":{const[e]=o(),t=this.temp(`Math.sqrt(${e.c.map((t,r)=>`${yt(e,r)} * ${yt(e,r)}`).join(" + ")})`);return this.componentwise([e],e=>`(${e} / ${t})`)}case"cross":{const[e,t]=o();3===wt(e)&&3===wt(t)||this.fail("cross() takes two colours (3 values each)");const[r,n,a]=e.c,[s,i,c]=t.c;return this.keep($t([`(${n} * ${c} - ${a} * ${i})`,`(${a} * ${s} - ${r} * ${c})`,`(${r} * ${i} - ${n} * ${s})`]))}case"convolve":{const e=o().map(e=>yt(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});`),$t([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=>yt(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=>yt(e)):[0,1,2].map(e=>yt(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($t([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(ft[e])return this.neighbourhood(e,t);this.fail(`unknown function "${e}"`)}geometry(e,t){const r=(e,t)=>this.keep($t([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($t([`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=ft[e];if(t.every(e=>this.isUniform(e))){const o=t.map(e=>yt(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?$t([0,1,2].map(e=>`${a}[$j3 + ${e}]`)):dt(`${a}[$j]`)}const o=t.map(e=>yt(this.value(e)));if(1===r)return dt(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});`),$t([0,1,2].map(e=>`${n}[${e}]`))}isUniform(e){return"number"===e.type||("symbol"===e.type?["w","h","t"].includes(e.value)||Boolean(ht[e.value])||Object.prototype.hasOwnProperty.call(this.params,e.value)&&"color"!==this.params[e.value].type:"op"===e.type&&!e.op.startsWith(it)&&"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=wt(o),a=e=>yt(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}`]),...ct.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)?Ae:Me),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),Oe(o.place)]}),...ct.map(e=>st[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 kt(e,t={}){const r="float"===t.precision||"half"===t.precision?"float":"byte",o=e.passes.map(e=>xt(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=new Map;const h={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=Et(t);return e&&"source"!==e?n[e]=r:a=r,h},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&&vt(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:u=null}={}){if(!a)throw new Error("setImage() first");const{width:p,height:f}=a;if(i<2||p*f<s)return h.draw({t:o,canvas:u});if(null===c&&(c=await 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:At(),ask:l,broadcast:e=>Promise.all(s.map((t,r)=>l(r,e))),close:()=>s.forEach(e=>e.close())};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)),!c)return h.draw({t:o,canvas:u});const m=p*f*4,d=()=>c.shared?new Float32Array(new SharedArrayBuffer(4*m)):new Float32Array(m);for(const[e,t]of[["source",a],...Object.entries(n)])l.get(e)!==t&&(await c.broadcast({type:"picture",name:e,picture:c.shared?Tt(t):t}),l.set(e,t));let g=c.shared?Tt(a).data:a.data;const $=[];for(let t=0;t<e.passes.length;t++){const n=e.passes[t];for(let e=0;e<n.keepInput;e++)$.push(g);const a=d();if(n.blendKept){const e=$.pop();for(let t=0;t<m;t++)a[t]=e[t]+(g[t]-e[t])*n.opacity;"byte"===r&&vt(a)}else{const e=Object.keys(n.params??{}).map(e=>n.values[e]),s=Mt(f,c.size),i=await Promise.all(s.map(([s,i],l)=>c.ask(l,{type:"run",pass:t,input:g,output:c.shared?a:null,width:p,height:f,t:o,params:e,opacity:n.opacity,placements:n.placements??{},y0:s,y1:i,quantize:"byte"===r})));c.shared||i.forEach((e,t)=>a.set(e.band,s[t][0]*p*4))}g=a}const y=new Uint8ClampedArray(m);for(let e=0;e<m;e++){const t=g[e];y[e]=t>0?t<1?Math.round(255*t):255:0}const w={data:y,width:p,height:f};return u&&(u.width=p,u.height=f,u.getContext("2d").putImageData(new ImageData(y,p,f),0,0)),w},get workers(){return c?c.size:0},dispose(){a=null;for(const e of Object.keys(n))delete n[e];c&&c.close(),c=null,l=new Map}};return h}function vt(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 Et(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),Et(o.getImageData(0,0,t,r))}throw new Error("setImage: give ImageData or { data, width, height }")}function Mt(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 At=()=>"undefined"!=typeof SharedArrayBuffer&&("undefined"==typeof crossOriginIsolated||!0===crossOriginIsolated);function Tt(e){if(e.data.buffer instanceof(globalThis.SharedArrayBuffer??Object))return e;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 Ot({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 jt(e,t={}){const r=Ot({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:kt(e,t),engine:"cpu",reason:`the GPU refused the shader (${r.message.split("\n")[0]})`}}return{runner:kt(e,t),...r}}const St=[{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))"}],Ft=e=>St.find(t=>t.name===e);St.push({name:"Old film",group:"Chains",description:"Sepia, a vignette and faint scanlines — a chain of three",steps:[Ft("Sepia"),{filter:Ft("Vignette"),with:{strength:1.2}},{filter:Ft("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:Ft("Gaussian blur"),with:{sigma:1.6}},{filter:Ft("Vivid"),with:{amount:1.5}},{filter:Ft("Posterize"),with:{levels:4}},{filter:Ft("Outline"),with:{gain:1.2}}]},{name:"Cartoon",group:"Chains",description:"Blur, then flatten the colours, then outline — a chain of three",steps:[{filter:Ft("Gaussian blur"),with:{sigma:1.5}},{filter:Ft("Posterize"),with:{levels:6}},{filter:Ft("Outline"),with:{gain:2}}]},{name:"Dreamy",group:"Chains",description:"A soft glow mixed over the picture",steps:[{filter:Ft("Bloom"),with:{amount:1.2}},{filter:Ft("Gaussian blur"),with:{sigma:2},opacity:.4}]},{name:"Tilt shift",group:"Chains",description:"Blurred where the mask is light — a chain",steps:[{filter:Ft("Gaussian blur"),with:{sigma:4}},Ft("Through a mask")]},{name:"Title card",group:"Chains",description:"A frosted panel with a caption on it — a chain of two",steps:[Ft("Frosted panel"),{filter:Ft("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:[Ft("Grayscale"),Ft("Through a mask")]});const Rt=St,zt=["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,T as GRAPHIC_DEFAULTS,A as GRAPHIC_TYPES,zt as GROUPS,Rt as LIBRARY,O as MAX_SHADOW_LAYERS,re as PLACEMENT,g as STROKES_DEFAULTS,p as TIMINGS,f as WIDTH_FROM,Ot as chooseEngine,xt as compileCpuPass,me as compileFilter,kt as createCpuRunner,ke as createFilterRunner,jt as createRunner,L as cssFont,K as drawGraphic,q as familyFor,ye as filterFromJSON,be as filterFromLink,ae as filterGraphics,le as filterImages,he as filterParams,$e as filterToJSON,we as filterToLink,D as fontFileFromCss,G as googleFontFamily,P as googleFontUrl,S as layeredExpression,X as loadGraphicFonts,oe as normalizeFilter,C as normalizeGraphic,w as normalizeStrokes,k as rasterizeStrokes,xe as readFilter,Y as renderGraphics,j as shadowLayerNames,M as simplify,E as simplifyLoop,b as strokeTimeline,Et as toPicture,v as traceContours,ue as validateFilter};