-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathq5.min.js
9 lines (9 loc) · 106 KB
/
q5.min.js
1
2
3
4
5
6
7
8
9
/**
* q5.js
* @version 2.28
* @author quinton-ashley
* @contributors evanalulu, Tezumie, ormaq, Dukemz, LingDong-
* @license LGPL-3.0
* @class Q5
*/
function Q5(e,t,r){let a=this;a._q5=!0,a._parent=t,"webgpu-fallback"==r?(a._renderer="c2d",a._webgpu=a._webgpuFallback=!0):(a._renderer=r||"c2d",a["_"+a._renderer]=!0);let n,i="auto"==e;if(e??="global","auto"==e){if(!(window.setup||window.update||window.draw))return;e="global"}a._scope=e,"global"==e&&(Q5._hasGlobal=a._isGlobal=!0,n=Q5._esm?globalThis:Q5._server?global:window),"graphics"==e&&(a._graphics=!0);let o=new Proxy(a,{set:(e,t,r)=>(a[t]=r,a._isGlobal&&(n[t]=r),!0)});a.canvas=a.ctx=a.drawingContext=null,a.pixels=[];let s=null,l=!0;async function d(e){for(let t of Q5.lifecycleHooks[e])await t.call(a)}a.frameCount=0,a.deltaTime=16,a._targetFrameRate=0,a._targetFrameDuration=16.666666666666668,a._frameRate=a._fps=60,a._loop=!0;let c=0;a.millis=()=>performance.now()-c,a.noCanvas=()=>{a.canvas?.remove&&a.canvas.remove(),a.canvas=0,o.ctx=o.drawingContext=0},window&&(a.windowWidth=window.innerWidth,a.windowHeight=window.innerHeight,a.deviceOrientation=window.screen?.orientation?.type),a._preloadPromises=[],a._usePreload=!0,a.usePromiseLoading=(e=!0)=>a._usePreload=!e,a.usePreloadSystem=(e=!0)=>a._usePreload=e,a.isPreloadSupported=()=>a._usePreload;const h=[];async function u(e){let t=e||performance.now();if(a._didResize&&(a.windowResized(),a._didResize=!1),a._loop)if(l)s=f(u);else{let e=t+a._targetFrameDuration,r=e-performance.now();for(;r<0;)r+=a._targetFrameDuration;s=setTimeout((()=>u(e)),r)}else if(a.frameCount&&!a._redraw)return;if(a.frameCount&&l&&!a._redraw){if(t-a._lastFrameTime<a._targetFrameDuration-4)return}o.deltaTime=t-a._lastFrameTime,a._frameRate=1e3/a.deltaTime,o.frameCount++;let r=performance.now();a.resetMatrix(),a._beginRender&&a._beginRender(),await d("predraw");try{await a.draw()}catch(e){throw Q5.errorTolerant||a.noLoop(),a._fes&&a._fes(e),e}await d("postdraw"),await a.postProcess(),a._render&&a._render(),a._finishRender&&a._finishRender(),o.pmouseX=a.mouseX,o.pmouseY=a.mouseY,o.moveX=o.moveY=0,a._lastFrameTime=t;let n=performance.now();a._fps=Math.round(1e3/(n-r))}a._incrementPreload=()=>{a._preloadPromises.push(new Promise((e=>h.push(e))))},a._decrementPreload=()=>{h.length&&h.pop()()},a.noLoop=()=>{a._loop=!1,null!=s&&(l&&window.cancelAnimationFrame?cancelAnimationFrame(s):clearTimeout(s)),s=null},a.loop=()=>{a._loop=!0,a._setupDone&&null==s&&u()},a.isLooping=()=>a._loop,a.redraw=async(e=1)=>{a._redraw=!0;for(let t=0;t<e;t++)await u();a._redraw=!1},a.remove=async()=>{a.noLoop(),a.canvas.remove(),await d("remove")},a.frameRate=e=>(e&&e!=a._targetFrameRate&&(a._targetFrameRate=e,a._targetFrameDuration=1e3/e,a._loop&&null!=s&&(l&&window.cancelAnimationFrame?cancelAnimationFrame(s):clearTimeout(s),s=null),l=e<=60,a._setupDone&&(s=l?f(u):setTimeout((()=>u()),a._targetFrameDuration))),a._frameRate),a.getTargetFrameRate=()=>a._targetFrameRate||60,a.getFPS=()=>a._fps,a.Element=function(e){this.elt=e},a._elements=[],a.describe=()=>{},a.log=a.print=console.log;for(let e in Q5.modules)Q5.modules[e](a,o);let p=Q5.renderers[a._renderer];for(let e in p)p[e](a,o);for(let e in Q5)"_"!=e[1]&&e[1]==e[1].toUpperCase()&&(a[e]=Q5[e]);if(a._graphics)return;if("global"==e){let e=Object.assign({},a);delete e.Color,Object.assign(Q5,e),delete Q5.Q5}for(let e of Q5.lifecycleHooks.init)e.call(a);for(let[e,t]of Object.entries(Q5.prototype))"_"!=e[0]&&"function"==typeof a[e]&&(a[e]=t.bind(a));for(let[e,t]of Object.entries(Q5.preloadMethods))a[e]=function(){return a._incrementPreload(),t.apply(a,arguments)};if("global"==e){let e=Object.getOwnPropertyNames(a);for(let t of e)"_"!=t[0]&&(n[t]=a[t]);for(let e of["_incrementPreload","_decrementPreload"])n[e]=a[e]}"function"==typeof e&&e(a),Q5._instanceCount++;let f=window.requestAnimationFrame||function(e){const t=a._lastFrameTime+a._targetFrameDuration;return setTimeout((()=>{e(t)}),t-performance.now())},g=n||a;a._isTouchAware=g.touchStarted||g.touchMoved||g.touchEnded;let m=["preload","setup","postProcess","mouseMoved","mousePressed","mouseReleased","mouseDragged","mouseClicked","doubleClicked","mouseWheel","keyPressed","keyReleased","keyTyped","touchStarted","touchMoved","touchEnded","windowResized"];for(let e of m)a[e]??=()=>{};function _(e){const t=g[e]||a[e];a[e]=e=>{try{return t(e)}catch(e){throw a._fes&&a._fes(e),e}}}async function x(){_("preload"),a.preload(),await Promise.all(a._preloadPromises),a._g&&await Promise.all(a._g._preloadPromises),"AsyncFunction"==g.setup?.constructor.name&&a.usePromiseLoading();for(let e of m)_(e);a.draw??=g.draw||(()=>{}),await d("presetup"),c=performance.now(),await a.setup(),a._setupDone=!0,null===a.ctx&&a.createCanvas(200,200),await d("postsetup"),a.frameCount||(a._lastFrameTime=performance.now()-15,f(u))}Q5.instances.push(a),i?x():setTimeout(x,32)}function createCanvas(e,t,r){if(!Q5._hasGlobal){(new Q5).createCanvas(e,t,r)}}Q5.renderers={},Q5.modules={},Q5._server="object"==typeof process,Q5._esm=void 0===this,Q5._instanceCount=0,Q5.instances=[],Q5._friendlyError=(e,t)=>{Q5.disableFriendlyErrors||console.error(t+": "+e)},Q5._validateParameters=()=>!0,Q5.lifecycleHooks={init:[],presetup:[],postsetup:[],predraw:[],postdraw:[],remove:[]},Q5.registerAddon=e=>{let t={};e(Q5,Q5.prototype,t);for(let e in t)Q5.lifecycleHooks[e].push(t[e])},Q5.prototype.registerMethod=(e,t)=>{("beforeSetup"==e||e.includes("Preload"))&&(e="presetup"),"afterSetup"==e&&(e="postsetup"),"pre"==e&&(e="predraw"),"post"==e&&(e="postdraw"),Q5.lifecycleHooks[e].push(t)},Q5.preloadMethods={},Q5.prototype.registerPreloadMethod=(e,t)=>Q5.preloadMethods[e]=t[e],Q5._server&&(global.p5??=global.Q5=Q5),"object"==typeof window?window.p5??=window.Q5=Q5:global.window=0,Q5.version=Q5.VERSION="2.28","object"==typeof document&&document.addEventListener("DOMContentLoaded",(()=>{Q5._hasGlobal||new Q5("auto")})),Q5.modules.canvas=(e,t)=>{e._Canvas=window.OffscreenCanvas||function(){return document.createElement("canvas")},Q5._server?Q5._createServerCanvas&&(t.canvas=Q5._createServerCanvas(200,200)):"image"!=e._scope&&"graphics"!=e._scope||(t.canvas=new e._Canvas(200,200)),e.canvas||("object"==typeof document?(t.canvas=document.createElement("canvas"),e.canvas.id="q5Canvas"+Q5._instanceCount,e.canvas.classList.add("q5Canvas")):e.noCanvas()),e.displayDensity=()=>window.devicePixelRatio||1,e.width=200,e.height=200,e._pixelDensity=1;let r=e.canvas;if(r&&(r.width=200,r.height=200,"image"!=e._scope&&(r.renderer=e._renderer,r[e._renderer]=!0,e._pixelDensity=Math.ceil(e.displayDensity()))),e._adjustDisplay=()=>{r.style&&(r.style.width=r.w+"px",r.style.height=r.h+"px")},e.createCanvas=function(t,n,i){"object"==typeof t&&(i=t,t=null),i??=arguments[3],"string"==typeof i&&(i={renderer:i});let o=Object.assign({},Q5.canvasOptions);if("object"==typeof i&&Object.assign(o,i),"image"!=e._scope)if("graphics"==e._scope)e._pixelDensity=this._pixelDensity;else if(Q5._server)r.visible=!0;else{let t=r;for(;t&&t.parentElement!=document.body;)t=t.parentElement;if(t||(document.getElementById(r.id)?.remove(),a()),window.IntersectionObserver){let t=!1;new IntersectionObserver((a=>{if(a[0].isIntersecting)r.visible=!0;else{let e=r.getBoundingClientRect();r.visible=e.top<window.innerHeight&&e.bottom>0&&e.left<window.innerWidth&&e.right>0}t||(e._wasLooping=e._loop,t=!0),r.visible?e._wasLooping&&!e._loop&&e.loop():(e._wasLooping=e._loop,e.noLoop())})).observe(r)}}e._setCanvasSize(t,n),Object.assign(r,o);let s=e._createCanvas(r.w,r.h,o);return e._addEventMethods&&e._addEventMethods(r),s},e.createGraphics=function(t,r,a={}){"string"==typeof a&&(a={renderer:a});let n=new Q5("graphics",void 0,a.renderer||(e._webgpuFallback?"webgpu-fallback":e._renderer));a.alpha??=!0,a.colorSpace??=e.canvas.colorSpace,n.createCanvas.call(e,t,r,a);let i=n._pixelDensity*e._defaultImageScale;return n.defaultWidth=t*i,n.defaultHeight=r*i,n},e._setCanvasSize=(a,n)=>{n??=a??window.innerHeight,a??=window.innerWidth,r.w=a=Math.ceil(a),r.h=n=Math.ceil(n),t.halfWidth=r.hw=a/2,t.halfHeight=r.hh=n/2,r.width=Math.ceil(a*e._pixelDensity),r.height=Math.ceil(n*e._pixelDensity),e._da?e.flexibleCanvas(e._dau):(t.width=a,t.height=n),e.displayMode&&!r.displayMode?e.displayMode():e._adjustDisplay()},e._setImageSize=(a,n)=>{t.width=r.w=a,t.height=r.h=n,t.halfWidth=r.hw=a/2,t.halfHeight=r.hh=n/2,r.width=Math.ceil(a*e._pixelDensity),r.height=Math.ceil(n*e._pixelDensity)},e.defaultImageScale=t=>t?e._defaultImageScale=t:e._defaultImageScale,e.defaultImageScale(.5),"image"!=e._scope){if(r&&"graphics"!=e._scope){function a(){let t=e._parent;t??=document.getElementsByTagName("main")[0],t||(t=document.createElement("main"),document.body.append(t)),r.parent(t)}r.parent=t=>{function a(){e.frameCount>1&&(e._didResize=!0,e._adjustDisplay())}r.parentElement&&r.parentElement.removeChild(r),"string"==typeof t&&(t=document.getElementById(t)),t.append(r),"function"==typeof ResizeObserver?(e._ro&&e._ro.disconnect(),e._ro=new ResizeObserver(a),e._ro.observe(t)):e.frameCount||window.addEventListener("resize",a)},document.body?a():document.addEventListener("DOMContentLoaded",a)}e.resizeCanvas=(t,a)=>{if(!e.ctx)return e.createCanvas(t,a);t==r.w&&a==r.h||e._resizeCanvas(t,a)},r&&!Q5._createServerCanvas&&(r.resize=e.resizeCanvas),e.pixelDensity=t=>t&&t!=e._pixelDensity?(e._pixelDensity=t,e._resizeCanvas(r.w,r.h),t):e._pixelDensity,e.flexibleCanvas=(a=400)=>{a?(e._da=r.width/(a*e._pixelDensity),t.width=e._dau=a,t.height=r.h/r.w*a):e._da=0},window&&"graphics"!=e._scope&&window.addEventListener("resize",(()=>{e._didResize=!0,t.windowWidth=window.innerWidth,t.windowHeight=window.innerHeight,t.deviceOrientation=window.screen?.orientation?.type}))}},Q5.CENTER="center",Q5.LEFT="left",Q5.RIGHT="right",Q5.TOP="top",Q5.BOTTOM="bottom",Q5.BASELINE="alphabetic",Q5.MIDDLE="middle",Q5.NORMAL="normal",Q5.ITALIC="italic",Q5.BOLD="bold",Q5.BOLDITALIC="italic bold",Q5.ROUND="round",Q5.SQUARE="butt",Q5.PROJECT="square",Q5.MITER="miter",Q5.BEVEL="bevel",Q5.NONE="none",Q5.SIMPLE="simple",Q5.CHORD_OPEN=0,Q5.PIE_OPEN=1,Q5.PIE=2,Q5.CHORD=3,Q5.RADIUS="radius",Q5.CORNER="corner",Q5.CORNERS="corners",Q5.OPEN=0,Q5.CLOSE=1,Q5.VIDEO="video",Q5.AUDIO="audio",Q5.LANDSCAPE="landscape",Q5.PORTRAIT="portrait",Q5.BLEND="source-over",Q5.REMOVE="destination-out",Q5.ADD="lighter",Q5.DARKEST="darken",Q5.LIGHTEST="lighten",Q5.DIFFERENCE="difference",Q5.SUBTRACT="subtract",Q5.EXCLUSION="exclusion",Q5.MULTIPLY="multiply",Q5.SCREEN="screen",Q5.REPLACE="copy",Q5.OVERLAY="overlay",Q5.HARD_LIGHT="hard-light",Q5.SOFT_LIGHT="soft-light",Q5.DODGE="color-dodge",Q5.BURN="color-burn",Q5.THRESHOLD=1,Q5.GRAY=2,Q5.OPAQUE=3,Q5.INVERT=4,Q5.POSTERIZE=5,Q5.DILATE=6,Q5.ERODE=7,Q5.BLUR=8,Q5.SEPIA=9,Q5.BRIGHTNESS=10,Q5.SATURATION=11,Q5.CONTRAST=12,Q5.HUE_ROTATE=13,Q5.C2D=Q5.P2D=Q5.P2DHDR="c2d",Q5.WEBGL="webgl",Q5.WEBGPU="webgpu",Q5.canvasOptions={alpha:!1,colorSpace:"display-p3"},window.matchMedia&&matchMedia("(dynamic-range: high) and (color-gamut: p3)").matches?Q5.supportsHDR=!0:Q5.canvasOptions.colorSpace="srgb",Q5.renderers.c2d={},Q5.renderers.c2d.canvas=(e,t)=>{let r=e.canvas;function a(){let t=e._styles.pop();for(let r of e._styleNames)e[r]=t[r]}e.colorMode&&e.colorMode("rgb",e._webgpu?1:255),e._createCanvas=function(a,n,i){if(r)return t.ctx=t.drawingContext=r.getContext("2d",i),"image"!=e._scope&&(e.ctx.fillStyle=e._fill="white",e.ctx.strokeStyle=e._stroke="black",e.ctx.lineCap="round",e.ctx.lineJoin="miter",e.ctx.textAlign="left",e._strokeWeight=1),e.ctx.scale(e._pixelDensity,e._pixelDensity),e.ctx.save(),r;console.error("q5 canvas could not be created. skia-canvas and jsdom packages not found.")},e.clear=()=>{e.ctx.save(),e.ctx.resetTransform(),e.ctx.clearRect(0,0,e.canvas.width,e.canvas.height),e.ctx.restore()},"image"!=e._scope&&(e.background=function(t){e.ctx.save(),e.ctx.resetTransform(),e.ctx.globalAlpha=1,t.canvas?e.image(t,0,0,e.canvas.width,e.canvas.height):(Q5.Color&&!t._q5Color&&(t=e.color(...arguments)),e.ctx.fillStyle=t.toString(),e.ctx.fillRect(0,0,e.canvas.width,e.canvas.height)),e.ctx.restore()},e._resizeCanvas=(t,a)=>{let n,i={};for(let t in e.ctx)"function"!=typeof e.ctx[t]&&(i[t]=e.ctx[t]);if(delete i.canvas,e.frameCount>1){n=new e._Canvas(r.width,r.height),n.w=r.w,n.h=r.h,n.getContext("2d").drawImage(r,0,0)}e._setCanvasSize(t,a);for(let t in i)e.ctx[t]=i[t];e.scale(e._pixelDensity),n&&e.ctx.drawImage(n,0,0,n.w,n.h)},e.fill=function(t){if(e._doFill=e._fillSet=!0,Q5.Color&&(t._q5Color||"string"==typeof t&&!e._namedColors[t]||(t=e.color(...arguments)),t.a<=0))return e._doFill=!1;e.ctx.fillStyle=e._fill=t.toString()},e.stroke=function(t){if(e._doStroke=e._strokeSet=!0,Q5.Color&&(t._q5Color||"string"==typeof t&&!e._namedColors[t]||(t=e.color(...arguments)),t.a<=0))return e._doStroke=!1;e.ctx.strokeStyle=e._stroke=t.toString()},e.strokeWeight=t=>{t||(e._doStroke=!1),e._da&&(t*=e._da),e.ctx.lineWidth=e._strokeWeight=t||1e-4},e.noFill=()=>e._doFill=!1,e.noStroke=()=>e._doStroke=!1,e.opacity=t=>e.ctx.globalAlpha=t,e._doShadow=!1,e._shadowOffsetX=e._shadowOffsetY=e._shadowBlur=10,e.shadow=function(t){if(Q5.Color&&(t._q5Color||"string"==typeof t&&!e._namedColors[t]||(t=e.color(...arguments)),t.a<=0))return e._doShadow=!1;e.ctx.shadowColor=e._shadow=t.toString(),e._doShadow=!0,e.ctx.shadowOffsetX||=e._shadowOffsetX,e.ctx.shadowOffsetY||=e._shadowOffsetY,e.ctx.shadowBlur||=e._shadowBlur},e.shadowBox=(t,r,a)=>{e.ctx.shadowOffsetX=e._shadowOffsetX=t,e.ctx.shadowOffsetY=e._shadowOffsetY=r||t,e.ctx.shadowBlur=e._shadowBlur=a||0},e.noShadow=()=>{e._doShadow=!1,e.ctx.shadowOffsetX=e.ctx.shadowOffsetY=e.ctx.shadowBlur=0},e.translate=(t,r)=>{e._da&&(t*=e._da,r*=e._da),e.ctx.translate(t,r)},e.rotate=t=>{e._angleMode&&(t=e.radians(t)),e.ctx.rotate(t)},e.scale=(t,r)=>{t.x&&(r=t.y,t=t.x),r??=t,e.ctx.scale(t,r)},e.applyMatrix=(t,r,a,n,i,o)=>e.ctx.transform(t,r,a,n,i,o),e.shearX=t=>e.ctx.transform(1,0,e.tan(t),1,0,0),e.shearY=t=>e.ctx.transform(1,e.tan(t),0,1,0,0),e.resetMatrix=()=>{e.ctx&&(e.ctx.resetTransform(),e.scale(e._pixelDensity),e._webgpu&&e.translate(e.halfWidth,e.halfHeight))},e._styleNames=["_fill","_stroke","_strokeWeight","_doFill","_doStroke","_fillSet","_strokeSet","_shadow","_doShadow","_shadowOffsetX","_shadowOffsetY","_shadowBlur","_tint","_textSize","_textAlign","_textBaseline","_imageMode","_rectMode","_ellipseMode","_colorMode","_colorFormat","Color"],e._styles=[],e.pushStyles=()=>{let t={};for(let r of e._styleNames)t[r]=e[r];e._styles.push(t)},e.popStyles=()=>{a(),e.ctx.fillStyle=e._fill,e.ctx.strokeStyle=e._stroke,e.ctx.lineWidth=e._strokeWeight,e.ctx.shadowColor=e._shadow,e.ctx.shadowOffsetX=e._doShadow?e._shadowOffsetX:0,e.ctx.shadowOffsetY=e._doShadow?e._shadowOffsetY:0,e.ctx.shadowBlur=e._doShadow?e._shadowBlur:0},e.pushMatrix=()=>e.ctx.save(),e.popMatrix=()=>e.ctx.restore(),e.push=()=>{e.ctx.save(),e.pushStyles()},e.pop=()=>{e.ctx.restore(),a()})},Q5.renderers.c2d.shapes=e=>{e._doStroke=!0,e._doFill=!0,e._strokeSet=!1,e._fillSet=!1,e._ellipseMode=Q5.CENTER,e._rectMode=Q5.CORNER;let t=!0,r=[];function a(){e._doFill&&e.ctx.fill(),e._doStroke&&e.ctx.stroke()}e.blendMode=t=>e.ctx.globalCompositeOperation=t,e.strokeCap=t=>e.ctx.lineCap=t,e.strokeJoin=t=>e.ctx.lineJoin=t,e.ellipseMode=t=>e._ellipseMode=t,e.rectMode=t=>e._rectMode=t,e.curveDetail=()=>{},e.line=(t,r,a,n)=>{e._doStroke&&(e._da&&(t*=e._da,r*=e._da,a*=e._da,n*=e._da),e.ctx.beginPath(),e.ctx.moveTo(t,r),e.ctx.lineTo(a,n),e.ctx.stroke())};const n=2*Math.PI;function i(t,r,a,i,o,s,l){if(e._angleMode&&(o=e.radians(o),s=e.radians(s)),(o%=n)<0&&(o+=n),(s%=n)<0&&(s+=n),o>s&&(s+=n),o==s)return e.ellipse(t,r,a,i);if(a/=2,i/=2,a=Math.abs(a),i=Math.abs(i),e._doFill||l!=e.PIE_OPEN||(l=e.CHORD_OPEN),e.ctx.beginPath(),e.ctx.ellipse(t,r,a,i,0,o,s),l!=e.PIE&&l!=e.PIE_OPEN||e.ctx.lineTo(t,r),e._doFill&&e.ctx.fill(),e._doStroke){if(l!=e.PIE&&l!=e.CHORD||e.ctx.closePath(),l!=e.PIE_OPEN)return e.ctx.stroke();e.ctx.beginPath(),e.ctx.ellipse(t,r,a,i,0,o,s),e.ctx.stroke()}}function o(t,r,i,o){e.ctx.beginPath(),e.ctx.ellipse(t,r,Math.abs(i/2),Math.abs(o/2),0,0,n),a()}function s(t,r,n,i,o,l,d,c){return void 0===o?function(t,r,n,i){e._da&&(t*=e._da,r*=e._da,n*=e._da,i*=e._da),e.ctx.beginPath(),e.ctx.rect(t,r,n,i),a()}(t,r,n,i):void 0===l?s(t,r,n,i,o,o,o,o):(e._da&&(t*=e._da,r*=e._da,n*=e._da,i*=e._da,o*=e._da,l*=e._da,c*=e._da,d*=e._da),e.ctx.roundRect(t,r,n,i,[o,l,d,c]),void a())}e.arc=(t,r,a,n,o,s,l)=>{if(o==s)return e.ellipse(t,r,a,n);e._da&&(t*=e._da,r*=e._da,a*=e._da,n*=e._da),l??=e.PIE_OPEN,e._ellipseMode==e.CENTER?i(t,r,a,n,o,s,l):e._ellipseMode==e.RADIUS?i(t,r,2*a,2*n,o,s,l):e._ellipseMode==e.CORNER?i(t+a/2,r+n/2,a,n,o,s,l):e._ellipseMode==e.CORNERS&&i((t+a)/2,(r+n)/2,a-t,n-r,o,s,l)},e.ellipse=(t,r,a,n)=>{n??=a,e._da&&(t*=e._da,r*=e._da,a*=e._da,n*=e._da),e._ellipseMode==e.CENTER?o(t,r,a,n):e._ellipseMode==e.RADIUS?o(t,r,2*a,2*n):e._ellipseMode==e.CORNER?o(t+a/2,r+n/2,a,n):e._ellipseMode==e.CORNERS&&o((t+a)/2,(r+n)/2,a-t,n-r)},e.circle=(t,r,i)=>{e._ellipseMode==e.CENTER?(e._da&&(t*=e._da,r*=e._da,i*=e._da),e.ctx.beginPath(),e.ctx.arc(t,r,Math.abs(i/2),0,n),a()):e.ellipse(t,r,i,i)},e.point=(t,r)=>{e._doStroke&&(t.x&&(r=t.y,t=t.x),e._da&&(t*=e._da,r*=e._da),e.ctx.beginPath(),e.ctx.moveTo(t,r),e.ctx.lineTo(t,r),e.ctx.stroke())},e.rect=(t,r,a,n=a,i,o,l,d)=>{e._rectMode==e.CENTER?s(t-a/2,r-n/2,a,n,i,o,l,d):e._rectMode==e.RADIUS?s(t-a,r-n,2*a,2*n,i,o,l,d):e._rectMode==e.CORNER?s(t,r,a,n,i,o,l,d):e._rectMode==e.CORNERS&&s(t,r,a-t,n-r,i,o,l,d)},e.square=(t,r,a,n,i,o,s)=>e.rect(t,r,a,a,n,i,o,s),e.beginShape=()=>{r=[],e.ctx.beginPath(),t=!0},e.beginContour=()=>{e.ctx.closePath(),r=[],t=!0},e.endContour=()=>{r=[],t=!0},e.vertex=(a,n)=>{e._da&&(a*=e._da,n*=e._da),r=[],t?e.ctx.moveTo(a,n):e.ctx.lineTo(a,n),t=!1},e.bezierVertex=(t,a,n,i,o,s)=>{e._da&&(t*=e._da,a*=e._da,n*=e._da,i*=e._da,o*=e._da,s*=e._da),r=[],e.ctx.bezierCurveTo(t,a,n,i,o,s)},e.quadraticVertex=(t,a,n,i)=>{e._da&&(t*=e._da,a*=e._da,n*=e._da,i*=e._da),r=[],e.ctx.quadraticCurveTo(t,a,n,i)},e.bezier=(t,r,a,n,i,o,s,l)=>{e.beginShape(),e.vertex(t,r),e.bezierVertex(a,n,i,o,s,l),e.endShape()},e.triangle=(t,r,a,n,i,o)=>{e.beginShape(),e.vertex(t,r),e.vertex(a,n),e.vertex(i,o),e.endShape(e.CLOSE)},e.quad=(t,r,a,n,i,o,s,l)=>{e.beginShape(),e.vertex(t,r),e.vertex(a,n),e.vertex(i,o),e.vertex(s,l),e.endShape(e.CLOSE)},e.endShape=t=>{r=[],t&&e.ctx.closePath(),a()},e.curveVertex=(a,n)=>{if(e._da&&(a*=e._da,n*=e._da),r.push([a,n]),r.length<4)return;let i=r.at(-4),o=r.at(-3),s=r.at(-2),l=r.at(-1),d=o[0]+(s[0]-i[0])/6,c=o[1]+(s[1]-i[1])/6,h=s[0]-(l[0]-o[0])/6,u=s[1]-(l[1]-o[1])/6;t&&(e.ctx.moveTo(o[0],o[1]),t=!1),e.ctx.bezierCurveTo(d,c,h,u,s[0],s[1])},e.curve=(t,r,a,n,i,o,s,l)=>{e.beginShape(),e.curveVertex(t,r),e.curveVertex(a,n),e.curveVertex(i,o),e.curveVertex(s,l),e.endShape()},e.curvePoint=(e,t,r,a,n)=>{const i=n*n*n,o=n*n;return e*(-.5*i+o-.5*n)+t*(1.5*i-2.5*o+1)+r*(-1.5*i+2*o+.5*n)+a*(.5*i-.5*o)},e.bezierPoint=(e,t,r,a,n)=>{const i=1-n;return Math.pow(i,3)*e+3*Math.pow(i,2)*n*t+3*i*Math.pow(n,2)*r+Math.pow(n,3)*a},e.curveTangent=(e,t,r,a,n)=>{const i=n*n;return e*(-3*i/2+2*n-.5)+t*(9*i/2-5*n)+r*(-9*i/2+4*n+.5)+a*(3*i/2-n)},e.bezierTangent=(e,t,r,a,n)=>{const i=1-n;return 3*a*Math.pow(n,2)-3*r*Math.pow(n,2)+6*r*i*n-6*t*i*n+3*t*Math.pow(i,2)-3*e*Math.pow(i,2)},e.erase=function(t,r){255==e._colorFormat&&(t&&(t/=255),r&&(r/=255)),e.ctx.save(),e.ctx.globalCompositeOperation="destination-out",e.ctx.fillStyle=`rgb(0 0 0 / ${t||1})`,e.ctx.strokeStyle=`rgb(0 0 0 / ${r||1})`},e.noErase=function(){e.ctx.globalCompositeOperation="source-over",e.ctx.restore()},e.inFill=(t,r)=>{const a=e._pixelDensity;return e.ctx.isPointInPath(t*a,r*a)},e.inStroke=(t,r)=>{const a=e._pixelDensity;return e.ctx.isPointInStroke(t*a,r*a)}},Q5.renderers.c2d.image=(e,t)=>{const r=e.canvas;r&&(r.convertToBlob??=e=>new Promise((t=>{r.toBlob((e=>t(e)),e.type,e.quality)}))),e._tint=null;let a=null;e.createImage=(t,a,n)=>(n??={},n.alpha??=!0,n.colorSpace??=r.colorSpace||Q5.canvasOptions.colorSpace,new Q5.Image(e,t,a,n)),e.loadImage=function(t,r,a){if(t.canvas)return t;if("gif"==t.slice(-3).toLowerCase())throw new Error("q5 doesn't support GIFs. Use a video or p5play animation instead. https://github.com/q5js/q5.js/issues/84");let n=[...arguments].at(-1);"object"==typeof n?(a=n,r=null):a=null;let i=e.createImage(1,1,a),o=i._pixelDensity,s=new window.Image;return s.crossOrigin="Anonymous",i.promise=new Promise(((t,a)=>{s.onload=()=>{s._pixelDensity=o,i.defaultWidth=s.width*e._defaultImageScale,i.defaultHeight=s.height*e._defaultImageScale,i.naturalWidth=s.naturalWidth||s.width,i.naturalHeight=s.naturalHeight||s.height,i._setImageSize(Math.ceil(i.naturalWidth/o),Math.ceil(i.naturalHeight/o)),i.ctx.drawImage(s,0,0),r&&r(i),delete i.promise,t(i)},s.onerror=a})),e._preloadPromises.push(i.promise),i.src=s.src=t,e._usePreload?i:i.promise},e.imageMode=t=>e._imageMode=t,e.image=(t,r,a,n,i,o=0,s=0,l,d)=>{if(!t)return;let c=t.canvas||t;n??=t.defaultWidth||c.width||t.videoWidth,i??=t.defaultHeight||c.height||t.videoHeight,"center"==e._imageMode&&(r-=.5*n,a-=.5*i),e._da&&(r*=e._da,a*=e._da,n*=e._da,i*=e._da,o*=e._da,s*=e._da,l*=e._da,d*=e._da);let h=t._pixelDensity||1;if(l?l*=h:l=c.width||c.videoWidth,d?d*=h:d=c.height||c.videoHeight,e._tint){if(t._retint||t._tint!=e._tint){t._tintImg??=e.createImage(t.w,t.h,{pixelDensity:h}),t._tintImg.width==t.width&&t._tintImg.height==t.height||t._tintImg.resize(t.w,t.h);let r=t._tintImg.ctx;r.globalCompositeOperation="copy",r.fillStyle=e._tint,r.fillRect(0,0,t.width,t.height),t.canvas.alpha&&(r.globalCompositeOperation="destination-in",r.drawImage(c,0,0,t.width,t.height)),r.globalCompositeOperation="multiply",r.drawImage(c,0,0,t.width,t.height),t._tint=e._tint,t._retint=!1}c=t._tintImg.canvas}t.flipped&&(e.ctx.save(),e.ctx.translate(r+n,0),e.ctx.scale(-1,1),r=0),e.ctx.drawImage(c,o*h,s*h,l,d,r,a,n,i),t.flipped&&e.ctx.restore()},e.filter=(t,a)=>{e.ctx.save();let n="";if(e.ctx.filter){if("string"==typeof t)n=t;else if(t==Q5.GRAY)n="saturate(0%)";else if(t==Q5.INVERT)n="invert(100%)";else if(t==Q5.BLUR){n=`blur(${Math.ceil(a*e._pixelDensity)||1}px)`}else if(t==Q5.THRESHOLD){a??=.5,n=`saturate(0%) brightness(${Math.floor(.5/Math.max(a,1e-5)*100)}%) contrast(1000000%)`}else if(t==Q5.SEPIA)n=`sepia(${a??1})`;else if(t==Q5.BRIGHTNESS)n=`brightness(${a??1})`;else if(t==Q5.SATURATION)n=`saturate(${a??1})`;else if(t==Q5.CONTRAST)n=`contrast(${a??1})`;else if(t==Q5.HUE_ROTATE){n=`hue-rotate(${a}${0==e._angleMode?"rad":"deg"})`}if(n&&(e.ctx.filter=n,"none"==e.ctx.filter))throw new Error(`Invalid filter format: ${t}`)}n||e._softFilter(t,a),e.ctx.globalCompositeOperation="source-over",e.ctx.drawImage(r,0,0,r.w,r.h),e.ctx.restore(),e.modified=e._retint=!0},"image"==e._scope&&(e.resize=(t,a)=>{let n=new e._Canvas(r.width,r.height);n.getContext("2d",{colorSpace:r.colorSpace}).drawImage(r,0,0),e._setImageSize(t,a),e.defaultWidth=r.width*e._defaultImageScale,e.defaultHeight=r.height*e._defaultImageScale,e.ctx.clearRect(0,0,r.width,r.height),e.ctx.drawImage(n,0,0,r.width,r.height),e.modified=e._retint=!0}),e._getImageData=(t,a,n,i)=>e.ctx.getImageData(t,a,n,i,{colorSpace:r.colorSpace}),e.trim=()=>{let t=e._pixelDensity||1,a=r.width,n=r.height,i=e._getImageData(0,0,a,n).data,o=a,s=0,l=n,d=0,c=3;for(let e=0;e<n;e++)for(let t=0;t<a;t++)0!==i[c]&&(t<o&&(o=t),t>s&&(s=t),e<l&&(l=e),e>d&&(d=e)),c+=4;return l=Math.floor(l/t),d=Math.floor(d/t),o=Math.floor(o/t),s=Math.floor(s/t),e.get(o,l,s-o+1,d-l+1)},e.mask=t=>{e.ctx.save(),e.ctx.resetTransform();let r=e.ctx.globalCompositeOperation;e.ctx.globalCompositeOperation="destination-in",e.ctx.drawImage(t.canvas,0,0),e.ctx.globalCompositeOperation=r,e.ctx.restore(),e.modified=e._retint=!0},e.inset=(t,a,n,i,o,s,l,d)=>{let c=e._pixelDensity||1;e.ctx.drawImage(r,t*c,a*c,n*c,i*c,o,s,l,d),e.modified=e._retint=!0},e.copy=()=>{let t=e.get();for(let r in e)"function"==typeof e[r]||/(canvas|ctx|texture)/.test(r)||(t[r]=e[r]);return t},e.get=(t,a,n,i)=>{let o=e._pixelDensity||1;if(void 0!==t&&void 0===n){let r=e._getImageData(t*o,a*o,1,1).data;return[r[0],r[1],r[2],r[3]/255]}t=Math.floor(t||0)*o,a=Math.floor(a||0)*o,n??=e.width,i??=e.height;let s=e.createImage(n,i,{pixelDensity:o});return s.ctx.drawImage(r,t,a,n*o,i*o,0,0,n,i),s.width=n,s.height=i,s},e.set=(t,r,a)=>{if(t=Math.floor(t),r=Math.floor(r),e.modified=e._retint=!0,a.canvas){let n=e._tint;return e._tint=null,e.image(a,t,r),void(e._tint=n)}e.pixels.length||e.loadPixels();let n=e._pixelDensity||1;for(let i=0;i<n;i++)for(let o=0;o<n;o++){let s=4*((r*n+i)*a.width+t*n+o);e.pixels[s]=a.r,e.pixels[s+1]=a.g,e.pixels[s+2]=a.b,e.pixels[s+3]=a.a}},e.loadPixels=()=>{a=e._getImageData(0,0,r.width,r.height),t.pixels=a.data},e.updatePixels=()=>{null!=a&&(e.ctx.putImageData(a,0,0),e.modified=e._retint=!0)},e.smooth=()=>e.ctx.imageSmoothingEnabled=!0,e.noSmooth=()=>e.ctx.imageSmoothingEnabled=!1,"image"!=e._scope&&(e.tint=function(t){e._tint=(t._q5Color?t:e.color(...arguments)).toString()},e.noTint=()=>e._tint=null)},Q5.Image=class{constructor(e,t,r,a={}){let n=this;n._scope="image",n.canvas=n.ctx=n.drawingContext=null,n.pixels=[],Q5.modules.canvas(n,n);let i=Q5.renderers.c2d;for(let e of["canvas","image","softFilters"])i[e]&&i[e](n,n);n._pixelDensity=a.pixelDensity||1,n.createCanvas(t,r,a);let o=n._pixelDensity*e._defaultImageScale;n.defaultWidth=t*o,n.defaultHeight=r*o,delete n.createCanvas,n._loop=!1}get w(){return this.width}get h(){return this.height}},Q5.renderers.c2d.softFilters=e=>{let t=null;function r(){let r=e.canvas.width*e.canvas.height*4;t&&t.length==r||(t=new Uint8ClampedArray(r))}e._softFilter=(a,n)=>{e._filters||(e._filters=[],e._filters[Q5.THRESHOLD]=(e,t)=>{void 0===t?t=127.5:t*=255;for(let r=0;r<e.length;r+=4){const a=.2126*e[r]+.7152*e[r+1]+.0722*e[r+2];e[r]=e[r+1]=e[r+2]=a>=t?255:0}},e._filters[Q5.GRAY]=e=>{for(let t=0;t<e.length;t+=4){const r=.2126*e[t]+.7152*e[t+1]+.0722*e[t+2];e[t]=e[t+1]=e[t+2]=r}},e._filters[Q5.OPAQUE]=e=>{for(let t=0;t<e.length;t+=4)e[t+3]=255},e._filters[Q5.INVERT]=e=>{for(let t=0;t<e.length;t+=4)e[t]=255-e[t],e[t+1]=255-e[t+1],e[t+2]=255-e[t+2]},e._filters[Q5.POSTERIZE]=(e,t=4)=>{let r=t-1;for(let a=0;a<e.length;a+=4)e[a]=255*(e[a]*t>>8)/r,e[a+1]=255*(e[a+1]*t>>8)/r,e[a+2]=255*(e[a+2]*t>>8)/r},e._filters[Q5.DILATE]=(a,n)=>{n??=Math.max,r(),t.set(a);let[i,o]=[e.canvas.width,e.canvas.height];for(let e=0;e<o;e++)for(let r=0;r<i;r++){let s=4*Math.max(r-1,0),l=4*Math.min(r+1,i-1),d=4*Math.max(e-1,0)*i,c=4*Math.min(e+1,o-1)*i,h=4*e*i,u=4*r;for(let e=0;e<4;e++){let r=e+d,i=e+c,o=e+h;a[h+u+e]=n(t[r+u],t[o+s],t[o+u],t[o+l],t[i+u])}}},e._filters[Q5.ERODE]=t=>{e._filters[Q5.DILATE](t,Math.min)},e._filters[Q5.BLUR]=(a,n)=>{n=n||1,n=Math.floor(n*e._pixelDensity),r(),t.set(a);let i=2*n+1,o=function(e){let t=new Float32Array(e),r=.3*n+.8,a=r*r*2;for(let n=0;n<e;n++){let i=n-e/2,o=Math.exp(-i*i/a)/(2.5066282746*r);t[n]=o}return t}(i),[s,l]=[e.canvas.width,e.canvas.height];for(let e=0;e<l;e++)for(let r=0;r<s;r++){let l=0,d=0,c=0,h=0;for(let a=0;a<i;a++){let i=4*(e*s+Math.min(Math.max(r-n+a,0),s-1));l+=t[i]*o[a],d+=t[i+1]*o[a],c+=t[i+2]*o[a],h+=t[i+3]*o[a]}let u=4*(e*s+r);a[u]=l,a[u+1]=d,a[u+2]=c,a[u+3]=h}t.set(a);for(let e=0;e<l;e++)for(let r=0;r<s;r++){let d=0,c=0,h=0,u=0;for(let a=0;a<i;a++){let i=4*(Math.min(Math.max(e-n+a,0),l-1)*s+r);d+=t[i]*o[a],c+=t[i+1]*o[a],h+=t[i+2]*o[a],u+=t[i+3]*o[a]}let p=4*(e*s+r);a[p]=d,a[p+1]=c,a[p+2]=h,a[p+3]=u}});let i=e._getImageData(0,0,e.canvas.width,e.canvas.height);e._filters[a](i.data,n),e.ctx.putImageData(i,0,0)}},Q5.renderers.c2d.text=(e,t)=>{e._textAlign="left",e._textBaseline="alphabetic",e._textSize=12;let r="sans-serif",a=!1,n=15,i=3,o="normal",s="normal",l=!1,d=0,c=[],h=!1,u=0,p=e._textCache={};e._textCacheMaxSize=12e3,e.loadFont=(t,r)=>{let a;if(t.includes("fonts.googleapis.com/css"))a=function(e,t){e.startsWith("http")||(e="https://"+e);const r=new URL(e).searchParams,a=r.get("family");if(!a)return console.error("Invalid Google Fonts URL: missing family parameter"),null;let n={family:a.split(":")[0]};return n.promise=(async()=>{try{const r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch Google Font: ${r.status} ${r.statusText}`);let a,i=await r.text(),o=/@font-face\s*{([^}]*)}/g,s=/src:\s*url\(([^)]+)\)[^;]*;/,l=/font-family:\s*['"]([^'"]+)['"]/,d=/font-weight:\s*([^;]+);/,c=/font-style:\s*([^;]+);/,h=[];for(;null!==(a=o.exec(i));){let e=a[1],t=s.exec(e);if(!t)continue;let r=t[1],n=l.exec(e);if(!n)continue;let i=n[1],o=d.exec(e),u=o?o[1]:"400",p=c.exec(e),f=p?p[1]:"normal",g=`${i}-${u}-${f}`.replace(/\s+/g,"-"),m=new FontFace(i,`url(${r})`,{weight:u,style:f});document.fonts.add(m);try{await m.load(),h.push(m)}catch(e){console.error(`Failed to load font face: ${g}`,e)}}return n.faces=h,delete n.promise,t&&t(n),n}catch(e){throw console.error("Error loading Google Font:",e),e}})(),n}(t,r);else{let e=t.split("/").pop().split(".")[0].replace(" ","");a=new FontFace(e,`url(${t})`),document.fonts.add(a),a.promise=(async()=>{let e;try{await a.load()}catch(t){e=t}if(delete a.promise,e)throw e;return r&&r(a),a})()}return e._preloadPromises.push(a.promise),e.textFont(a.family),e._usePreload?a:a.promise},e.textFont=e=>{if(e&&"string"!=typeof e&&(e=e.family),!e||e==r)return r;r=e,l=!0,d=-1},e.textSize=t=>{if(null==t)return e._textSize;e._da&&(t*=e._da),e._textSize=t,l=!0,d=-1,a||(n=1.25*t,i=n-t)},e.textStyle=e=>{if(!e)return o;o=e,l=!0,d=-1},e.textWeight=e=>{if(!e)return s;s=e,l=!0,d=-1},e.textLeading=t=>null==t?n||1.25*e._textSize:(a=!0,t==n?n:(e._da&&(t*=e._da),n=t,i=t-e._textSize,void(d=-1))),e.textAlign=(t,r)=>{e.ctx.textAlign=e._textAlign=t,r&&(e.ctx.textBaseline=e._textBaseline=r==e.CENTER?"middle":r)};const f=()=>{e.ctx.font=`${o} ${s} ${e._textSize}px ${r}`,l=!1};e.textWidth=t=>(l&&f(),e.ctx.measureText(t).width),e.textAscent=t=>(l&&f(),e.ctx.measureText(t).actualBoundingBoxAscent),e.textDescent=t=>(l&&f(),e.ctx.measureText(t).actualBoundingBoxDescent),e.textFill=e.fill,e.textStroke=e.stroke;e.createTextImage=(t,r,a)=>{h=!0;let n=e.text(t,0,0,r,a);return h=!1,n};let g=[];e.text=(t,a,s,m,_)=>{if(void 0===t||!e._doFill&&!e._doStroke)return;t=t.toString(),e._da&&(a*=e._da,s*=e._da);let x,v,y,b,w=e.ctx;if(l&&f(),h&&(-1==d&&(()=>{let t=r+e._textSize+o+n,a=5381;for(let e=0;e<t.length;e++)a=33*a^t.charCodeAt(e);d=a>>>0})(),x=p[t],x&&(x=x[d]),x)){if(x._fill==e._fill&&x._stroke==e._stroke&&x._strokeWeight==e._strokeWeight)return x;x.clear()}if(-1==t.indexOf("\n")?g[0]=t:g=t.split("\n"),t.length>m){let e=[];for(let t of g){let r=0;for(;r<t.length;){let a=r+m;if(a>=t.length){e.push(t.slice(r));break}let n=t.lastIndexOf(" ",a);(-1===n||n<r)&&(n=a),e.push(t.slice(r,n)),r=n+1}}g=e}if(h){if(v=0,y=n,x)x.modified=!0;else{let t=e.ctx.textBaseline;e.ctx.textBaseline="alphabetic";let r=w.measureText(" "),a=r.fontBoundingBoxAscent,o=r.fontBoundingBoxDescent;e.ctx.textBaseline=t;let s=0;for(let e of g){let t=w.measureText(e).width;t>s&&(s=t)}let l=Math.ceil(s),d=Math.ceil(n*g.length+o);x=e.createImage.call(e,l,d,{pixelDensity:e._pixelDensity}),x._ascent=a,x._descent=o,x._top=o+i,x._middle=x._top+.5*a+n*(g.length-1)*.5,x._bottom=x._top+a+n*(g.length-1),x._leading=n}x._fill=e._fill,x._stroke=e._stroke,x._strokeWeight=e._strokeWeight,w=x.ctx,w.font=e.ctx.font,w.fillStyle=e._fill,w.strokeStyle=e._stroke,w.lineWidth=e.ctx.lineWidth}else v=a,y=s,"middle"==e._textBaseline?y-=n*(g.length-1)*.5:"bottom"==e._textBaseline&&(y-=n*(g.length-1));e._fillSet||(b=w.fillStyle,w.fillStyle="black");let S=0;for(let t of g)if(e._doStroke&&e._strokeSet&&w.strokeText(t,v,y),e._doFill&&w.fillText(t,v,y),y+=n,S++,S>=_)break;if(g=[],e._fillSet||(w.fillStyle=b),h){if(c.push(d),(p[t]??={})[d]=x,u++,u>e._textCacheMaxSize){let e=Math.ceil(u/2),t=c.splice(0,e);for(let e in p){e=p[e];for(let r of t)delete e[r]}u-=e}return x}},e.textImage=(t,r,a)=>{"string"==typeof t&&(t=e.createTextImage(t));let n=e._imageMode;e._imageMode="corner";let i=e._textAlign;"center"==i?r-=t.canvas.hw:"right"==i&&(r-=t.width);let o=e._textBaseline;"alphabetic"==o?a-=t._leading:"middle"==o?a-=t._middle:"bottom"==o?a-=t._bottom:"top"==o&&(a-=t._top),e.image(t,r,a),e._imageMode=n}},Q5.fonts=[],Q5.modules.color=(e,t)=>{e.RGB=e.RGBA=e.RGBHDR=e._colorMode="rgb",e.HSL="hsl",e.HSB="hsb",e.OKLCH="oklch",e.SRGB="srgb",e.DISPLAY_P3="display-p3",e.colorMode=(r,a,n)=>{e._colorMode=r;let i="srgb"==e.canvas.colorSpace||"srgb"==n;a??="rgb"==r&&(e._c2d||i)?255:1,e._colorFormat="integer"==a||255==a?255:1,"oklch"==r?t.Color=Q5.ColorOKLCH:"hsl"==r?t.Color=i?Q5.ColorHSL:Q5.ColorHSL_P3:"hsb"==r?t.Color=i?Q5.ColorHSB:Q5.ColorHSB_P3:(255==e._colorFormat?t.Color=i?Q5.ColorRGB_8:Q5.ColorRGB_P3_8:t.Color=i?Q5.ColorRGB:Q5.ColorRGB_P3,e._colorMode="rgb")},e._namedColors={aqua:[0,255,255],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],crimson:[220,20,60],cyan:[0,255,255],darkviolet:[148,0,211],gold:[255,215,0],green:[0,128,0],gray:[128,128,128],grey:[128,128,128],hotpink:[255,105,180],indigo:[75,0,130],khaki:[240,230,140],lightgreen:[144,238,144],lime:[0,255,0],magenta:[255,0,255],navy:[0,0,128],orange:[255,165,0],olive:[128,128,0],peachpuff:[255,218,185],pink:[255,192,203],purple:[128,0,128],red:[255,0,0],skyblue:[135,206,235],tan:[210,180,140],turquoise:[64,224,208],transparent:[0,0,0,0],white:[255,255,255],violet:[238,130,238],yellow:[255,255,0]},e.color=(t,r,a,n)=>{let i=e.Color;if(t._q5Color)return new i(...t.levels);if(null==r){if("string"==typeof t){if("#"==t[0])t.length<=5?(t.length>4&&(n=parseInt(t[4]+t[4],16)),a=parseInt(t[3]+t[3],16),r=parseInt(t[2]+t[2],16),t=parseInt(t[1]+t[1],16)):(t.length>7&&(n=parseInt(t.slice(7,9),16)),a=parseInt(t.slice(5,7),16),r=parseInt(t.slice(3,5),16),t=parseInt(t.slice(1,3),16));else{if(!e._namedColors[t]){let e=new i(0,0,0);return e._css=t,e.toString=function(){return this._css},e}[t,r,a,n]=e._namedColors[t]}1==e._colorFormat&&(t/=255,r&&(r/=255),a&&(a/=255),n&&(n/=255))}(Array.isArray(t)||t.constructor==Float32Array)&&([t,r,a,n]=t)}return null==a?e._colorMode==Q5.OKLCH?new i(t,0,0,r):new i(t,t,t,r):new i(t,r,a,n)},e.red=e=>e.r,e.green=e=>e.g,e.blue=e=>e.b,e.alpha=e=>e.a,e.lightness=t=>{if(t.l)return t.l;let r=100*(.2126*t.r+.7152*t.g+.0722*t.b);return 255==e._colorFormat?r/255:r},e.hue=t=>{if(t.h)return t.h;let r=t.r,a=t.g,n=t.b;255==e._colorFormat&&(r/=255,a/=255,n/=255);let i,o=Math.max(r,a,n),s=Math.min(r,a,n);return i=o==s?0:o==r?60*(a-n)/(o-s):o==a?60*(n-r)/(o-s)+120:60*(r-a)/(o-s)+240,i<0&&(i+=360),i},e.lerpColor=(t,r,a)=>{if(a=Math.max(0,Math.min(1,a)),"rgb"==e._colorMode)return new e.Color(e.lerp(t.r,r.r,a),e.lerp(t.g,r.g,a),e.lerp(t.b,r.b,a),e.lerp(t.a,r.a,a));{let n=r.h-t.h;n>180&&(n-=360),n<-180&&(n+=360);let i=t.h+a*n;return i<0&&(i+=360),i>360&&(i-=360),new e.Color(e.lerp(t.l,r.l,a),e.lerp(t.c,r.c,a),i,e.lerp(t.a,r.a,a))}}},Q5.Color=class{constructor(){this._q5Color=!0}get alpha(){return this.a}set alpha(e){this.a=e}},Q5.ColorOKLCH=class extends Q5.Color{constructor(e,t,r,a){super(),this.l=e,this.c=t,this.h=r,this.a=a??1}get levels(){return[this.l,this.c,this.h,this.a]}equals(e){return e&&this.l==e.l&&this.c==e.c&&this.h==e.h&&this.a==e.a}isSameColor(e){return e&&this.l==e.l&&this.c==e.c&&this.h==e.h}toString(){return`oklch(${this.l} ${this.c} ${this.h} / ${this.a})`}get lightness(){return this.l}set lightness(e){this.l=e}get chroma(){return this.c}set chroma(e){this.c=e}get hue(){return this.h}set hue(e){this.h=e}},Q5.ColorRGB=class extends Q5.Color{constructor(e,t,r,a){super(),this.r=e,this.g=t,this.b=r,this.a=a??1}get levels(){return[this.r,this.g,this.b,this.a]}equals(e){return e&&this.r==e.r&&this.g==e.g&&this.b==e.b&&this.a==e.a}isSameColor(e){return e&&this.r==e.r&&this.g==e.g&&this.b==e.b}toString(){return`color(srgb ${this.r} ${this.g} ${this.b} / ${this.a})`}get red(){return this.r}set red(e){this.r=e}get green(){return this.g}set green(e){this.g=e}get blue(){return this.b}set blue(e){this.b=e}},Q5.ColorRGB_P3=class extends Q5.ColorRGB{toString(){return`color(display-p3 ${this.r} ${this.g} ${this.b} / ${this.a})`}},Q5.ColorRGB_8=class extends Q5.ColorRGB{constructor(e,t,r,a){super(e,t,r,a??255)}setRed(e){this.r=e}setGreen(e){this.g=e}setBlue(e){this.b=e}setAlpha(e){this.a=e}toString(){return`rgb(${this.r} ${this.g} ${this.b} / ${this.a/255})`}},Q5.ColorRGB_P3_8=class extends Q5.ColorRGB_8{constructor(e,t,r,a){super(e,t,r,a??255),this._edited=!0}get r(){return this._r}set r(e){this._r=e,this._edited=!0}get g(){return this._g}set g(e){this._g=e,this._edited=!0}get b(){return this._b}set b(e){this._b=e,this._edited=!0}get a(){return this._a}set a(e){this._a=e,this._edited=!0}toString(){if(this._edited){let e=(this._r/255).toFixed(3),t=(this._g/255).toFixed(3),r=(this._b/255).toFixed(3),a=(this._a/255).toFixed(3);this._css=`color(display-p3 ${e} ${t} ${r} / ${a})`,this._edited=!1}return this._css}},Q5.ColorHSL=class extends Q5.Color{constructor(e,t,r,a){super(),this.h=e,this.s=t,this.l=r,this.a=a??1}get levels(){return[this.h,this.s,this.l,this.a]}equals(e){return e&&this.h==e.h&&this.s==e.s&&this.l==e.l&&this.a==e.a}isSameColor(e){return e&&this.h==e.h&&this.s==e.s&&this.l==e.l}toString(){return`hsl(${this.h} ${this.s} ${this.l} / ${this.a})`}get hue(){return this.h}set hue(e){this.h=e}get saturation(){return this.s}set saturation(e){this.s=e}get lightness(){return this.l}set lightness(e){this.l=e}},Q5.ColorHSL_P3=class extends Q5.ColorHSL{toString(){return`color(display-p3 ${Q5.HSLtoRGB(this.h,this.s,this.l).join(" ")} / ${this.a})`}},Q5.ColorHSB=class extends Q5.ColorHSL{constructor(e,t,r,a){super(e,t,r,a),delete this.l,this.b=r}get levels(){return[this.h,this.s,this.b,this.a]}equals(e){return e&&this.h==e.h&&this.s==e.s&&this.b==e.b&&this.a==e.a}isSameColor(e){return e&&this.h==e.h&&this.s==e.s&&this.b==e.b}toString(){return`hsl(${Q5.HSBtoHSL(this.h,this.s,this.b).join(" ")} / ${this.a})`}get v(){return this.b}set v(e){this.b=e}get brightness(){return this.b}set brightness(e){this.b=e}get value(){return this.b}set value(e){this.b=e}},Q5.ColorHSB_P3=class extends Q5.ColorHSB{toString(){return`color(display-p3 ${Q5.HSLtoRGB(...Q5.HSBtoHSL(this.h,this.s,this.b)).join(" ")} / ${this.a})`}},Q5.HSLtoRGB=(e,t,r)=>{r/=100;let a=t/100*Math.min(r,1-r),n=(t,n=(t+e/30)%12)=>r-a*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]},Q5.HSBtoHSL=(e,t,r,a=r*(1-t/200))=>[e,a&&100!=a?(r-a)/Math.min(a,100-a)*100:0,a];{const e=(e,t)=>[e[0]*t[0]+e[1]*t[1]+e[2]*t[2],e[3]*t[0]+e[4]*t[1]+e[5]*t[2],e[6]*t[0]+e[7]*t[1]+e[8]*t[2]],t=(e,t,r)=>[e,isNaN(r)?0:t*Math.cos(r*Math.PI/180),isNaN(r)?0:t*Math.sin(r*Math.PI/180)],r=e=>e.map((e=>Math.max(0,Math.min(1,Math.abs(e)>.0031308?(e<0?-1:1)*(1.055*Math.abs(e)**(1/2.4)-.055):12.92*e)))),a=t=>{const r=e([1,.3963377773761749,.2158037573099136,1,-.1055613458156586,-.0638541728258133,1,-.0894841775298119,-1.2914855480194092],t);return e([1.2268798758459243,-.5578149944602171,.2813910456659647,-.0405757452148008,1.112286803280317,-.0717110580655164,-.0763729366746601,-.4214933324022432,1.5869240198367816],r.map((e=>e**3)))},n=t=>e([3.2409699419045226,-1.537383177570094,-.4986107602930034,-.9692436362808796,1.8759675015077202,.04155505740717559,.05563007969699366,-.20397695888897652,1.0569715142428786],t);Q5.OKLCHtoRGB=(e,i,o)=>r(n(a(t(e,i,o))))}Q5.modules.display=e=>{if(!e.canvas||"graphics"==e._scope)return;let t=e.canvas;e.MAXED="maxed",e.SMOOTH="smooth",e.PIXELATED="pixelated",0!=Q5._instanceCount||Q5._server||document.head.insertAdjacentHTML("beforeend","<style>\nhtml, body {\n\tmargin: 0;\n\tpadding: 0;\n}\n.q5Canvas {\n\toutline: none;\n\t-webkit-touch-callout: none;\n\t-webkit-text-size-adjust: none;\n\t-webkit-user-select: none;\n\toverscroll-behavior: none;\n}\n.q5-pixelated {\n\timage-rendering: pixelated;\n\tfont-smooth: never;\n\t-webkit-font-smoothing: none;\n}\n.q5-centered,\n.q5-maxed {\n display: flex;\n\talign-items: center;\n\tjustify-content: center;\n}\nmain.q5-centered,\nmain.q5-maxed {\n\theight: 100vh;\n}\nmain {\n\toverscroll-behavior: none;\n}\n</style>"),e._adjustDisplay=()=>{let r=t.style,a=t.parentElement;r&&a&&t.displayMode&&("pixelated"==t.renderQuality&&(t.classList.add("q5-pixelated"),e.pixelDensity(1),e.defaultImageScale(1),e.noSmooth&&e.noSmooth(),e.textFont&&e.textFont("monospace")),"normal"==t.displayMode?(a.classList.remove("q5-centered","q5-maxed"),r.width=t.w*t.displayScale+"px",r.height=t.h*t.displayScale+"px"):(a.classList.add("q5-"+t.displayMode),a=a.getBoundingClientRect(),t.w/t.h>a.width/a.height?("centered"==t.displayMode?(r.width=t.w*t.displayScale+"px",r.maxWidth="100%"):r.width="100%",r.height="auto",r.maxHeight=""):(r.width="auto",r.maxWidth="","centered"==t.displayMode?(r.height=t.h*t.displayScale+"px",r.maxHeight="100%"):r.height="100%")))},e.displayMode=(r="normal",a="smooth",n=1)=>{"string"==typeof n&&(n=parseFloat(n.slice(1))),"fullscreen"==r&&(r="maxed"),"center"==r&&(r="centered"),Object.assign(t,{displayMode:r,renderQuality:a,displayScale:n}),e.ctx&&e.pushStyles(),e._adjustDisplay(),e.ctx&&e.popStyles()},e.fullscreen=e=>{if(null==e)return document.fullscreenElement;e?document.body.requestFullscreen():document.body.exitFullscreen()}},Q5.modules.dom=(e,t)=>{e.elementMode=t=>e._elementMode=t,e.createElement=(t,r)=>{let a=document.createElement(t);return"center"==e._elementMode&&(a.style.transform="translate(-50%, -50%)"),r&&(a.innerHTML=r),Object.defineProperty(a,"x",{get:()=>a._x,set:t=>{let r=a.style.position;r&&"relative"!=r||(a.style.position="absolute");let n=e.canvas.offsetLeft+t;a.style.left=n+"px",a._x=n}}),Object.defineProperty(a,"y",{get:()=>a._y,set:t=>{let r=a.style.position;r&&"relative"!=r||(a.style.position="absolute");let n=e.canvas.offsetTop+t;a.style.top=n+"px",a._y=n}}),Object.defineProperty(a,"width",{get:()=>parseFloat(a.style.width||0),set:e=>a.style.width=e+"px"}),Object.defineProperty(a,"height",{get:()=>parseFloat(a.style.height||0),set:e=>a.style.height=e+"px"}),a.position=(e,t,r)=>(r&&(a.style.position=r),a.x=e,a.y=t,a),Object.defineProperty(a,"size",{writable:!0}),a.size=(e,t)=>(a.width=e,a.height=t,a),a.center=()=>(a.style.position="absolute",a.x=e.canvas.hw,a.y=e.canvas.hh,a),a.show=()=>(a.style.display="",a),a.hide=()=>(a.style.display="none",a),a.parent=e=>(e.append(a),a),e._addEventMethods(a),e._elements.push(a),e.canvas?e.canvas.parentElement.append(a):document.body.append(a),a.elt=a,a},e.createEl=e.createElement,e._addEventMethods=e=>{let t=e.addEventListener;e.mousePressed=e=>t("mousedown",e),e.mouseReleased=e=>t("mouseup",e),e.mouseClicked=e=>t("click",e),e.mouseMoved=e=>t("mousemove",e),e.mouseWheel=e=>t("wheel",e)},e.createA=(t,r,a)=>{let n=e.createEl("a",r);return n.href=t,n.target=a?"_blank":"_self",n},e.createButton=t=>e.createEl("button",t),e.createCheckbox=(t="",r=!1)=>{let a=e.createEl("input");a.type="checkbox",a.checked=r;let n=e.createEl("label",t);return n.addEventListener("click",(()=>{a.checked=!a.checked,a.dispatchEvent(new Event("input",{bubbles:!0})),a.dispatchEvent(new Event("change",{bubbles:!0}))})),a.insertAdjacentElement("afterend",n),a.label=n,a},e.createColorPicker=(t="#ffffff")=>{let r=e.createEl("input");return r.type="color",r.value=t.toString(),r},e.createDiv=t=>e.createEl("div",t),e.createImg=t=>{let r=e.createEl("img");return r.crossOrigin="anonymous",r.src=t,r},e.createInput=(t="",r="text")=>{let a=e.createEl("input");return a.value=t,a.type=r,a.style.boxSizing="border-box",a},e.createP=t=>e.createEl("p",t);let r=0;e.createRadio=t=>{let a=e.createEl("div");return a.name=t||"radio"+r++,a.buttons=[],Object.defineProperty(a,"value",{get:()=>a.selected?.value,set:e=>{let t=a.buttons.find((t=>t.value==e));t&&(t.checked=!0,a.selected=t)}}),a.option=(t,r)=>{let n=e.createEl("input");n.type="radio",n.name=a.name,n.value=r||t,n.addEventListener("input",(()=>a.selected=n));let i=e.createEl("label",t);return i.addEventListener("click",(()=>{n.checked=!0,a.selected=n,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))})),n.label=i,a.append(n),a.append(i),a.buttons.push(n),a},a},e.createSelect=t=>{let r=e.createEl("select");if(t){let a=e.createEl("option",t);a.disabled=!0,a.selected=!0,r.append(a)}return Object.defineProperty(r,"selected",{get:()=>r.multiple?Array.from(r.selectedOptions).map((e=>e.textContent)):r.selectedOptions[0]?.textContent,set:e=>{if(r.multiple)Array.from(r.options).forEach((t=>{t.selected=e.includes(t.textContent)}));else{const t=Array.from(r.options).find((t=>t.textContent===e));t&&(t.selected=!0)}}}),Object.defineProperty(r,"value",{get:()=>r.multiple?Array.from(r.selectedOptions).map((e=>e.value)):r.selectedOptions[0]?.value,set:e=>{if(r.multiple)r.options.forEach((t=>t.selected=e.includes(t.value)));else{let t;for(let a=0;a<r.options.length;a++)if(r.options[a].value==e){t=r.options[a];break}t&&(t.selected=!0)}}}),r.option=(t,a)=>{let n=e.createEl("option",t);return n.value=a||t,r.append(n),r},r},e.createSlider=(t,r,a,n)=>{let i=e.createEl("input");return i.type="range",i.min=t,i.max=r,i.value=a,i.step=n,i.val=()=>parseFloat(i.value),i},e.createSpan=t=>e.createEl("span",t),e.createVideo=t=>{let r=e.createEl("video");return r.crossOrigin="anonymous",r._load=()=>{r.width||=r.videoWidth,r.height||=r.videoHeight,r.defaultWidth=r.width*e._defaultImageScale,r.defaultHeight=r.height*e._defaultImageScale,r.ready=!0},t&&(r.promise=new Promise((e=>{r.addEventListener("loadeddata",(()=>{r._load(),e(r)})),r.src=t})),e._preloadPromises.push(r.promise),!e._usePreload)?r.promise:r},e.createCapture=function(t,r=!0,a){let n="string"==typeof t?{[t]:!0}:t||{video:!0,audio:!0};!0===n.video&&(n.video={width:3840,height:2160}),n.video.facingMode??="user";let i=e.createVideo();return i.playsinline=i.autoplay=!0,r&&(i.flipped=!0,i.style.transform="scale(-1, 1)"),i.loadPixels=()=>{let t=e.createGraphics(i.videoWidth,i.videoHeight,{renderer:"c2d"});t.image(i,0,0),t.loadPixels(),i.pixels=t.pixels,t.remove()},i.promise=(async()=>{let e;try{e=await navigator.mediaDevices.getUserMedia(n)}catch(e){throw e}return i.srcObject=e,await new Promise((e=>i.addEventListener("loadeddata",e))),i._load(),a&&a(i),i})(),e._preloadPromises.push(i.promise),e._usePreload?i:i.promise},e.findElement=e=>document.querySelector(e),e.findElements=e=>document.querySelectorAll(e)},Q5.modules.fes=e=>{e._fes=async t=>{if(Q5.disableFriendlyErrors)return;let r=t.stack?.split("\n");if(!t.stack||r.length<=1)return;let a=1,n="(";for(-1==navigator.userAgent.indexOf("Chrome")&&(a=0,n="@");r[a].indexOf("q5")>=0;)a++;let i=r[a].split(n).at(-1);i.startsWith("blob:")&&(i=i.slice(5));let o=i.split(":"),s=parseInt(o.at(-2));o[o.length-1]=o.at(-1).split(")")[0];let l=o.slice(0,-2).join(":"),d=l.split("/").at(-1);try{let t=(await(await fetch(l)).text()).split("\n")[s-1].trim(),r=["🐛","🐞","🐜","🦗","🦋","🪲"][Math.floor(6*Math.random())];e.log("%cq5.js "+r+"%c Error in "+d+" on line "+s+":\n\n"+t,"background: #b7ebff; color: #000;","")}catch(e){}}},Q5.modules.input=(e,t)=>{if("graphics"==e._scope)return;e.mouseX=0,e.mouseY=0,e.pmouseX=0,e.pmouseY=0,e.touches=[],e.mouseButton="",e.keyIsPressed=!1,e.mouseIsPressed=!1,e.key="",e.keyCode=0,e.UP_ARROW=38,e.DOWN_ARROW=40,e.LEFT_ARROW=37,e.RIGHT_ARROW=39,e.SHIFT=16,e.TAB=9,e.BACKSPACE=8,e.ENTER=e.RETURN=13,e.ALT=e.OPTION=18,e.CONTROL=17,e.DELETE=46,e.ESCAPE=27,e.ARROW="default",e.CROSS="crosshair",e.HAND="pointer",e.MOVE="move",e.TEXT="text";let r={},a=[Q5.LEFT,Q5.CENTER,Q5.RIGHT],n=e.canvas;e._startAudio=()=>{Q5.aud&&"running"==Q5.aud?.state||e.userStartAudio()},e._updateMouse=r=>{if(!r.changedTouches){if(document.pointerLockElement)t.mouseX+=r.movementX,t.mouseY+=r.movementY;else if(n){let a=n.getBoundingClientRect(),i=n.scrollWidth/e.width||1,o=n.scrollHeight/e.height||1;t.mouseX=(r.clientX-a.left)/i,t.mouseY=(r.clientY-a.top)/o,e._webgpu&&(t.mouseX-=n.hw,t.mouseY-=n.hh)}else t.mouseX=r.clientX,t.mouseY=r.clientY;t.moveX=r.movementX,t.moveY=r.movementY}};let i=0;function o(t){const r=e.canvas.getBoundingClientRect(),a=e.canvas.scrollWidth/e.width||1,n=e.canvas.scrollHeight/e.height||1;let i=0,o=0;return e._webgpu&&(i=e.halfWidth,o=e.halfHeight),{x:(t.clientX-r.left)/a-i,y:(t.clientY-r.top)/n-o,id:t.identifier}}if(e._onmousedown=r=>{i++,e._startAudio(),e._updateMouse(r),t.mouseIsPressed=!0,t.mouseButton=a[r.button],e.mousePressed(r)},e._onmousemove=t=>{n&&!n.visible||(e._updateMouse(t),e.mouseIsPressed?e.mouseDragged(t):e.mouseMoved(t))},e._onmouseup=r=>{t.mouseIsPressed=!1,i>0&&(i--,e._updateMouse(r),e.mouseReleased(r))},e._onclick=r=>{e._updateMouse(r),t.mouseIsPressed=!0,e.mouseClicked(r),t.mouseIsPressed=!1},e._ondblclick=r=>{e._updateMouse(r),t.mouseIsPressed=!0,e.doubleClicked(r),t.mouseIsPressed=!1},e._onwheel=t=>{e._updateMouse(t),t.delta=t.deltaY;let r=e.mouseWheel(t);(e._isGlobal&&!r||0==r)&&t.preventDefault()},e.cursor=(t,r,a)=>{let n="";t.includes(".")&&(t=`url("${t}")`,n=", auto"),void 0!==r&&(t+=" "+r+" "+a),e.canvas.style.cursor=t+n},e.noCursor=()=>e.canvas.style.cursor="none",e.pointerLock=(e=!1)=>{document.body?.requestPointerLock({unadjustedMovement:e})},e._onkeydown=a=>{a.repeat||(e._startAudio(),t.keyIsPressed=!0,t.key=a.key,t.keyCode=a.keyCode,r[e.keyCode]=r[e.key.toLowerCase()]=!0,e.keyPressed(a),1==a.key.length&&e.keyTyped(a))},e._onkeyup=a=>{t.keyIsPressed=!1,t.key=a.key,t.keyCode=a.keyCode,r[e.keyCode]=r[e.key.toLowerCase()]=!1,e.keyReleased(a)},e.keyIsDown=e=>!!r["string"==typeof e?e.toLowerCase():e],e._ontouchstart=r=>{e._startAudio(),t.touches=[...r.touches].map(o),e.touchStarted(r)||r.preventDefault()},e._ontouchmove=r=>{n&&!n.visible||(t.touches=[...r.touches].map(o),e.touchMoved(r)||r.preventDefault())},e._ontouchend=r=>{t.touches=[...r.touches].map(o),e.touchEnded(r)||r.preventDefault()},window){let t=window.addEventListener;t("keydown",(t=>e._onkeydown(t)),!1),t("keyup",(t=>e._onkeyup(t)),!1);let r=window.PointerEvent?"pointer":"mouse";t(r+"move",(t=>e._onmousemove(t)),!1),t("touchmove",(t=>e._ontouchmove(t))),t(r+"up",(t=>e._onmouseup(t))),t("touchend",(t=>e._ontouchend(t))),t("touchcancel",(t=>e._ontouchend(t))),n&&n.addEventListener("wheel",(t=>e._onwheel(t))),!e._isGlobal&&n&&(t=n.addEventListener.bind(n)),t(r+"down",(t=>e._onmousedown(t))),t("touchstart",(t=>e._ontouchstart(t))),t("click",(t=>e._onclick(t))),t("dblclick",(t=>e._ondblclick(t)))}},Q5.modules.math=(e,t)=>{e.RADIANS=0,e.DEGREES=1,e.PI=Math.PI,e.HALF_PI=Math.PI/2,e.QUARTER_PI=Math.PI/4,e.TWO_PI=e.TAU=2*Math.PI,e.abs=Math.abs,e.ceil=Math.ceil,e.exp=Math.exp,e.floor=e.int=Math.floor,e.loge=Math.log,e.mag=Math.hypot,e.max=Math.max,e.min=Math.min,e.pow=Math.pow,e.sqrt=Math.sqrt,e.SHR3=1,e.LCG=2,e.round=(e,t=0)=>{let r=10**t;return Math.round(e*r)/r};let r=e._angleMode=0;e.angleMode=t=>(r=e._angleMode=0==t||"radians"==t?0:1,r?"degrees":"radians");let a=e._DEGTORAD=Math.PI/180,n=e._RADTODEG=180/Math.PI;function i(){let e,t,r=4294967295;return{setSeed(a){e=t=(a??Math.random()*r)>>>0},getSeed:()=>t,rand:()=>(e^=e<<17,e^=e>>13,e^=e<<5,(e>>>0)/r)}}e.degrees=t=>t*e._RADTODEG,e.radians=t=>t*e._DEGTORAD,e.map=Q5.prototype.map=(e,t,r,a,n,i)=>{let o=a+1*(e-t)/(r-t)*(n-a);return i?a<n?Math.min(Math.max(o,a),n):Math.min(Math.max(o,n),a):o},e.dist=function(){let e=arguments;return 2==e.length?Math.hypot(e[0].x-e[1].x,e[0].y-e[1].y):4==e.length?Math.hypot(e[0]-e[2],e[1]-e[3]):Math.hypot(e[0]-e[3],e[1]-e[4],e[2]-e[5])},e.lerp=(e,t,r)=>e*(1-r)+t*r,e.constrain=(e,t,r)=>Math.min(Math.max(e,t),r),e.norm=(t,r,a)=>e.map(t,r,a,0,1),e.sq=e=>e*e,e.fract=e=>e-Math.floor(e),e.sin=e=>Math.sin(r?e*a:e),e.cos=e=>Math.cos(r?e*a:e),e.tan=e=>Math.tan(r?e*a:e),e.asin=e=>{let t=Math.asin(e);return r?t*n:t},e.acos=e=>{let t=Math.acos(e);return r?t*n:t},e.atan=e=>{let t=Math.atan(e);return r?t*n:t},e.atan2=(e,t)=>{let a=Math.atan2(e,t);return r?a*n:a};let o=i();o.setSeed(),e.randomSeed=e=>o.setSeed(e),e.random=(e,t)=>void 0===e?o.rand():"number"==typeof e?void 0!==t?o.rand()*(t-e)+e:o.rand()*e:e[Math.trunc(e.length*o.rand())],e.jit=(t=1)=>e.random(-t,t),e.randomGenerator=t=>{t==e.LCG?o=function(){const e=4294967296;let t,r;return{setSeed(a){r=t=(a??Math.random()*e)>>>0},getSeed:()=>t,rand:()=>(r=(1664525*r+1013904223)%e,r/e)}}():t==e.SHR3&&(o=i()),o.setSeed()};var s=new function(){var e,t,r,a=new Array(128),n=new Array(256),i=new Array(128),s=new Array(128),l=new Array(256),d=new Array(256),c=()=>4294967296*o.rand()-2147483648,h=()=>.5+2.328306e-10*(c()|0),u=()=>{for(var t,n,o,l,d=3.44262;;){if(t=r*i[e],0==e){do{o=h(),l=h(),t=.2904764*-Math.log(o),n=-Math.log(l)}while(n+n<t*t);return r>0?d+t:-d-t}if(s[e]+h()*(s[e-1]-s[e])<Math.exp(-.5*t*t))return t;if(r=c(),e=127&r,Math.abs(r)<a[e])return r*i[e]}},p=()=>{for(var r;;){if(0==e)return 7.69711-Math.log(h());if(r=t*l[e],d[e]+h()*(d[e-1]-d[e])<Math.exp(-r))return r;if((t=c())<n[e=255&t])return t*l[e]}};this.SHR3=c,this.UNI=h,this.RNOR=()=>(r=c(),e=127&r,Math.abs(r)<a[e]?r*i[e]:u()),this.REXP=()=>(t=c()>>>0)<a[e=255&t]?t*l[e]:p(),this.zigset=()=>{var e,t,r=2147483648,o=4294967296,c=3.442619855899,h=c,u=.00991256303526217,p=7.697117470131487,f=p,g=.003949659822581572;for(e=u/Math.exp(-.5*c*c),a[0]=Math.floor(c/e*r),a[1]=0,i[0]=e/r,i[127]=c/r,s[0]=1,s[127]=Math.exp(-.5*c*c),t=126;t>=1;t--)c=Math.sqrt(-2*Math.log(u/c+Math.exp(-.5*c*c))),a[t+1]=Math.floor(c/h*r),h=c,s[t]=Math.exp(-.5*c*c),i[t]=c/r;for(e=g/Math.exp(-p),n[0]=Math.floor(p/e*o),n[1]=0,l[0]=e/o,l[255]=p/o,d[0]=1,d[255]=Math.exp(-p),t=254;t>=1;t--)p=-Math.log(g/p+Math.exp(-p)),n[t+1]=Math.floor(p/f*o),f=p,d[t]=Math.exp(-p),l[t]=p/o}};let l;s.hasInit=!1,e.randomGaussian=(e,t)=>(s.hasInit||(s.zigset(),s.hasInit=!0),s.RNOR()*t+e),e.randomExponential=()=>(s.hasInit||(s.zigset(),s.hasInit=!0),s.REXP()),e.PERLIN="perlin",e.SIMPLEX="simplex",e.BLOCKY="blocky",e.NoiseGenerator=Q5.PerlinNoise,e.noiseMode=e=>{t.NoiseGenerator=Q5[e[0].toUpperCase()+e.slice(1)+"Noise"],l=null},e.noiseSeed=t=>{l=new e.NoiseGenerator(t)},e.noise=(t=0,r=0,a=0)=>(l??=new e.NoiseGenerator,l.noise(t,r,a)),e.noiseDetail=(t,r)=>{l??=new e.NoiseGenerator,t>0&&(l.octaves=t),r>0&&(l.falloff=r)}},Q5.NoiseGenerator=class{},Q5.PerlinNoise=class extends Q5.NoiseGenerator{constructor(e){super(),this.grad3=[[1,1,0],[-1,1,0],[1,-1,0],[-1,-1,0],[1,0,1],[-1,0,1],[1,0,-1],[-1,0,-1],[0,1,1],[0,-1,1],[0,1,-1],[0,-1,-1]],this.octaves=1,this.falloff=.5,this.p=null==e?Array.from({length:256},(()=>Math.floor(256*Math.random()))):this.seedPermutation(e),this.p=this.p.concat(this.p)}seedPermutation(e){let t,r,a=[];for(let e=0;e<256;e++)a[e]=e;for(let n=255;n>0;n--)t=(e=16807*e%2147483647)%(n+1),r=a[n],a[n]=a[t],a[t]=r;return a}dot(e,t,r,a){return e[0]*t+e[1]*r+e[2]*a}mix(e,t,r){return(1-r)*e+r*t}fade(e){return e*e*e*(e*(6*e-15)+10)}noise(e,t,r){let a=this,n=0,i=1,o=1,s=0;for(let l=0;l<a.octaves;l++){const l=255&Math.floor(e*i),d=255&Math.floor(t*i),c=255&Math.floor(r*i),h=e*i-Math.floor(e*i),u=t*i-Math.floor(t*i),p=r*i-Math.floor(r*i),f=a.fade(h),g=a.fade(u),m=a.fade(p),_=a.p[l]+d,x=a.p[_]+c,v=a.p[_+1]+c,y=a.p[l+1]+d,b=a.p[y]+c,w=a.p[y+1]+c,S=a.mix(a.dot(a.grad3[a.p[x]%12],h,u,p),a.dot(a.grad3[a.p[b]%12],h-1,u,p),f),C=a.mix(a.dot(a.grad3[a.p[v]%12],h,u-1,p),a.dot(a.grad3[a.p[w]%12],h-1,u-1,p),f),M=a.mix(a.dot(a.grad3[a.p[x+1]%12],h,u,p-1),a.dot(a.grad3[a.p[b+1]%12],h-1,u,p-1),f),Q=a.mix(a.dot(a.grad3[a.p[v+1]%12],h,u-1,p-1),a.dot(a.grad3[a.p[w+1]%12],h-1,u-1,p-1),f),P=a.mix(S,C,g),E=a.mix(M,Q,g);n+=a.mix(P,E,m)*o,s+=o,o*=a.falloff,i*=2}return(n/s+1)/2}},Q5.modules.record=(e,t)=>{let r,a,n,i,o,s,l;function d(t={}){document.head.insertAdjacentHTML("beforeend","<style>\n.rec {\n\tdisplay: flex;\n\tz-index: 1000;\n\tgap: 6px;\n\tbackground: #1a1b1d;\n\tpadding: 6px 8px;\n\tborder-radius: 21px;\n\tbox-shadow: #0000001a 0px 4px 12px;\n\tborder: 2px solid transparent; \n\topacity: 0.6;\n\ttransition: all 0.3s;\n\twidth: 134px;\n\toverflow: hidden;\n}\n\n.rec:hover {\n\twidth: unset;\n\topacity: 0.96;\n}\n\n.rec.recording { border-color: #cc3e44; }\n\n.rec button,\n.rec select { cursor: pointer; }\n\n.rec button,\n.rec select,\n.rec input,\n.rec span {\n\tfont-family: sans-serif;\n\tfont-size: 14px;\n\tpadding: 2px 10px;\n\tborder-radius: 18px;\n\toutline: none;\n\tbackground: #232529;\n\tcolor: #d4dae6;\n\tbox-shadow: #0000001a 0px 4px 12px;\n\tborder: 1px solid #46494e;\n\tvertical-align: middle;\n\tline-height: 18px;\n\ttransition: all 0.3s;\n}\n\n.rec .audio-toggle {\n\tfont-size: 16px;\n\tpadding: 2px 10px;\n}\n\n.rec .bitrate input {\n\tborder-radius: 18px 0 0 18px;\n\tborder-right: 0;\n\twidth: 40px;\n\tpadding: 2px 5px 2px 10px;\n\ttext-align: right;\n}\n\n.rec .bitrate span {\n\tborder-radius: 0 18px 18px 0;\n\tborder-left: 0;\n\tpadding: 2px 10px 2px 5px;\n\tbackground: #333;\n}\n\n.rec .record-button { \n\tcolor: #cc3e44;\n\tfont-size: 18px;\n}\n\n.rec select:hover,\n.rec button:hover { background: #32343b; }\n\n.rec button:disabled {\n\topacity: 0.5;\n\tcolor: #969ba5;\n\tcursor: not-allowed;\n}\n</style>"),r=e.createEl("div"),r.className="rec",r.innerHTML='\n<button class="record-button"></button>\n<span class="record-timer"></span>\n<button></button>\n',[a,i,n]=r.children,r.x=r.y=8,r.resetTimer=()=>r.time={hours:0,minutes:0,seconds:0,frames:0},r.resetTimer();let d="video/mp4; codecs=";r.formats={"H.264":d+'"avc1.42E01E"',VP9:d+"vp9"};let u=d+'"avc1.640034"';e.canvas.width*e.canvas.height>32e5&&MediaRecorder.isTypeSupported(u)&&(r.formats["H.264"]=u),Object.assign(r.formats,t.formats),o=e.createSelect("format");for(const e in r.formats)o.option(e,r.formats[e]);o.title="Video Format",r.append(o);let g=e.createEl("div");g.className="bitrate",g.style.display="flex",r.append(g),s=e.createInput();let m=document.createElement("span");function _(){r.encoderSettings.mimeType=o.value}function x(){r.encoderSettings.videoBitsPerSecond=1e6*s.value}m.textContent="mbps",s.title=m.title="Video Bitrate",g.append(s),g.append(m),l=e.createEl("button"),l.className="audio-toggle active",l.textContent="🔊",l.title="Toggle Audio Recording",r.append(l),r.captureAudio=!0,l.addEventListener("click",(()=>{r.captureAudio=!r.captureAudio,l.textContent=r.captureAudio?"🔊":"🔇",l.classList.toggle("active",r.captureAudio)})),r.encoderSettings={},o.addEventListener("change",_),s.addEventListener("change",x),Object.defineProperty(r,"bitrate",{get:()=>s.value,set:e=>{s.value=e,x()}}),Object.defineProperty(r,"format",{get:()=>o.selected,set:e=>{e=e.toUpperCase(),r.formats[e]&&(o.selected=e,_())}}),r.format="H.264";let v=e.canvas.height;r.bitrate=v>=4320?96:v>=2160?64:v>=1440?48:v>=1080?32:v>=720?26:16,a.addEventListener("click",(()=>{e.recording?r.paused?h():e.pauseRecording():c()})),n.addEventListener("click",(()=>{r.paused?e.saveRecording():e.deleteRecording()})),p(),e.registerMethod("post",f)}function c(){if(!e.recording){if(e.userStartAudio(),!r.stream){r.frameRate??=e.getTargetFrameRate();let t=e.canvas.captureStream(r.frameRate);if(r.videoTrack=t.getVideoTracks()[0],r.captureAudio&&e.getAudioContext){let t=e.getAudioContext(),a=t.createMediaStreamDestination();t.destination.input?t.destination.input.connect(a):Q5.soundOut.connect(a),r.audioTrack=a.stream.getAudioTracks()[0],r.stream=new MediaStream([r.videoTrack,r.audioTrack])}else r.stream=t}r.mediaRecorder=new MediaRecorder(r.stream,r.encoderSettings),r.chunks=[],r.mediaRecorder.addEventListener("dataavailable",(e=>{e.data.size>0&&r.chunks.push(e.data)})),r.mediaRecorder.start(),t.recording=!0,r.paused=!1,r.classList.add("recording"),r.resetTimer(),p(!0)}}function h(){e.recording&&r.paused&&(r.mediaRecorder.resume(),r.paused=!1,p(!0))}function u(){e.recording&&(r.resetTimer(),r.mediaRecorder.stop(),t.recording=!1,r.paused=!1,r.classList.remove("recording"))}function p(e){a.textContent=e?"⏸":"⏺",a.title=(e?"Pause":"Start")+" Recording",n.textContent=e?"🗑️":"💾",n.title=(e?"Delete":"Save")+" Recording",n.disabled=!e}function f(){if(e.recording&&!r.paused){r.time.frames++;let t=e.getTargetFrameRate();r.time.frames>=t&&(r.time.seconds+=Math.floor(r.time.frames/t),r.time.frames%=t,r.time.seconds>=60&&(r.time.minutes+=Math.floor(r.time.seconds/60),r.time.seconds%=60,r.time.minutes>=60&&(r.time.hours+=Math.floor(r.time.minutes/60),r.time.minutes%=60)))}i.textContent=function(){let{hours:e,minutes:t,seconds:a,frames:n}=r.time;return`${String(e).padStart(2,"0")}:${String(t).padStart(2,"0")}:${String(a).padStart(2,"0")}:${String(n).padStart(2,"0")}`}()}e.recording=!1,e.createRecorder=e=>(r||d(e),r),e.record=t=>{r||(d(t),r.hide()),e.recording?r.paused&&h():c()},e.pauseRecording=()=>{e.recording&&!r.paused&&(r.mediaRecorder.pause(),r.paused=!0,p(),a.title="Resume Recording",n.disabled=!1)},e.deleteRecording=()=>{u(),p(),t.recording=!1},e.saveRecording=async a=>{if(!e.recording)return;await new Promise((e=>{r.mediaRecorder.onstop=e,u()}));let n=r.encoderSettings.mimeType,i=n.slice(6,n.indexOf(";")),o=URL.createObjectURL(new Blob(r.chunks,{type:n})),s=document.createElement("iframe"),l=document.createElement("a");s.style.display="none",s.name="download_"+Date.now(),document.body.append(s),l.target=s.name,l.href=o,a??=document.title+" "+(new Date).toLocaleString(void 0,{hour12:!1}).replace(","," at").replaceAll("/","-").replaceAll(":","_"),l.download=`${a}.${i}`,await new Promise((e=>{s.onload=()=>{document.body.removeChild(s),e()},l.click()})),setTimeout((()=>URL.revokeObjectURL(o)),1e3),p(),t.recording=!1}},Q5.modules.sound=(e,t)=>{e.Sound=Q5.Sound;let r=[];e.loadSound=(t,a)=>{let n=new Q5.Sound;return r.push(n),n.promise=(async()=>{let e;try{await n.load(t)}catch(t){e=t}if(delete n.promise,e)throw e;return a&&a(n),n})(),e._preloadPromises.push(n.promise),e._usePreload?n:n.promise},e.loadAudio=(t,r)=>{let a=new Audio(t);return a.crossOrigin="Anonymous",a.promise=new Promise(((e,t)=>{a.addEventListener("canplaythrough",(()=>{a.loaded||(a.loaded=!0,r&&r(a),e(a))})),a.addEventListener("suspend",e),a.addEventListener("error",t)})),e._preloadPromises.push(a.promise),e._usePreload?a:a.promise},e.getAudioContext=()=>Q5.aud,e.userStartAudio=()=>{if(window.AudioContext){if(Q5._offlineAudio){Q5._offlineAudio=!1,Q5.aud=new window.AudioContext,Q5.soundOut=Q5.aud.createGain(),Q5.soundOut.connect(Q5.aud.destination);for(let e of Q5.instances)e._userAudioStarted()}return Q5.aud.resume()}},e._userAudioStarted=()=>{for(let e of r)e.init()},e.outputVolume=e=>{Q5.soundOut&&(Q5.soundOut.gain.value=e)}},window.OfflineAudioContext&&(Q5.aud=new window.OfflineAudioContext(2,1,44100),Q5._offlineAudio=!0,Q5.soundOut=Q5.aud.createGain(),Q5.soundOut.connect(Q5.aud.destination)),Q5.Sound=class{constructor(){this.sources=new Set,this.loaded=this.paused=!1}async load(e){this.url=e;let t=await fetch(e);this.buffer=await t.arrayBuffer(),this.buffer=await Q5.aud.decodeAudioData(this.buffer),Q5.aud&&this.init()}init(){this.gainNode=Q5.aud.createGain(),this.pannerNode=Q5.aud.createStereoPanner(),this.gainNode.connect(this.pannerNode),this.pannerNode.connect(Q5.soundOut),this.loaded=!0,this._volume&&(this.volume=this._volume),this._pan&&(this.pan=this._pan)}_newSource(e,t){let r=Q5.aud.createBufferSource();r.buffer=this.buffer,r.connect(this.gainNode),r.loop=this._loop,r._startedAt=Q5.aud.currentTime,r._offset=e,r._duration=t,r.start(0,r._offset,r._duration),this.sources.add(r),r.onended=()=>{this.paused||(this.ended=!0,this._onended&&this._onended(),this.sources.delete(r))}}play(e=0,t){if(this.loaded){if(this.paused){let e=[];for(let t of this.sources)e.push(t._offset,t._duration),this.sources.delete(t);for(let t=0;t<e.length;t+=2)this._newSource(e[t],e[t+1])}else this._newSource(e,t);this.paused=this.ended=!1}}pause(){if(this.isPlaying()){for(let e of this.sources){e.stop();let t=Q5.aud.currentTime-e._startedAt;e._offset+=t,e._duration&&(e._duration-=t)}this.paused=!0}}stop(){for(let e of this.sources)e.stop(),this.sources.delete(e);this.paused=!1,this.ended=!0}get volume(){return this._volume}set volume(e){this.loaded&&(this.gainNode.gain.value=e),this._volume=e}get pan(){return this._pan}set pan(e){this.loaded&&(this.pannerNode.pan.value=e),this._pan=e}get loop(){return this._loop}set loop(e){this.sources.forEach((t=>t.loop=e)),this._loop=e}get playing(){return!this.paused&&this.sources.size>0}setVolume(e){this.volume=e}setPan(e){this.pan=e}setLoop(e){this.loop=e}isLoaded(){return this.loaded}isPlaying(){return this.playing}isPaused(){return this.paused}isLooping(){return this._loop}onended(e){this._onended=e}},Q5.modules.util=(e,t)=>{e._loadFile=(t,r,a)=>{let n={};return n.promise=new Promise(((i,o)=>{fetch(t).then((e=>e.ok?"json"==a?e.json():e.text():(o("error loading file"),null))).then((t=>{"csv"==a&&(t=e.CSV.parse(t)),"string"==typeof t?n.text=t:Object.assign(n,t),delete n.promise,r&&r(t),i(t)}))})),n},e.loadText=(t,r)=>e._loadFile(t,r,"text"),e.loadJSON=(t,r)=>e._loadFile(t,r,"json"),e.loadCSV=(t,r)=>e._loadFile(t,r,"csv");const r=/(jpe?g|png|gif|webp|avif|svg)/i,a=/(ttf|otf|woff2?|eot|json)/i,n=/(serif|sans-serif|monospace|cursive|fantasy)/i,i=/(wav|flac|mp3|ogg|m4a|aac|aiff|weba)/i;async function o(e,t,a){let n;if(t=t||"untitled",a=a||"png",r.test(a)){let t=e.canvas||e;n=await t.convertToBlob({type:"image/"+a})}else{let t="text/plain";"json"==a&&("string"!=typeof e&&(e=JSON.stringify(e)),t="text/json"),n=new Blob([e],{type:t})}let i=document.createElement("a");i.href=URL.createObjectURL(n),i.download=t+"."+a,i.click(),setTimeout((()=>URL.revokeObjectURL(i.href)),1e3)}e.load=function(...t){Array.isArray(t[0])&&(t=t[0]);let o=[];for(let s of t){let t,l=s.split(".").pop().toLowerCase();t="json"!=l||s.includes("-msdf.")?"csv"==l?e.loadCSV(s):r.test(l)?e.loadImage(s):a.test(l)||n.test(s)?e.loadFont(s):i.test(l)?e.loadSound(s):e.loadText(s):e.loadJSON(s),o.push(e._usePreload?t.promise:t)}return 1==t.length?o[0]:Promise.all(o)},e.save=(t,r,a)=>{if((!t||"string"==typeof t&&(!r||!a&&r.length<5))&&(a=r,r=t,t=e),a)o(t,r,a);else if(r){let e=r.lastIndexOf(".");o(t,r.slice(0,e),r.slice(e+1))}else o(t)},e.CSV={},e.CSV.parse=(e,t=",",r="\n")=>{if(!e.length)return[];let a=[],n=e.split(r),i=n[0].split(t).map((e=>e.replaceAll('"',"")));for(let e=1;e<n.length;e++){let r={},o=n[e].split(t);i.forEach(((e,t)=>r[e]=JSON.parse(o[t]))),a.push(r)}return a},e.canvas&&!Q5._createServerCanvas&&(e.canvas.save=e.saveCanvas=e.save),"object"==typeof localStorage&&(e.storeItem=(e,t)=>localStorage.setItem(e,t),e.getItem=e=>localStorage.getItem(e),e.removeItem=e=>localStorage.removeItem(e),e.clearStorage=()=>localStorage.clear()),e.year=()=>(new Date).getFullYear(),e.day=()=>(new Date).getDay(),e.hour=()=>(new Date).getHours(),e.minute=()=>(new Date).getMinutes(),e.second=()=>(new Date).getSeconds(),e.nf=(e,t,r)=>{let a=e<0,n=(e=Math.abs(e)).toFixed(r).split(".");n[0]=n[0].padStart(t,"0");let i=n.join(".");return a&&(i="-"+i),i},e.shuffle=(t,r)=>{r||(t=[...t]);for(let r=t.length-1;r>0;r--){let a=Math.floor(e.random()*(r+1));[t[r],t[a]]=[t[a],t[r]]}return t}},Q5.modules.vector=e=>{e.Vector=Q5.Vector,e.createVector=(t,r,a)=>new e.Vector(t,r,a,e)},Q5.Vector=class{constructor(e,t,r,a){this.x=e||0,this.y=t||0,this.z=r||0,this._$=a||window,this._cn=null,this._cnsq=null}set(e,t,r){return this.x=e?.x||e||0,this.y=e?.y||t||0,this.z=e?.z||r||0,this}copy(){return new Q5.Vector(this.x,this.y,this.z)}_arg2v(e,t,r){return void 0!==e?.x?e:void 0!==t?{x:e,y:t,z:r||0}:{x:e,y:e,z:e}}_calcNorm(){this._cnsq=this.x*this.x+this.y*this.y+this.z*this.z,this._cn=Math.sqrt(this._cnsq)}add(){let e=this._arg2v(...arguments);return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}rem(){let e=this._arg2v(...arguments);return this.x%=e.x,this.y%=e.y,this.z%=e.z,this}sub(){let e=this._arg2v(...arguments);return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}mult(){let e=this._arg2v(...arguments);return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}div(){let e=this._arg2v(...arguments);return e.x?this.x/=e.x:this.x=0,e.y?this.y/=e.y:this.y=0,e.z?this.z/=e.z:this.z=0,this}mag(){return this._calcNorm(),this._cn}magSq(){return this._calcNorm(),this._cnsq}dot(){let e=this._arg2v(...arguments);return this.x*e.x+this.y*e.y+this.z*e.z}dist(){let e=this._arg2v(...arguments),t=this.x-e.x,r=this.y-e.y,a=this.z-e.z;return Math.sqrt(t*t+r*r+a*a)}cross(){let e=this._arg2v(...arguments),t=this.y*e.z-this.z*e.y,r=this.z*e.x-this.x*e.z,a=this.x*e.y-this.y*e.x;return this.x=t,this.y=r,this.z=a,this}normalize(){this._calcNorm();let e=this._cn;return 0!=e&&(this.x/=e,this.y/=e,this.z/=e),this._cn=1,this._cnsq=1,this}limit(e){this._calcNorm();let t=this._cn;if(t>e){let r=e/t;this.x*=r,this.y*=r,this.z*=r,this._cn=e,this._cnsq=e*e}return this}setMag(e){this._calcNorm();let t=e/this._cn;return this.x*=t,this.y*=t,this.z*=t,this._cn=e,this._cnsq=e*e,this}heading(){return this._$.atan2(this.y,this.x)}setHeading(e){let t=this.mag();return this.x=t*this._$.cos(e),this.y=t*this._$.sin(e),this}rotate(e){let t=this._$.cos(e),r=this._$.sin(e),a=this.x*t-this.y*r,n=this.x*r+this.y*t;return this.x=a,this.y=n,this}angleBetween(){let e=this._arg2v(...arguments),t=Q5.Vector.cross(this,e);return this._$.atan2(t.mag(),this.dot(e))*Math.sign(t.z||1)}lerp(){let e=[...arguments],t=e.at(-1);if(0==t)return this;let r=this._arg2v(...e.slice(0,-1));return this.x+=(r.x-this.x)*t,this.y+=(r.y-this.y)*t,this.z+=(r.z-this.z)*t,this}slerp(){let e=[...arguments],t=e.at(-1);if(0==t)return this;let r=this._arg2v(...e.slice(0,-1));if(1==t)return this.set(r);let a=this.mag(),n=r.mag();if(0==a||0==n)return this.mult(1-t).add(r.mult(t));let i=Q5.Vector.cross(this,r),o=i.mag(),s=Math.atan2(o,this.dot(r));if(o>0)i.div(o);else{if(s<this._$.HALF_PI)return this.mult(1-t).add(r.mult(t));0==this.z&&0==r.z?i.set(0,0,1):0!=this.x?i.set(this.y,-this.x,0).normalize():i.set(1,0,0)}let l=i.cross(this),d=1-t+t*n/a,c=d*Math.cos(t*s),h=d*Math.sin(t*s);return this.x=this.x*c+l.x*h,this.y=this.y*c+l.y*h,this.z=this.z*c+l.z*h,this}reflect(e){return e.normalize(),this.sub(e.mult(2*this.dot(e)))}array(){return[this.x,this.y,this.z]}equals(e,t){return t??=Number.EPSILON||0,Math.abs(e.x-this.x)<t&&Math.abs(e.y-this.y)<t&&Math.abs(e.z-this.z)<t}fromAngle(e,t){return void 0===t&&(t=1),this._cn=t,this._cnsq=t*t,this.x=t*this._$.cos(e),this.y=t*this._$.sin(e),this.z=0,this}fromAngles(e,t,r){void 0===r&&(r=1),this._cn=r,this._cnsq=r*r;const a=this._$.cos(t),n=this._$.sin(t),i=this._$.cos(e),o=this._$.sin(e);return this.x=r*o*n,this.y=-r*i,this.z=r*o*a,this}random2D(){return this._cn=this._cnsq=1,this.fromAngle(Math.random()*Math.PI*2)}random3D(){return this._cn=this._cnsq=1,this.fromAngles(Math.random()*Math.PI*2,Math.random()*Math.PI*2)}toString(){return`[${this.x}, ${this.y}, ${this.z}]`}},Q5.Vector.add=(e,t)=>e.copy().add(t),Q5.Vector.cross=(e,t)=>e.copy().cross(t),Q5.Vector.dist=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y,e.z-t.z),Q5.Vector.div=(e,t)=>e.copy().div(t),Q5.Vector.dot=(e,t)=>e.copy().dot(t),Q5.Vector.equals=(e,t,r)=>e.equals(t,r),Q5.Vector.lerp=(e,t,r)=>e.copy().lerp(t,r),Q5.Vector.slerp=(e,t,r)=>e.copy().slerp(t,r),Q5.Vector.limit=(e,t)=>e.copy().limit(t),Q5.Vector.heading=e=>this._$.atan2(e.y,e.x),Q5.Vector.magSq=e=>e.x*e.x+e.y*e.y+e.z*e.z,Q5.Vector.mag=e=>Math.sqrt(Q5.Vector.magSq(e)),Q5.Vector.mult=(e,t)=>e.copy().mult(t),Q5.Vector.normalize=e=>e.copy().normalize(),Q5.Vector.rem=(e,t)=>e.copy().rem(t),Q5.Vector.sub=(e,t)=>e.copy().sub(t),Q5.Vector.reflect=(e,t)=>e.copy().reflect(t),Q5.Vector.random2D=()=>(new Q5.Vector).random2D(),Q5.Vector.random3D=()=>(new Q5.Vector).random3D(),Q5.Vector.fromAngle=(e,t)=>(new Q5.Vector).fromAngle(e,t),Q5.Vector.fromAngles=(e,t,r)=>(new Q5.Vector).fromAngles(e,t,r),Q5.renderers.webgpu={},Q5.renderers.webgpu.canvas=(e,t)=>{const r=e.canvas;e.colorMode&&e.colorMode("rgb",1),e._baseShaderCode="\nstruct Q5 {\n\twidth: f32,\n\theight: f32,\n\thalfWidth: f32,\n\thalfHeight: f32,\n\tpixelDensity: f32,\n\tframeCount: f32,\n\ttime: f32,\n\tdeltaTime: f32,\n\tmouseX: f32,\n\tmouseY: f32,\n\tmouseIsPressed: f32,\n\tkeyCode: f32,\n\tkeyIsPressed: f32\n}",e._g=e.createGraphics(1,1,"c2d"),e._g.colorMode&&e._g.colorMode(e.RGB,1);let a,n,i,o,s,l,d,c,h=1,u=8,p=0,f=0;e._pipelineConfigs=[],e._pipelines=[],e._buffers=[];let g=[],m=new Float32Array(1e6);m.set([0,0,0,1,1,1,1,1]);let _=Q5.device.createBindGroupLayout({label:"mainLayout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}}]});e._bindGroupLayouts=[_];let x=Q5.device.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),v=()=>{let t=[e.canvas.width,e.canvas.height],r="bgra8unorm";i=Q5.device.createTexture({size:t,sampleCount:4,format:r,usage:GPUTextureUsage.RENDER_ATTACHMENT}).createView();let a=GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT;e._frameA=s=Q5.device.createTexture({label:"frameA",size:t,format:r,usage:a}),e._frameB=o=Q5.device.createTexture({label:"frameB",size:t,format:r,usage:a}),e._frameShaderCode=e._baseShaderCode+"\nstruct VertexParams {\n\t@builtin(vertex_index) vertexIndex: u32\n}\nstruct FragParams {\n\t@builtin(position) position: vec4f,\n\t@location(0) texCoord: vec2f\n}\n\nconst ndc = array(vec2f(-1,-1), vec2f(1,-1), vec2f(-1,1), vec2f(1,1));\nconst quad = array(vec2f(0,1), vec2f(1,1), vec2f(0,0), vec2f(1,0));\n\n@group(0) @binding(0) var<uniform> q: Q5;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var tex: texture_2d<f32>;\n\n@vertex\nfn vertexMain(v: VertexParams) -> FragParams {\n\tvar f: FragParams;\n\tf.position = vec4f(ndc[v.vertexIndex], 0.0, 1.0);\n\tf.texCoord = quad[v.vertexIndex];\n\treturn f;\n}\n\n@fragment\nfn fragMain(f: FragParams ) -> @location(0) vec4f {\n\treturn textureSample(tex, samp, f.texCoord);\n}";let n=Q5.device.createShaderModule({label:"frameShader",code:e._frameShaderCode});d=Q5.device.createSampler({magFilter:"linear",minFilter:"linear"}),l=Q5.device.createBindGroupLayout({label:"frameLayout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{viewDimension:"2d",sampleType:"float"}}]});let c=Q5.device.createPipelineLayout({bindGroupLayouts:[l]});e._pipelineConfigs[0]={layout:c,vertex:{module:n,entryPoint:"vertexMain"},fragment:{module:n,entryPoint:"fragMain",targets:[{format:r}]},primitive:{topology:"triangle-strip"},multisample:{count:4}},e._pipelines[0]=Q5.device.createRenderPipeline(e._pipelineConfigs[0])};e._createCanvas=(a,n,i)=>(t.ctx=t.drawingContext=r.getContext("webgpu"),i.format??=navigator.gpu.getPreferredCanvasFormat(),i.device??=Q5.device,i.alpha&&(i.alphaMode="premultiplied"),e.ctx.configure(i),v(),r),e._resizeCanvas=(t,r)=>{e._setCanvasSize(t,r),v()};let y=!0,b="rgb",w=1;if(e.colorMode){let t=e.colorMode;e.colorMode=function(){t(...arguments),b=e._colorMode,y="rgb"==b,w=e._colorFormat}}const S=(t,r,a,n)=>{if(!1===y||void 0===r&&!t._q5Color&&"number"!=typeof t?!1!==y&&"string"!=typeof t&&Array.isArray(t)?[t,r,a,n]=t:t=e.color(t,r,a,n):void 0===a&&(n=r??w,r=a=t),n??=w,t._q5Color){let e=t;y?({r:t,g:r,b:a,a:n}=e):(n=e.a,e=null!=e.c?Q5.OKLCHtoRGB(e.l,e.c,e.h):null!=e.l?Q5.HSLtoRGB(e.h,e.s,e.l):Q5.HSLtoRGB(...Q5.HSBtoHSL(e.h,e.s,e.b)),[t,r,a]=e)}255===w&&(t/=255,r/=255,a/=255,n/=255);let i=m,o=u;i[o++]=t,i[o++]=r,i[o++]=a,i[o++]=n,u=o,h++};let C=!0,M=!0,Q=!1,P=!1,E=0,R=1,T=1,I=1,A=1,O=.5,k=1;e.fill=(e,t,r,a)=>{S(e,t,r,a),C=Q=!0,R=h},e.stroke=(e,t,r,a)=>{S(e,t,r,a),M=P=!0,E=h},e.tint=(e,t,r,a)=>{S(e,t,r,a),T=h},e.opacity=e=>I=e,e.noFill=()=>C=!1,e.noStroke=()=>M=!1,e.noTint=()=>T=1,e.strokeWeight=e=>{if(void 0===e)return A;e=Math.abs(e),A=e,k=e*U,O=e/2},e._getFillIdx=()=>R,e._setFillIdx=e=>R=e,e._doFill=()=>C=!0,e._getStrokeIdx=()=>E,e._setStrokeIdx=e=>E=e,e._doStroke=()=>M=!0;const G=e._graphics?1e3:1e7,D=new Float32Array(16*G);let L,F=[],B=[],z=0,N=!1;F.push([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),D.set(F[0]),e.resetMatrix=()=>{L=F[0].slice(),z=0},e.resetMatrix(),e.translate=(e,t,r=0)=>{if(!e&&!t&&!r)return;let a=L;a[12]+=e*a[0],a[13]-=t*a[5],a[14]+=r*a[10],N=!0},e.rotate=e.rotateZ=t=>{if(!t)return;e._angleMode&&(t*=e._DEGTORAD);let r=Math.cos(t),a=Math.sin(t),n=L,i=n[0],o=n[1],s=n[4],l=n[5];1!=i||o||s||1!=l?(n[0]=i*r+o*a,n[1]=o*r-i*a,n[4]=s*r+l*a,n[5]=l*r-s*a):(n[0]=r,n[1]=-a,n[4]=a,n[5]=r),N=!0};let U=1;e.scale=(e=1,t,r=1)=>{t??=e,U=Math.max(Math.abs(e),Math.abs(t)),k=A*U;let a=L;a[0]*=e,a[1]*=e,a[2]*=e,a[3]*=e,a[4]*=t,a[5]*=t,a[6]*=t,a[7]*=t,a[8]*=r,a[9]*=r,a[10]*=r,a[11]*=r,N=!0},e.shearX=t=>{if(!t)return;e._angleMode&&(t*=e._DEGTORAD);let r=Math.tan(t),a=L,n=a[0],i=a[1],o=a[4],s=a[5];a[0]=n+o*r,a[1]=i+s*r,N=!0},e.shearY=t=>{if(!t)return;e._angleMode&&(t*=e._DEGTORAD);let r=Math.tan(t),a=L,n=a[0],i=a[1],o=a[4],s=a[5];a[4]=o+n*r,a[5]=s+i*r,N=!0},e.applyMatrix=(...e)=>{let t;if(t=1==e.length?e[0]:e,9==t.length)t=[t[0],t[1],0,t[2],t[3],t[4],0,t[5],0,0,1,0,t[6],t[7],0,t[8]];else if(16!=t.length)throw new Error("Matrix must be a 3x3 or 4x4 array.");L=t.slice(),N=!0};const H=()=>{D.set(L,16*F.length),z=F.length,F.push(L.slice()),N=!1};e.pushMatrix=()=>{N&&H(),B.push(z)},e.popMatrix=()=>{if(!B.length)return console.warn("Matrix index stack is empty!");let e=B.pop();L=F[e].slice(),z=e,N=!1};let V=[];e.pushStyles=()=>{V.push([R,E,A,O,k,C,M,Q,P,T,qe,We,$e,ke,de,he,y,b,w,Color])},e.popStyles=()=>{let t=V.pop();[R,E,A,O,k,C,M,Q,P,T,qe,We,$e,ke,de,he,y,b,w]=t,e._colorFormat=w,e._colorMode=b,e.Color=t.at(-1)},e.push=()=>{e.pushMatrix(),e.pushStyles()},e.pop=()=>{e.popMatrix(),e.popStyles()};const q=(e,t,r,a,n)=>{let i,o,s,l;if(n&&"corner"!=n)if("center"==n){let n=r/2,d=a/2;i=e-n,o=e+n,s=-(t-d),l=-(t+d)}else i=e,o=r,s=-t,l=-a;else i=e,o=e+r,s=-t,l=-(t+a);return[i,o,s,l]};let W=["zero","one","src-alpha","one-minus-src-alpha","dst","dst-alpha","one-minus-dst-alpha","one-minus-src"],$=["add","subtract","reverse-subtract","min","max"];const j={"source-over":[2,3,0,2,3,0],"destination-over":[6,1,0,6,1,0],"source-in":[5,0,0,5,0,0],"destination-in":[0,2,0,0,2,0],"source-out":[6,0,0,6,0,0],"destination-out":[0,3,0,0,3,0],"source-atop":[5,3,0,5,3,0],"destination-atop":[6,2,0,6,2,0],lighter:[1,1,0,1,1,0],darken:[1,1,3,3,5,0],lighten:[1,1,4,3,5,0],replace:[1,0,0,1,0,0]};let X=Object.keys(j);e.blendConfigs={};for(const[t,r]of Object.entries(j))e.blendConfigs[t]={color:{srcFactor:W[r[0]],dstFactor:W[r[1]],operation:$[r[2]]},alpha:{srcFactor:W[r[3]],dstFactor:W[r[4]],operation:$[r[5]]}};let Y,J="source-over";e.blendMode=e=>{if(e==J)return;J=e;let t=X.indexOf(e);-1!=t?g.push(0,t):console.error(`Blend mode "${e}" not supported in q5.js WebGPU.`)},e.clear=()=>{Y=!0},e.background=(t,a,n,i)=>{if(t.canvas){e.push(),e.resetMatrix();let a=t;ke="corner",e.image(a,-r.hw,-r.hh,r.w,r.h),e.pop()}else S(t,a,n,i),oe(-r.hw,r.hh,r.hw,r.hh,r.hw,-r.hh,-r.hw,-r.hh,h,0)},e._beginRender=()=>{const t=o;o=s,s=t,a=Q5.device.createCommandEncoder(),e._pass=n=a.beginRenderPass({label:"q5-webgpu",colorAttachments:[{view:i,resolveTarget:o.createView(),loadOp:"clear",storeOp:"store",clearValue:[0,0,0,0]}]}),c=Q5.device.createBindGroup({layout:l,entries:[{binding:0,resource:{buffer:x}},{binding:1,resource:d},{binding:2,resource:s.createView()}]}),Y||(n.setPipeline(e._pipelines[p]),n.setBindGroup(0,c),n.draw(4)),Y=!1},e._render=()=>{let t=Q5.device.createBuffer({size:16*F.length*4,usage:GPUBufferUsage.STORAGE,mappedAtCreation:!0});new Float32Array(t.getMappedRange()).set(D.slice(0,16*F.length)),t.unmap(),e._buffers.push(t);let r=Q5.device.createBuffer({size:4*u,usage:GPUBufferUsage.STORAGE,mappedAtCreation:!0});new Float32Array(r.getMappedRange()).set(m.slice(0,u)),r.unmap(),e._buffers.push(r),e._uniforms=[e.width,e.height,e.halfWidth,e.halfHeight,e._pixelDensity,e.frameCount,performance.now(),e.deltaTime,e.mouseX,e.mouseY,e.mouseIsPressed?1:0,e.keyCode,e.keyIsPressed?1:0],Q5.device.queue.writeBuffer(x,0,new Float32Array(e._uniforms));let a=Q5.device.createBindGroup({layout:_,entries:[{binding:0,resource:{buffer:x}},{binding:1,resource:{buffer:t}},{binding:2,resource:{buffer:r}}]});n.setBindGroup(0,a),e._pass.setPipeline(e._pipelines[1]);let i=Q5.device.createBuffer({size:4*te,usage:GPUBufferUsage.VERTEX,mappedAtCreation:!0});if(new Float32Array(i.getMappedRange()).set(ee.slice(0,te)),i.unmap(),e._pass.setVertexBuffer(0,i),e._buffers.push(i),Ce){e._pass.setPipeline(e._pipelines[2]);let t=Q5.device.createBuffer({size:5*Ce,usage:GPUBufferUsage.VERTEX,mappedAtCreation:!0});new Float32Array(t.getMappedRange()).set(Se.slice(0,Ce)),t.unmap(),e._pass.setVertexBuffer(1,t),e._buffers.push(t),Ae&&(e._pass.setPipeline(e._pipelines[3]),e._pass.setVertexBuffer(1,t))}if(et.length){let t=0;for(let e of et)t+=4*e.length;let r=Q5.device.createBuffer({size:t,usage:GPUBufferUsage.STORAGE,mappedAtCreation:!0});new Float32Array(r.getMappedRange()).set(et.flat()),r.unmap();let a=8*tt.length*4,n=Q5.device.createBuffer({label:"textBuffer",size:a,usage:GPUBufferUsage.STORAGE,mappedAtCreation:!0});new Float32Array(n.getMappedRange()).set(tt.flat()),n.unmap(),e._buffers.push(r,n),e._textBindGroup=Q5.device.createBindGroup({label:"textBindGroup",layout:Fe,entries:[{binding:0,resource:{buffer:r}},{binding:1,resource:{buffer:n}}]})}let o=0,s=0,l=0,d=-1;for(let t=0;t<g.length;t+=2){let r=g[t+1];if(g[t]!=d){if(0==g[t]){let t=X[r];for(let r=1;r<e._pipelines.length;r++)e._pipelineConfigs[r].fragment.targets[0].blend=e.blendConfigs[t],e._pipelines[r]=Q5.device.createRenderPipeline(e._pipelineConfigs[r]);continue}d=g[t],n.setPipeline(e._pipelines[d])}if(4==d||d>=4e3){let a=g[t+2];n.setBindGroup(1,He[a].bindGroup),n.setBindGroup(2,e._textBindGroup),n.draw(4,r,0,l),l+=r,t++}else 2==d||3==d||d>=2e3?(n.setBindGroup(1,e._textureBindGroups[r]),n.draw(4,1,s),s+=4):(n.draw(r,1,o),o+=r)}},e._finishRender=()=>{n.end(),n=a.beginRenderPass({colorAttachments:[{view:i,resolveTarget:e.ctx.getCurrentTexture().createView(),loadOp:"clear",storeOp:"store",clearValue:[0,0,0,0]}]}),c=Q5.device.createBindGroup({layout:l,entries:[{binding:0,resource:{buffer:x}},{binding:1,resource:d},{binding:2,resource:o.createView()}]}),n.setPipeline(e._pipelines[f]),n.setBindGroup(0,c),n.draw(4),n.end(),Q5.device.queue.submit([a.finish()]),e._pass=n=a=null,g.splice(0,g.length),h=1,u=8,F=[F[0]],B=[],e._texture=o,te=0,Ce=0,e._textureBindGroups.splice(Ie,Ae),Ae=0,et=[],tt=[],Q5.device.queue.onSubmittedWorkDone().then((()=>{for(let t of e._buffers)t.destroy();e._buffers=[]}))};let K=1;e._shapesShaderCode=e._baseShaderCode+"\nstruct VertexParams {\n\t@builtin(vertex_index) vertexIndex : u32,\n\t@location(0) pos: vec2f,\n\t@location(1) colorIndex: f32,\n\t@location(2) matrixIndex: f32\n}\nstruct FragParams {\n\t@builtin(position) position: vec4f,\n\t@location(0) color: vec4f\n}\n\n@group(0) @binding(0) var<uniform> q: Q5;\n@group(0) @binding(1) var<storage> transforms: array<mat4x4<f32>>;\n@group(0) @binding(2) var<storage> colors : array<vec4f>;\n\nfn transformVertex(pos: vec2f, matrixIndex: f32) -> vec4f {\n\tvar vert = vec4f(pos, 0.0, 1.0);\n\tvert = transforms[i32(matrixIndex)] * vert;\n\tvert.x /= q.halfWidth;\n\tvert.y /= q.halfHeight;\n\treturn vert;\n}\n\n@vertex\nfn vertexMain(v: VertexParams) -> FragParams {\n\tvar vert = transformVertex(v.pos, v.matrixIndex);\n\n\tvar f: FragParams;\n\tf.position = vert;\n\tf.color = colors[i32(v.colorIndex)];\n\treturn f;\n}\n\n@fragment\nfn fragMain(f: FragParams) -> @location(0) vec4f {\n\treturn f.color;\n}\n";let Z=Q5.device.createShaderModule({label:"shapesShader",code:e._shapesShaderCode}),ee=new Float32Array(e._graphics?1e3:1e7),te=0;const re=2*Math.PI,ae=Math.PI/2;let ne=Q5.device.createPipelineLayout({label:"shapesPipelineLayout",bindGroupLayouts:e._bindGroupLayouts});e._pipelineConfigs[1]={label:"shapesPipeline",layout:ne,vertex:{module:Z,entryPoint:"vertexMain",buffers:[{arrayStride:16,attributes:[{format:"float32x2",offset:0,shaderLocation:0},{format:"float32",offset:8,shaderLocation:1},{format:"float32",offset:12,shaderLocation:2}]}]},fragment:{module:Z,entryPoint:"fragMain",targets:[{format:"bgra8unorm",blend:e.blendConfigs["source-over"]}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint32"},multisample:{count:4}},e._pipelines[1]=Q5.device.createRenderPipeline(e._pipelineConfigs[1]);const ie=(e,t,r,a)=>{let n=ee,i=te;n[i++]=e,n[i++]=t,n[i++]=r,n[i++]=a,te=i},oe=(e,t,r,a,n,i,o,s,l,d)=>{let c=ee,h=te;c[h++]=e,c[h++]=t,c[h++]=l,c[h++]=d,c[h++]=r,c[h++]=a,c[h++]=l,c[h++]=d,c[h++]=o,c[h++]=s,c[h++]=l,c[h++]=d,c[h++]=n,c[h++]=i,c[h++]=l,c[h++]=d,te=h,g.push(K,4)},se=(e,t,r,a,n,i,o,s,l)=>{let d=(i-n)/o,c=n,h=ee,u=te;for(let n=0;n<=o;n++){h[u++]=e,h[u++]=t,h[u++]=s,h[u++]=l;let n=e+r*Math.cos(c),i=t-a*Math.sin(c);h[u++]=n,h[u++]=i,h[u++]=s,h[u++]=l,c+=d}te=u,g.push(K,2*(o+1))},le=(e,t,r,a,n,i,o,s,l,d,c)=>{let h=(s-o)/l,u=o,p=ee,f=te;for(let o=0;o<=l;o++){let o=e+r*Math.cos(u),s=t-a*Math.sin(u),l=e+n*Math.cos(u),g=t-i*Math.sin(u);p[f++]=o,p[f++]=s,p[f++]=d,p[f++]=c,p[f++]=l,p[f++]=g,p[f++]=d,p[f++]=c,u+=h}te=f,g.push(K,2*(l+1))};let de="corner";e.rectMode=e=>de=e,e.rect=(e,t,r,a,n=0)=>{a??=r;let i,o,[s,l,d,c]=q(e,t,r,a,de);if(N&&H(),o=z,!n){if(C&&(i=R,oe(s,d,l,d,l,c,s,c,i,o)),M){i=E;let e=s-O,t=l+O,r=d+O,a=c-O,n=s+O,h=l-O,u=d-O,p=c+O;oe(e,u,t,u,t,r,e,r,i,o),oe(e,a,t,a,t,p,e,p,i,o),r=d-O,a=c+O,oe(e,r,n,r,n,a,e,a,i,o),oe(h,r,t,r,t,a,h,a,i,o)}return}s+=n,l-=n,d-=n,c+=n,n=Math.min(n,Math.min(r,a)/2);let h=ce(n*U),u=d+n,p=c-n,f=s-n,g=l+n;if(C&&(i=R,se(l,c,n,n,0,ae,h,i,o),se(s,c,n,n,Math.PI,ae,h,i,o),se(s,d,n,n,-Math.PI,-ae,h,i,o),se(l,d,n,n,-ae,0,h,i,o),oe(s,u,l,u,l,p,s,p,i,o),oe(s,d,f,d,f,c,s,c,i,o),oe(g,d,l,d,l,c,g,c,i,o)),M){i=E;let e=n+O,t=n+O,r=n-O,a=n-O;le(l,c,e,t,r,a,0,ae,h,i,o),le(s,c,e,t,r,a,Math.PI,ae,h,i,o),le(s,d,e,t,r,a,-Math.PI,-ae,h,i,o),le(l,d,e,t,r,a,-ae,0,h,i,o);let m=f-O,_=f+O,x=g-O,v=g+O,y=u-O,b=u+O,w=p-O,S=p+O;oe(m,d,_,d,_,c,m,c,i,o),oe(x,d,v,d,v,c,x,c,i,o),oe(s,y,l,y,l,b,s,b,i,o),oe(s,w,l,w,l,S,s,S,i,o)}},e.square=(t,r,a)=>e.rect(t,r,a,a),e.plane=(e,t,r,a)=>{a??=r;let[n,i,o,s]=q(e,t,r,a,"center");N&&H(),oe(n,o,i,o,i,s,n,s,R,z)};const ce=e=>e<4?6:e<6?8:e<10?10:e<16?12:e<20?14:e<22?16:e<24?18:e<28?20:e<34?22:e<42?24:e<48?26:e<56?28:e<64?30:e<72?32:e<84?34:e<96?36:e<98?38:e<113?40:e<149?44:e<199?48:e<261?52:e<353?56:e<461?60:e<585?64:e<1200?70:e<1800?80:e<2400?90:100;let he="center";e.ellipseMode=e=>he=e,e.ellipse=(e,t,r,a)=>{let n=ce(Math.max(Math.abs(r),Math.abs(a))*U),i=r/2,o=r==a?i:a/2;N&&H();let s=z;C&&se(e,-t,i,o,0,re,n,R,s),M&&le(e,-t,i+O,o+O,i-O,o-O,0,re,n,E,s)},e.circle=(t,r,a)=>e.ellipse(t,r,a,a),e.arc=(t,r,a,n,i,o)=>{if(i===o)return e.ellipse(t,r,a,n);if(e._angleMode&&(i=e.radians(i),o=e.radians(o)),(i%=re)<0&&(i+=re),(o%=re)<0&&(o+=re),i>o&&(o+=re),i==o)return e.ellipse(t,r,a,n);let s,l;he==e.CENTER?(s=a/2,l=n/2):he==e.RADIUS?(s=a,l=n):he==e.CORNER?(t+=a/2,r+=n/2,s=a/2,l=n/2):he==e.CORNERS&&(s=(a-(t=(t+a)/2))/2,l=(n-(r=(r+n)/2))/2),N&&H();let d=z,c=ce(Math.max(Math.abs(a),Math.abs(n))*U);C&&se(t,-r,s,l,i,o,c,R,d),M&&(le(t,-r,s+O,l+O,s-O,l-O,i,o,c,E,d),"round"==ue&&(se(t+s*Math.cos(i),-r-l*Math.sin(i),O,O,0,re,c,E,d),se(t+s*Math.cos(o),-r-l*Math.sin(o),O,O,0,re,c,E,d)))},e.point=(e,t)=>{N&&H();let r=z,a=E;if(k<2){let[n,i,o,s]=q(e,t,A,A,"corner");oe(n,o,i,o,i,s,n,s,a,r)}else{let n=ce(k);A/=2,se(e,-t,A,A,0,re,n,a,r)}};let ue="round",pe="round";e.strokeCap=e=>ue=e,e.strokeJoin=e=>pe=e,e.lineMode=()=>{ue="square",pe="none"},e.line=(e,t,r,a)=>{N&&H();let n=z,i=E,o=r-e,s=a-t,l=Math.hypot(o,s),d=-s/l*O,c=o/l*O;if(oe(e+d,-t-c,e-d,-t+c,r-d,-a+c,r+d,-a-c,i,n),k>2&&"square"!=ue){let o=ce(k);se(e,-t,O,O,0,re,o,i,n),se(r,-a,O,O,0,re,o,i,n)}};let fe=20;e.curveDetail=e=>fe=e;let ge,me=20;e.bezierDetail=e=>me=e;let _e=[],xe=[];e.beginShape=()=>{ge=0,_e=[],xe=[]},e.vertex=(e,t)=>{N&&H(),_e.push(e,-t,R,z),ge++},e.curveVertex=(e,t)=>{N&&H(),xe.push({x:e,y:-t})},e.bezierVertex=function(e,t,r,a,n,i){if(0===ge)throw new Error("Shape needs a vertex()");N&&H();let o,s,l=4*(ge-1),d=_e[l],c=_e[l+1],h=1/me,u=4==arguments.length;u&&(n=r,i=a);let p=1+h;for(let l=h;l<=p;l+=h){let h=l*l,p=1-l,f=p*p;if(u)o=f*d+2*p*l*e+h*n,s=f*c+2*p*l*-t+h*-i;else{let u=h*l,g=f*p;o=g*d+3*f*l*e+3*p*h*r+u*n,s=g*c+3*f*l*-t+3*p*h*-a+u*-i}_e.push(o,s,R,z),ge++}},e.quadraticVertex=(t,r,a,n)=>e.bezierVertex(t,r,a,n),e.endShape=t=>{if(xe.length>0){let e=[...xe];if(e.length<4)for(;e.length<4;)e.unshift(e[0]),e.push(e[e.length-1]);let t=1/fe;for(let r=0;r<e.length-3;r++){let a=e[r],n=e[r+1],i=e[r+2],o=e[r+3];for(let e=0;e<=1;e+=t){let t=e*e,r=t*e,s=.5*(2*n.x+(-a.x+i.x)*e+(2*a.x-5*n.x+4*i.x-o.x)*t+(-a.x+3*n.x-3*i.x+o.x)*r),l=.5*(2*n.y+(-a.y+i.y)*e+(2*a.y-5*n.y+4*i.y-o.y)*t+(-a.y+3*n.y-3*i.y+o.y)*r);_e.push(s,l,R,z),ge++}}}if(ge){if(1==ge)return e.point(_e[0],-_e[1]);if(2==ge)return e.line(_e[0],-_e[1],_e[4],-_e[5]);if(t){let e=0,t=4*(ge-1),r=_e[e],a=_e[e+1],n=_e[t],i=_e[t+1];r===n&&a===i||(_e.push(r,a,_e[e+2],_e[e+3]),ge++)}if(C)if(5==ge)ie(_e[0],_e[1],_e[2],_e[3]),ie(_e[4],_e[5],_e[6],_e[7]),ie(_e[12],_e[13],_e[14],_e[15]),ie(_e[8],_e[9],_e[10],_e[11]),g.push(K,4);else{for(let e=1;e<ge-1;e++){let t=0,r=4*e,a=4*(e+1);ie(_e[t],_e[t+1],_e[t+2],_e[t+3]),ie(_e[r],_e[r+1],_e[r+2],_e[r+3]),ie(_e[a],_e[a+1],_e[a+2],_e[a+3])}g.push(K,3*(ge-2))}if(M){let r=ce(k),a=z,n=ue;ue="square";for(let t=0;t<ge-1;t++){let n=4*t,i=4*(t+1);e.line(_e[n],-_e[n+1],_e[i],-_e[i+1]),se(_e[n],_e[n+1],O,O,0,re,r,E,a)}let i=4*(ge-1),o=0;t&&e.line(_e[i],-_e[i+1],_e[o],-_e[o+1]),se(_e[i],_e[i+1],O,O,0,re,r,E,a),ue=n}ge=0,_e=[],xe=[]}},e.curve=(t,r,a,n,i,o,s,l)=>{e.beginShape(),e.curveVertex(t,r),e.curveVertex(a,n),e.curveVertex(i,o),e.curveVertex(s,l),e.endShape()},e.bezier=(t,r,a,n,i,o,s,l)=>{e.beginShape(),e.vertex(t,r),e.bezierVertex(a,n,i,o,s,l),e.endShape()},e.triangle=(t,r,a,n,i,o)=>{e.beginShape(),e.vertex(t,r),e.vertex(a,n),e.vertex(i,o),e.endShape(!0)},e.quad=(t,r,a,n,i,o,s,l)=>{e.beginShape(),e.vertex(t,r),e.vertex(a,n),e.vertex(i,o),e.vertex(s,l),e.endShape(!0)};let ve=2,ye=3;e._imageShaderCode=e._baseShaderCode+"\n\tstruct VertexParams {\n\t\t@builtin(vertex_index) vertexIndex : u32,\n\t\t@location(0) pos: vec2f,\n\t\t@location(1) texCoord: vec2f,\n\t\t@location(2) tintIndex: f32,\n\t\t@location(3) matrixIndex: f32,\n\t\t@location(4) imageAlpha: f32\n\t}\n\tstruct FragParams {\n\t\t@builtin(position) position: vec4f,\n\t\t@location(0) texCoord: vec2f,\n\t\t@location(1) tintColor: vec4f,\n\t\t@location(2) imageAlpha: f32\n\t}\n\t\n\t@group(0) @binding(0) var<uniform> q: Q5;\n\t@group(0) @binding(1) var<storage> transforms: array<mat4x4<f32>>;\n\t@group(0) @binding(2) var<storage> colors : array<vec4f>;\n\t\n\t@group(1) @binding(0) var samp: sampler;\n\t@group(1) @binding(1) var tex: texture_2d<f32>;\n\t\n\tfn transformVertex(pos: vec2f, matrixIndex: f32) -> vec4f {\n\t\tvar vert = vec4f(pos, 0f, 1f);\n\t\tvert = transforms[i32(matrixIndex)] * vert;\n\t\tvert.x /= q.halfWidth;\n\t\tvert.y /= q.halfHeight;\n\t\treturn vert;\n\t}\n\t\n\tfn applyTint(texColor: vec4f, tintColor: vec4f) -> vec4f {\n\t\t// apply the tint color to the sampled texture color at full strength\n\t\tlet tinted = vec4f(texColor.rgb * tintColor.rgb, texColor.a);\n\t\t// mix in the tint using the tint alpha as the blend strength\n\t\treturn mix(texColor, tinted, tintColor.a);\n\t}\n\t\n\t@vertex\n\tfn vertexMain(v: VertexParams) -> FragParams {\n\t\tvar vert = transformVertex(v.pos, v.matrixIndex);\n\t\n\t\tvar f: FragParams;\n\t\tf.position = vert;\n\t\tf.texCoord = v.texCoord;\n\t\tf.tintColor = colors[i32(v.tintIndex)];\n\t\tf.imageAlpha = v.imageAlpha;\n\t\treturn f;\n\t}\n\t\n\t@fragment\n\tfn fragMain(f: FragParams) -> @location(0) vec4f {\n\t\tvar texColor = textureSample(tex, samp, f.texCoord);\n\t\ttexColor.a *= f.imageAlpha;\n\t\treturn applyTint(texColor, f.tintColor);\n\t}\n\t";let be=Q5.device.createShaderModule({label:"imageShader",code:e._imageShaderCode});e._videoShaderCode=e._imageShaderCode.replace("texture_2d<f32>","texture_external").replace("textureSample","textureSampleBaseClampToEdge");let we=Q5.device.createShaderModule({label:"videoShader",code:e._videoShaderCode}),Se=new Float32Array(e._graphics?1e3:1e7),Ce=0,Me={arrayStride:28,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"float32"},{shaderLocation:3,offset:20,format:"float32"},{shaderLocation:4,offset:24,format:"float32"}]},Qe=Q5.device.createBindGroupLayout({label:"textureLayout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{viewDimension:"2d",sampleType:"float"}}]}),Pe=Q5.device.createBindGroupLayout({label:"videoTextureLayout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,externalTexture:{}}]}),Ee=Q5.device.createPipelineLayout({label:"imagePipelineLayout",bindGroupLayouts:[...e._bindGroupLayouts,Qe]}),Re=Q5.device.createPipelineLayout({label:"videoPipelineLayout",bindGroupLayouts:[...e._bindGroupLayouts,Pe]});e._pipelineConfigs[2]={label:"imagePipeline",layout:Ee,vertex:{module:be,entryPoint:"vertexMain",buffers:[{arrayStride:0,attributes:[]},Me]},fragment:{module:be,entryPoint:"fragMain",targets:[{format:"bgra8unorm",blend:e.blendConfigs["source-over"]}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint32"},multisample:{count:4}},e._pipelines[2]=Q5.device.createRenderPipeline(e._pipelineConfigs[2]),e._pipelineConfigs[3]={label:"videoPipeline",layout:Re,vertex:{module:we,entryPoint:"vertexMain",buffers:[{arrayStride:0,attributes:[]},Me]},fragment:{module:we,entryPoint:"fragMain",targets:[{format:"bgra8unorm",blend:e.blendConfigs["source-over"]}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint32"},multisample:{count:4}},e._pipelines[3]=Q5.device.createRenderPipeline(e._pipelineConfigs[3]),e._textureBindGroups=[],r&&(r.convertToBlob=async t=>{let r=e._drawStack?.length;r&&(e._render(),e._finishRender());let a=e._texture;r&&e._beginRender();let n=a.width,i=a.height,o=256*Math.ceil(4*n/256),s=Q5.device.createBuffer({size:o*i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),l=Q5.device.createCommandEncoder();l.copyTextureToBuffer({texture:a},{buffer:s,bytesPerRow:o,rowsPerImage:i},{width:n,height:i}),Q5.device.queue.submit([l.finish()]),await s.mapAsync(GPUMapMode.READ);let d=new Uint8Array(s.getMappedRange()),c=new Uint8Array(n*i*4);for(let e=0;e<i;e++){const t=e*o,r=e*n*4;for(let e=0;e<n;e++){const a=t+4*e,n=r+4*e;c[n+0]=d[a+2],c[n+1]=d[a+1],c[n+2]=d[a+0],c[n+3]=d[a+3]}}s.unmap();let h=e.canvas.colorSpace;c=new Uint8ClampedArray(c.buffer),c=new ImageData(c,n,i,{colorSpace:h});let u=new OffscreenCanvas(n,i);return u.getContext("2d",{colorSpace:h}).putImageData(c,0,0),e._buffers.push(s),await u.convertToBlob(t)});let Te=t=>{e._imageSampler=Q5.device.createSampler({magFilter:t,minFilter:t})};e.smooth=()=>Te("linear"),e.noSmooth=()=>Te("nearest"),e.smooth();let Ie=0,Ae=0;e._addTexture=(t,r)=>{let a=t.canvas||t;if(!r){let t=[a.width,a.height,1];r=Q5.device.createTexture({size:t,format:"bgra8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT}),Q5.device.queue.copyExternalImageToTexture({source:a},{texture:r,colorSpace:e.canvas.colorSpace},t)}r.index=Ie+Ae,t._texture=r,e._textureBindGroups[r.index]=Q5.device.createBindGroup({label:t.src||r.label||"canvas",layout:Qe,entries:[{binding:0,resource:e._imageSampler},{binding:1,resource:r.createView()}]}),Ie++},e.loadImage=(t,r)=>{let a=e._g.loadImage(t,(()=>{e._extendImage(a),r&&r(a)}));return a},e._extendImage=t=>{e._addTexture(t);let r=t.copy;t.copy=function(){let t=r();return e._addTexture(t),t},t.modified=!0},e.createImage=(t,r,a)=>{let n=e._g.createImage(t,r,a);return e._extendImage(n),n};let Oe=e.createGraphics;e.createGraphics=(t,r,a={})=>{if(!Q5.experimental)throw new Error("createGraphics is disabled by default in q5 WebGPU. See issue https://github.com/q5js/q5.js/issues/104 for details.");"string"==typeof a&&(a={renderer:a}),a.renderer??="c2d";let n=Oe(t,r,a);return n.canvas.webgpu?(e._addTexture(n,n._frameA),e._addTexture(n,n._frameB),n._beginRender()):e._extendImage(n),n};let ke="corner";e.imageMode=e=>ke=e;const Ge=(e,t,r,a,n,i,o)=>{let s=Se,l=Ce;s[l++]=e,s[l++]=t,s[l++]=r,s[l++]=a,s[l++]=n,s[l++]=i,s[l++]=o,Ce=l};e.image=(t,r=0,a=0,n,i,o=0,s=0,l,d)=>{let c;if(null==t._texture){if(c="VIDEO"==t.tagName,!c||!t.width||!t.currentTime)return;t.flipped&&e.scale(-1,1)}N&&H();let h=t.canvas||t,u=h.width,p=h.height,f=t._pixelDensity||1,m=t._graphics&&t._drawStack?.length;m&&(t._render(),t._finishRender()),t.modified&&(Q5.device.queue.copyExternalImageToTexture({source:h},{texture:t._texture,colorSpace:e.canvas.colorSpace},[u,p,1]),t.frameCount++,t.modified=!1),n??=t.defaultWidth||t.videoWidth,i??=t.defaultHeight||t.videoHeight,l??=u,d??=p,o*=f,s*=f;let[_,x,v,y]=q(r,a,n,i,ke),b=o/u,w=s/p,S=(o+l)/u,C=(s+d)/p,M=z,Q=T,P=I;if(Ge(_,v,b,w,Q,M,P),Ge(x,v,S,w,Q,M,P),Ge(_,y,b,C,Q,M,P),Ge(x,y,S,C,Q,M,P),c){let r=Q5.device.importExternalTexture({source:t});e._textureBindGroups.push(Q5.device.createBindGroup({layout:Pe,entries:[{binding:0,resource:e._imageSampler},{binding:1,resource:r}]})),g.push(ye,e._textureBindGroups.length-1),t.flipped&&e.scale(-1,1)}else g.push(ve,t._texture.index),m&&(t.resetMatrix(),t._beginRender(),t.frameCount++)};let De=4;e._textShaderCode=e._baseShaderCode+"\nstruct VertexParams {\n\t@builtin(vertex_index) vertexIndex : u32,\n\t@builtin(instance_index) instanceIndex : u32\n}\nstruct FragParams {\n\t@builtin(position) position : vec4f,\n\t@location(0) texCoord : vec2f,\n\t@location(1) fillColor : vec4f,\n\t@location(2) strokeColor : vec4f,\n\t@location(3) strokeWeight : f32,\n\t@location(4) edge : f32\n}\nstruct Char {\n\ttexOffset: vec2f,\n\ttexExtent: vec2f,\n\tsize: vec2f,\n\toffset: vec2f,\n}\nstruct Text {\n\tpos: vec2f,\n\tscale: f32,\n\tmatrixIndex: f32,\n\tfillIndex: f32,\n\tstrokeIndex: f32,\n\tstrokeWeight: f32,\n\tedge: f32\n}\n\n@group(0) @binding(0) var<uniform> q: Q5;\n@group(0) @binding(1) var<storage> transforms: array<mat4x4<f32>>;\n@group(0) @binding(2) var<storage> colors : array<vec4f>;\n\n@group(1) @binding(0) var fontTexture: texture_2d<f32>;\n@group(1) @binding(1) var fontSampler: sampler;\n@group(1) @binding(2) var<storage> fontChars: array<Char>;\n\n@group(2) @binding(0) var<storage> textChars: array<vec4f>;\n@group(2) @binding(1) var<storage> textMetadata: array<Text>;\n\nconst quad = array(vec2f(0, -1), vec2f(1, -1), vec2f(0, 0), vec2f(1, 0));\nconst uvs = array(vec2f(0, 1), vec2f(1, 1), vec2f(0, 0), vec2f(1, 0));\n\nfn calcPos(i: u32, char: vec4f, fontChar: Char, text: Text) -> vec2f {\n\treturn ((quad[i] * fontChar.size + char.xy + fontChar.offset) *\n\t\ttext.scale) + text.pos;\n}\n\nfn calcUV(i: u32, fontChar: Char) -> vec2f {\n\treturn uvs[i] * fontChar.texExtent + fontChar.texOffset;\n}\n\nfn transformVertex(pos: vec2f, matrixIndex: f32) -> vec4f {\n\tvar vert = vec4f(pos, 0.0, 1.0);\n\tvert = transforms[i32(matrixIndex)] * vert;\n\tvert.x /= q.halfWidth;\n\tvert.y /= q.halfHeight;\n\treturn vert;\n}\n\nfn calcDist(texCoord: vec2f, edgeWidth: f32) -> f32 {\n\tlet c = textureSample(fontTexture, fontSampler, texCoord);\n\tlet sigDist = max(min(c.r, c.g), min(max(c.r, c.g), c.b)) - edgeWidth;\n\n\tlet pxRange = 4.0;\n\tlet sz = vec2f(textureDimensions(fontTexture, 0));\n\tlet dx = sz.x * length(vec2f(dpdxFine(texCoord.x), dpdyFine(texCoord.x)));\n\tlet dy = sz.y * length(vec2f(dpdxFine(texCoord.y), dpdyFine(texCoord.y)));\n\tlet toPixels = pxRange * inverseSqrt(dx * dx + dy * dy);\n\treturn sigDist * toPixels;\n}\n\n@vertex\nfn vertexMain(v : VertexParams) -> FragParams {\n\tlet char = textChars[v.instanceIndex];\n\tlet text = textMetadata[i32(char.w)];\n\tlet fontChar = fontChars[i32(char.z)];\n\tlet pos = calcPos(v.vertexIndex, char, fontChar, text);\n\n\tvar vert = transformVertex(pos, text.matrixIndex);\n\n\tvar f : FragParams;\n\tf.position = vert;\n\tf.texCoord = calcUV(v.vertexIndex, fontChar);\n\tf.fillColor = colors[i32(text.fillIndex)];\n\tf.strokeColor = colors[i32(text.strokeIndex)];\n\tf.strokeWeight = text.strokeWeight;\n\tf.edge = text.edge;\n\treturn f;\n}\n\n@fragment\nfn fragMain(f : FragParams) -> @location(0) vec4f {\n\tlet edge = f.edge;\n\tlet dist = calcDist(f.texCoord, edge);\n\n\tif (f.strokeWeight == 0.0) {\n\t\tlet fillAlpha = smoothstep(-edge, edge, dist);\n\t\tlet color = vec4f(f.fillColor.rgb, f.fillColor.a * fillAlpha);\n\t\tif (color.a < 0.01) {\n\t\t\tdiscard;\n\t\t}\n\t\treturn color;\n\t}\n\n\tlet halfStroke = f.strokeWeight / 2.0;\n\tlet fillAlpha = smoothstep(-edge, edge, dist - halfStroke);\n\tlet strokeAlpha = smoothstep(-edge, edge, dist + halfStroke);\n\tvar color = mix(f.strokeColor, f.fillColor, fillAlpha);\n\tcolor = vec4f(color.rgb, color.a * strokeAlpha);\n\tif (color.a < 0.01) {\n\t\tdiscard;\n\t}\n\treturn color;\n}\n";let Le=Q5.device.createShaderModule({label:"textShader",code:e._textShaderCode}),Fe=Q5.device.createBindGroupLayout({label:"textBindGroupLayout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}}]}),Be=Q5.device.createSampler({minFilter:"linear",magFilter:"linear",mipmapFilter:"linear",maxAnisotropy:16}),ze=Q5.device.createBindGroupLayout({label:"fontBindGroupLayout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:2,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),Ne=Q5.device.createPipelineLayout({bindGroupLayouts:[...e._bindGroupLayouts,ze,Fe]});e._pipelineConfigs[4]={label:"textPipeline",layout:Ne,vertex:{module:Le,entryPoint:"vertexMain"},fragment:{module:Le,entryPoint:"fragMain",targets:[{format:"bgra8unorm",blend:e.blendConfigs["source-over"]}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint32"},multisample:{count:4}},e._pipelines[4]=Q5.device.createRenderPipeline(e._pipelineConfigs[4]);class Ue{constructor(e,t,r,a){this.bindGroup=e,this.lineHeight=t,this.chars=r,this.kernings=a;let n=Object.values(r);this.charCount=n.length,this.defaultChar=n[0]}getChar(e){return this.chars[e]??this.defaultChar}getXAdvance(e,t=-1){let r=this.getChar(e);if(t>=0){let a=this.kernings.get(e);if(a)return r.xadvance+(a.get(t)??0)}return r.xadvance}}let He=[],Ve={};e.loadFont=(t,r)=>{if(t.startsWith("https://fonts.googleapis.com/css"))return e._g.loadFont(t,r);let a=t.slice(t.lastIndexOf(".")+1);if(t==a)return e._loadDefaultFont(t,r);if("json"!=a)return e._g.loadFont(t,r);let n=t.slice(t.lastIndexOf("/")+1,t.lastIndexOf("-")),i={family:n};return i.promise=async function(t,r,a){let n=await fetch(t);if(404==n.status)return"";let i=await n.json(),o=t.lastIndexOf("/"),s=-1!=o?t.substring(0,o+1):"";n=await fetch(s+i.pages[0]);let l=await createImageBitmap(await n.blob()),d=[l.width,l.height,1],c=Q5.device.createTexture({label:`MSDF ${r}`,size:d,format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT});Q5.device.queue.copyExternalImageToTexture({source:l},{texture:c},d),"string"==typeof i.chars&&(i.chars=e.CSV.parse(i.chars," "),i.kernings=e.CSV.parse(i.kernings," "));let h=i.chars.length,u=Q5.device.createBuffer({size:32*h,usage:GPUBufferUsage.STORAGE,mappedAtCreation:!0}),p=new Float32Array(u.getMappedRange()),f=1/i.common.scaleW,g=1/i.common.scaleH,m={},_=0;for(let[e,t]of i.chars.entries())m[t.id]=t,m[t.id].charIndex=e,p[_]=t.x*f,p[_+1]=t.y*g,p[_+2]=t.width*f,p[_+3]=t.height*g,p[_+4]=t.width,p[_+5]=t.height,p[_+6]=t.xoffset,p[_+7]=-t.yoffset,_+=8;u.unmap();let x=Q5.device.createBindGroup({label:"fontBindGroup",layout:ze,entries:[{binding:0,resource:c.createView()},{binding:1,resource:Be},{binding:2,resource:{buffer:u}}]}),v=new Map;if(i.kernings)for(let e of i.kernings){let t=v.get(e.first);t||(t=new Map,v.set(e.first,t)),t.set(e.second,e.amount)}e._font=new Ue(x,i.common.lineHeight,m,v),e._font.index=He.length,He.push(e._font),Ve[r]=e._font,a&&a(r)}(t,n,(()=>{delete i.promise,r&&r(i)})),e._preloadPromises.push(i.promise),e._usePreload?i:i.promise},e._loadDefaultFont=(t,r)=>{Ve[t]=null;let a=`https://q5js.org/fonts/${t}-msdf.json`;return navigator.onLine||(a=`/node_modules/q5/builtinFonts/${t}-msdf.json`),e.loadFont(a,r)};let qe=18,We="left",$e="alphabetic",je=!1,Xe=22.5,Ye=4.5,Je=1.25;e.textFont=t=>{if(!t)return e._font;"string"!=typeof t&&(t=t.family);let r=Ve[t];if(r)e._font=r;else if(void 0===r)return e._loadDefaultFont(t)},e.textSize=e=>{if(null==e)return qe;qe=e,je||(Xe=e*Je,Ye=Xe-e)};let Ke={thin:100,extralight:200,light:300,normal:400,regular:400,medium:500,semibold:600,bold:700,bolder:800,extrabold:800,black:900,heavy:900},Ze=.5;e.textWeight=t=>{if(!t)return e._textWeight;if("string"==typeof t&&!(t=Ke[t.toLowerCase().replace(/[ _-]/g,"")]))throw new Error(`Invalid font weight: ${t}`);Ze=.6875-375e-6*t},e.textLeading=t=>{e._font.lineHeight=Xe=t,Ye=Xe-qe,Je=Xe/qe,je=!0},e.textAlign=(e,t)=>{We=e,t&&($e=t)};let et=[],tt=[],rt=(e,t,r)=>{let a=0,n=0,i=0,o=0,s=0,l=[],d=t.charCodeAt(0);for(let c=0;c<t.length;++c){let h=d;switch(d=c<t.length-1?t.charCodeAt(c+1):-1,h){case 10:l.push(n),o++,a=Math.max(a,n),n=0,i-=e.lineHeight*Je;break;case 13:break;case 32:n+=e.getXAdvance(h);break;case 9:n+=2*e.getXAdvance(h);break;default:r&&r(n,i,o,e.getChar(h)),n+=e.getXAdvance(h,d),s++}}return l.push(n),a=Math.max(a,n),{width:a,height:l.length*e.lineHeight*Je,lineWidths:l,printedCharCount:s}};e.text=(t,r,a,n,i)=>{if(!e._font)return void(null!==e._font&&e.textFont("sans-serif"));let o=typeof t;if("string"!=o&&("object"==o?t=t.toString():t+=""),t.length>n){let e=[],r=0;for(;r<t.length&&e.length<i;){let a=r+n;if(a>=t.length){e.push(t.slice(r));break}let i=t.lastIndexOf(" ",a);(-1==i||i<r)&&(i=a),e.push(t.slice(r,i)),r=i+1}t=e.join("\n")}let s;for(let e=0;e<t.length;e++){switch(t[e]){case"\n":s=!0;case"\r":case"\t":case" ":0}}let l,d=[],c=We,h=$e,u=tt.length,p=0;if("left"!=c||s){l=rt(e._font,t);let r=0;"alphabetic"==h?a-=qe:"center"==h?r=.5*l.height:"bottom"==h&&(r=l.height),rt(e._font,t,((e,t,a,n)=>{let i=0;"center"==c?i=-.5*l.width- -.5*(l.width-l.lineWidths[a]):"right"==c&&(i=-l.lineWidths[a]),d[p]=e+i,d[p+1]=t+r,d[p+2]=n.charIndex,d[p+3]=u,p+=4}))}else l=rt(e._font,t,((e,t,r,a)=>{d[p]=e,d[p+1]=t,d[p+2]=a.charIndex,d[p+3]=u,p+=4})),"alphabetic"==h?a-=qe:"center"==h?a-=.5*qe:"bottom"==h&&(a-=Xe);et.push(d);let f=[];N&&H(),f[0]=r,f[1]=-a,f[2]=qe/42,f[3]=z,f[4]=C&&Q?R:0,f[5]=E,f[6]=M&&P?A:0,f[7]=Ze,tt.push(f),g.push(De,l.printedCharCount,e._font.index)},e.textWidth=t=>e._font?rt(e._font,t).width:0,e.createTextImage=(t,r,a)=>{if(e._g.textSize(qe),C&&Q){let t=4*R;e._g.fill(m.slice(t,t+4))}if(M&&P){let t=4*E;e._g.stroke(m.slice(t,t+4))}let n=e._g.createTextImage(t,r,a);return e._extendImage(n),n},e.textImage=(t,r,a)=>{"string"==typeof t&&(t=e.createTextImage(t));let n=ke;ke="corner";let i=We;"center"==i?r-=t.canvas.hw:"right"==i&&(r-=t.width);let o=$e;"alphabetic"==o?a-=t._leading:"center"==o?a-=t._middle:"bottom"==o?a-=t._bottom:"top"==o&&(a-=t._top),e.image(t,r,a),ke=n};let at=["frame","shapes","image","video","text"],nt={frame:10,shapes:1e3,image:2e3,video:3e3,text:4e3};e._createShader=(t,r="shapes")=>{t=t.trim();let a=e["_"+r+"ShaderCode"],n=a.indexOf("@vertex"),i=a.indexOf("@fragment");t=t.includes("@fragment")?t.includes("@vertex")?a.slice(0,n)+t:a.slice(0,i)+t:a.slice(0,n)+t+"\n\n"+a.slice(i);let o=Q5.device.createShaderModule({label:r+"Shader",code:t});o.type=r;let s=at.indexOf(r),l=Object.assign({},e._pipelineConfigs[s]);l.vertex.module=l.fragment.module=o;let d=nt[r];return e._pipelines[d]=Q5.device.createRenderPipeline(l),e._pipelines[d].shader=o,o.pipelineIndex=d,nt[r]++,o},e.createShader=e.createShapesShader=e._createShader,e.createFrameShader=t=>e._createShader(t,"frame"),e.createImageShader=t=>e._createShader(t,"image"),e.createVideoShader=t=>e._createShader(t,"video"),e.createTextShader=t=>e._createShader(t,"text"),e.shader=e=>{let t=e.type,r=e.pipelineIndex;"frame"==t?e.applyBeforeDraw?p=r:f=r:"shapes"==t?K=r:"image"==t?ve=r:"video"==t?ye=r:"text"==t&&(De=r)},e.resetShader=e.resetShapesShader=()=>K=1,e.resetFrameShader=()=>p=f=0,e.resetImageShader=()=>ve=2,e.resetVideoShader=()=>ye=3,e.resetTextShader=()=>De=4,e.resetShaders=()=>{p=f=0,K=1,ve=2,ye=3,De=4}},Q5.THRESHOLD=1,Q5.GRAY=2,Q5.OPAQUE=3,Q5.INVERT=4,Q5.POSTERIZE=5,Q5.DILATE=6,Q5.ERODE=7,Q5.BLUR=8,Q5.initWebGPU=async()=>{if(!navigator.gpu)return console.warn("q5 WebGPU not supported on this browser! Use Google Chrome or Edge."),!1;if(!Q5.requestedGPU){let e=await navigator.gpu.requestAdapter();if(!e)return console.warn("q5 WebGPU could not start! No appropriate GPUAdapter found, vulkan may need to be enabled."),!1;Q5.device=await e.requestDevice(),Q5.device.lost.then((e=>{console.error("WebGPU crashed!"),console.error(e)}))}return!0},Q5.WebGPU=async function(e,t){return e&&"global"!=e||(Q5._hasGlobal=!0),await Q5.initWebGPU()?new Q5(e,t,"webgpu"):new Q5(e,t,"webgpu-fallback")},Q5.webgpu=Q5.WebGPU;