1var xc=Object.defineProperty;var Rc=(r,t,e)=>t in r?xc(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var oe=(r,t,e)=>Rc(r,typeof t!="symbol"?t+"":t,e);(function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};r.SENTRY_RELEASE={id:"ec65497b241fdbfd1cbd148776c6a752d3b4e69a"}}catch{}})();class Le{subscribable=new qn(this);subscribers=new Set;subscribe(t){return this.subscribers.add(t),()=>this.unsubscribe(t)}unsubscribe(t){this.subscribers.delete(t)}clear(){this.subscribers.clear()}notifySubscribers(t){return[...this.subscribers].map(e=>e(t))}}class qn{dispatcher;constructor(t){this.dispatcher=t}subscribe(t){return this.dispatcher.subscribe(t)}unsubscribe(t){this.dispatcher.unsubscribe(t)}}class Ec extends Le{async dispatch(t){await Promise.all(this.notifySubscribers(t))}}class yt extends Le{dispatch(t){this.notifySubscribers(t)}}class Tc extends Le{value=!1;raise(){this.value||(this.value=!0,this.notifySubscribers())}reset(){this.value=!1}isRaised(){return this.value}subscribe(t){const e=super.subscribe(t);return this.value&&t(),e}}class pt extends Le{value;subscribable=new Mc(this);get current(){return this.value}set current(t){this.value=t,this.notifySubscribers(t)}constructor(t){super(),this.value=t}subscribe(t,e=!0){const n=super.subscribe(t);return e&&t(this.value),n}}class Mc extends qn{get current(){return this.dispatcher.current}subscribe(t,e=!0){return this.dispatcher.subscribe(t,e)}}class bt{name;initial;type=void 0;spacing=!1;description="";get onChanged(){return this.value.subscribable}value;get onDisabled(){return this.disabled.subscribable}disabled=new pt(!1);constructor(t,e){this.name=t,this.initial=e,this.value=new pt(e)}get(){return this.value.current}set(t){this.value.current=this.parse(t)}parse(t){return t}serialize(){return this.value.current}clone(){return new this.constructor(this.name,this.get())}disable(t=!0){return this.disabled.current=t,this}space(t=!0){return this.spacing=t,this}describe(t){return this.description=t,this}}const At=class extends bt{type=Object;get onFieldsChanged(){return this.event.subscribable}ignoreChange=!1;customFields={};fields;event;constructor(r,t){const e=new Map(Object.entries(t));super(r,Object.fromEntries(Array.from(e,([n,a])=>[n,a.get()]))),this.event=new pt([...e.values()]),this.fields=e;for(const[n,a]of this.fields)Object.defineProperty(this,n,{value:a}),a.onChanged.subscribe(this.handleChange)}set(r){this.ignoreChange=!0;for(const[t,e]of Object.entries(r)){const n=this.fields.get(t);n?n.set(e):this.customFields[t]=e}this.ignoreChange=!1,this.handleChange()}serialize(){return{...this.transform("serialize"),...this.customFields}}clone(){const r=new this.constructor(this.name,this.transform("clone"));return r.set(structuredClone(this.customFields)),r}handleChange=()=>{this.ignoreChange||(this.value.current={...this.transform("get"),...this.customFields})};transform(r){return Object.fromEntries(Array.from(this.fields,([t,e])=>[t,e[r]()]))}};class vs extends bt{type=Boolean;parse(t){return!!t}}class Dn extends Error{remarks;object;durationMs;inspect;constructor(t,e){typeof t=="string"?(super(t),this.remarks=e):(super(t.message),this.remarks=t.remarks,this.object=t.object,this.durationMs=t.durationMs,this.inspect=t.inspect)}}class Nn{resolveCurrent=null;current=null;async acquire(){for(;this.current;)await this.current;this.current=new Promise(t=>{this.resolveCurrent=t})}release(){this.current=null,this.resolveCurrent?.(),this.resolveCurrent=null}}const je=[];function Et(){const r=je.at(-1);if(!r)throw new Error("The scene is not available in the current context.");return r}function Pc(r){je.push(r)}function Ac(r){je.pop()!==r&&console.error("startScene/endScene were called out of order.")}function Lt(){return je.at(-1)?.logger??console}const js=[];function qt(){const r=js.at(-1);if(!r)throw new Dn("The thread is not available in the current context.",`<p><code>useThread()</code> can only be called from within generator functions. 2 It's not available during rendering.</p> 3`);return r}function bn(r){js.push(r)}function yn(r){if(js.pop()!==r)throw new Error("startThread/endThread was called out of order.")}function $l(r){return r[0].toUpperCase()+r.slice(1)}function Gl(){let r;return t=>{if(t===void 0)return r;r=t}}function Vl(r,t){return e=>{r[t]=e}}function Bn(r){return{message:r.message,stack:r.stack,remarks:r.remarks}}function Wl(r,t){return{level:xt.Error,message:r,remarks:`<p>This feature requires enabling the <code>experimentalFeatures</code>
3 flag in your project 4configuration:</p> 5<pre class=""><code class="language-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title function_">makeProject</span>({ 6 <span class="hljs-attr">experimentalFeatures</span>: <span class="hljs-literal">true</span>, 7 <span class="hljs-comment">// ...</span> 8});</code></pre><p><a href='https://motioncanvas.io/docs/experimental' target='_blank'>Learn more</a> about experimental 9features.</p> 10`}}function Qt(r,t=document.createElement("canvas")){const e=t.getContext("2d",r);if(!e)throw new Error("Could not create a 2D context.");return e}const Lc=180/Math.PI,ws=Math.PI/180;function Xl(r){return r}function vn(r,t,e){let n=0,a=r;t!==void 0&&(n=r,a=t),e=e===void 0?n<a?1:-1:e;const u=[];let l=Math.max(Math.ceil((a-n)/e),0),p=0;for(;l--;)u[p++]=n,n+=e;return u}function zn(r){const t=Et(),e=qt();return t.timeEvents.register(r,e.time())}const Cs=[];function Fs(){const r=Cs.at(-1);if(!r)throw new Error("The playback is not available in the current context.");return r}function jc(r){Cs.push(r)}function Cc(r){Cs.pop()!==r&&console.error("startPlayback/endPlayback were called out of order.")}function dt(r,...t){const e={[r.name]:r},n=Object.getOwnPropertyDescriptor(e,r.name);if(n)for(let a=t.length-1;a>=0;a--)t[a](e,r.name,n)}const wn=Symbol.for("@imaginix-inc/motion-canvas-core/decorators/UNINITIALIZED");function Yl(r){return(t,e)=>{let n=wn;Object.defineProperty(t,e,{get(){return n===wn&&(n=r.call(this)),n}})}}function st(r){return function(t,e,n){n.value.prototype.name=r??e,n.value.prototype.threadable=!0}}async function*Ce(...r){for(const t of r)yield t;yield*Oe(...r)}async function*Fc(...r){for(const t of r)yield t;yield*Oe(!1,...r)}async function*Oc(...r){for(const t of r)Fe(t)?yield*t:t()}async function*Ic(r,t){yield*Q(zn(r)),t&&(yield*t)}async function*Q(r=0,t){const e=qt(),n=Fs().framesToSeconds(1),a=e.time()+r;for(;a-n>e.fixed;)yield;e.time(a),t&&(yield*t)}async function*qc(r,t){yield*Q(r),Fe(t)?yield*t:t()}async function*Dc(r,t){if(typeof r!="number"&&(t=r,r=1/0),r!==1/0||qt().parent!==null)for(let e=0;e<r;e++){const n=t(e);n?yield*n:yield}else Lt().error({message:"Tried to execute an infinite loop in the main thread.",remarks:`<p>Make sure to use <code>yield</code> or <code>spawn()</code> to execute the loop concurrently in a 11separate thread:</p> 12<pre class="wrong"><code class="language-ts"><span class="hljs-keyword">yield</span>* <span class="hljs-title function_">loop</span>(<span class="hljs-function">() =></span> <span class="hljs-title function_">rect</span>().<span class="hljs-title function_">opacity</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">opacity</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>));</code></pre><pre class="correct"><code class="language-ts"><span class="hljs-keyword">yield</span> <span class="hljs-title function_">loop</span>(<span class="hljs-function">() =></span> <span class="hljs-title function_">rect</span>().<span class="hljs-title function_">opacity</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">opacity</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>)); 13<span class="hljs-comment">// or</span> 14<span class="hljs-title function_">spawn</span>(<span class="hljs-title function_">loop</span>(<span class="hljs-function">() =></span> <span class="hljs-title function_">rect</span>().<span class="hljs-title function_">opacity</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">opacity</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>)));</code></pre><p>If you want to execute the loop a finite number of times, specify the iteration 15count as the first argument:</p> 16<pre class=""><code class="language-ts"><span class="hljs-keyword">yield</span>* <span class="hljs-title function_">loop</span>(<span class="hljs-number">10</span>, <span class="hljs-function">() =></span> <span class="hljs-title function_">rect</span>().<span class="hljs-title function_">opacity</span>(<span class="hljs-number">0</span>
16).<span class="hljs-title function_">opacity</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>)); 17<span class="hljs-comment">// ^ iteration count</span></code></pre>`,stack:new Error().stack})}async function*Un(r,t){const e=qt(),n=Fs().framesToSeconds(1),a=e.time()+r;let u=0;for(;a-n>e.fixed;){const l=t(u);l?yield*l:yield,u+=1}e.time(a)}async function*Nc(r,t){yield*Un(zn(r),t)}async function*$n(){}function kn(r,t){let e;return typeof r=="string"?(e=t(),xe(e,r)):(e=r(),xe(e,r)),e}async function*Bc(r,...t){for(const e of t)yield e,yield*Q(r);yield*Oe(...t)}function xe(r,t){const e=Object.getPrototypeOf(r);e.threadable||(e.threadable=!0,e.name=typeof t=="string"?t:Gn(t))}function Gn(r){return Object.getPrototypeOf(r).name??null}function zc(r){return r&&(typeof r=="object"||typeof r=="function")&&"toPromise"in r}function Fe(r){return r!==null&&typeof r=="object"&&(Symbol.iterator in r||Symbol.asyncIterator in r)&&"next"in r}function Uc(r){return r!==null&&typeof r=="object"&&Symbol.asyncIterator in r&&"next"in r}dt(Ce,st()),dt(Fc,st()),dt(Oc,st()),dt(Ic,st()),dt(Q,st()),dt(qc,st()),dt(Dc,st()),dt(Un,st()),dt(Nc,st()),dt($n,st()),dt(Bc,st());class ps{runner;get onDeferred(){return this.deferred.subscribable}deferred=new yt;children=[];value;time=le(0);get fixed(){return this.fixedTime}get canceled(){return this.isCanceled||(this.parent?.canceled??!1)}get paused(){return this.isPaused||(this.parent?.paused??!1)}get root(){return this.parent?.root??this}parent=null;isCanceled=!1;isPaused=!1;fixedTime=0;queue=[];constructor(t){this.runner=t,this.runner.task&&(Lt().error({message:`The generator "${Gn(this.runner)}" is already being executed by another thread.`,remarks:`<p>This usually happens when you mistakenly reuse a generator that is already 18running.</p> 19<p>For example, using <code>yield</code> here will run the opacity generator concurrently and 20store it in the <code>task</code> variable (in case you want to cancel or await it later):</p> 21<pre class=""><code class="language-ts"><span class="hljs-keyword">const</span> task = <span class="hljs-keyword">yield</span> <span class="hljs-title function_">rect</span>().<span class="hljs-title function_">opacity</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);</code></pre><p>Trying to <code>yield</code> this task again will cause the current error:</p> 22<pre class=""><code class="language-ts"><span class="hljs-keyword">yield</span> task;</code></pre><p>Passing it to other flow functions will also cause the error:</p> 23<pre class=""><code class="language-ts"><span class="hljs-keyword">yield</span>* <span class="hljs-title function_">all</span>(task);</code></pre><p>Try to investigate your code looking for <code>yield</code> statements whose return value 24is reused in this way. Here's an example of a common mistake:</p> 25<pre class="wrong"><code class="language-ts"><span class="hljs-keyword">yield</span>* <span class="hljs-title function_">all</span>( 26 <span class="hljs-keyword">yield</span> <span class="hljs-title function_">rect</span>().<span class="hljs-title function_">opacity</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>), 27 <span class="hljs-keyword">yield</span> <span class="hljs-title function_">rect</span>().<span class="hljs-title function_">x</span>(<span class="hljs-number">200</span>, <span class="hljs-number">1</span>), 28);</code></pre><pre class="correct"><code class="language-ts"><span class="hljs-keyword">yield</span>* <span class="hljs-title function_">all</span>( 29 <span class="hljs-title function_">rect</span>().<span class="hljs-title function_">opacity</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>), 30 <span class="hljs-title function_">rect</span>().<span class="hljs-title function_">x</span>(<span class="hljs-number">200</span>, <span class="hljs-number">1</span>), 31);</code></pre>`}),this.runner=$n()),this.runner.task=this}async next(){if(this.paused)return{value:void 0,done:!1};bn(this);const t=await this.runner.next(this.value);return yn(this),this.value=null,t}update(t){this.paused||(this.time(this.time()+t),this.fixedTime+=t),this.children=this.children.filter(e=>!e.canceled)}spawn(t){return Fe(t)||(t=t()),this.queue.push(t),t}add(t){t.parent=this,t.isCanceled=!1,t.time(this.time()),t.fixedTime=this.fixedTime,this.children.push(t),xe(t.runner,`unknown ${this.children.length}`)}drain(t){this.queue.forEach(t),this.queue=[]}cancel(){this.deferred.clear(),this.runner.return(),this.isCanceled=!0,this.parent=null,this.drain(t=>t.return())}pause(t){this.isPaused=t}runDeferred(){bn(this),this.deferred.dispatch(),yn(this)}}async function*Oe(r,...t){let e=!0;typeof r=="boolean"?e=r:t.push(r);const n=qt(),a=t.map(p=>n.children.find(w=>w.runner===p)).filter(p=>p),u=n.time();let l;if(e){for(;a.find(p=>!p.canceled);)yield;l=Math.max(...a.map(p=>p.time()))}else{for(;!a.find(w=>w.canceled);)yield;const p=a.filter(w=>w.canceled);l=Math.min(...p.map(w=>w.time()))}n.time(Math.max(u,l))}function $c(r){return typeof r?.then=="function"}async function*Vn(r,t){const e=Fs(),n=r();xe(n,"root");const a=new ps(n);t?.(a);let u=[a];for(;u.length>0;){const l=[],p=[...u],w=e.deltaTime;for(;p.length>0;){const k=p.pop();if(!k||k.canceled)continue;const E=await k.next();if(E.done)k.cancel();else if(Fe(E.value)||Uc(E.value)){const O=new ps(E.value);k.value=E.value,k.add(O),p.push(k),p.push(O)}else E.value?(k.value=yield E.value,p.push(k)):(k.update(w),k.drain(O=>{const j=new ps(O);k.add(j),l.unshift(j)}),l.unshift(k))}u=[];
31for(const k of l)k.canceled||(u.push(k),k.runDeferred());u.length>0&&(yield)}}var te,ot;dt(Oe,st()),dt(Vn,st()),(function(r){r[r.BeforeRender=0]="BeforeRender",r[r.BeginRender=1]="BeginRender",r[r.FinishRender=2]="FinishRender",r[r.AfterRender=3]="AfterRender"})(te||(te={}));class Gc{scene;get onBeforeRender(){return this.beforeRender.subscribable}beforeRender=new yt;get onBeginRender(){return this.beginRender.subscribable}beginRender=new yt;get onFinishRender(){return this.finishRender.subscribable}finishRender=new yt;get onAfterRender(){return this.afterRender.subscribable}afterRender=new yt;constructor(t){this.scene=t,this.scene.onRenderLifecycle.subscribe(([e,n])=>{switch(e){case te.BeforeRender:return this.beforeRender.dispatch(n);case te.BeginRender:return this.beginRender.dispatch(n);case te.FinishRender:return this.finishRender.dispatch(n);case te.AfterRender:return this.afterRender.dispatch(n)}}),this.scene.onReset.subscribe(()=>{this.beforeRender.clear(),this.beginRender.clear(),this.finishRender.clear(),this.afterRender.clear()})}}class se{state;nextGauss=null;constructor(t){this.state=t}static createSeed(){return Math.floor(4294967296*Math.random())}nextFloat(t=0,e=1){return q(t,e,this.next())}nextInt(t=0,e=4294967296){let n=Math.floor(q(t,e,this.next()));return n===e&&(n=t),n}gauss(t=0,e=1){let n=this.nextGauss;if(this.nextGauss=null,n===null){const a=2*this.next()*Math.PI,u=Math.sqrt(-2*Math.log(1-this.next()));n=Math.cos(a)*u,this.nextGauss=Math.sin(a)*u}return t+n*e}floatArray(t,e=0,n=1){return vn(t).map(()=>this.nextFloat(e,n))}intArray(t,e=0,n=4294967296){return vn(t).map(()=>this.nextInt(e,n))}spawn(){return new se(this.nextInt())}next(){this.state|=0,this.state=this.state+1831565813|0;let t=Math.imul(this.state^this.state>>>15,1|this.state);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}(function(r){r[r.Initial=0]="Initial",r[r.AfterTransitionIn=1]="AfterTransitionIn",r[r.CanTransitionOut=2]="CanTransitionOut",r[r.Finished=3]="Finished"})(ot||(ot={}));const Vc="resolution",Wc="destinationTexture",Xc="sourceTexture",Hl="time",Yc="deltaTime",Hc="framerate",Jl="sourceMatrix",Zl="destinationMatrix";class Jc{scene;sharedContext;gl=null;positionBuffer=null;sourceTexture=null;destinationTexture=null;positionLocation=0;quadPositions=new Float32Array([-1,1,-1,-1,1,1,1,-1]);constructor(t,e){this.scene=t,this.sharedContext=e,t.onReloaded.subscribe(this.handleReload)}setup(t){this.gl=t,this.updateViewport(),this.positionBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,this.quadPositions,t.STATIC_DRAW),t.vertexAttribPointer(this.positionLocation,2,t.FLOAT,!1,0,0),t.enableVertexAttribArray(this.positionLocation),this.sourceTexture=t.createTexture(),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.sourceTexture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),this.destinationTexture=t.createTexture(),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.destinationTexture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}teardown(t){t.deleteBuffer(this.positionBuffer),t.disableVertexAttribArray(this.positionLocation),t.deleteTexture(this.sourceTexture),t.deleteTexture(this.destinationTexture),this.positionBuffer=null,this.sourceTexture=null,this.destinationTexture=null,this.gl=null}handleReload=()=>{this.gl&&this.updateViewport()};updateViewport(){if(this.gl){const t=this.scene.getRealSize();this.gl.canvas.width=t.width,this.gl.canvas.height=t.height,this.gl.viewport(0,0,t.width,t.height)}}getGL(){return this.gl??this.sharedContext.borrow(this)}getProgram(t){const e=this.sharedContext.getProgram(t,`#version 300 es 32 33in vec2 position; 34 35out vec2 screenUV; 36out vec2 sourceUV; 37out vec2 destinationUV; 38 39uniform mat4 sourceMatrix; 40uniform mat4 destinationMatrix; 41 42void main() { 43 vec2 position_source = position * 0.5 + 0.5; 44 vec4 position_screen = sourceMatrix * vec4(position_source, 0, 1); 45 46 screenUV = position_screen.xy; 47 sourceUV = position_source; 48 destinationUV = (destinationMatrix * position_screen).xy; 49 50 gl_Position = (position_screen - 0.5) * 2.0; 51} 52`);if(!e)return null;const n=this.scene.getRealSize(),a=this.getGL();return a.useProgram(e),a.uniform1i(a.getUniformLocation(e,Xc),0),a.uniform1i(a.getUniformLocation(e,Wc),1),a.uniform2f(a.getUniformLocation(e,Vc),n.x,n.y),a.uniform1f(a.getUniformLocation(e,Yc),this.scene.playback.deltaTime),a.uniform1f(a.getUniformLocation(e,Hc),this.scene.playback.fps),e}copyTextures(t,e){this.copyTexture(e,this.sourceTexture),this.copyTexture(t,this.destinationTexture)}clear(){const t=this.getGL();t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT)}render(){const t=this.getGL();t.drawArrays(t.TRIANGLE_STRIP,0,4)}copyTexture(t,e){const n=this.getGL();n.bindTexture(n.TEXTURE_2D,e),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),n.generateMipmap(n.TEXTURE_2D)}}var It;(function(r){r[r.Playing=0]="Playing",r[r.Rendering=1]="Rendering",r[r.Paused=2]="Paused",r[r.Presenting=3]="Presenting"})(It||(It={}));class Zc{get onSceneChanged(){return this.currentSceneReference===null&&console.error("PlaybackManager has not been properly initialized"),this.currentSceneReference?.subscribable}get onScenesRecalculated(){return this.scenes.subscribable}frame=0;speed=1;fps=30;duration=0;finished=!1;slides=[];previousScene=null;state=It.Paused;get currentScene(){if(this.currentSceneReference===null)throw new Error("PlaybackManager has not been properly initialized");return this.currentSceneReference.current}set currentScene(t){if(!t)throw new Error("Invalid scene.");this.currentSceneReference??=new pt(t),this.currentSceneReference.current=t}currentSceneReference=null;scenes=new pt([]);setup(t){this.scenes.current=t,this.currentScene=t[0]}async progress(){return this.finished=await this.next(),this.finished}async seek(t){if(t<=this.frame||this.currentScene.isCached()&&this.currentScene.lastFrame<t){const e=this.findBestScene(t);e!==this.currentScene?(this.previousScene=null,this.currentScene=e,this.frame=this.currentScene.firstFrame,await this.currentScene.reset(void 0)):this.frame>=t&&(this.previousScene=null,this.frame=this.currentScene.firstFrame,await this.currentScene.reset(void 0))}for(this.finished=!1;this.frame<t&&!this.finished;)this.finished=await this.next();return this.finished}async goBack(){let t=this.currentScene.slides.getCurrent();
52if(t&&this.currentScene.slides.isWaiting()){const e=this.slides.indexOf(t);t=this.slides[e-1]}await this.seekSlide(t)}async goForward(){const t=this.currentScene.slides.getCurrent(),e=this.slides.indexOf(t);await this.seekSlide(this.slides[e+1])}async goTo(t){await this.seekSlide(this.slides.find(e=>e.id===t))}async seekSlide(t=null){if(!t)return;const{id:e,scene:n}=t;for((this.currentScene!==n||this.currentScene.slides.didHappen(e))&&(this.previousScene=null,this.currentScene=n,this.frame=this.currentScene.firstFrame,this.currentScene.slides.setTarget(e),await this.currentScene.reset()),this.finished=!1,this.currentScene.slides.setTarget(e);!this.currentScene.slides.isWaitingFor(e)&&!this.finished;)this.finished=await this.next();return this.currentScene.slides.setTarget(null),this.finished}async reset(){this.previousScene=null,this.currentScene=this.scenes.current[0],this.frame=0,this.finished=!1,await this.currentScene.reset()}reload(t){this.scenes.current.forEach(e=>e.reload(t))}async recalculate(){this.previousScene=null,this.slides=[],this.finished=!1;const t=this.speed;this.frame=0,this.speed=1;const e=[];try{for(const n of this.scenes.current)await n.recalculate(a=>{this.frame=a}),this.slides.push(...n.slides.onChanged.current),e.push(n)}finally{this.speed=t}this.scenes.current=e,this.duration=this.frame,this.finished=!1}async next(){if(this.previousScene&&(await this.previousScene.next(),this.currentScene.isFinished()&&(this.previousScene=null)),this.frame+=this.speed,this.currentScene.isFinished())return!0;if(await this.currentScene.next(),this.previousScene&&this.currentScene.isAfterTransitionIn()&&(this.previousScene=null),this.currentScene.canTransitionOut()){this.previousScene=this.currentScene;const t=this.getNextScene(this.previousScene);t&&(this.currentScene=t,await this.currentScene.reset(this.previousScene)),t&&!this.currentScene.isAfterTransitionIn()||(this.previousScene=null)}return this.currentScene.isFinished()}findBestScene(t){let e=this.scenes.current[0];for(const n of this.scenes.current){if(!n.isCached()||n.lastFrame>t)return t>n.firstFrame+n.transitionDuration?n:e;e=n}return e}getNextScene(t){const e=this.scenes.current;if(!t)return e[0];const n=e.findIndex(a=>a===t);return n<0?null:e[n+1]??null}}class Kc{scene;get onChanged(){return this.slides.subscribable}slides=new pt([]);lookup=new Map;collisionLookup=new Set;current=null;canResume=!1;waitsForId=null;targetId=null;constructor(t){this.scene=t,this.scene.onReloaded.subscribe(this.handleReload),this.scene.onReset.subscribe(this.handleReset),this.scene.onRecalculated.subscribe(this.handleRecalculated)}setTarget(t){this.targetId=t}resume(){this.canResume=!0}isWaitingFor(t){return this.waitsForId===t}isWaiting(){return this.waitsForId!==null}didHappen(t){if(this.current===null)return!1;for(const e of this.lookup.keys()){if(e===t)return!0;if(e===this.current?.id)return!1}return!1}getCurrent(){return this.current}register(t,e){if(this.waitsForId!==null)throw new Error(`The animation already waits for a slide: ${this.waitsForId}.`);const n=this.toId(t);this.scene.playback.state!==It.Presenting&&(this.lookup.has(n)||this.lookup.set(n,{id:n,name:t,time:e,scene:this.scene,stack:new Error().stack}),this.collisionLookup.has(t)?this.scene.logger.warn({message:`A slide named "${t}" already exists.`,stack:new Error().stack}):this.collisionLookup.add(t)),this.waitsForId=n,this.current=this.lookup.get(n)??null,this.canResume=!1}shouldWait(t){const e=this.toId(t);if(this.waitsForId!==e)throw new Error(`The animation waits for a different slide: ${this.waitsForId}.`);if(!this.lookup.get(e))throw new Error(`Could not find the "${t}" slide.`);let n=this.canResume;return this.scene.playback.state!==It.Presenting&&(n=e!==this.targetId),n&&(this.waitsForId=null),!n}handleReload=()=>{this.lookup.clear(),this.collisionLookup.clear(),this.current=null,this.waitsForId=null,this.targetId=null};handleReset=()=>{this.collisionLookup.clear(),this.current=null,this.waitsForId=null};handleRecalculated=()=>{this.slides.current=[...this.lookup.values()]};toId(t){return`${this.scene.name}:${t}`}}class _c{scene;get onChanged(){return this.sounds.subscribable}sounds=new pt([]);registeredSounds=[];constructor(t){this.scene=t,this.scene.onReset.subscribe(this.reset),this.scene.onReloaded.subscribe(this.reset),this.scene.onRecalculated.subscribe(this.handleRecalculated)}add(t,e){const n=this.scene.playback.time+(e??0);this.registeredSounds.push({offset:n,realPlaybackRate:2**((t.detune??0)/1200)*(t.playbackRate??1),...t}),this.sounds.current=[...this.registeredSounds]}getSounds(){return this.registeredSounds}handleRecalculated=()=>{this.sounds.current=[...this.registeredSounds]};reset=()=>{this.registeredSounds=[],this.sounds.current=[]}}class Qc{scene;get onChanged(){return this.sounds.subscribable}sounds=new pt([]);registeredSounds=[];constructor(t){this.scene=t,this.scene.onReset.subscribe(this.reset),this.scene.onReloaded.subscribe(this.reset),this.scene.onRecalculated.subscribe(this.handleRecalculated)}add(t,e=-.1){const n=this.scene.playback.time+(e??0);this.registeredSounds.push({offset:n,realPlaybackRate:2**((t.detune??0)/1200)*(t.playbackRate??1),...t}),this.sounds.current=[...this.registeredSounds]}getSounds(){return this.registeredSounds}handleRecalculated=()=>{this.sounds.current=[...this.registeredSounds]};reset=()=>{this.registeredSounds=[],this.sounds.current=[]}}class tl{scene;signals={};variables={};constructor(t){this.scene=t,t.onReset.subscribe(this.handleReset)}get(t,e){return this.signals[t]??=le(this.variables[t]??e),()=>this.signals[t]()}updateSignals(t){this.variables=t,Object.keys(t).map(e=>{e in this.signals&&this.signals[e](t[e])})}handleReset=()=>{this.signals={}}}class Kl{name;playback;logger;meta;timeEvents;shaders;slides;sounds;ttsStreamSounds;ttsEndpoint;ttsQuery;gifEndpoint;variables;random;creationStack;previousOnTop;get firstFrame(){return this.cache.current.firstFrame}get transitionDuration(){return this.cache.current.transitionDuration}get lastFrame(){return this.firstFrame+this.cache.current.duration}get onCacheChanged(){return this.cache.subscribable}cache=new pt({firstFrame:0,transitionDuration:0,duration:0,lastFrame:0});get onReloaded(){return this.reloaded.subscribable}reloaded=new yt;get onRecalculated(){return this.recalculated.subscribable}recalculated=new yt;get onThreadChanged(){return this.thread.subscribable}thread=new pt(null);get onRenderLifecycle(){return this.renderLifecycle.subscribable}renderLifecycle=new yt;get onReset(){return this.afterReset.subscribable}afterReset=new yt;lifecycleEvents=new Gc(this);get LifecycleEvents(){return this.logger.warn("LifecycleEvents is deprecated. Use lifecycleEvents instead."),this.lifecycleEvents}get previous(){return this.previousScene}experimentalFeatures;resolutionScale;runnerFactory;previousScene=null;runner=null;state=ot.Initial;cached=!1;counters={};size;constructor(t){this.name=t.name,this.size=t.size,this.resolutionScale=t.resolutionScale,this.logger=t.logger,this.playback=t.playback,this.ttsEndpoint=t.ttsEndpoint,this.tt
52sQuery=t.ttsQuery,this.gifEndpoint=t.gifEndpoint,this.meta=t.meta,this.runnerFactory=t.config,this.creationStack=t.stack,this.experimentalFeatures=t.experimentalFeatures??!1,dt(this.runnerFactory,st(this.name)),this.timeEvents=new t.timeEventsClass(this),this.variables=new tl(this),this.shaders=new Jc(this,t.sharedWebGLContext),this.slides=new Kc(this),this.sounds=new _c(this),this.ttsStreamSounds=new Qc(this),this.random=new se(this.meta.seed.get()),this.previousOnTop=!1}get isRecalculating(){return this.runnerFactory?.recalculating??!1}update(){}async render(t){let e=0;do e++,await ft.consumePromises(),t.save(),t.clearRect(0,0,t.canvas.width,t.canvas.height),this.execute(()=>this.draw(t)),t.restore();while(ft.hasPromises()&&e<10);e>1&&this.logger.debug(`render iterations: ${e}`)}reload({config:t,size:e,stack:n,resolutionScale:a}={}){t&&(this.runnerFactory=t),e&&(this.size=e),a&&(this.resolutionScale=a),n&&(this.creationStack=n),this.cached=!1,this.reloaded.dispatch()}async recalculate(t){this.runnerFactory.recalculating=!0;const e=this.cache.current;if(e.firstFrame=this.playback.frame,e.lastFrame=e.firstFrame+e.duration,this.isCached())return t(e.lastFrame),this.cache.current={...e},void(this.runnerFactory.recalculating=!1);for(e.transitionDuration=-1,await this.reset();!this.canTransitionOut();)e.transitionDuration<0&&this.state===ot.AfterTransitionIn&&(e.transitionDuration=this.playback.frame-e.firstFrame),t(this.playback.frame+1),await this.next();e.transitionDuration===-1&&(e.transitionDuration=0),e.lastFrame=this.playback.frame,e.duration=e.lastFrame-e.firstFrame,await new Promise(n=>setTimeout(n,0)),this.cached=!0,this.cache.current={...e},this.recalculated.dispatch(),this.runnerFactory.recalculating=!1}async next(){if(!this.runner)return;let t=await this.execute(()=>this.runner.next());for(this.update();t.value;){if(zc(t.value)){const e=await t.value.toPromise();t=await this.execute(()=>this.runner.next(e))}else if($c(t.value)){const e=await t.value;t=await this.execute(()=>this.runner.next(e))}else this.logger.warn({message:"Invalid value yielded by the scene.",object:t.value}),t=await this.execute(()=>this.runner.next(t.value));this.update()}if(ft.hasPromises()){const e=await ft.consumePromises();this.logger.error({message:"Tried to access an asynchronous property before the node was ready. Make sure to yield the node before accessing the property.",stack:e[0].stack,inspect:e[0].owner?.key??void 0})}t.done&&(this.state=ot.Finished)}async reset(t=null){this.counters={},this.previousScene=t,this.previousOnTop=!1,this.random=new se(this.meta.seed.get()),this.runner=Vn(()=>this.runnerFactory(this.getView()),e=>{this.thread.current=e}),this.state=ot.AfterTransitionIn,this.afterReset.dispatch(),await this.next()}getSize(){return this.size}getRealSize(){return this.size.mul(this.resolutionScale)}isAfterTransitionIn(){return this.state===ot.AfterTransitionIn}canTransitionOut(){return this.state===ot.CanTransitionOut||this.state===ot.Finished}isFinished(){return this.state===ot.Finished}enterInitial(){this.state===ot.AfterTransitionIn?this.state=ot.Initial:this.logger.warn(`Scene ${this.name} entered initial in an unexpected state: ${this.state}`)}enterAfterTransitionIn(){this.state===ot.Initial?this.state=ot.AfterTransitionIn:this.logger.warn(`Scene ${this.name} transitioned in an unexpected state: ${this.state}`)}enterCanTransitionOut(){this.state===ot.AfterTransitionIn||this.state===ot.Initial?this.state=ot.CanTransitionOut:this.logger.warn(`Scene ${this.name} was marked as finished in an unexpected state: ${this.state}`)}isCached(){return this.cached}async execute(t){let e;Pc(this),jc(this.playback);try{e=await t()}finally{Cc(this.playback),Ac(this)}return e}}function _l(){return new At("scene",{version:new bt("version",1),timeEvents:new bt("time events",[]),seed:new bt("seed",se.createSeed())})}function Ql(r,t=!0){return typeof r=="number"?new se(t?r:r+Et().meta.seed.get()):Et().random}function th(){return qt().time()}function el(r,t,e){const n=[...r],a=[...t];if(a.length>
52=n.length){const u=Math.floor(a.length*e),l=Math.floor(q(n.length-1,a.length,e));let p="";for(let w=0;w<a.length;w++)w<u?p+=a[w]:(n[w]||w<=l)&&(p+=n[w]??a[w]);return p}{const u=Math.round(n.length*(1-e)),l=Math.floor(q(n.length+1,a.length,e)),p=[];for(let w=n.length-1;w>=0;w--)w<u?p.unshift(n[w]):(a[w]||w<l)&&p.unshift(a[w]??n[w]);return p.join("")}}function ks(r,t,e,n=!1){if(e===0)return r;if(e===1)return t;if(r!=null&&t!=null){if(typeof r=="number"&&typeof t=="number")return q(r,t,e);if(typeof r=="string"&&typeof t=="string")return el(r,t,e);if(typeof r=="boolean"&&typeof t=="boolean")return e<.5?r:t;if("lerp"in r)return r.lerp(t,e);if(r&&t&&typeof r=="object"&&typeof t=="object")if(Array.isArray(r)&&Array.isArray(t)){if(r.length===t.length)return r.map((a,u)=>ks(a,t[u],e))}else{let a=!1;if(r instanceof Map||t instanceof Map||(a=!0,r=new Map(Object.entries(r)),t=new Map(Object.entries(t))),r instanceof Map&&t instanceof Map){const u=new Map;for(const l of new Set([...r.keys(),...t.keys()])){const p=ks(r.get(l),t.get(l),e,!0);p!==void 0&&u.set(l,p)}return a?Object.fromEntries(u):u}}return t}n||Lt().warn(`Attempting to lerp ${r} -> ${t} may result in unexpected behavior.`)}function eh(r,t,e){return e<.5?r:t}function q(r,t,e){return r+(t-r)*e}function sl(r,t,e,n,a){return e+(a-r)*(n-e)/(t-r)}function Tt(r,t,e){return e<r?r:e>t?t:e}function Re(r,t,e,n,a){const u=sl(r,t,e,n,a);return e>n&&([e,n]=[n,e]),Tt(e,n,u)}function Wn(r,t,e){let n=t;e>1?e=1/e:n=!n;const a=q(n?Math.acos(Tt(-1,1,1-r)):Math.asin(r),q(0,Math.PI/2,r),e);let u=Math.sin(a),l=1-Math.cos(a);return t&&([u,l]=[l,u]),new v(u,l)}async function*rl(r,t,e,n,a,u){const l=typeof n=="number"?n:.001;u=typeof n=="number"?u:a;const p=(K,lt)=>{typeof n=="function"?n(K,lt):typeof a=="function"&&a(K,lt)};if((r=r??{mass:.05,stiffness:10,damping:.5}).mass<=0)return void Lt().error(new Error("Spring mass must be greater than 0."));if(r.stiffness<0)return void Lt().error(new Error("Spring stiffness must be greater or equal to 0."));if(r.damping<0)return void Lt().error(new Error("Spring damping must be greater or equal to 0."));const w=qt();let k=t,E=r.initialVelocity??0;const O=K=>{if(r===null)return;const lt=k-e,A=-r.stiffness*lt-r.damping*E;E+=A/r.mass*K,k+=E*K},j=1/120;p(t,0);const b=w.time();let F=b,Z=!1;for(;!Z;){for(;F<w.fixed;){const K=w.fixed-F;if(j>K?(O(K),F=w.fixed):(O(j),F+=j),Math.abs(e-k)<l&&Math.abs(E)<l){w.time(F),Z=!0;break}}Z||(p(k,w.fixed-b),yield)}p(e,w.fixed-b),u?.(e,w.fixed-b)}function Xn(r,t,e,n){return{mass:r,stiffness:t,damping:e,initialVelocity:n}}dt(rl,st());const sh=Xn(.2,20,.68,0),rh=Xn(.16,15.35,1.88,0);function nh(r,t=0,e=1){return q(t,e,r=1-Math.cos(r*Math.PI/2))}function ih(r,t=0,e=1){return q(t,e,r=Math.sin(r*Math.PI/2))}function ah(r,t=0,e=1){return q(t,e,r=-(Math.cos(Math.PI*r)-1)/2)}function oh(r,t=0,e=1){return q(t,e,r*=r)}function uh(r,t=0,e=1){return q(t,e,r=1-Math.pow(1-r,2))}function ch(r,t=0,e=1){return q(t,e,r=r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2)}function lh(r,t=0,e=1){return q(t,e,r*=r*r)}function hh(r,t=0,e=1){return q(t,e,r=1-Math.pow(1-r,3))}function Ee(r,t=0,e=1){return q(t,e,r=r<.5?4*r*r*r:1-Math.pow(-2*r+2,3)/2)}function dh(r,t=0,e=1){return q(t,e,r=r===0?0:Math.pow(2,10*r-10))}function fh(r,t=0,e=1){return q(t,e,r=r===1?1:1-Math.pow(2,-10*r))}function ph(r,t=0,e=1){return q(t,e,r=r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2)}function nl(r=1.70158){return(t,e=0,n=1)=>q(e,n,t=(r+1)*t*t*t-r*t*t)}function il(r=1.70158){return(t,e=0,n=1)=>q(e,n,t=1+(r+1)*Math.pow(t-1,3)+r*Math.pow(t-1,2))}function al(r=1.70158,t=1.525){return(e,n=0,a=1)=>q(n,a,e=e<.5?Math.pow(2*e,2)*(2*(r*t+1)*e-r*t)/2:(Math.pow(2*e-2,2)*((r*t+1)*(2*e-2)+r*t)+2)/2)}function ol(r=2.094395){return(t,e=0,n=1)=>q(e,n,t=t===0?0:t===1?1:-Math.pow(2,10*t-10)*Math.sin((10*t-10.75)*r))}function ul(r=2.094395){return(t,e=0,n=1)=>q(e,n,t=t===0?0:t===1?1:Math.pow(2,-10*t)*Math.sin((10*t-.75)*r)+1)}function cl(r=1.39626){return(t,e=0,n=1)=>q(e,n,t=t===0?0:t===1?1:t<.5?-Math.pow(2,20*t-10)*Math.sin((20*t-11.125)*r)/2:Math.pow(2,-20*t+10)*Math.sin((20*t-11.125)*r)/2+1)}function ll(r=7.5625,t=2.75){const e=Os(r,t);return(n,a=0,u=1)=>1-e(1-n,a,u)}function Os(r=7.5625,t=2.75){return(e,n=0,a=1)=>(e<1/t?e*=r*e:e=e<2/t?r*(e-=1.505/t)*e+.75:e<2.5/t?r*(e-=2.25/t)*e+.9375:r*(e-=2.625/t)*e+.984375,q(n,a,e))}function hl(r=7.5625,t=2.75){const e=Os(r,t);return(n,a=0,u=1)=>n<.5?(1-e(1-2*n,a,u))/2:(1+e(2*n-1,a,u))/2}function Yn(r,t=0,e=1){return q(t,e,r)}const gh=nl(),mh=il(),bh=al(),yh=ll(),vh=Os(),wh=hl(),kh=ol(),Sh=ul(),xh=cl();async function*Hn(r,t,e){const n=qt(),a=n.time(),u=n.time()+r;for(t(0,0);u>n.fixed;){const l=n.fixed-a;l>0&&t(l/r,l),yield}n.time(u),t(1,r),e?.(1,r)}dt(Hn,st());class ft{owner;static collectionSet=new Set;static collectionStack=[];static promises=[];static collectPromise(t,e=null){const n={promise:t,value:e,stack:new Error().stack},a=this.collectionStack.at(-1);return a&&(n.owner=a.owner),t.then(u=>{n.value=u,a?.markDirty()}),this.promises.push(n),n}static hasPromises(){return this.promises.length>0}static async consumePromises(){const t=[...this.promises];return await Promise.all(t.map(e=>e.promise)),this.promises=this.promises.filter(e=>!t.includes(e)),t}invokable;dependencies=new Set;event=new Tc;markDirty=()=>this.event.raise();constructor(t){this.owner=t,this.invokable=this.invoke.bind(this),Ob
52ject.defineProperty(this.invokable,"context",{value:this}),Object.defineProperty(this.invokable,"toPromise",{value:this.toPromise.bind(this)})}invoke(){}startCollecting(){if(ft.collectionSet.has(this))throw new Dn("A circular dependency occurred between signals.",`This can happen when signals reference each other in a loop. 53 Try using the attached stack trace to locate said loop.`);ft.collectionSet.add(this),ft.collectionStack.push(this)}finishCollecting(){if(ft.collectionSet.delete(this),ft.collectionStack.pop()!==this)throw new Error("collectStart/collectEnd was called out of order.")}clearDependencies(){this.dependencies.forEach(t=>t.unsubscribe(this.markDirty)),this.dependencies.clear()}collect(){const t=ft.collectionStack.at(-1);t&&(t.dependencies.add(this.event.subscribable),this.event.subscribe(t.markDirty))}dispose(){this.clearDependencies(),this.event.clear(),this.owner=null}async toPromise(){do await ft.consumePromises(),this.invokable();while(ft.hasPromises());return this.invokable}}const Sn=Symbol.for("@imaginix-inc/motion-canvas-core/signals/default");function ee(r){return typeof r=="function"}function dl(r,t){return ee(r)?()=>t(r()):t(r)}function Jn(r){return ee(r)?r():r}class Te extends ft{initial;interpolation;parser;extensions;current;last;tweening=!1;constructor(t,e,n=void 0,a=l=>l,u={}){super(n),this.initial=t,this.interpolation=e,this.parser=a,Object.defineProperty(this.invokable,"reset",{value:this.reset.bind(this)}),Object.defineProperty(this.invokable,"save",{value:this.save.bind(this)}),Object.defineProperty(this.invokable,"isInitial",{value:this.isInitial.bind(this)}),this.initial!==void 0&&(this.current=this.initial,this.markDirty(),ee(this.initial)||(this.last=this.parse(this.initial))),this.extensions={getter:this.getter.bind(this),setter:this.setter.bind(this),tweener:this.tweener.bind(this),...u}}toSignal(){return this.invokable}parse(t){return this.parser(t)}set(t){return this.extensions.setter(t),this.owner}setter(t){return t===Sn&&(t=this.initial),this.current===t||(this.current=t,this.clearDependencies(),ee(t)||(this.last=this.parse(t)),this.markDirty()),this.owner}get(){return this.extensions.getter()}getter(){if(this.event.isRaised()&&ee(this.current)){this.clearDependencies(),this.startCollecting();try{this.last=this.parse(this.current())}catch(t){Lt().error({...Bn(t),inspect:this.owner?.key})}this.finishCollecting()}return this.event.reset(),this.collect(),this.last}invoke(t,e,n=Ee,a=this.interpolation){return t===void 0?this.get():e===void 0?this.set(t):this.createQueue(Ee,a).to(t,e,n,a)}createQueue(t,e){const n=this.get(),a=[],u=kn("animation chain",async function*(){for(;a.length>0;)yield*a.shift()});return u.to=(l,p,w=t,k=e)=>{const E=this.resolveTweenTiming(w,t);return t=E.timingFunction,e=k,E.delay>0&&a.push(Q(E.delay)),a.push(this.tween(l,p,E.timingFunction,k)),u},u.back=(l,p=t,w=e)=>{const k=this.resolveTweenTiming(p,t);return t=k.timingFunction,e=w,k.delay>0&&a.push(Q(k.delay)),a.push(this.tween(n,l,k.timingFunction,e)),u},u.wait=l=>(a.push(Q(l)),u),u.run=l=>(a.push(l),u),u.do=l=>(a.push(kn(async function*(){l()})),u),u}resolveTweenTiming(t,e){if(typeof t=="function")return{delay:0,timingFunction:t};const n=typeof t=="number"?t:t?.delay??0;return{delay:Number.isFinite(n)?Math.max(0,n):0,timingFunction:e}}async*tween(t,e,n,a){t===Sn&&(t=this.initial),this.tweening=!0,yield*this.extensions.tweener(t,e,n,a),this.set(t),this.tweening=!1}async*tweener(t,e,n,a){const u=this.get();yield*Hn(e,l=>{this.set(a(u,this.parse(Jn(t)),n(l)))})}dispose(){super.dispose(),this.initial=void 0,this.current=void 0,this.last=void 0}reset(){return this.initial!==void 0&&this.set(this.initial),this.owner}save(){return this.set(this.get())}isInitial(){return this.collect(),this.current===this.initial}getInitial(){return this.initial}raw(){return this.current}isTweening(){return this.tweening}}class Is extends Te{entries;signals=[];constructor(t,e,n,a,u=void 0,l={}){super(void 0,a,u,e,l),this.entries=t,this.parser=e;for(const p of t){let w,k;Array.isArray(p)?([w,k]=p,k.context.owner??=this):(w=p,k=new Te(dl(n,E=>e(E)[p]),q,u??this.invokable).toSignal()),this.signals.push([w,k]),Object.defineProperty(this.invokable,w,{value:k})}}toSignal(){return this.invokable}parse(t){return this.parser(t)}getter(){return this.parse(Object.fromEntries(this.signals.map(([t,e])=>[t,e()])))}setter(t){if(ee(t))for(const[e,n]of this.signals)n(()=>this.parser(t())[e]);else{const e=this.parse(t);for(const[n,a]of this.signals)a(e[n])}return this.owner}reset(){for(const[,t]of this.signals)t.reset();return this.owner}save(){for(const[,t]of this.signals)t.save();return this.owner}isInitial(){for(const[,t]of this.signals)if(!t.isInitial())return!1;return!0}raw(){return Object.fromEntries(this.signals.map(([t,e])=>
53[t,e.context.raw()]))}}class fl extends ft{factory;last;constructor(t,e){super(e),this.factory=t,this.markDirty()}toSignal(){return this.invokable}dispose(){super.dispose(),this.last=void 0}invoke(...t){if(this.event.isRaised()){this.clearDependencies(),this.startCollecting();try{this.last=this.factory(...t)}catch(e){Lt().error({...Bn(e),inspect:this.owner?.key})}this.finishCollecting()}return this.event.reset(),this.collect(),this.last}}class pl extends ft{callback;constructor(t){super(),this.callback=t,this.event.subscribe(this.update),this.markDirty()}update=()=>{this.clearDependencies(),this.startCollecting(),this.callback(),this.finishCollecting(),this.event.reset()}}class gl extends Is{constructor(t,e,n,a,u=void 0,l={}){super(t,e,n,a,u,l),Object.defineProperty(this.invokable,"edit",{value:this.edit.bind(this)}),Object.defineProperty(this.invokable,"mul",{value:this.mul.bind(this)}),Object.defineProperty(this.invokable,"div",{value:this.div.bind(this)}),Object.defineProperty(this.invokable,"add",{value:this.add.bind(this)}),Object.defineProperty(this.invokable,"sub",{value:this.sub.bind(this)}),Object.defineProperty(this.invokable,"dot",{value:this.dot.bind(this)}),Object.defineProperty(this.invokable,"cross",{value:this.cross.bind(this)}),Object.defineProperty(this.invokable,"mod",{value:this.mod.bind(this)})}toSignal(){return this.invokable}edit(t,e,n,a){const u=t(this.get());return this.invoke(u,e,n,a)}mul(t,e,n,a){const u=l=>l.mul(t);return e===void 0?this.edit(u):this.edit(u,e,n,a)}div(t,e,n,a){const u=l=>l.div(t);return e===void 0?this.edit(u):this.edit(u,e,n,a)}add(t,e,n,a){const u=l=>l.add(t);return e===void 0?this.edit(u):this.edit(u,e,n,a)}sub(t,e,n,a){const u=l=>l.sub(t);return e===void 0?this.edit(u):this.edit(u,e,n,a)}dot(t,e,n,a){const u=l=>l.dot(t);return e===void 0?this.edit(u):this.edit(u,e,n,a)}cross(t,e,n,a){const u=l=>l.cross(t);return e===void 0?this.edit(u):this.edit(u,e,n,a)}mod(t,e,n,a){const u=l=>l.mod(t);return e===void 0?this.edit(u):this.edit(u,e,n,a)}}function Rh(r,t){return new fl(r,t).toSignal()}function Eh(r){const t=new pl(r);return()=>t.dispose()}function le(r,t=ks,e){return new Te(r,t,e).toSignal()}class Pt{static symbol=Symbol.for("@imaginix-inc/motion-canvas-core/types/Spacing");top=0;right=0;bottom=0;left=0;static createSignal(t,e=Pt.lerp){return new Is(["top","right","bottom","left"],n=>new Pt(n),t,e).toSignal()}static lerp(t,e,n){return new Pt(q(t.top,e.top,n),q(t.right,e.right,n),q(t.bottom,e.bottom,n),q(t.left,e.left,n))}get x(){return this.left+this.right}get y(){return this.top+this.bottom}constructor(t=0,e,n,a){if(t!=null){if(Array.isArray(t)&&(a=t[3],n=t[2],e=t[1],t=t[0]),typeof t=="number")return this.top=t,this.right=e!==void 0?e:t,this.bottom=n!==void 0?n:t,void(this.left=a!==void 0?a:e!==void 0?e:t);this.top=t.top,this.right=t.right,this.bottom=t.bottom,this.left=t.left}}lerp(t,e){return Pt.lerp(this,t,e)}scale(t){return new Pt(this.top*t,this.right*t,this.bottom*t,this.left*t)}addScalar(t){return new Pt(this.top+t,this.right+t,this.bottom+t,this.left+t)}toSymbol(){return Pt.symbol}toString(){return`Spacing(${this.top}, ${this.right}, ${this.bottom}, ${this.left})`}toUniform(t,e){t.uniform4f(e,this.top,this.right,this.bottom,this.left)}serialize(){return{top:this.top,right:this.right,bottom:this.bottom,left:this.left}}}const ue=1e-6;function Th(r){return r&&typeof r=="object"&&"toSymbol"in r}class et{static symbol=Symbol.for("@imaginix-inc/motion-canvas-core/types/Matrix2D");values=new Float32Array(6);static identity=new et(1,0,0,1,0,0);static zero=new et(0,0,0,0,0,0);static fromRotation(t){return et.identity.rotate(t)}static fromTranslation(t){return et.identity.translate(new v(t))}static fromScaling(t){return et.identity.scale(new v(t))}get x(){return new v(this.values[0],this.values[1])}get y(){return new v(this.values[2],this.values[3])}get scaleX(){return this.values[0]}set scaleX(t){this.values[0]=this.x.normalized.scale(t).x}get skewX(){return this.values[1]}set skewX(t){this.values[1]=t}get scaleY(){return this.values[3]}set scaleY(t){this.values[3]=this.y.normalized.scale(t).y}get skewY(){return this.values[2]}set skewY(t){this.values[2]=t}get translateX(){return this.values[4]}set translateX(t){this.values[4]=t}get translateY(){return this.values[5]}set translateY(t){this.values[5]=t}get rotation(){return v.degrees(this.values[0],this.values[1])}set rotation(t){const e=this.rotate(t-this.rotation);this.values[0]=e.values[0],this.values[1]=e.values[1],this.values[2]=e.values[2],this.values[3]=e.values[3]}get translation(){return new v(this.values[4],this.values[5])}set translation(t){const e=new v(t);this.values[4]=e.x,this.values[5]=e.y}get scaling(){return new v(this.values[0],this.values[3])}set scaling(t){const e=new v(t),n=new v(this.values[0],this.values[1]).normalized,a=new v(this.values[2],this.values[3]).normalized;this.values[0]=n.x*e.x,this.values[1]=n.y*e.y,this.values[2]=a.x*e.x,this.values[3]=a.y*e.y}get inverse(){const t=this.values[0],e=this.values[1],n=this.values[2],a=this.values[3],u=this.values[4],l=this.values[5];let p=t*a-e*n;return p?(p=1/p,new et(a*p,-e*p,-n*p,t*p,(n*l-a*u)*p,(e*u-t*l)*p)):null}get determinant(){return this.values[0]*this.values[3]-this.values[1]*this.values[2]}get domMatrix(){return new DOMMatrix([this.values[0],this.values[1],this.values[2],this.values[3],this.values[4],this.values[5]])}constructor(t,e,n,a,u,l){if(arguments.length===0)return void(this.values=new Float32Array([1,0,0,1,0,0]));if(arguments.length===6)return this.values[0]=t,this.values[1]=e,this.values[2]=n,this.values[3]=a,this.values[4]=u,void(this.values[5]=l);if(t instanceof DOMMatrix)return this.values[0]=t.m11,this.values[1]=t.m12,this.values[2]=t.m21,this.values[3]=t.m22,this.values[4]=t.m41,void(this.values[5]=t.m42);if(t instanceof et)return void(this.values=t.values);if(Array.isArray(t)){if(t.length===2)return this.values[0]=t[0],this.values[1]=t[1],this.values[2]=e[0],this.values[3]=e[1],this.values[4]=n[0],void(this.values[5]=n[1]);if(t.length===3){const E=new v(t[0]),O=new v(t[1]),j=new v(t[2]);return this.values[0]=E.x,this.values[1]=E.y,this.values[2]=O.x,this.values[3]=O.y,this.values[4]=j.x,void(this.values[5]=j.y)}return this.values[0]=t[0],this.values[1]=t[1],this.values[2]=t[2],this.values[3]=t[3],this.values[4]=t[4],void(this.values[5]=t[5])}const p=new v(t),w=new v(e),k=new v(n);this.values[0]=p.x,this.values[1]=p.y,this.values[2]=w.x,this.values[3]=w.y,this.values[4]=k.x,this.values[5]=k.y}column(t){return new v(this.values[2*t],this.values[2*t+1])}row(t){return[this.values[t],this.values[t+2],this.values[t+4]]}mul(t){const e=this.values[0],n=this.values[1],a=this.values[2],u=this.values[3],l=this.values[4],p=this.values[5],w=t.values[0],k=t.values[1],E=t.values[2],O=t.values[3],j=t.values[4],b=t.values[5];return new et(e*w+a*k,n*w+u*k,e*E+a*O,n*E+u*O,e*j+a*b+l,n*j+u*b+p)}rotate(t,e=!0){e&&(t*=ws);const n=this.values[0],a=this.values[1],u=this.values[2],l=this.values[3],p=this.values[4],w=this.values[5],k=Math.sin(t),E=Math.cos(t);return new et(n*E+u*k,a*E+l*k,n*-k+u*E,a*-k+l*E,p,w)}scale(t){const e=new v(t);return new et(this.values[0]*e.x,this.values[1]*e.x,this.values[2]*e.y,this.values[3]*e.y,this.values[4],this.values[5])}mulScalar(t){return new et(this.values[0]*t,this.values[1]*t,this.values[2]*t,this.values[3]*t,this.values[4]*t,this.values[5]*t)}translate(t){const e=new v(t);return new et(this.values[0],this.values[1],this.values[2],this.values[3],this.values[0]*e.x+this.values[2]*e.y+this.values[4],this.values[1]*e.x+this.values[3]*e.y+this.values[5])}add(t){return new et(this.values[0]+t.values[0],this.values[1]+t.values[1],this.values[2]+t.values[2],this.values[3]+t.values[3],this.values[4]+t.values[4],this.values[5]+t.values[5])}sub(t){return new et(this.values[0]-t.values[0],this.values[1]-t.values[1],this.values[2]-t.values[2],this.values[3]-t.values[3],this.values[4]-t.values[4],this.values[5]-t.values[5])}toSymbol(){return et.symbol}toUniform(t,e){t.uniformMatrix3fv(e,!1,[this.values[0],this.values[1],0,this.values[2],this.values[3],0,this.values[4],this.values[5],1])}equals(t,e=ue){return Math.abs(this.values[0]-t.values[0])<=e+Number.EPSILON&&Math.abs(this.values[1]-t.values[1])<=e+Number.EPSILON&&Math.abs(this.values[2]-t.values[2])<=e+Number.EPSILON&&Math.abs(this.values[3]-t.values[3])<=e+Number.EPSILON&&Math.abs(this.values[4]-t.values[4])<=e+Number.EPSILON&&Math.abs(this.values[5]-t.values[5])<=e+Number.EPSILON}exactlyEquals(t){return this.values[0]===t.values[0]&&this.values[1]===t.values[1]&&this.values[2]===t.values[2]&&this.values[3]===t.values[3]&&this.values[4]===t.values[4]&&this.values[5]===t.values[5]}}var xn,Rt,Me;function Mh(r){if(r===Me.Middle)return v.zero;let t=0;r&Rt.Left?t=-1:r&Rt.Right&&(t=1);let e=0;return r&Rt.Top?e=-1:r&Rt.Bottom&&(e=1),new v(t,e)}(function(r){r[r.Vertical=1]="Vertical",r[r.Horizontal=2]="Horizontal"})(xn||(xn={})),(function(r){r[r.Top=4]="Top",r[r.Bottom=8]="Bottom",r[r.Left=16]="Left",r[r.Right=32]="Right"})(Rt||(Rt={})),(function(r){r[r.Middle=3]="Middle",r[r.Top=5]="Top",r[r.Bottom=9]="Bottom",r[r.Left=18]="Left",r[r.Right=34]="Right",r[r.TopLeft=20]="TopLeft",r[r.TopRight=36]="TopRight",r[r.BottomLeft=24]="BottomLeft",r[r.BottomRight=40]="BottomRight"})(Me||(Me={}));class v{static symbol=Symbol.for("@imaginix-inc/motion-canvas-core/types/Vector2");static zero=new v;static one=new v(1,1);static right=new v(1,0);static left=new v(-1,0);static up=new v(0,1);static down=new v(0,-1);static top=new v(0,-1);static bottom=new v(0,1);static topLeft=new v(-1,-1);static topRight=new v(1,-1);static bottomLeft=new v(-1,1);static bottomRight=new v(1,1);x=0;y=0;static createSignal(t,e=v.lerp,n){return new gl(["x","y"],a=>new v(a),t,e,n).toSignal()}static lerp(t,e,n){let a,u;return typeof n=="number"?a=u=n:(a=n.x,u=n.y),new v(q(t.x,e.x,a),q(t.y,e.y,u))}static arcLerp(t,e,n,a=!1,u){return u??=t.sub(e).ctg,v.lerp(t,e,Wn(n,a,u))}static createArcLerp(t,e){return(n,a,u)=>v.arcLerp(n,a,u,t,e)}static polarLerp(t,e,n,a=!1,u=v.zero){t=t.sub(u),e=e.sub(u);const l=t.degrees;let p=e.degrees;l>p!==a&&(p+=a?-360:360);const w=q(l,p,n)*ws,k=q(t.magnitude,e.magnitude,n);return new v(k*Math.cos(w)+u.x,k*Math.sin(w)+u.y)}static createPolarLerp(t=!1,e=v.zero){return(n,a,u)=>v.polarLerp(n,a,u,t,new v(e))}static fromOrigin(t){const e=new v;return t===Me.Middle||(t&Rt.Left?e.x=-1:t&Rt.Right&&(e.x=1),t&Rt.Top?e.y=-1:t&Rt.Bottom&&(e.y=1)),e}static fromScalar(t){return new v(t,t)}static fromRadians(t){return new v(Math.cos(t),Math.sin(t))}static fromDegrees(t){return v.fromRadians(t*ws)}static radians(t,e){return Math.atan2(e,t)}static degrees(t,e){return v.radians(t,e)*Lc}
53static magnitude(t,e){return Math.sqrt(t*t+e*e)}static squaredMagnitude(t,e){return t*t+e*e}static angleBetween(t,e){return Math.acos(Tt(-1,1,t.dot(e)/(t.magnitude*e.magnitude)))*(t.cross(e)>=0?1:-1)}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}get magnitude(){return v.magnitude(this.x,this.y)}get squaredMagnitude(){return v.squaredMagnitude(this.x,this.y)}get normalized(){return this.scale(1/v.magnitude(this.x,this.y))}get safe(){return new v(isNaN(this.x)?0:this.x,isNaN(this.y)?0:this.y)}get flipped(){return new v(-this.x,-this.y)}get floored(){return new v(Math.floor(this.x),Math.floor(this.y))}get rounded(){return new v(Math.round(this.x),Math.round(this.y))}get ceiled(){return new v(Math.ceil(this.x),Math.ceil(this.y))}get perpendicular(){return new v(this.y,-this.x)}get radians(){return v.radians(this.x,this.y)}get degrees(){return v.degrees(this.x,this.y)}get ctg(){return this.x/this.y}constructor(t,e){if(t!=null){if(typeof t!="object")return this.x=t,void(this.y=e??t);if(Array.isArray(t))return this.x=t[0],void(this.y=t[1]);if("width"in t)return this.x=t.width,void(this.y=t.height);this.x=t.x,this.y=t.y}}lerp(t,e){return v.lerp(this,t,e)}getOriginOffset(t){const e=v.fromOrigin(t);return e.x*=this.x/2,e.y*=this.y/2,e}scale(t){return new v(this.x*t,this.y*t)}transformAsPoint(t){const e=new et(t);return new v(this.x*e.scaleX+this.y*e.skewY+e.translateX,this.x*e.skewX+this.y*e.scaleY+e.translateY)}transform(t){const e=new et(t);return new v(this.x*e.scaleX+this.y*e.skewY,this.x*e.skewX+this.y*e.scaleY)}mul(t){const e=new v(t);return new v(this.x*e.x,this.y*e.y)}div(t){const e=new v(t);return new v(this.x/e.x,this.y/e.y)}add(t){const e=new v(t);return new v(this.x+e.x,this.y+e.y)}sub(t){const e=new v(t);return new v(this.x-e.x,this.y-e.y)}dot(t){const e=new v(t);return this.x*e.x+this.y*e.y}cross(t){const e=new v(t);return this.x*e.y-this.y*e.x}mod(t){const e=new v(t);return new v(this.x%e.x,this.y%e.y)}rotate(t,e=v.zero){const n=new v(e),a=et.fromTranslation(n).rotate(t).translate(n.flipped);return this.transformAsPoint(a)}addX(t){return new v(this.x+t,this.y)}addY(t){return new v(this.x,this.y+t)}map(t){return new v(t(this.x,0),t(this.y,1))}toSymbol(){return v.symbol}toString(){return`Vector2(${this.x}, ${this.y})`}toArray(){return[this.x,this.y]}toUniform(t,e){t.uniform2f(e,this.x,this.y)}serialize(){return{x:this.x,y:this.y}}exactlyEquals(t){return this.x===t.x&&this.y===t.y}equals(t,e=ue){return Math.abs(this.x-t.x)<=e+Number.EPSILON&&Math.abs(this.y-t.y)<=e+Number.EPSILON}*[Symbol.iterator](){yield this.x,yield this.y}}class ht{static symbol=Symbol.for("@imaginix-inc/motion-canvas-core/types/Rect");x=0;y=0;width=0;height=0;static createSignal(t,e=ht.lerp){return new Is(["x","y","width","height"],n=>new ht(n),t,e).toSignal()}static lerp(t,e,n){let a,u,l,p;return typeof n=="number"?a=u=l=p=n:n instanceof v?(a=l=n.x,u=p=n.y):(a=n.x,u=n.y,l=n.width,p=n.height),new ht(q(t.x,e.x,a),q(t.y,e.y,u),q(t.width,e.width,l),q(t.height,e.height,p))}static arcLerp(t,e,n,a=!1,u){return u??=(t.position.sub(e.position).ctg+t.size.sub(e.size).ctg)/2,ht.lerp(t,e,Wn(n,a,u))}static fromSizeCentered(t){return new ht(-t.width/2,-t.height/2,t.width,t.height)}static fromPoints(...t){let e=1/0,n=1/0,a=-1/0,u=-1/0;for(const l of t)l.x>a&&(a=l.x),l.x<e&&(e=l.x),l.y>u&&(u=l.y),l.y<n&&(n=l.y);return new ht(e,n,a-e,u-n)}static fromBBoxes(...t){let e=1/0,n=1/0,a=-1/0,u=-1/0;for(const l of t){const p=l.x+l.width;p>a&&(a=p),l.x<e&&(e=l.x);const w=l.y+l.height;w>u&&(u=w),l.y<n&&(n=l.y)}return new ht(e,n,a-e,u-n)}lerp(t,e){return ht.lerp(this,t,e)}get position(){return new v(this.x,this.y)}set position(t){this.x=t.x,this.y=t.y}get size(){return new v(this.width,this.height)}get center(){return new v(this.x+this.width/2,this.y+this.height/2)}get left(){return this.x}set left(t){this.width+=this.x-t,this.x=t}get right(){return this.x+this.width}set right(t){this.width=t-this.x}get top(){return this.y}set top(t){this.height+=this.y-t,this.y=t}get bottom(){return this.y+this.height}set bottom(t){this.height=t-this.y}get topLeft(){return this.position}get topRight(){return new v(this.x+this.width,this.y)}get bottomLeft(){return new v(this.x,this.y+this.height)}get bottomRight(){return new v(this.x+this.width,this.y+this.height)}get corners(){return[this.topLeft,this.topRight,this.bottomRight,this.bottomLeft]}get pixelPerfect(){return new ht(Math.floor(this.x),Math.floor(this.y),Math.ceil(this.width+1),Math.ceil(this.height+1))}constructor(t,e=0,n=0,a=0){if(t!=null){if(typeof t=="number")return this.x=t,this.y=e,this.width=n,void(this.height=a);if(t instanceof v)return this.x=t.x,this.y=t.y,void(e instanceof v&&(this.width=e.x,this.height=e.y));if(Array.isArray(t))return this.x=t[0],this.y=t[1],this.width=t[2],void(this.height=t[3]);this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height}}transform(t){return new ht(this.position.transformAsPoint(t),this.size.transform(t))}transformCorners(t){return this.corners.map(e=>e.transformAsPoint(t))}translate(t){const e=new v(t);return new ht(this.x+e.x,this.y+e.y,this.width,this.height)}expand(t){const e=new Pt(t),n=new ht(this);return n.left-=e.left,n.top-=e.top,n.right+=e.right,n.bottom+=e.bottom,n}addSpacing(t){return this.expand(t)}includes(t){return t.x>=this.x&&t.x<=this.x+this.width&&t.y>=this.y&&t.y<=this.y+this.height}intersects(t){return this.left<t.right&&this.right>t.left&&this.top<t.bottom&&this.bottom>t.top}intersection(t){const e=new ht;return this.intersects(t)&&(e.left=Math.max(this.left,t.left),e.top=Math.max(this.top,t.top),e.right=Math.min(this.right,t.right),e.bottom=Math.min(this.bottom,t.bottom)),e}union(t){const e=new ht;return e.left=Math.min(this.left,t.left),e.top=Math.min(this.top,t.top),e.right=Math.max(this.right,t.right),e.bottom=Math.max(this.bottom,t.bottom),e}toSymbol(){return ht.symbol}toString(){return`BBox(${this.x}, ${this.y}, ${this.width}, ${this.height})`}toUniform(t,e){t.uniform4f(e,this.x,this.y,this.width,this.height)}serialize(){return{x:this.x,y:this.y,width:this.width,height:this.height}}}var Zn={exports:{}};Zn.exports=(function(){for(var r=function(s,i,o){return i===void 0&&(i=0),o===void 0&&(o=1),s<i?i:s>o?o:s},t=r,e=function(s){s._clipped=!1,s._unclipped=s.slice(0);for(var i=0;i<=3;i++)i<3?((s[i]<0||s[i]>255)&&(s._clipped=!0),s[i]=t(s[i],0,255)):i===3&&(s[i]=t(s[i],0,1));return s},n={},a=0,u=["Boolean","Number","String","Function","Array","Date","RegExp","Undefined","Null"];a<u.length;a+=1){var l=u[a];n["[object "+l+"]"]=l.toLowerCase()}var p=function(s){return n[Object.prototype.toString.call(s)]||"object"},w=p,k=function(s,i){return i===void 0&&(i=null),s.length>=3?Array.prototype.slice.call(s):w(s[0])=="object"&&i?i.split("").filter(function(o){return s[0][o]!==void 0}).map(function(o){return s[0][o]}):s[0]},E=p,O=function(s){if(s.length<2)return null;var i=s.length-1;return E(s[i])=="string"?s[i].toLowerCase():null},j=Math.PI,b={clip_rgb:e,limit:r,type:p,unpack:k,last:O,TWOPI:2*j,PITHIRD:j/3,DEG2RAD:j/180,RAD2DEG:180/j},F={format:{},autodetect:[]},Z=b.last,K=b.clip_rgb,lt=b.type,A=F,X=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=this;if(lt(s[0])==="object"&&s[0].constructor&&s[0].constructor===this.constructor)return s[0];var c=Z(s),d=!1;if(!c){d=!0,A.sorted||(A.autodetect=A.autodetect.sort(function(y,x){return x.p-y.p}),A.sorted=!0);for(var f=0,h=A.autodetect;f<h.length;f+=1){var g=h[f];if(c=g.test.apply(g,s))break}}if(!A.format[c])throw new Error("unknown format: "+s);var m=A.format[c].apply(null,d?s:s.slice(0,-1));o._rgb=K(m),o._rgb.length===3&&o._rgb.push(1)};X.prototype.toString=function(){return lt(this.hex)=="function"?this.hex():"["+this._rgb.join(",")+"]"};var L=X,it=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(it.Color,[null].concat(s)))};it.Color=L,it.version="2.4.2";var H=it,ni=b.unpack,zs=Math.max,ii=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];
53var o=ni(s,"rgb"),c=o[0],d=o[1],f=o[2],h=1-zs(c/=255,zs(d/=255,f/=255)),g=h<1?1/(1-h):0;return[(1-c-h)*g,(1-d-h)*g,(1-f-h)*g,h]},ai=ii,oi=b.unpack,ui=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=(s=oi(s,"cmyk"))[0],c=s[1],d=s[2],f=s[3],h=s.length>4?s[4]:1;return f===1?[0,0,0,h]:[o>=1?0:255*(1-o)*(1-f),c>=1?0:255*(1-c)*(1-f),d>=1?0:255*(1-d)*(1-f),h]},ci=ui,li=H,Us=L,$s=F,hi=b.unpack,di=b.type,fi=ai;Us.prototype.cmyk=function(){return fi(this._rgb)},li.cmyk=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(Us,[null].concat(s,["cmyk"])))},$s.format.cmyk=ci,$s.autodetect.push({p:2,test:function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];if(s=hi(s,"cmyk"),di(s)==="array"&&s.length===4)return"cmyk"}});var pi=b.unpack,gi=b.last,qe=function(s){return Math.round(100*s)/100},mi=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=pi(s,"hsla"),c=gi(s)||"lsa";return o[0]=qe(o[0]||0),o[1]=qe(100*o[1])+"%",o[2]=qe(100*o[2])+"%",c==="hsla"||o.length>3&&o[3]<1?(o[3]=o.length>3?o[3]:1,c="hsla"):o.length=3,c+"("+o.join(",")+")"},bi=mi,yi=b.unpack,vi=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=(s=yi(s,"rgba"))[0],c=s[1],d=s[2];o/=255,c/=255,d/=255;var f,h,g=Math.min(o,c,d),m=Math.max(o,c,d),y=(m+g)/2;return m===g?(f=0,h=Number.NaN):f=y<.5?(m-g)/(m+g):(m-g)/(2-m-g),o==m?h=(c-d)/(m-g):c==m?h=2+(d-o)/(m-g):d==m&&(h=4+(o-c)/(m-g)),(h*=60)<0&&(h+=360),s.length>3&&s[3]!==void 0?[h,f,y,s[3]]:[h,f,y]},Gs=vi,wi=b.unpack,ki=b.last,Si=bi,xi=Gs,De=Math.round,Ri=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=wi(s,"rgba"),c=ki(s)||"rgb";return c.substr(0,3)=="hsl"?Si(xi(o),c):(o[0]=De(o[0]),o[1]=De(o[1]),o[2]=De(o[2]),(c==="rgba"||o.length>3&&o[3]<1)&&(o[3]=o.length>3?o[3]:1,c="rgba"),c+"("+o.slice(0,c==="rgb"?3:4).join(",")+")")},Ei=Ri,Ti=b.unpack,Ne=Math.round,Mi=function(){for(var s,i=[],o=arguments.length;o--;)i[o]=arguments[o];var c,d,f,h=(i=Ti(i,"hsl"))[0],g=i[1],m=i[2];if(g===0)c=d=f=255*m;else{var y=[0,0,0],x=[0,0,0],M=m<.5?m*(1+g):m+g-m*g,R=2*m-M,P=h/360;y[0]=P+1/3,y[1]=P,y[2]=P-1/3;for(var T=0;T<3;T++)y[T]<0&&(y[T]+=1),y[T]>1&&(y[T]-=1),6*y[T]<1?x[T]=R+6*(M-R)*y[T]:2*y[T]<1?x[T]=M:3*y[T]<2?x[T]=R+(M-R)*(2/3-y[T])*6:x[T]=R;c=(s=[Ne(255*x[0]),Ne(255*x[1]),Ne(255*x[2])])[0],d=s[1],f=s[2]}return i.length>3?[c,d,f,i[3]]:[c,d,f,1]},Vs=Mi,Ws=Vs,Xs=F,Ys=/^rgb\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*\)$/,Hs=/^rgba\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*([01]|[01]?\.\d+)\)$/,Js=/^rgb\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/,Zs=/^rgba\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/,Ks=/^hsl\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/,_s=/^hsla\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/,Qs=Math.round,tr=function(s){var i;if(s=s.toLowerCase().trim(),Xs.format.named)try{return Xs.format.named(s)}catch{}if(i=s.match(Ys)){for(var o=i.slice(1,4),c=0;c<3;c++)o[c]=+o[c];return o[3]=1,o}if(i=s.match(Hs)){for(var d=i.slice(1,5),f=0;f<4;f++)d[f]=+d[f];return d}if(i=s.match(Js)){for(var h=i.slice(1,4),g=0;g<3;g++)h[g]=Qs(2.55*h[g]);return h[3]=1,h}if(i=s.match(Zs)){for(var m=i.slice(1,5),y=0;y<3;y++)m[y]=Qs(2.55*m[y]);return m[3]=+m[3],m}if(i=s.match(Ks)){var x=i.slice(1,4);x[1]*=.01,x[2]*=.01;var M=Ws(x);return M[3]=1,M}if(i=s.match(_s)){var R=i.slice(1,4);R[1]*=.01,R[2]*=.01;var P=Ws(R);return P[3]=+i[4],P}};tr.test=function(s){return Ys.test(s)||Hs.test(s)||Js.test(s)||Zs.test(s)||Ks.test(s)||_s.test(s)};var Pi=tr,Ai=H,er=L,sr=F,Li=b.type,ji=Ei,rr=Pi;er.prototype.css=function(s){return ji(this._rgb,s)},Ai.css=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(er,[null].concat(s,["css"])))},sr.format.css=rr,sr.autodetect.push({p:5,test:function(s){for(var i=[],o=arguments.length-1;o-- >0;)i[o]=arguments[o+1];if(!i.length&&Li(s)==="string"&&rr.test(s))return"css"}});var nr=L,Ci=H,Fi=F,Oi=b.unpack;Fi.format.gl=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=Oi(s,"rgba");return o[0]*=255,o[1]*=255,o[2]*=255,o},Ci.gl=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(nr,[null].concat(s,["gl"])))},nr.prototype.gl=function(){var s=this._rgb;return[s[0]/255,s[1]/255,s[2]/255,s[3]]};var Ii=b.unpack,qi=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o,c=Ii(s,"rgb"),d=c[0],f=c[1],h=c[2],g=Math.min(d,f,h),m=Math.max(d,f,h),y=m-g,x=100*y/255,M=g/(255-y)*100;return y===0?o=Number.NaN:(d===m&&(o=(f-h)/y),f===m&&(o=2+(h-d)/y),h===m&&(
53o=4+(d-f)/y),(o*=60)<0&&(o+=360)),[o,x,M]},Di=qi,Ni=b.unpack,Bi=Math.floor,zi=function(){for(var s,i,o,c,d,f,h=[],g=arguments.length;g--;)h[g]=arguments[g];var m,y,x,M=(h=Ni(h,"hcg"))[0],R=h[1],P=h[2];P*=255;var T=255*R;if(R===0)m=y=x=P;else{M===360&&(M=0),M>360&&(M-=360),M<0&&(M+=360);var z=Bi(M/=60),N=M-z,W=P*(1-R),$=W+T*(1-N),at=W+T*N,nt=W+T;switch(z){case 0:m=(s=[nt,at,W])[0],y=s[1],x=s[2];break;case 1:m=(i=[$,nt,W])[0],y=i[1],x=i[2];break;case 2:m=(o=[W,nt,at])[0],y=o[1],x=o[2];break;case 3:m=(c=[W,$,nt])[0],y=c[1],x=c[2];break;case 4:m=(d=[at,W,nt])[0],y=d[1],x=d[2];break;case 5:m=(f=[nt,W,$])[0],y=f[1],x=f[2]}}return[m,y,x,h.length>3?h[3]:1]},Ui=zi,$i=b.unpack,Gi=b.type,Vi=H,ir=L,ar=F,Wi=Di;ir.prototype.hcg=function(){return Wi(this._rgb)},Vi.hcg=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(ir,[null].concat(s,["hcg"])))},ar.format.hcg=Ui,ar.autodetect.push({p:1,test:function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];if(s=$i(s,"hcg"),Gi(s)==="array"&&s.length===3)return"hcg"}});var Xi=b.unpack,Yi=b.last,he=Math.round,Hi=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=Xi(s,"rgba"),c=o[0],d=o[1],f=o[2],h=o[3],g=Yi(s)||"auto";h===void 0&&(h=1),g==="auto"&&(g=h<1?"rgba":"rgb");var m="000000"+((c=he(c))<<16|(d=he(d))<<8|(f=he(f))).toString(16);m=m.substr(m.length-6);var y="0"+he(255*h).toString(16);switch(y=y.substr(y.length-2),g.toLowerCase()){case"rgba":return"#"+m+y;case"argb":return"#"+y+m;default:return"#"+m}},or=Hi,Ji=/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,Zi=/^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{4})$/,ur=function(s){if(s.match(Ji)){s.length!==4&&s.length!==7||(s=s.substr(1)),s.length===3&&(s=(s=s.split(""))[0]+s[0]+s[1]+s[1]+s[2]+s[2]);var i=parseInt(s,16);return[i>>16,i>>8&255,255&i,1]}if(s.match(Zi)){s.length!==5&&s.length!==9||(s=s.substr(1)),s.length===4&&(s=(s=s.split(""))[0]+s[0]+s[1]+s[1]+s[2]+s[2]+s[3]+s[3]);var o=parseInt(s,16);return[o>>24&255,o>>16&255,o>>8&255,Math.round((255&o)/255*100)/100]}throw new Error("unknown hex color: "+s)},Ki=H,cr=L,_i=b.type,lr=F,Qi=or;cr.prototype.hex=function(s){return Qi(this._rgb,s)},Ki.hex=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(cr,[null].concat(s,["hex"])))},lr.format.hex=ur,lr.autodetect.push({p:4,test:function(s){for(var i=[],o=arguments.length-1;o-- >0;)i[o]=arguments[o+1];if(!i.length&&_i(s)==="string"&&[3,4,5,6,7,8,9].indexOf(s.length)>=0)return"hex"}});var ta=b.unpack,hr=b.TWOPI,ea=Math.min,sa=Math.sqrt,ra=Math.acos,na=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o,c=ta(s,"rgb"),d=c[0],f=c[1],h=c[2],g=ea(d/=255,f/=255,h/=255),m=(d+f+h)/3,y=m>0?1-g/m:0;return y===0?o=NaN:(o=(d-f+(d-h))/2,o/=sa((d-f)*(d-f)+(d-h)*(f-h)),o=ra(o),h>f&&(o=hr-o),o/=hr),[360*o,y,m]},ia=na,aa=b.unpack,Be=b.limit,Vt=b.TWOPI,ze=b.PITHIRD,Wt=Math.cos,oa=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o,c,d,f=(s=aa(s,"hsi"))[0],h=s[1],g=s[2];return isNaN(f)&&(f=0),isNaN(h)&&(h=0),f>360&&(f-=360),f<0&&(f+=360),(f/=360)<1/3?c=1-((d=(1-h)/3)+(o=(1+h*Wt(Vt*f)/Wt(ze-Vt*f))/3)):f<2/3?d=1-((o=(1-h)/3)+(c=(1+h*Wt(Vt*(f-=1/3))/Wt(ze-Vt*f))/3)):o=1-((c=(1-h)/3)+(d=(1+h*Wt(Vt*(f-=2/3))/Wt(ze-Vt*f))/3)),[255*(o=Be(g*o*3)),255*(c=Be(g*c*3)),255*(d=Be(g*d*3)),s.length>3?s[3]:1]},ua=oa,ca=b.unpack,la=b.type,ha=H,dr=L,fr=F,da=ia;dr.prototype.hsi=function(){return da(this._rgb)},ha.hsi=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(dr,[null].concat(s,["hsi"])))},fr.format.hsi=ua,fr.autodetect.push({p:2,test:function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];if(s=ca(s,"hsi"),la(s)==="array"&&s.length===3)return"hsi"}});var fa=b.unpack,pa=b.type,ga=H,pr=L,gr=F,ma=Gs;pr.prototype.hsl=function(){return ma(this._rgb)},ga.hsl=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(pr,[null].concat(s,["hsl"])))},gr.format.hsl=Vs,gr.autodetect.push({p:2,test:function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];if(s=fa(s,"hsl"),pa(s)==="array"&&s.length===3)return"hsl"}});var ba=b.unpack,ya=Math.min,va=Math.max,wa=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o,c,d,f=(s=ba(s,"rgb"))[0],h=s[1],g=s[2],m=ya(f,h,g),y=va(f,h,g),x=y-m;return d=y/255,y===0?(o=Number.NaN,c=0):(c=x/y,f===y&&(o=(h-g)/x),h===y&&(o=2+(g-f)/x),g===y&&(o=4+(f-h)/x),(o*=60)<0&&(o+=360)),[o,c,d]},ka=wa,Sa=b.unpack,xa=Math.floor,Ra=function(){for(var s,i,o,c,d,f,h=[],g=arguments.length;g--;)h[g]=arguments[g];var m,y,x,M=(h=Sa(h,"hsv"))[0],R=h[1],P=h[2];
53if(P*=255,R===0)m=y=x=P;else{M===360&&(M=0),M>360&&(M-=360),M<0&&(M+=360);var T=xa(M/=60),z=M-T,N=P*(1-R),W=P*(1-R*z),$=P*(1-R*(1-z));switch(T){case 0:m=(s=[P,$,N])[0],y=s[1],x=s[2];break;case 1:m=(i=[W,P,N])[0],y=i[1],x=i[2];break;case 2:m=(o=[N,P,$])[0],y=o[1],x=o[2];break;case 3:m=(c=[N,W,P])[0],y=c[1],x=c[2];break;case 4:m=(d=[$,N,P])[0],y=d[1],x=d[2];break;case 5:m=(f=[P,N,W])[0],y=f[1],x=f[2]}}return[m,y,x,h.length>3?h[3]:1]},Ea=Ra,Ta=b.unpack,Ma=b.type,Pa=H,mr=L,br=F,Aa=ka;mr.prototype.hsv=function(){return Aa(this._rgb)},Pa.hsv=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(mr,[null].concat(s,["hsv"])))},br.format.hsv=Ea,br.autodetect.push({p:2,test:function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];if(s=Ta(s,"hsv"),Ma(s)==="array"&&s.length===3)return"hsv"}});var de={Kn:18,Xn:.95047,Yn:1,Zn:1.08883,t0:.137931034,t1:.206896552,t2:.12841855,t3:.008856452},Xt=de,La=b.unpack,yr=Math.pow,ja=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=La(s,"rgb"),c=o[0],d=o[1],f=o[2],h=Ca(c,d,f),g=h[0],m=h[1],y=116*m-16;return[y<0?0:y,500*(g-m),200*(m-h[2])]},Ue=function(s){return(s/=255)<=.04045?s/12.92:yr((s+.055)/1.055,2.4)},$e=function(s){return s>Xt.t3?yr(s,1/3):s/Xt.t2+Xt.t0},Ca=function(s,i,o){return s=Ue(s),i=Ue(i),o=Ue(o),[$e((.4124564*s+.3575761*i+.1804375*o)/Xt.Xn),$e((.2126729*s+.7151522*i+.072175*o)/Xt.Yn),$e((.0193339*s+.119192*i+.9503041*o)/Xt.Zn)]},vr=ja,Yt=de,Fa=b.unpack,Oa=Math.pow,Ia=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o,c,d,f=(s=Fa(s,"lab"))[0],h=s[1],g=s[2];return c=(f+16)/116,o=isNaN(h)?c:c+h/500,d=isNaN(g)?c:c-g/200,c=Yt.Yn*Ve(c),o=Yt.Xn*Ve(o),d=Yt.Zn*Ve(d),[Ge(3.2404542*o-1.5371385*c-.4985314*d),Ge(-.969266*o+1.8760108*c+.041556*d),Ge(.0556434*o-.2040259*c+1.0572252*d),s.length>3?s[3]:1]},Ge=function(s){return 255*(s<=.00304?12.92*s:1.055*Oa(s,1/2.4)-.055)},Ve=function(s){return s>Yt.t1?s*s*s:Yt.t2*(s-Yt.t0)},wr=Ia,qa=b.unpack,Da=b.type,Na=H,kr=L,Sr=F,Ba=vr;kr.prototype.lab=function(){return Ba(this._rgb)},Na.lab=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(kr,[null].concat(s,["lab"])))},Sr.format.lab=wr,Sr.autodetect.push({p:2,test:function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];if(s=qa(s,"lab"),Da(s)==="array"&&s.length===3)return"lab"}});var za=b.unpack,Ua=b.RAD2DEG,$a=Math.sqrt,Ga=Math.atan2,Va=Math.round,Wa=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=za(s,"lab"),c=o[0],d=o[1],f=o[2],h=$a(d*d+f*f),g=(Ga(f,d)*Ua+360)%360;return Va(1e4*h)===0&&(g=Number.NaN),[c,h,g]},xr=Wa,Xa=b.unpack,Ya=vr,Ha=xr,Ja=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=Xa(s,"rgb"),c=o[0],d=o[1],f=o[2],h=Ya(c,d,f),g=h[0],m=h[1],y=h[2];return Ha(g,m,y)},Za=Ja,Ka=b.unpack,_a=b.DEG2RAD,Qa=Math.sin,to=Math.cos,eo=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=Ka(s,"lch"),c=o[0],d=o[1],f=o[2];return isNaN(f)&&(f=0),[c,to(f*=_a)*d,Qa(f)*d]},Rr=eo,so=b.unpack,ro=Rr,no=wr,io=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=(s=so(s,"lch"))[0],c=s[1],d=s[2],f=ro(o,c,d),h=f[0],g=f[1],m=f[2],y=no(h,g,m);return[y[0],y[1],y[2],s.length>3?s[3]:1]},Er=io,ao=b.unpack,oo=Er,uo=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=ao(s,"hcl").reverse();return oo.apply(void 0,o)},co=uo,lo=b.unpack,ho=b.type,Tr=H,fe=L,We=F,Mr=Za;fe.prototype.lch=function(){return Mr(this._rgb)},fe.prototype.hcl=function(){return Mr(this._rgb).reverse()},Tr.lch=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(fe,[null].concat(s,["lch"])))},Tr.hcl=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(fe,[null].concat(s,["hcl"])))},We.format.lch=Er,We.format.hcl=co,["lch","hcl"].forEach(function(s){return We.autodetect.push({p:2,test:function(){for(var i=[],o=arguments.length;o--;)i[o]=arguments[o];if(i=lo(i,s),ho(i)==="array"&&i.length===3)return s}})});var Pr={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflower:"#6495ed",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",laserlemon:"#ffff54",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrod:"#fafad2",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",maroon2:"#7f0000",maroon3:"#b03060",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",purple2:"#7f007f",purple3:"#a020f0",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",s
53almon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},fo=L,Ar=F,po=b.type,re=Pr,go=ur,mo=or;fo.prototype.name=function(){for(var s=mo(this._rgb,"rgb"),i=0,o=Object.keys(re);i<o.length;i+=1){var c=o[i];if(re[c]===s)return c.toLowerCase()}return s},Ar.format.named=function(s){if(s=s.toLowerCase(),re[s])return go(re[s]);throw new Error("unknown color name: "+s)},Ar.autodetect.push({p:5,test:function(s){for(var i=[],o=arguments.length-1;o-- >0;)i[o]=arguments[o+1];if(!i.length&&po(s)==="string"&&re[s.toLowerCase()])return"named"}});var bo=b.unpack,yo=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=bo(s,"rgb");return(o[0]<<16)+(o[1]<<8)+o[2]},vo=yo,wo=b.type,ko=function(s){if(wo(s)=="number"&&s>=0&&s<=16777215)return[s>>16,s>>8&255,255&s,1];throw new Error("unknown num color: "+s)},So=H,Lr=L,jr=F,xo=b.type,Ro=vo;Lr.prototype.num=function(){return Ro(this._rgb)},So.num=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(Lr,[null].concat(s,["num"])))},jr.format.num=ko,jr.autodetect.push({p:5,test:function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];if(s.length===1&&xo(s[0])==="number"&&s[0]>=0&&s[0]<=16777215)return"num"}});var Eo=H,Xe=L,Cr=F,Fr=b.unpack,Or=b.type,Ir=Math.round;Xe.prototype.rgb=function(s){return s===void 0&&(s=!0),s===!1?this._rgb.slice(0,3):this._rgb.slice(0,3).map(Ir)},Xe.prototype.rgba=function(s){return s===void 0&&(s=!0),this._rgb.slice(0,4).map(function(i,o){return o<3?s===!1?i:Ir(i):i})},Eo.rgb=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(Xe,[null].concat(s,["rgb"])))},Cr.format.rgb=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=Fr(s,"rgba");return o[3]===void 0&&(o[3]=1),o},Cr.autodetect.push({p:3,test:function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];if(s=Fr(s,"rgba"),Or(s)==="array"&&(s.length===3||s.length===4&&Or(s[3])=="number"&&s[3]>=0&&s[3]<=1))return"rgb"}});var pe=Math.log,qr=function(s){var i,o,c,d=s/100;return d<66?(i=255,o=d<6?0:-155.25485562709179-.44596950469579133*(o=d-2)+104.49216199393888*pe(o),c=d<20?0:.8274096064007395*(c=d-10)-254.76935184120902+115.67994401066147*pe(c)):(i=351.97690566805693+.114206453784165*(i=d-55)-40.25366309332127*pe(i),o=325.4494125711974+.07943456536662342*(o=d-50)-28.0852963507957*pe(o),c=255),[i,o,c,1]},To=qr,Mo=b.unpack,Po=Math.round,Ao=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];for(var o,c=Mo(s,"rgb"),d=c[0],f=c[2],h=1e3,g=4e4,m=.4;g-h>m;){var y=To(o=.5*(g+h));y[2]/y[0]>=f/d?g=o:h=o}return Po(o)},Ye=H,ge=L,He=F,Lo=Ao;ge.prototype.temp=ge.prototype.kelvin=ge.prototype.temperature=function(){return Lo(this._rgb)},Ye.temp=Ye.kelvin=Ye.temperature=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(ge,[null].concat(s,["temp"])))},He.format.temp=He.format.kelvin=He.format.temperature=qr;var jo=b.unpack,Je=Math.cbrt,Co=Math.pow,Fo=Math.sign,Oo=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=jo(s,"rgb"),c=o[0],d=o[1],f=o[2],h=[Ze(c/255),Ze(d/255),Ze(f/255)],g=h[0],m=h[1],y=h[2],x=Je(.4122214708*g+.5363325363*m+.0514459929*y),M=Je(.2119034982*g+.6806995451*m+.1073969566*y),R=Je(.0883024619*g+.2817188376*m+.6299787005*y);return[.2104542553*x+.793617785*M-.0040720468*R,1.9779984951*x-2.428592205*M+.4505937099*R,.0259040371*x+.7827717662*M-.808675766*R]},Dr=Oo;function Ze(s){var i=Math.abs(s);return i<.04045?s/12.92:(Fo(s)||1)*Co((i+.055)/1.055,2.4)}var Io=b.unpack,me=Math.pow,qo=Math.sign,Do=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=(s=Io(s,"lab"))[0],c=s[1],d=s[2],f=me(o+.3963377774*c+.2158037573*d,3),h=me(o-.1055613458*c-.0638541728*d,3),g=me(o-.0894841775*c-1.291485548*d,3);return[255*Ke(4.0767416621*f-3.3077115913*h+.2309699292*g),255*Ke(-1.2684380046*f+2.6097574011*h-.3413193965*g),255*Ke(-.0041960863*f-.7034186147*h+1.707614701*g),s.length>3?s[3]:1]},Nr=Do;function Ke(s){var i=Math.abs(s);return i>.0031308?(qo(s)||1)*(1.055*me(i,1/2.4)-.055):12.92*s}var No=b.unpack,Bo=b.type,zo=H,Br=L,zr=F,Uo=Dr;Br.prototype.oklab=function(){return Uo(this._rgb)},zo.oklab=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(Br,[null].concat(s,["oklab"])))},zr.format.oklab=Nr,zr.autodetect.push({p:3,test:function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];if(s=No(s,"oklab"),Bo(s)==="array"&&s.length===3)return"oklab"}});var $o=b.unpack,Go=Dr,Vo=xr,Wo=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];
53var o=$o(s,"rgb"),c=o[0],d=o[1],f=o[2],h=Go(c,d,f),g=h[0],m=h[1],y=h[2];return Vo(g,m,y)},Xo=Wo,Yo=b.unpack,Ho=Rr,Jo=Nr,Zo=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];var o=(s=Yo(s,"lch"))[0],c=s[1],d=s[2],f=Ho(o,c,d),h=f[0],g=f[1],m=f[2],y=Jo(h,g,m);return[y[0],y[1],y[2],s.length>3?s[3]:1]},Ko=Zo,_o=b.unpack,Qo=b.type,tu=H,Ur=L,$r=F,eu=Xo;Ur.prototype.oklch=function(){return eu(this._rgb)},tu.oklch=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];return new(Function.prototype.bind.apply(Ur,[null].concat(s,["oklch"])))},$r.format.oklch=Ko,$r.autodetect.push({p:3,test:function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];if(s=_o(s,"oklch"),Qo(s)==="array"&&s.length===3)return"oklch"}});var Gr=L,su=b.type;Gr.prototype.alpha=function(s,i){return i===void 0&&(i=!1),s!==void 0&&su(s)==="number"?i?(this._rgb[3]=s,this):new Gr([this._rgb[0],this._rgb[1],this._rgb[2],s],"rgb"):this._rgb[3]},L.prototype.clipped=function(){return this._rgb._clipped||!1};var Dt=L,ru=de;Dt.prototype.darken=function(s){s===void 0&&(s=1);var i=this,o=i.lab();return o[0]-=ru.Kn*s,new Dt(o,"lab").alpha(i.alpha(),!0)},Dt.prototype.brighten=function(s){return s===void 0&&(s=1),this.darken(-s)},Dt.prototype.darker=Dt.prototype.darken,Dt.prototype.brighter=Dt.prototype.brighten,L.prototype.get=function(s){var i=s.split("."),o=i[0],c=i[1],d=this[o]();if(c){var f=o.indexOf(c)-(o.substr(0,2)==="ok"?2:0);if(f>-1)return d[f];throw new Error("unknown channel "+c+" in mode "+o)}return d};var Ht=L,nu=b.type,iu=Math.pow,au=1e-7,ou=20;Ht.prototype.luminance=function(s){if(s!==void 0&&nu(s)==="number"){if(s===0)return new Ht([0,0,0,this._rgb[3]],"rgb");if(s===1)return new Ht([255,255,255,this._rgb[3]],"rgb");var i=this.luminance(),o="rgb",c=ou,d=function(h,g){var m=h.interpolate(g,.5,o),y=m.luminance();return Math.abs(s-y)<au||!c--?m:y>s?d(h,m):d(m,g)},f=(i>s?d(new Ht([0,0,0]),this):d(this,new Ht([255,255,255]))).rgb();return new Ht(f.concat([this._rgb[3]]))}return uu.apply(void 0,this._rgb.slice(0,3))};var uu=function(s,i,o){return .2126*(s=_e(s))+.7152*(i=_e(i))+.0722*(o=_e(o))},_e=function(s){return(s/=255)<=.03928?s/12.92:iu((s+.055)/1.055,2.4)},mt={},Vr=L,Wr=b.type,be=mt,Xr=function(s,i,o){o===void 0&&(o=.5);for(var c=[],d=arguments.length-3;d-- >0;)c[d]=arguments[d+3];var f=c[0]||"lrgb";if(be[f]||c.length||(f=Object.keys(be)[0]),!be[f])throw new Error("interpolation mode "+f+" is not defined");return Wr(s)!=="object"&&(s=new Vr(s)),Wr(i)!=="object"&&(i=new Vr(i)),be[f](s,i,o).alpha(s.alpha()+o*(i.alpha()-s.alpha()))},Yr=L,cu=Xr;Yr.prototype.mix=Yr.prototype.interpolate=function(s,i){i===void 0&&(i=.5);for(var o=[],c=arguments.length-2;c-- >0;)o[c]=arguments[c+2];return cu.apply(void 0,[this,s,i].concat(o))};var Hr=L;Hr.prototype.premultiply=function(s){s===void 0&&(s=!1);var i=this._rgb,o=i[3];return s?(this._rgb=[i[0]*o,i[1]*o,i[2]*o,o],this):new Hr([i[0]*o,i[1]*o,i[2]*o,o],"rgb")};var Qe=L,lu=de;Qe.prototype.saturate=function(s){s===void 0&&(s=1);var i=this,o=i.lch();return o[1]+=lu.Kn*s,o[1]<0&&(o[1]=0),new Qe(o,"lch").alpha(i.alpha(),!0)},Qe.prototype.desaturate=function(s){return s===void 0&&(s=1),this.saturate(-s)};var Jr=L,Zr=b.type;Jr.prototype.set=function(s,i,o){o===void 0&&(o=!1);var c=s.split("."),d=c[0],f=c[1],h=this[d]();if(f){var g=d.indexOf(f)-(d.substr(0,2)==="ok"?2:0);if(g>-1){if(Zr(i)=="string")switch(i.charAt(0)){case"+":case"-":h[g]+=+i;break;case"*":h[g]*=+i.substr(1);break;case"/":h[g]/=+i.substr(1);break;default:h[g]=+i}else{if(Zr(i)!=="number")throw new Error("unsupported value for Color.set");h[g]=i}var m=new Jr(h,d);return o?(this._rgb=m._rgb,this):m}throw new Error("unknown channel "+f+" in mode "+d)}return h};var hu=L,du=function(s,i,o){var c=s._rgb,d=i._rgb;return new hu(c[0]+o*(d[0]-c[0]),c[1]+o*(d[1]-c[1]),c[2]+o*(d[2]-c[2]),"rgb")};mt.rgb=du;var fu=L,ts=Math.sqrt,Jt=Math.pow,pu=function(s,i,o){var c=s._rgb,d=c[0],f=c[1],h=c[2],g=i._rgb,m=g[0],y=g[1],x=g[2];return new fu(ts(Jt(d,2)*(1-o)+Jt(m,2)*o),ts(Jt(f,2)*(1-o)+Jt(y,2)*o),ts(Jt(h,2)*(1-o)+Jt(x,2)*o),"rgb")};mt.lrgb=pu;var gu=L,mu=function(s,i,o){var c=s.lab(),d=i.lab();return new gu(c[0]+o*(d[0]-c[0]),c[1]+o*(d[1]-c[1]),c[2]+o*(d[2]-c[2]),"lab")};mt.lab=mu;var bu=L,Zt=function(s,i,o,c){var d,f,h,g,m,y,x,M,R,P,T,z,N;return c==="hsl"?(h=s.hsl(),g=i.hsl()):c==="hsv"?(h=s.hsv(),g=i.hsv()):c==="hcg"?(h=s.hcg(),g=i.hcg(
53)):c==="hsi"?(h=s.hsi(),g=i.hsi()):c==="lch"||c==="hcl"?(c="hcl",h=s.hcl(),g=i.hcl()):c==="oklch"&&(h=s.oklch().reverse(),g=i.oklch().reverse()),c.substr(0,1)!=="h"&&c!=="oklch"||(m=(d=h)[0],x=d[1],R=d[2],y=(f=g)[0],M=f[1],P=f[2]),isNaN(m)||isNaN(y)?isNaN(m)?isNaN(y)?z=Number.NaN:(z=y,R!=1&&R!=0||c=="hsv"||(T=M)):(z=m,P!=1&&P!=0||c=="hsv"||(T=x)):z=m+o*(y>m&&y-m>180?y-(m+360):y<m&&m-y>180?y+360-m:y-m),T===void 0&&(T=x+o*(M-x)),N=R+o*(P-R),new bu(c==="oklch"?[N,T,z]:[z,T,N],c)},yu=Zt,Kr=function(s,i,o){return yu(s,i,o,"lch")};mt.lch=Kr,mt.hcl=Kr;var vu=L,wu=function(s,i,o){var c=s.num(),d=i.num();return new vu(c+o*(d-c),"num")};mt.num=wu;var ku=Zt,Su=function(s,i,o){return ku(s,i,o,"hcg")};mt.hcg=Su;var xu=Zt,Ru=function(s,i,o){return xu(s,i,o,"hsi")};mt.hsi=Ru;var Eu=Zt,Tu=function(s,i,o){return Eu(s,i,o,"hsl")};mt.hsl=Tu;var Mu=Zt,Pu=function(s,i,o){return Mu(s,i,o,"hsv")};mt.hsv=Pu;var Au=L,Lu=function(s,i,o){var c=s.oklab(),d=i.oklab();return new Au(c[0]+o*(d[0]-c[0]),c[1]+o*(d[1]-c[1]),c[2]+o*(d[2]-c[2]),"oklab")};mt.oklab=Lu;var ju=Zt,Cu=function(s,i,o){return ju(s,i,o,"oklch")};mt.oklch=Cu;var es=L,Fu=b.clip_rgb,ss=Math.pow,rs=Math.sqrt,ns=Math.PI,_r=Math.cos,Qr=Math.sin,Ou=Math.atan2,Iu=function(s,i,o){i===void 0&&(i="lrgb"),o===void 0&&(o=null);var c=s.length;o||(o=Array.from(new Array(c)).map(function(){return 1}));var d=c/o.reduce(function(z,N){return z+N});if(o.forEach(function(z,N){o[N]*=d}),s=s.map(function(z){return new es(z)}),i==="lrgb")return qu(s,o);for(var f=s.shift(),h=f.get(i),g=[],m=0,y=0,x=0;x<h.length;x++)if(h[x]=(h[x]||0)*o[0],g.push(isNaN(h[x])?0:o[0]),i.charAt(x)==="h"&&!isNaN(h[x])){var M=h[x]/180*ns;m+=_r(M)*o[0],y+=Qr(M)*o[0]}var R=f.alpha()*o[0];s.forEach(function(z,N){var W=z.get(i);R+=z.alpha()*o[N+1];for(var $=0;$<h.length;$++)if(!isNaN(W[$]))if(g[$]+=o[N+1],i.charAt($)==="h"){var at=W[$]/180*ns;m+=_r(at)*o[N+1],y+=Qr(at)*o[N+1]}else h[$]+=W[$]*o[N+1]});for(var P=0;P<h.length;P++)if(i.charAt(P)==="h"){for(var T=Ou(y/g[P],m/g[P])/ns*180;T<0;)T+=360;for(;T>=360;)T-=360;h[P]=T}else h[P]=h[P]/g[P];return R/=c,new es(h,i).alpha(R>.99999?1:R,!0)},qu=function(s,i){for(var o=s.length,c=[0,0,0,0],d=0;d<s.length;d++){var f=s[d],h=i[d]/o,g=f._rgb;c[0]+=ss(g[0],2)*h,c[1]+=ss(g[1],2)*h,c[2]+=ss(g[2],2)*h,c[3]+=g[3]*h}return c[0]=rs(c[0]),c[1]=rs(c[1]),c[2]=rs(c[2]),c[3]>.9999999&&(c[3]=1),new es(Fu(c))},vt=H,Kt=b.type,Du=Math.pow,is=function(s){var i="rgb",o=vt("#ccc"),c=0,d=[0,1],f=[],h=[0,0],g=!1,m=[],y=!1,x=0,M=1,R=!1,P={},T=!0,z=1,N=function(S){if((S=S||["#fff","#000"])&&Kt(S)==="string"&&vt.brewer&&vt.brewer[S.toLowerCase()]&&(S=vt.brewer[S.toLowerCase()]),Kt(S)==="array"){S.length===1&&(S=[S[0],S[0]]),S=S.slice(0);for(var C=0;C<S.length;C++)S[C]=vt(S[C]);f.length=0;for(var I=0;I<S.length;I++)f.push(I/(S.length-1))}return gt(),m=S},W=function(S){if(g!=null){for(var C=g.length-1,I=0;I<C&&S>=g[I];)I++;return I-1}return 0},$=function(S){return S},at=function(S){return S},nt=function(S,C){var I,D;if(C==null&&(C=!1),isNaN(S)||S===null)return o;D=C?S:g&&g.length>2?W(S)/(g.length-2):M!==x?(S-x)/(M-x):1,D=at(D),C||(D=$(D)),z!==1&&(D=Du(D,z)),D=h[0]+D*(1-h[0]-h[1]),D=Math.min(1,Math.max(0,D));var tt=Math.floor(1e4*D);if(T&&P[tt])I=P[tt];else{if(Kt(m)==="array")for(var G=0;G<f.length;G++){var U=f[G];if(D<=U){I=m[G];break}if(D>=U&&G===f.length-1){I=m[G];break}if(D>U&&D<f[G+1]){D=(D-U)/(f[G+1]-U),I=vt.interpolate(m[G],m[G+1],D,i);break}}else Kt(m)==="function"&&(I=m(D));T&&(P[tt]=I)}return I},gt=function(){return P={}};N(s);var B=function(S){var C=vt(nt(S));return y&&C[y]?C[y]():C};return B.classes=function(S){if(S!=null){if(Kt(S)==="array")g=S,d=[S[0],S[S.length-1]];else{var C=vt.analyze(d);g=S===0?[C.min,C.max]:vt.limits(C,"e",S)}return B}return g},B.domain=function(S){if(!arguments.length)return d;x=S[0],M=S[S.length-1],f=[];var C=m.length;if(S.length===C&&x!==M)for(var I=0,D=Array.from(S);I<D.length;I+=1){var tt=D[I];f.push((tt-x)/(M-x))}else{for(var G=0;G<C;G++)f.push(G/(C-1));if(S.length>2){var U=S.map(function(J,V){return V/(S.length-1)}),Y=S.map(function(J){return(J-x)/(M-x)});Y.every(function(J,V){return U[V]===J})||(at=function(J){if(J<=0||J>=1)return J;for(var V=0;J>=Y[V+1];)V++;var kt=(J-Y[V])/(Y[V+1]-Y[V]);return U[V]+kt*(U[V+1]-U[V])})}}return d=[x,M],B},B.mode=function(S){return arguments.length?(i=S,gt(),B):i},B.range=function(S,C){return N(S),B},B.out=function(S){return y=S,B},B.spread=function(S){return arguments.length?(c=S,B):c},B.correctLightness=function(S){return S==null&&(S=!0),R=S,gt(),$=R?function(C){for(var I=nt(0,!0).lab()[0],D=nt(1,!0).lab()[0],tt=I>D,G=nt(C,!0).lab()[0],U=I+(D-I)*C,Y=G-U,J=0,V=1,kt=20;Math.abs(Y)>.01&&kt-- >0;)(function(){tt&&(Y*=-1),Y<0?(J=C,C+=.5*(V-C)):(V=C,C+=.5*(J-C)),G=nt(C,!0).lab()[0],Y=G-U})();return C}:function(C){return C},B},B.padding=function(S){return S!=null?(Kt(S)==="number"&&(S=[S,S]),h=S,B):h},B.colors=function(S,C){arguments.length<2&&(C="hex");var I=[];if(arguments.length===0)I=m.slice(0);else if(S===1)I=[B(.5)];else if(S>1){var D=d[0],tt=d[1]-D;I=Nu(0,S).map(function(V){return B(D+V/(S-1)*tt)})}else{s=[];var G=[];if(g&&g.length>2)for(var U=1,Y=g.length,J=1<=Y;J?U<Y:U>Y;J?U++:U--)G.push(.5*(g[U-1]+g[U]));else G=d;I=G.map(function(V){return B(V)})}return vt[C]&&(I=I.map(function(V){return V[C]()})),I},B.cache=function(S){return S!=null?(T=S,B):T},B.gamma=function(S){return S!=null?(z=S,B):z},B.nodata=function(S){return S!=null?(o=vt(S),B):o},B};function Nu(s,i,o){for(var c=[],d=s<i,f=i,h=s;d?h<f:h>f;d?h++:h--)c.push(h);return c}var ne=L,Bu=is,zu=function(s){for(var i=[1,1],o=1;o<s;o++){for(var c=[1],d=1;d<=i.length;d++)c[d]=(i[d]||0)+i[d-1];i=c}return i},Uu=function(s){var i,o,c,d,f,h,g;if((s=s.map(function(R){return new ne(R)})).length===2)i=s.map(function(R){return R.lab()}),f=i[0],h=i[1],d=function(R){var P=[0,1,2].map(function(T){return f[T]+R*(h[T]-f[T])});return new ne(P,"lab")};else if(s.length===3)o=s.map(function(R){return R.lab()}),f=o[0],h=o[1],g=o[2],d=function(R){var P=[0,1,2].map(function(T){return(1-R)*(1-R)*f[T]+2*(1-R)*R*h[T]+R*R*g[T]});return new ne(P,"lab")};else if(s.length===4){var m;c=s.map(function(R){return R.lab()}),f=c[0],h=c[1],g=c[2],m=c[3],d=function(R){var P=[0,1,2].map(function(T){return(1-R)*(1-R)*(1-R)*f[T]+3*(1-R)*(1-R)*R*h[T]+3*(1-R)*R*R*g[T]+R*R*R*m[T]});return new ne(P,"lab")}}else{if(!(s.length>=5))throw new RangeError("No point in running bezier with only one color.");var y,x,M;y=s.map(function(R){return R.lab()}),M=s.length-1,x=zu(M),d=function(R){var P=1-R,T=[0,1,2].map(function(z){return y.reduce(function(N,W,$){return N+x[$]*Math.pow(P,M-$)*Math.pow(R,$)*W[z]},0)});return new ne(T,"lab")}}return d},$u=function(s){var i=Uu(s);return i.scale=function(){return Bu(i)},i},as=H,wt=function(s,i,o){if(!wt[o])throw new Error("unknown blend mode "+o
53);return wt[o](s,i)},jt=function(s){return function(i,o){var c=as(o).rgb(),d=as(i).rgb();return as.rgb(s(c,d))}},Ct=function(s){return function(i,o){var c=[];return c[0]=s(i[0],o[0]),c[1]=s(i[1],o[1]),c[2]=s(i[2],o[2]),c}},Gu=function(s){return s},Vu=function(s,i){return s*i/255},Wu=function(s,i){return s>i?i:s},Xu=function(s,i){return s>i?s:i},Yu=function(s,i){return 255*(1-(1-s/255)*(1-i/255))},Hu=function(s,i){return i<128?2*s*i/255:255*(1-2*(1-s/255)*(1-i/255))},Ju=function(s,i){return 255*(1-(1-i/255)/(s/255))},Zu=function(s,i){return s===255||(s=i/255*255/(1-s/255))>255?255:s};wt.normal=jt(Ct(Gu)),wt.multiply=jt(Ct(Vu)),wt.screen=jt(Ct(Yu)),wt.overlay=jt(Ct(Hu)),wt.darken=jt(Ct(Wu)),wt.lighten=jt(Ct(Xu)),wt.dodge=jt(Ct(Zu)),wt.burn=jt(Ct(Ju));for(var Ku=wt,os=b.type,_u=b.clip_rgb,Qu=b.TWOPI,tc=Math.pow,ec=Math.sin,sc=Math.cos,tn=H,rc=function(s,i,o,c,d){s===void 0&&(s=300),i===void 0&&(i=-1.5),o===void 0&&(o=1),c===void 0&&(c=1),d===void 0&&(d=[0,1]);var f,h=0;os(d)==="array"?f=d[1]-d[0]:(f=0,d=[d,d]);var g=function(m){var y=Qu*((s+120)/360+i*m),x=tc(d[0]+f*m,c),M=(h!==0?o[0]+m*h:o)*x*(1-x)/2,R=sc(y),P=ec(y);return tn(_u([255*(x+M*(-.14861*R+1.78277*P)),255*(x+M*(-.29227*R-.90649*P)),255*(x+M*(1.97294*R)),1]))};return g.start=function(m){return m==null?s:(s=m,g)},g.rotations=function(m){return m==null?i:(i=m,g)},g.gamma=function(m){return m==null?c:(c=m,g)},g.hue=function(m){return m==null?o:(os(o=m)==="array"?(h=o[1]-o[0])===0&&(o=o[1]):h=0,g)},g.lightness=function(m){return m==null?d:(os(m)==="array"?(d=m,f=m[1]-m[0]):(d=[m,m],f=0),g)},g.scale=function(){return tn.scale(g)},g.hue(o),g},nc=L,ic="0123456789abcdef",ac=Math.floor,oc=Math.random,uc=function(){for(var s="#",i=0;i<6;i++)s+=ic.charAt(ac(16*oc()));return new nc(s,"hex")},us=p,en=Math.log,cc=Math.pow,lc=Math.floor,hc=Math.abs,sn=function(s,i){i===void 0&&(i=null);var o={min:Number.MAX_VALUE,max:-1*Number.MAX_VALUE,sum:0,values:[],count:0};return us(s)==="object"&&(s=Object.values(s)),s.forEach(function(c){i&&us(c)==="object"&&(c=c[i]),c==null||isNaN(c)||(o.values.push(c),o.sum+=c,c<o.min&&(o.min=c),c>o.max&&(o.max=c),o.count+=1)}),o.domain=[o.min,o.max],o.limits=function(c,d){return rn(o,c,d)},o},rn=function(s,i,o){i===void 0&&(i="equal"),o===void 0&&(o=7),us(s)=="array"&&(s=sn(s));var c=s.min,d=s.max,f=s.values.sort(function(ds,fs){return ds-fs});if(o===1)return[c,d];var h=[];if(i.substr(0,1)==="c"&&(h.push(c),h.push(d)),i.substr(0,1)==="e"){h.push(c);for(var g=1;g<o;g++)h.push(c+g/o*(d-c));h.push(d)}else if(i.substr(0,1)==="l"){if(c<=0)throw new Error("Logarithmic scales are only possible for values > 0");var m=Math.LOG10E*en(c),y=Math.LOG10E*en(d);h.push(c);for(var x=1;x<o;x++)h.push(cc(10,m+x/o*(y-m)));h.push(d)}else if(i.substr(0,1)==="q"){h.push(c);for(var M=1;M<o;M++){var R=(f.length-1)*M/o,P=lc(R);if(P===R)h.push(f[P]);else{var T=R-P;h.push(f[P]*(1-T)+f[P+1]*T)}}h.push(d)}else if(i.substr(0,1)==="k"){var z,N=f.length,W=new Array(N),$=new Array(o),at=!0,nt=0,gt=null;(gt=[]).push(c);for(var B=1;B<o;B++)gt.push(c+B/o*(d-c));for(gt.push(d);at;){for(var S=0;S<o;S++)$[S]=0;for(var C=0;C<N;C++)for(var I=f[C],D=Number.MAX_VALUE,tt=void 0,G=0;G<o;G++){var U=hc(gt[G]-I);U<D&&(D=U,tt=G),$[tt]++,W[C]=tt}for(var Y=new Array(o),J=0;J<o;J++)Y[J]=null;for(var V=0;V<N;V++)Y[z=W[V]]===null?Y[z]=f[V]:Y[z]+=f[V];for(var kt=0;kt<o;kt++)Y[kt]*=1/$[kt];at=!1;for(var Nt=0;Nt<o;Nt++)if(Y[Nt]!==gt[Nt]){at=!0;break}gt=Y,++nt>200&&(at=!1)}for(var Bt={},ie=0;ie<o;ie++)Bt[ie]=[];for(var _t=0;_t<N;_t++)Bt[z=W[_t]].push(f[_t]);for(var St=[],ae=0;ae<o;ae++)St.push(Bt[ae][0]),St.push(Bt[ae][Bt[ae].length-1]);St=St.sort(function(ds,fs){return ds-fs}),h.push(St[0]);for(var ls=1;ls<St.length;ls+=2){var hs=St[ls];isNaN(hs)||h.indexOf(hs)!==-1||h.push(hs)}}return h},nn={analyze:sn,limits:rn},an=L,dc=function(s,i){s=new an(s),i=new an(i);var o=s.luminance(),c=i.luminance();return o>c?(o+.05)/(c+.05):(c+.05)/(o+.05)},on=L,Mt=Math.sqrt,_=Math.pow,fc=Math.min,pc=Math.max,un=Math.atan2,cn=Math.abs,ye=Math.cos,ln=Math.sin,gc=Math.exp,hn=Math.PI,mc=function(s,i,o,c,d){o===void 0&&(o=1),c===void 0&&(c=1),d===void 0&&(d=1);var f=function(St){return 360*St/(2*hn)},h=function(St){return 2*hn*St/360};s=new on(s),i=new on(i);var g=Array.from(s.lab()),m=g[0],y=g[1],x=g[2],M=Array.from(i.lab()),R=M[0],P=M[1],T=M[2],z=(m+R)
53/2,N=(Mt(_(y,2)+_(x,2))+Mt(_(P,2)+_(T,2)))/2,W=.5*(1-Mt(_(N,7)/(_(N,7)+_(25,7)))),$=y*(1+W),at=P*(1+W),nt=Mt(_($,2)+_(x,2)),gt=Mt(_(at,2)+_(T,2)),B=(nt+gt)/2,S=f(un(x,$)),C=f(un(T,at)),I=S>=0?S:S+360,D=C>=0?C:C+360,tt=cn(I-D)>180?(I+D+360)/2:(I+D)/2,G=1-.17*ye(h(tt-30))+.24*ye(h(2*tt))+.32*ye(h(3*tt+6))-.2*ye(h(4*tt-63)),U=D-I;U=cn(U)<=180?U:D<=I?U+360:U-360,U=2*Mt(nt*gt)*ln(h(U)/2);var Y=R-m,J=gt-nt,V=1+.015*_(z-50,2)/Mt(20+_(z-50,2)),kt=1+.045*B,Nt=1+.015*B*G,Bt=30*gc(-_((tt-275)/25,2)),ie=-2*Mt(_(B,7)/(_(B,7)+_(25,7)))*ln(2*h(Bt)),_t=Mt(_(Y/(o*V),2)+_(J/(c*kt),2)+_(U/(d*Nt),2)+ie*(J/(c*kt))*(U/(d*Nt)));return pc(0,fc(100,_t))},dn=L,bc=function(s,i,o){o===void 0&&(o="lab"),s=new dn(s),i=new dn(i);var c=s.get(o),d=i.get(o),f=0;for(var h in c){var g=(c[h]||0)-(d[h]||0);f+=g*g}return Math.sqrt(f)},yc=L,vc=function(){for(var s=[],i=arguments.length;i--;)s[i]=arguments[i];try{return new(Function.prototype.bind.apply(yc,[null].concat(s))),!0}catch{return!1}},fn=H,pn=is,wc={cool:function(){return pn([fn.hsl(180,1,.9),fn.hsl(250,.7,.4)])},hot:function(){return pn(["#000","#f00","#ff0","#fff"]).mode("rgb")}},ve={OrRd:["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#b30000","#7f0000"],PuBu:["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#045a8d","#023858"],BuPu:["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#810f7c","#4d004b"],Oranges:["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"],BuGn:["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#006d2c","#00441b"],YlOrBr:["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#993404","#662506"],YlGn:["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#006837","#004529"],Reds:["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"],RdPu:["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177","#49006a"],Greens:["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"],YlGnBu:["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"],Purples:["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"],GnBu:["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#0868ac","#084081"],Greys:["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"],YlOrRd:["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"],PuRd:["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#980043","#67001f"],Blues:["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"],PuBuGn:["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016c59","#014636"],Viridis:["#440154","#482777","#3f4a8a","#31678e","#26838f","#1f9d8a","#6cce5a","#b6de2b","#fee825"],Spectral:["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"],RdYlGn:["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"],RdBu:["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"],PiYG:["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"],PRGn:["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"],RdYlBu:["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"],BrBG:["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"],RdGy:["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"],PuOr:["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"],Set2:["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494","#b3b3b3"],Accent:["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17","#666666"],Set1:["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf","#999999"],Set3:["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"],Dark2:["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d","#666666"],Paired:["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99","#b15928"],Pastel2:["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc","#cccccc"],Pastel1:["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec","#f2f2f2"]},cs=0,gn=Object.keys(ve);cs<gn.length;cs+=1){var mn=gn[cs];ve[mn.toLowerCase()]=ve[mn]}var kc=ve,rt=H;rt.average=Iu,rt.bezier=$u,rt.blend=Ku,rt.cubehelix=rc,rt.mix=rt.interpolate=Xr,rt.random=uc,rt.scale=is,rt.analyze=nn.analyze,rt.contrast=dc,rt.deltaE=mc,rt.distance=bc,rt.limits=nn.limits,rt.valid=vc,rt.scales=wc,rt.colors=Pr,rt.brewer=kc;var Sc=rt;return Sc})();var Kn=Zn.exports;const ml=Kn.mix,bl=Kn.Color,Ss=(()=>{const r=bl;return r.symbol=r.prototype.symbol=Symbol.for("@imaginix-inc/motion-canvas-core/types/Color"),r.lerp=r.prototype.lerp=(t,e,n,a="lch")=>{typeof t=="string"&&(t=new r(t)),typeof e=="string"&&(e=new r(e));const u=t instanceof r,l=e instanceof r;return u||(t=l?e.alpha(0):new r("rgba(0, 0, 0, 0)")),l||(e=u?t.alpha(0):new r("rgba(0, 0, 0, 0)")),ml(t,e,n,a)},r.createLerp=r.prototype.createLerp=t=>(e,n,a)=>r.lerp(e,n,a,t),r.createSignal=r.prototype.createSignal=(t,e=r.lerp)=>new Te(t,e,void 0,n=>new r(n)).toSignal(),r.prototype.toSymbol=()=>r.symbol,r.prototype.toUniform=function(t,e){t.uniform4fv(e,this.gl())},r.prototype.serialize=function(){return this.css()},r.prototype.lerp=function(t,e,n){return r.lerp(this,t,e,n)},r})();function Ph(r,t){return v.fromDegrees(r).transform(t).degrees}function Ah(r,t){return v.magnitude(t.m11,t.m12)*r}class xs extends bt{type=Ss.symbol;parse(t){return t===null?null:new Ss(t)}serialize(){return this.value.current?.serialize()??null}}class Gt extends bt{options;static symbol=Symbol.for("@imaginix-inc/motion-canvas-core/meta/EnumMetaField");type=Gt.symbol;constructor(t,e,n=e[0]?.value){super(t,n),this.options=e}set(t){super.set(this.getOption(t)?.value)}parse(t){return this.getOption(t)?.value}getOption(t){return this.options.find(e=>e.value===t)??this.options[0]}}class yl extends bt{current;type=Object;get onFieldsChanged(){return this.fields.subscribable}fields;get options(){return this.optionFields[this.current]}exporterField;optionFields;exporters;constructor(t,e,n=0){const a=e.plugins.flatMap(p=>p.exporters?.(e)??[]),u=a.map(p=>p.meta(e)),l=new Gt("exporter",a.map(p=>({value:p.id,text:p.displayName})),a[n]?.id);super(t,{name:l.get(),options:u[n]?.get()}),this.current=n,this.exporters=a,this.exporterField=l,this.exporterField.onChanged.subscribe(this.handleChange,!1),this.exporterField.disable(u.length<2).space(),this.optionFields=u,this.fields=new pt([this.exporterField]),this.options&&(this.options.onChanged.subscribe(this.handleChange,!1),this.fields.current=[this.exporterField,this.options])}set(t){this.exporterField.set(t.name),this.options?.set(t.options??{})}
53serialize(){return{name:this.exporterField.serialize(),options:this.options?.serialize()??null}}clone(){return new this.constructor(this.name,this.exporters,this.current)}handleChange=()=>{const t=this.exporterField.get(),e=Math.max(this.exporters.findIndex(n=>n.id===t),0);this.current!==e&&(this.options?.onChanged.unsubscribe(this.handleChange),this.current=e,this.options?.onChanged.subscribe(this.handleChange,!1),this.fields.current=this.options?[this.exporterField,this.options]:[this.exporterField]),this.value.current={name:this.exporterField.get(),options:this.options?.get()??null}}}const zt=class zt{name;source;lock=new Nn;ignoreChange=!1;cache=null;metaField=null;constructor(t,e=!1){this.name=t,this.source=e}attach(t){this.metaField||(this.metaField=t,this.cache&&this.metaField.set(this.cache),this.metaField?.onChanged.subscribe(this.handleChanged))}handleChanged=async()=>{};async saveData(t){if(this.source===!1)return;if(!this.source)throw new Error(`The meta file for ${this.name} is missing.`);if(zt.sourceLookup[this.source])throw new Error(`Metadata for ${this.name} is already being updated`);const e=this.source;await new Promise((n,a)=>{setTimeout(()=>{delete zt.sourceLookup[e],a(`Connection timeout when updating metadata for ${this.name}`)},1e3),zt.sourceLookup[e]=()=>{delete zt.sourceLookup[e],n()},(void 0).send("motion-canvas:meta",{source:e,data:t})})}loadData(t){this.ignoreChange=!0,this.cache=t,this.metaField?.set(t),this.ignoreChange=!1}};oe(zt,"sourceLookup",{});let Rn=zt;class ke extends bt{type=Number;presets=[];min=-1/0;max=1/0;precision=0;step=1;parse(t){let e=parseFloat(t);return isNaN(e)&&(e=this.initial),Tt(this.min,this.max,e)}getPresets(){return this.presets}setPresets(t){return this.presets=t,this}setRange(t,e){return this.min=t??-1/0,this.max=e??1/0,this}getMin(){return this.min??-1/0}getMax(){return this.max??1/0}setPrecision(t){return this.precision=Tt(0,100,t),this}getPrecision(){return this.precision}setStep(t){return this.step=t,this}getStep(){return this.step}}class qs extends bt{static symbol=Symbol.for("@imaginix-inc/motion-canvas-core/meta/RangeMetaField");type=qs.symbol;parse(t){return this.parseRange(1/0,t[0],t[1]??1/0)}update(t,e,n,a){this.value.current=this.parseRange(n/a-ue,t/a-ue,e/a-ue)}parseRange(t,e=this.value.current[0],n=this.value.current[1]){return(e=Tt(0,t,e))>(n=Tt(0,t,n??1/0))&&([e,n]=[n,e]),n>=t&&(n=1/0),[e,n]}}class _n extends bt{type=v.symbol;parse(t){return new v(t)}serialize(){return this.value.current.serialize()}}const En=[{value:.25,text:"0.25x (Quarter)"},{value:.5,text:"0.5x (Half)"},{value:1,text:"1.0x (Full)"},{value:2,text:"2.0x (Double)"}],vl=[{value:"srgb",text:"sRGB"},{value:"display-p3",text:"DCI-P3"}],wl=[{value:"image/png",text:"png"},{value:"image/jpeg",text:"jpeg"},{value:"image/webp",text:"webp"}],Tn=[{value:30,text:"30 FPS"},{value:60,text:"60 FPS"}],Ot=class Ot{logger;settings;static meta(){const t=new At(this.name,{fileType:new Gt("file type",wl),quality:new ke("quality",100).setRange(0,100).describe("A number between 0 and 100 indicating the image quality."),groupByScene:new vs("group by scene",!1).describe("Group exported images by scene. When checked, separates the sequence into subdirectories for each scene in the project.")});return t.fileType.onChanged.subscribe(e=>{t.quality.disable(e==="image/png")}),t}static async create(t,e){return new Ot(t.logger,e)}frameLookup=new Set;projectName;quality;fileType;groupByScene;constructor(t,e){this.logger=t,this.settings=e;const n=e.exporter.options;this.projectName=e.name,this.quality=Tt(0,1,n.quality/100),this.fileType=n.fileType,this.groupByScene=n.groupByScene}async start(){Ot.response.subscribe(this.handleResponse)}async handleFrame(t,e,n,a,u){this.frameLookup.has(e)&&this.logger.warn(`Frame no. ${e} is already being exported.`)}async stop(){for(;this.frameLookup.size>0;)await new Promise(t=>setTimeout(t,1e3));Ot.response.unsubscribe(this.handleResponse)}handleResponse=({frame:t})=>{this.frameLookup.delete(t)}};oe(Ot,"id","@imaginix-inc/motion-canvas-core/image-sequence"),oe(Ot,"displayName","Image sequence"),oe(Ot,"response",new yt);let Rs=Ot;var xt;(function(r){r.Error="error",r.Warn="warn",r.Info="info",r.Http="http",r.Verbose="verbose",r.Debug="debug",r.Silly="silly"})(xt||(xt={}));class Ds{get onLogged(){return this.logged.subscribable}logged=new yt;history=[];profilers={};log(t){this.logged.dispatch(t),this.history.push(t)}error(t){this.logLevel(xt.Error,t)}warn(t){this.logLevel(xt.Warn,t)}info(t){this.logLevel(xt.Info,t)}http(t){this.logLevel(xt.Http,t)}verbose(t){this.logLevel(xt.Verbose,t)}debug(t){this.logLevel(xt.Debug,t)}silly(t){this.logLevel(xt.Silly,t)}logLevel(t,e){const n=typeof e=="string"?{message:e}:e;n.level=t,this.log(n)}profile(t,e){const n=performance.now();if(this.profilers[t]){const a=this.profilers[t];delete this.profilers[t];const u=e??{message:t};
53return u.level??=xt.Debug,u.durationMs=n-a,void this.log(u)}this.profilers[t]=n}}class kl{playback;constructor(t){this.playback=t}secondsToFrames(t){return Math.ceil(t*this.playback.fps)}framesToSeconds(t){return t/this.playback.fps}get time(){return this.framesToSeconds(this.playback.frame)}get frame(){return this.playback.frame}get speed(){return this.playback.speed}get fps(){return this.playback.fps}get state(){return this.playback.state}get deltaTime(){return this.framesToSeconds(1)*this.speed}}function Ns(r,t,e,n){var a,u=arguments.length,l=u<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")l=Reflect.decorate(r,t,e,n);else for(var p=r.length-1;p>=0;p--)(a=r[p])&&(l=(u<3?a(l):u>3?a(t,e,l):a(t,e))||l);return u>3&&l&&Object.defineProperty(t,e,l),l}const Mn={peaks:[],length:0,absoluteMax:0,sampleRate:0,duration:0},Es="accessed-tts-urls";function gs(r){const t=(function(){const e=sessionStorage.getItem(Es);if(!e)return new Set;try{return new Set(JSON.parse(e))}catch{return new Set}})();t.add(r),(function(e){sessionStorage.setItem(Es,JSON.stringify(Array.from(e)))})(t)}typeof window<"u"&&(sessionStorage.removeItem(Es),(function(){for(let r=0;r<localStorage.length;r++){const t=localStorage.key(r);t&&t.startsWith("audio-stream-duration-cache-v1-")&&!t.startsWith("audio-stream-duration-cache-v1.1-")&&localStorage.removeItem(t)}})());const Pn=new class{maxConcurrency;currentRunning;queue;constructor(r){this.maxConcurrency=r,this.currentRunning=0,this.queue=[]}async acquire(r){if(r?.aborted)throw new DOMException("Aborted","AbortError");if(!(this.currentRunning<this.maxConcurrency))return new Promise((t,e)=>{const n=()=>{u(),t()},a=()=>{u();const l=this.queue.indexOf(n);l>-1&&this.queue.splice(l,1),e(new DOMException("Aborted","AbortError"))},u=()=>{r?.removeEventListener("abort",a)};r?.addEventListener("abort",a,{once:!0}),this.queue.push(n)});this.currentRunning++}release(){this.queue.length>0?this.queue.shift()?.():this.currentRunning=Math.max(0,this.currentRunning-1)}}(2),Sl=300,xl=2;async function Rl(r,t={}){const{signal:e}=t;if(e?.aborted)throw new DOMException("Aborted","AbortError");const n=await caches.open("audio-stream-cache-v1"),a=await n.match(r);if(a?.body)return gs(r),console.log("[MotionCanvas] ä» cache ä¸è·å 1",r),a.body;await Pn.acquire(e);try{const u=await n.match(r);if(u?.body)return gs(r),console.log("[MotionCanvas] ä» cache ä¸è·å 2",r),u.body;const l=await(async function(k,E){let O;for(let j=0;j<=E.retries;j++)try{return await k()}catch(b){O=b instanceof Error?b:new Error(String(b)),j<E.retries&&await new Promise(F=>setTimeout(F,E.delay))}throw O||new Error("Retry failed")})(async()=>{console.log("[MotionCanvas] ç´æ¥è¯·æ±",r);const k=await fetch(r,{signal:e});if(!k.ok)throw new Error(`HTTP error! status: ${k.status}`);if(!k.body)throw new Error("Response has no body (not a stream)");return k},{delay:Sl,retries:xl}),[p,w]=l.body.tee();return gs(r),(async function(k,E,O,j){const b=new Headers(O.headers);b.delete("Transfer-Encoding");const F=new Response(j,{status:200,headers:b});try{await k.put(E,F)}catch(Z){console.warn("[audio stream cache failed]",Z)}})(n,r,l,w),p}finally{Pn.release()}}const Ts="audio-stream-duration-cache-v1.1";function we(r){try{const t=localStorage.getItem(`${Ts}-${r}`),{duration:e}=El(t,{duration:0});return e}catch(t){return console.warn("[audio duration cache] read failed",t),0}}function Se(r,t){const e=`${Ts}-${r}`,n=JSON.stringify({duration:t});try{localStorage.setItem(e,n)}catch(a){console.warn("[audio duration cache] write failed, clearing stale entries and retrying",a);try{(function(){for(let u=localStorage.length-1;u>=0;u--){const l=localStorage.key(u);l?.startsWith(Ts)&&localStorage.removeItem(l)}})(),localStorage.setItem(e,n)}catch(u){console.warn("[audio duration cache] retry failed, giving up",u)}}}const El=(r,t)=>{if(r==null)return t;try{return JSON.parse(r)}catch{return t}},Ms=globalThis.globalAsudioDataCache??(globalThis.globalAsudioDataCache=new Map);class ct{logger;onResourceLoaded;static globalListeners=new Set;static context=null;lookup=new Map;static getContext(){if(!ct.context){const t=(()=>
53{if(typeof globalThis>"u")return;const e=globalThis;return e.AudioContext??e.webkitAudioContext})();if(!t)throw new Error("AudioContext is not available in this environment.");ct.context=new t}return ct.context}constructor(t,e){this.logger=t,this.onResourceLoaded=e}peekDuration(t){return this.get(t).getDuration()}get(t){let e=this.lookup.get(t);return e||(e=new Ut(this,this.logger,t,ct.getContext()),this.lookup.set(t,e)),e}has(t){return this.lookup.has(t)}notifyLoaded(t,e){this.onResourceLoaded?.(t,e),ct.notifyGlobalListeners(t,e)}static addGlobalListener(t){return this.globalListeners.add(t),()=>{this.globalListeners.delete(t)}}static async prepareAudioUrl(t,e,n=t){const a=await Ut.loadData(ct.getContext(),t,new Ds,e);if(a){if(a.duration>0)for(const u of(function(l,p){const w=new Set,k=E=>{w.add(E);try{const O=new URL(E);if(!O.pathname.endsWith("/tts/no-stream"))return;O.pathname=O.pathname.replace(/\/tts\/no-stream$/,"/tts/stream"),w.add(O.toString())}catch{}};return k(l),k(p),w})(t,n))Se(u,a.duration);Ms.set(t,a)}return a}static notifyGlobalListeners(t,e){for(const n of this.globalListeners)try{n(t,e)}catch(a){console.error(a)}}}class Ut{manager;logger;source;context;get onData(){return this.data.subscribable}data=new pt(Mn);abort=null;lastReportedDuration=0;static audioCache=typeof globalThis<"u"&&"caches"in globalThis?globalThis.caches.open("audio-cache-v1"):null;constructor(t,e,n,a){this.manager=t,this.logger=e,this.source=n,this.context=a,this.reload()}getDuration(){const t=this.data.current.duration;if(t>0&&Number.isFinite(t))return t;const e=Ms.get(this.source)?.duration??0;return e>0&&Number.isFinite(e)?e:0}async reload(){this.abort?.abort();const t=new AbortController;this.abort=t;const e=Ms.get(this.source)??await Ut.loadData(this.context,this.source,this.logger,t.signal);if(!t.signal.aborted){const n=e??Mn;this.data.current=n,this.handleLoaded(n)}}static async loadData(t,e,n,a){let u;const l=(e.startsWith("http://")||e.startsWith("https://"))&&Ut.audioCache?Ut.audioCache:null;try{if(l&&(u=await(await l).match(e)),!u){const b=await fetch(e,{signal:a});if(!b.ok)return void n.error(`Failed to fetch audio resource (${b.status}): ${e}`);if(l)try{await(await l).put(e,b.clone())}
53catch(F){n.warn(F instanceof Error?F.message:String(F))}u=b}}catch(b){return void(b.name!=="AbortError"&&n.error(b))}if(!u)return;const p=await u.arrayBuffer();if(a.aborted)return;let w;try{w=await Ut.decodeAudioData(t,p)}catch{return}if(a.aborted)return;const k=256,E=~~(w.length/k),O=[];let j=0;for(let b=0;b<w.numberOfChannels;b++){const F=w.getChannelData(b);for(let Z=0;Z<E;Z++){const K=~~(Z*k),lt=~~(K+k);let A=F[K],X=A;for(let L=K;L<lt;L++){const it=F[L];it>X&&(X=it),it<A&&(A=it)}(b===0||X>O[2*Z])&&(O[2*Z]=X),(b===0||A<O[2*Z+1])&&(O[2*Z+1]=A),X>j&&(j=X),Math.abs(A)>j&&(j=Math.abs(A))}}return{peaks:O,absoluteMax:j,length:E,sampleRate:w.sampleRate/k*2,duration:w.duration}}static decodeAudioData(t,e){return new Promise((n,a)=>t.decodeAudioData(e,n,a).catch(a))}handleLoaded(t){t.duration>0&&t.duration!==this.lastReportedDuration&&(this.lastReportedDuration=t.duration,this.manager.notifyLoaded(this.source,t))}}class Ft{static managers=new WeakMap;settings;constructor(t){if(typeof t=="string")this.settings={audio:t};else{if(!t?.audio)throw new Error("AudioClip requires an audio source.");this.settings={...t}}}trim(t,e){return this.settings.start=t,this.settings.end=e,this}gain(t){return this.settings.gain=t,this}detune(t){return this.settings.detune=t,this}playbackRate(t){return this.settings.playbackRate=t>0?t:1,this}async*play(t=0,e="auto"){const n=Et();if(n.sounds.add({...this.settings},t),e===!1)return;const a=typeof e=="number"?e:yield*Ft.resolveDuration(n,this.settings);a&&a>0&&(yield*Q(a))}static async*resolveDuration(t,e){const n=Ft.getManager(t).get(e.audio);let a=Ft.calculateDuration(n,e);if(a>0)return a;for(let u=0;u<600;u++)if(yield,a=Ft.calculateDuration(n,e),a>0)return a;return a}static calculateDuration(t,e){const n=t.getDuration();if(!n||!Number.isFinite(n))return 0;const a=e.start??0,u=e.end??n,l=Math.max(0,u-a);if(l===0)return 0;const p=2**((e.detune??0)/1200)*(e.playbackRate??1);return p&&Number.isFinite(p)?l/p:l}static getManager(t){let e=Ft.managers.get(t);return e||(e=new ct(t.logger),Ft.managers.set(t,e)),e}}Ns([st()],Ft.prototype,"play",null);function Qn(){const r=globalThis;return r.__motion_canvas_audio_element_pool__||(r.__motion_canvas_audio_element_pool__=[]),r.__motion_canvas_audio_element_pool__}function ti(r){const t=new Audio;t.crossOrigin="anonymous",t.preload="auto";const e=r.createMediaElementSource(t),n=r.createGain();return e.connect(n),n.connect(r.destination),{audio:t,sourceNode:e,gainNode:n,inUse:!1,primed:!1}}function Tl(r){if(r.primed)return;const t=r.audio,e=t.muted;let n;t.muted=!0,t.src="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=";try{n=t.play()}catch{}n&&typeof n.then=="function"?n.then(()=>{t.pause(),t.currentTime=0,t.muted=e,r.primed=!0}).catch(()=>{t.muted=e}):t.muted=e}function Lh(r=8){const t=ct.getContext();t.state==="suspended"&&t.resume().catch(()=>{});const e=Qn();for(;e.length<r;)e.push(ti(t));for(const n of e)Tl(n)}function Ml(){const r=ct.getContext(),t=Qn();for(const n of t)if(!n.inUse)return n.inUse=!0,ei(n),n;const e=ti(r);return e.inUse=!0,t.push(e),e}function Pl(r){r.inUse&&(ei(r),r.inUse=!1)}function ei(r){const{audio:t,gainNode:e}=r;t.pause(),t.removeAttribute("src"),t.load(),t.muted=!1,t.volume=1,t.playbackRate=1,t.preservesPitch=!0,e.gain.value=1}class Pe{logger;context;slot=Ml();get audioElement(){if(!this.slot)throw new Error("AudioManager used after dispose().");return this.slot.audio}get gainNode(){if(!this.slot)throw new Error("AudioManager used after dispose().");return this.slot.gainNode}static audioCache=typeof globalThis<"u"&&"caches"in globalThis?globalThis.caches.open("audio-cache-v1"):null;source=null;error=!1;offset=0;start;duration;clipPlaybackRate=1;globalPlaybackRate=1;clipPitchShift=!1;constructor(t,e){this.logger=t,this.context=e}async setSound(t){this.setOffset(t.offset),this.setTrim(t.start,t.end),await this.setSource(t.audio),this.gainNode.gain.value=Math.pow(10,(t.gain??0)/10),this.setClipPlaybackRate(t.realPlaybackRate,!0)}getTime(){return this.toAbsoluteTime(this.audioElement.currentTime)}setTime(t){this.audioElement.currentTime=this.toRelativeTime(t)}setTrim(t,e){this.start=t,this.duration=e!==void 0?e-(t??0):void 0}setOffset(t){this.offset=t}setClipPlaybackRate(t,e=!1){this.clipPlaybackRate=t>0?t:1,this.clipPitchShift=e,this.applyPlaybackRate()}setGlobalPlaybackRate(t){this.globalPlaybackRate=t>0?t:1,this.applyPlaybackRate()}setMuted(t){this.audioElement.muted=t}setVolume(t){this.audioElement.volume=t}getSource(){return this.source}async setSource(t){const e=(t.startsWith("http://")||t.startsWith("https://"))&&Pe.audioCache?Pe.audioCache:null;if(e)try{const n=await e;let a=await n.match(t);if(!a&&(await(async()=>{const l=await fetch(t);if(l.ok){try{await n.put(t,l.clone())}catch(p){this.logger.warn(p instanceof Error?p.message:String(p))}a=l}else this.logger.warn(`Failed to fetch audio source (${l.status}): ${t}`)})(),!a))return void this.logger.warn(`Failed to fetch audio source: ${t}`);if(a){const u=await a.blob(),l=URL.createObjectURL(u);return this.source=l,void(this.audioElement.src=l)}}catch(n){this.logger.warn(n instanceof Error?n.message:String(n))}}isInRange(t){return t>=this.offset&&t<this.offset+(this.duration??this.audioElement.duration*this.audioElement.playbackRate)}toRelativeTime(t){return Math.max(0,t-this.offset)*this.clipPlaybackRate+(this.start??0)}toAbsoluteTime(t){return(t-(this.start??0))/this.clipPlaybackRate+this.offset}isReady(){return this.source&&!this.error}async setPaused(t){if(this.source&&this.audioElement.paused!==t){if(t)this.audioElement.pause();else if(this.audioElement.currentTime<this.audioElement.duration)try{return await this.audioElement.play(),this.error=!1,!0}catch(e){this.error||Lt().error(e),this.error=!0}}return!1}dispose(){this.slot&&(Pl(this.slot),this.slot=null),this.source=null}applyPlaybackRate(){this.audioElement.playbackRate=this.clipPlaybackRate*this.globalPlaybackRate,this.audioElement.preservesPitch=this.globalPlaybackRate!==1||!this.clipPitchShift}}class Ae{logger;audioResources;context=ct.getContext();pool=[];managers=new Map;sounds=[];muted=!0;volume=1;paused=!0;speed=1;constructor(t,e){this.logger=t,this.audioResources=e}async setupPool(t){for(const e of this.pool)e.dispose();this.pool=[];
53for(const e of this.managers.values())e.dispose();this.managers.clear(),this.sounds=[...t];for(const e of this.sounds)this.audioResources.get(e.audio)}updateSounds(t){const e=this.sounds,n=new Set(t);for(const a of e)if(!n.has(a)){const u=this.managers.get(a);u&&(u.setPaused(!0),this.pool.push(u),this.managers.delete(a))}this.sounds=[...t]}setMuted(t){this.muted=t,this.managers.forEach(e=>e.setMuted(t))}setVolume(t){this.volume=t,this.managers.forEach(e=>e.setVolume(t))}setSpeed(t){this.speed=t>0?t:1,this.managers.forEach(e=>e.setGlobalPlaybackRate(this.speed))}setTime(t,e=!0){e&&this.managers.forEach(n=>{n.setTime(t)})}async setPaused(t){this.paused=t,await Promise.all(Array.from(this.managers.values()).map(e=>e.setPaused(t)))}hasActiveSounds(){return this.managers.size>0}getEndTime(t){const e=this.audioResources.peekDuration(t.audio),n=t.start??0,a=(Math.min(e,t.end??1/0)-n)/t.realPlaybackRate;return t.offset+a}isInRange(t,e){return e>=t.offset&&e<this.getEndTime(t)}static isTts(t){return typeof t.text=="string"&&t.text.length>0}activeTtsSound(t){let e=null;for(const n of this.sounds)Ae.isTts(n)&&this.isInRange(n,t)&&(!e||n.offset>e.offset)&&(e=n);return e}async prepare(t){const e=[],n=this.activeTtsSound(t);for(const a of this.sounds){const u=Ae.isTts(a)&&n!==null&&a!==n;if(this.isInRange(a,t)&&!u){if(this.managers.has(a))continue;e.push((async()=>{const l=this.pool.pop()??this.spawn();try{await l.setSound(a),l.setGlobalPlaybackRate(this.speed),l.setMuted(this.muted),l.setVolume(this.volume),l.setTime(t),l.setPaused(this.paused),this.managers.set(a,l)}catch(p){throw this.pool.push(l),p}})())}else{const l=this.managers.get(a);if(!l)continue;l.setPaused(!0),this.pool.push(l),this.managers.delete(a)}}await Promise.all(e)}spawn(){return new Pe(this.logger,this.context)}resume(){this.context.state==="suspended"&&this.context.resume()}}const Al="font-cache-v1",An=new class{maxConcurrency;currentRunning;queue;constructor(r){this.maxConcurrency=r,this.currentRunning=0,this.queue=[]}async acquire(r){if(r?.aborted)throw new DOMException("Aborted","AbortError");if(!(this.currentRunning<this.maxConcurrency))return new Promise((t,e)=>{const n=()=>{u(),t()},a=()=>{u();const l=this.queue.indexOf(n);l>-1&&this.queue.splice(l,1),e(new DOMException("Aborted","AbortError"))},u=()=>{r?.removeEventListener("abort",a)};r?.addEventListener("abort",a,{once:!0}),this.queue.push(n)});this.currentRunning++}release(){this.queue.length>0?this.queue.shift()?.():this.currentRunning=Math.max(0,this.currentRunning-1)}}(8);async function Ll(r,t={}){try{const{signal:e}=t;if(e?.aborted)throw new DOMException("Aborted","AbortError");const n=await caches.open(Al),a=await n.match(r);if(a)return a.arrayBuffer();await An.acquire(e);try{const u=await n.match(r);if(u)return u.arrayBuffer();const l=await fetch(r,{signal:e});if(!l.ok)throw new Error(`Failed to fetch font: ${l.status} ${l.statusText}`);const p=await l.arrayBuffer();return(async function(w,k,E,O){const j=new Headers(E.headers);j.delete("Transfer-Encoding");const b=new Response(O,{status:200,headers:j});try{await w.put(k,b)}catch(F){console.warn("[font cache failed]",F)}})(n,r,l,p),p}finally{An.release()}}catch{return null}}async function jh(r,t={}){return Promise.all(r.map(e=>Ll(e,t)))}class $t{static activePlayers=new Set;mediaElement;mediaSource=null;sourceBuffer=null;audioContext;logger;objectUrl=null;progressQueue=[];lastReportedTime=0;finished=!1;playResolve=null;playReject=null;aborted=!1;abortController=null;onPlayEnd;currentOptions;playerSpeed=1;pendingTime=null;playbackStarted=!1;playbackStarting=!1;playbackStartPromise=null;playbackStartResolve=null;playbackStartReject=null;computePlaybackRate(){return this.playerSpeed>0?this.playerSpeed:1}constructor(t,e){this.audioContext=t,this.logger=e.logger,this.onPlayEnd=e.onPlayEnd,this.mediaElement=new Audio,this.mediaElement.crossOrigin="anonymous",this.mediaElement.disableRemotePlayback=!0,$t.activePlayers.add(this),this.setupEventListeners()}setupEventListeners(){this.mediaElement.addEventListener("timeupdate",()=>{const t=this.mediaElement.currentTime,e=t-this.lastReportedTime;e>.1&&(this.progressQueue.push(e),this.lastReportedTime=t)}),this.mediaElement.addEventListener("ended",()=>{this.finished=!0,this.onPlayEnd?.(this.mediaElement.duration),this.playResolve?.()}),this.mediaElement.addEventListener("error",t=>{this.logger.error({message:"Audio playback error",object:t}),this.finished=!0,this.onPlayEnd?.(this.mediaElement.currentTime),this.playReject?.(t)})}async play(t,e={}){return new Promise((n,a)=>{this.playResolve=n,this.playReject=a,this.currentOptions=e,this.playbackStartPromise=new Promise((u,l)=>{this.playbackStartResolve=u,this.playbackStartReject=l}),this.playbackStartPromise.catch(()=>{}),(async()=>{try{const u="MediaSource"in window?MediaSource:"ManagedMediaSource"in window?window.ManagedMediaSource:null;if(!u)throw new Error("MediaSource API is not supported");this.abortController=new AbortController,this.mediaSource=new u,this.objectUrl=URL.createObjectURL(this.mediaSource),this.mediaElement.src=this.objectUrl,await new Promise((p,w)=>{this.mediaSource?this.mediaSource.addEventListener("sourceopen",()=>{try{const k="audio/mpeg";
53if(!u.isTypeSupported(k))throw new Error(`Unsupported MIME type: ${k}`);this.sourceBuffer=this.mediaSource.addSourceBuffer(k),this.sourceBuffer.addEventListener("updateend",()=>{this.applyPendingTime()},{once:!1}),p()}catch(k){w(k)}},{once:!0}):w(new Error("MediaSource is not initialized"))});const l=this.streamAndBuffer(t,this.abortController.signal,e);await this.playbackStartPromise,await l}catch(u){this.logger.error({message:"Failed to play streaming audio",object:u}),this.finished=!0,this.onPlayEnd?.(this.mediaElement.currentTime),this.playbackStartReject?.(u),a(u)}})()})}async streamAndBuffer(t,e,n){try{const a=(await Rl(t,{signal:e})).getReader();let u=0,l=0;for(;!this.aborted;){const{done:p,value:w}=await a.read();if(p)break;if(u+=w.length,l++,this.sourceBuffer){this.sourceBuffer.updating&&await new Promise(k=>{this.sourceBuffer?.addEventListener("updateend",()=>{k()},{once:!0})});try{const k=w.buffer instanceof ArrayBuffer?w.buffer:new Uint8Array(w).buffer;this.sourceBuffer.appendBuffer(k),await this.waitForSourceBufferUpdate(),await this.startPlaybackIfNeeded(n)}catch(k){this.logger.warn({message:"Failed to append buffer",object:k})}}}if(await this.waitForSourceBufferUpdate(),await this.startPlaybackIfNeeded(n),!this.playbackStarted)throw new Error("No playable audio data was buffered");if(this.mediaSource&&this.mediaSource.readyState==="open")try{this.mediaSource.endOfStream(),this.logger.debug({message:"[TTS] endOfStream called successfully"})}catch(p){this.logger.warn({message:"Failed to end stream",object:p})}}catch(a){if(this.playbackStartReject?.(a),this.logger.warn({message:"Failed to stream audio, treating as 0s duration",object:a}),this.mediaSource&&this.mediaSource.readyState==="open")try{await this.waitForSourceBufferUpdate(),this.mediaSource.endOfStream()}catch(u){this.logger.warn({message:"Failed to end stream after error",object:u})}}}async startPlaybackIfNeeded(t){this.playbackStarted||this.playbackStarting||this.aborted||this.finished||this.mediaElement.buffered.length!==0&&(this.playbackStarting=!0,this.playbackStarted=!0,this.startPlayback(t).then(()=>{this.playbackStartResolve?.()}).catch(e=>{this.playbackStarted=!1,this.playbackStartReject?.(e)}).finally(()=>{this.playbackStarting=!1}))}async waitForSourceBufferUpdate(){this.sourceBuffer&&this.sourceBuffer.updating!==!1&&await new Promise(t=>{this.sourceBuffer?.addEventListener("updateend",()=>{this.waitForSourceBufferUpdate().then(t)},{once:!0})})}async startPlayback(t){t.start!==void 0&&(this.mediaElement.currentTime=t.start),this.mediaElement.playbackRate=this.computePlaybackRate(),this.applyPendingTime();try{await this.mediaElement.play()}catch(e){throw this.logger.error({message:"Failed to start playback",object:e}),e}}getNextProgress(){return this.progressQueue.shift()??null}isFinished(){return this.finished}setPaused(t){t?this.mediaElement.paused||this.mediaElement.pause():this.mediaElement.paused&&!this.finished&&this.mediaElement.play().catch(e=>{this.logger.error({message:"Failed to resume playback",object:e})})}setMuted(t){this.mediaElement.muted=t}setVolume(t){this.mediaElement.volume=t}getTime(){const t=this.currentOptions?.offset??0,e=this.currentOptions?.start??0;return(this.mediaElement.currentTime-e)/this.mediaElement.playbackRate+t}setTime(t){this.pendingTime=t,this.applyPendingTime()}setPlaybackRate(t){this.playerSpeed=t,this.mediaElement.playbackRate=this.computePlaybackRate()}dispose(){const t=new DOMException("Aborted","AbortError");this.aborted=!0,this.finished=!0,this.abortController?.abort(),$t.activePlayers.delete(this),this.playbackStartReject?.(t),this.playReject?.(t),this.mediaElement.pause(),this.objectUrl&&(URL.revokeObjectURL(this.objectUrl),this.objectUrl=null),this.mediaElement.src="",this.mediaElement.load(),this.mediaSource=null,this.sourceBuffer=null,this.abortController=null,this.progressQueue.length=0,this.lastReportedTime=0,this.playerSpeed=1,this.pendingTime=null,this.playbackStarted=!1,this.playbackStarting=!1,this.playbackStartPromise=null,this.playbackStartResolve=null,this.playbackStartReject=null,this.playResolve=null,this.playReject=null}applyPendingTime(){if(this.pendingTime===null)return;const t=this.currentOptions?.offset??0,e=this.currentOptions?.start??0,n=this.mediaElement.playbackRate,a=Math.max(0,this.pendingTime-t)*n+e;if(this.mediaElement.seekable.length>0){const[u,l]=[this.mediaElement.seekable.start(0),this.mediaElement.seekable.end(0)];a>=u&&a<=l&&(this.mediaElement.currentTime=a,this.pendingTime=null)}}
53static disposeAll(){for(const t of $t.activePlayers)t.dispose();$t.activePlayers.clear()}}const Ps="tts:sentence:end";function As(r,t,e){typeof window<"u"&&typeof CustomEvent<"u"&&window.dispatchEvent(new CustomEvent(Ps,{detail:{content:r,duration:t,kind:e}}))}function si(r){return r.replace(/\/+$/,"")}function ri(r,t){const e=t?.replace(/^[?&]+/,"");return e?`${r}&${e}`:r}function Ls(r,t,e){return ri(t?`${si(t)}/tts/no-stream?text=${encodeURIComponent(r)}`:`https://tts.videotutor.io/tts/no-stream?text=${encodeURIComponent(r)}`,e)}function ms(r,t,e){return ri(t?`${si(t)}/tts/stream?text=${encodeURIComponent(r)}`:`https://tts.videotutor.io/tts/stream?text=${encodeURIComponent(r)}`,e)}class ce{static managers=new WeakMap;static DEFAULT_PLAYBACK_RATE=1;settings;text;constructor(t,{lang:e}={}){const n=Et();this.settings={audio:Ls(t,n.ttsEndpoint,n.ttsQuery),lang:e,playbackRate:ce.DEFAULT_PLAYBACK_RATE},this.text=t}trim(t,e){return this.settings.start=t,this.settings.end=e,this}gain(t){return this.settings.gain=t,this}detune(t){return this.settings.detune=t,this}playbackRate(t){return this.settings.playbackRate=t>0?t:1,this}async*play(t=0,e="auto",n=.4){const a=Et(),u=typeof e=="number"?e:ce.resolveDuration(a,this.settings);if(a.sounds.add({text:this.text,...this.settings},t),e===!1)return;const l=a.isRecalculating===!0;let p=0;u&&u>0?(yield*Q(u),p=u):typeof e!="number"&&(yield*Q(1),p=1),l||As(this.text,p,"TTSClip"),n&&n>0&&(yield*Q(n))}static resolveDuration(t,e){const n=this.getManager(t).get(e.audio),a=this.calculateDuration(n,e);return a>0?a:(t.logger.warn({message:"TTS Data not preloaded.",object:{audio:e.audio,waitSeconds:120}}),0)}static calculateDuration(t,e){const n=t.getDuration();if(!n||!Number.isFinite(n))return 0;const a=e.start??0,u=e.end??n,l=Math.max(0,u-a);if(l===0)return 0;const p=Math.pow(2,(e.detune??0)/1200)*(e.playbackRate??ce.DEFAULT_PLAYBACK_RATE);return p&&Number.isFinite(p)?l/p:l}static getManager(t){let e=this.managers.get(t);return e||(e=new ct(t.logger),this.managers.set(t,e)),e}}Ns([st()],ce.prototype,"play",null);const jl=/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/;function Ln(r){const t=r.replace(/^\[[\w]+\]\s*/,"").trim();if(!t)return 1.5;if(jl.test(t)){const n=(t.match(/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g)??[]).length;return Math.max(1.5,n/4.5)}const e=t.split(/\s+/).length;return Math.max(1.5,e/2.8)}function jn(r){return typeof r=="object"&&r!==null}class Bs{static preloadPromises=new Map;static managers=new WeakMap;settings;fakeDuration;text;static getManager(t){let e=this.managers.get(t);return e||(e=new ct(t.logger),this.managers.set(t,e)),e}constructor(t,e,n){let a,u,l={};typeof t=="number"?(a=t,u=typeof e=="string"?e:"",l=jn(n)?n:{}):(u=t,l=jn(e)?e:{});const{lang:p}=l;this.settings={audio:ms(u),lang:p},this.fakeDuration=a||0,this.text=u}trim(t,e){return this.settings.start=t,this.settings.end=e,this}async*play(t=0,e="auto",n=.3){const a=Et();yield*this.playStreaming(a,t,e,n)}async*playInEditor(t,e,n,a){const u=Ls(this.text,t.ttsEndpoint,t.ttsQuery),l=Bs.getManager(t).get(u);if(t.sounds.add({text:this.text,audio:u,lang:this.settings.lang},e),n===!1)return;let p;if(typeof n=="number")p=n;else{if(p=l.getDuration(),!(p>0)){const w=ms(this.text,t.ttsEndpoint,t.ttsQuery);p=we(u)||we(w)||0}p>0||(p=this.fakeDuration&&this.fakeDuration>0?this.fakeDuration:Ln(this.text))}p>0&&(yield*Q(p)),t.isRecalculating===!0||As(this.text,p,"TTSStream"),a>0&&(yield*Q(a))}async*playStreaming(t,e,n,a){const u=ut.forPlaybackStatus(t.playback),l=ms(this.text,t.ttsEndpoint,t.ttsQuery),p=Ls(this.text,t.ttsEndpoint,t.ttsQuery);u?t.ttsStreamSounds.add({text:this.text,...this.settings,audio:l},e):t.sounds.add({text:this.text,audio:p,lang:this.settings.lang},e);const w=()=>{const A=t.isRecalculating===!0,X=u?.getState();return{isRecalculating:A,isSeeking:X?.seeking===!0,isPaused:X?.paused===!0}},{isRecalculating:k,isSeeking:E}=w();if(k||E||!u){if(n===!1)return;let A=we(l)||we(p);if(A>0||(A=this.fakeDuration??0),!(A>0||u))try{const X=await fetch(p);if(X.ok){const L=await X.arrayBuffer(),it=new AudioContext({sampleRate:24e3});A=(await it.decodeAudioData(L)).duration,Se(p,A),Se(l,A),await it.close()}}catch{}return(n==="auto"||n==="actual")&&A>0&&!Number.isNaN(A)?void(yield*Q(A+a)):typeof n=="number"&&n>0?(yield*Q(n),void(a>0&&(yield*Q(a)))):void(n!=="auto"&&n!=="actual"||(yield*Q(Ln(this.text)+a)))}const O=()=>{const A=new $t(ct.getContext(),{logger:t.logger,onPlayEnd:it=>{it>0&&Se(l,it)}}),X=u?.getState(),L=X?.volume??-1;return L!==-1&&A.setVolume(L),X&&(A.setMuted(X.muted),A.setPaused(X.paused||X.seeking),A.setPlaybackRate(X.speed)),A};if(n===!1)return void O().play(l,{offset:e,start:this.settings.start,end:this.settings.end,gain:this.settings.gain}).catch(A=>{t.logger.error({message:"Failed to play TTS audio",object:A})});const j=O(),b=j.play(l,{offset:e,start:this.settings.start,end:this.settings.end,gain:this.settings.gain}),F=u?.addStateChangeListener(A=>{j.setPaused(A.paused||A.seeking),j.setMuted(A.muted),j.setVolume(A.volume),j.setPlaybackRate(A.speed)},!1)??(()=>{}),Z=u?.addSeekListener(A=>{const X=t.playback.framesToSeconds(A)-e;j.setTime(X)})??(()=>{}),K=typeof performance<"u"?performance.now():Date.now();let lt=0;try{if(n==="auto"||n==="actual"){for(;!j.isFinished();){const A=j.getNextProgress();A!==null&&A>0?yield*Q(A):yield}try{await b}catch{}lt=((typeof performance<"u"?performance.now():Date.now())-K)/1e3}else if(typeof n=="number"&&n>0){let A=0;for(;A<n&&!j.isFinished();){const{isSeeking:X}=w();if(X){yield;continue}const L=j.getNextProgress();if(L!==null&&L>0){const it=n-A,H=Math.min(L,it);yield*Q(H),A+=H}else yield}lt=A}As(this.text,lt,"TTSStream"),a>0&&(yield*Q(a))}finally{Z?.(),F(),j.dispose()}}static async consumeStream(t){const e=t.getReader();try{for(;!(await e.read()).done;);}finally{e.releaseLock()}}}
53Ns([st()],Bs.prototype,"play",null);class Cl{scene;get onChanged(){return this.events.subscribable}events=new pt([]);registeredEvents=new Map;lookup=new Map;collisionLookup=new Set;previousReference=[];didEventsChange=!1;preserveTiming=!0;constructor(t){this.scene=t,this.previousReference=t.meta.timeEvents.get(),this.load(this.previousReference),t.onReloaded.subscribe(this.handleReload),t.onRecalculated.subscribe(this.handleRecalculated),t.onReset.subscribe(this.handleReset),t.meta.timeEvents.onChanged.subscribe(this.handleMetaChanged,!1)}set(t,e,n=!0){let a=this.lookup.get(t);a&&a.offset!==e&&(this.preserveTiming=n,a={...a,targetTime:a.initialTime+e,offset:e},this.lookup.set(t,a),this.registeredEvents.set(t,a),this.events.current=[...this.registeredEvents.values()],this.didEventsChange=!0,this.scene.reload())}register(t,e){if(this.collisionLookup.has(t))return this.scene.logger.error({message:`name "${t}" has already been used for another event name.`,stack:new Error().stack}),0;this.collisionLookup.add(t);let n=this.lookup.get(t);if(n){let a=!1;const u={...n},l=new Error().stack;u.stack!==l&&(u.stack=l,a=!0),u.initialTime!==e&&(u.initialTime=e,a=!0);const p=Math.max(0,u.targetTime-u.initialTime);this.preserveTiming&&u.offset!==p&&(u.offset=p,a=!0);const w=u.initialTime+u.offset;this.preserveTiming||u.targetTime===w||(this.didEventsChange=!0,u.targetTime=w,a=!0),a&&(n=u,this.lookup.set(t,n))}else this.didEventsChange=!0,n={name:t,initialTime:e,targetTime:e,offset:0,stack:new Error().stack},this.lookup.set(t,n);return this.registeredEvents.set(t,n),n.offset}handleReload=()=>{this.registeredEvents.clear(),this.collisionLookup.clear()};handleRecalculated=()=>{this.preserveTiming=!0,this.events.current=[...this.registeredEvents.values()],(this.didEventsChange||(this.previousReference?.length??0)!==this.events.current.length)&&(this.didEventsChange=!1,this.previousReference=[...this.registeredEvents.values()].map(t=>({name:t.name,targetTime:t.targetTime})),this.scene.meta.timeEvents.set(this.previousReference))};handleReset=()=>{this.collisionLookup.clear()};handleMetaChanged=t=>{t!==this.previousReference&&(this.previousReference=t,this.load(t),this.scene.reload())};load(t){for(const e of t){if(typeof e.name!="string")continue;const n=this.lookup.get(e.name)??{name:e.name,initialTime:0,offset:0};this.lookup.set(e.name,{...n,targetTime:e.targetTime??0})}}}const Cn=/^\/\/# sourceURL=(.*)$/gm,Fl=/ERROR: \d+:(\d+): (.*)/g,Ol=/^'([^']+)'/;class Il{logger;gl=null;currentOwner=null;programLookup=new Map;constructor(t){this.logger=t}borrow(t){return this.currentOwner===t||(this.currentOwner?.teardown(this.gl),this.currentOwner=t,this.currentOwner.setup(this.getGL())),this.gl}dispose(){if(this.gl){this.currentOwner?.teardown(this.gl),this.currentOwner=null,this.gl.useProgram(null);for(const{program:t,fragment:e,vertex:n}of this.programLookup.values())this.gl.deleteProgram(t),this.gl.deleteShader(e),this.gl.deleteShader(n);this.programLookup.clear(),this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl.canvas.remove(),this.gl=null}}getProgram(t,e){const n=`${t}#${e}`;if(this.programLookup.has(n))return this.programLookup.get(n).program;const a=this.getGL(),u=this.getShader(a.FRAGMENT_SHADER,t),l=this.getShader(a.VERTEX_SHADER,e);if(!u||!l)return null;const p=a.createProgram();return a.attachShader(p,u),a.attachShader(p,l),a.linkProgram(p),a.getProgramParameter(p,a.LINK_STATUS)?(this.programLookup.set(n,{program:p,fragment:u,vertex:l}),p):(this.logger.error({message:"Failed to initialize the shader program.",remarks:a.getProgramInfoLog(p)??void 0,stack:new Error().stack}),a.deleteProgram(p),null)}getShader(t,e){const n=this.getGL(),a=n.createShader(t);if(n.shaderSource(a,e),n.compileShader(a),!n.getShaderParameter(a,n.COMPILE_STATUS)){const u=n.getShaderInfoLog(a);return(function(l,p,w){let k=null;Cn.lastIndex=0;const E=Cn.exec(w);if(E){const b=new URL(E[1],window.location.origin);b.searchParams.set("t",Date.now().toString()),k=b.toString()}if(!p)return void l.error({message:"Unknown shader compilation error.",stack:bs(k,1,0)});let O,j=!1;for(;O=Fl.exec(p);){const[,b,F]=O;let Z=0;const K=F.match(Ol);if(K){const lt=w.split(` 54`)[parseInt(b)-1].indexOf(K[1]);if(lt!==-1&&(Z=lt),K[1]==="include"&&w.split(` 55`).find(A=>A.startsWith("#include"))){j=!0,l.error({message:`Shader compilation error: ${F}`,remarks:`<p>The <code>#include</code> directive requires the use of a preprocessor.</p> 56<p>Make sure to import the shader from a file:</p> 57<pre class=""><code class="language-ts"><span class="hljs-keyword">
57import</span> shader <span class="hljs-keyword">from</span> <span class="hljs-string">'./shader.glsl'</span>;</code></pre><p>Do <strong>NOT</strong> use the raw loader:</p> 58<pre class=""><code class="language-ts"><span class="hljs-keyword">import</span> shader <span class="hljs-keyword">from</span> <span class="hljs-string">'./shader.glsl?raw'</span>;</code></pre><p>Do <strong>NOT</strong> use <code>#include</code> in an inline string:</p> 59<pre class=""><code class="language-ts"><span class="hljs-keyword">const</span> shader = <span class="hljs-string">\`\\ 60#include "example.glsl" 61\`</span>;</code></pre><p><a href='https://motioncanvas.io/docs/shaders' target='_blank'>Learn more</a> about working with shaders.</p> 62`});break}}j=!0,l.error({message:`Shader compilation error: ${F}`,stack:bs(k,b,Z)})}j||l.error({message:`Shader compilation error: ${p}`,stack:bs(k,1,0)})})(this.logger,u,e),n.deleteShader(a),null}return a}getGL(){if(this.gl)return this.gl;if(this.gl=document.createElement("canvas").getContext("webgl2",{depth:!1,premultipliedAlpha:!1,stencil:!1,powerPreference:"high-performance"}),!this.gl)throw new Error("Failed to initialize WebGL.");return this.gl}}function bs(r,t,e){if(r)return navigator.userAgent.toLowerCase().includes("chrome")?` at (${r}:${t}:${e})`:`@${r}:${t}:${e}`}class ut{project;settings;initialState;initialFrame;options;static currentPlayer=null;static playersByPlaybackStatus=new WeakMap;static stateListeners=new Set;static seekListeners=new Set;get onRender(){return this.render.subscribable}render=new Ec;get onStateChanged(){return this.playerState.subscribable}playerState;instanceStateListeners=new Set;instanceSeekListeners=new Set;get onFrameChanged(){return this.frame.subscribable}
62frame=new pt(0);get onDurationChanged(){return this.duration.subscribable}duration=new pt(0);get onRecalculated(){return this.recalculated.subscribable}recalculated=new yt;playback;status;audio;audioPool;audioResources;logger;sharedWebGLContext;lock=new Nn;startTime=0;endTime=1/0;requestId=null;renderTime=0;requestedSeek=-1;requestedRender=!1;requestedRecalculation;size;resolutionScale;active=!1;pendingSoundUpdate=!1;pendingAudioMetadataReload=!1;justRestartedAtSceneStart=!1;canResetOnReplay=!1;removeAudioResourceListener=null;loadedSources=new Set;deferredAudioMetadataReload=!1;sentenceEndFlushHandler=null;handleAudioResourceLoaded=(t,e)=>{this.loadedSources.has(t)||(this.loadedSources.add(t),this.deferredAudioMetadataReload=!0,this.pendingSoundUpdate=!0,this.request(),this.armSentenceEndFlush())};get startFrame(){return Math.min(this.playback.duration,this.status.secondsToFrames(this.startTime))}get endFrame(){return Math.min(this.playback.duration,this.status.secondsToFrames(this.endTime))}get finished(){return this.playback.finished||this.endFrame>this.startFrame&&this.playback.frame>=this.endFrame}constructor(t,e={},n={},a=-1,u){this.project=t,this.settings=e,this.initialState=n,this.initialFrame=a,this.options=u,this.playerState=new pt({loop:!0,muted:!1,seeking:!1,volume:1,speed:1,...n,paused:!0}),this.requestedRecalculation=!u?.streamMode,this.sharedWebGLContext=new Il(this.project.logger),this.requestedSeek=a,this.logger=this.project.logger,this.playback=new Zc,this.status=new kl(this.playback),this.audioResources=new ct(this.logger),this.removeAudioResourceListener=ct.addGlobalListener(this.handleAudioResourceLoaded),this.audioPool=new Ae(this.logger,this.audioResources),this.audio=this.audioPool.spawn(),this.size=e.size??new v(2560,1920),this.resolutionScale=e.resolutionScale??1,this.startTime=e.range?.[0]??0,this.endTime=e.range?.[1]??1/0,this.playback.fps=e.fps??60,this.audio.setOffset(e.audioOffset??0);const l=this.playerState.current;this.playback.speed=l.speed,this.audioPool.setSpeed(l.speed),this.audioPool.setVolume(l.volume),this.audioPool.setMuted(l.muted),t.audio&&this.audio.setSource(t.audio),ut.currentPlayer=this,ut.playersByPlaybackStatus.set(this.status,this),this.pushScenesPromise=this.pushScenes()}pushScenesPromise=null;async pushScenes(){const t=this.project,e=[];for(const n of t.scenes){const a=new n.klass({...n,playback:this.status,logger:this.project.logger,size:this.size,resolutionScale:this.resolutionScale,ttsEndpoint:this.options?.ttsEndpoint,ttsQuery:this.options?.ttsQuery,gifEndpoint:this.options?.gifEndpoint,timeEventsClass:Cl,sharedWebGLContext:this.sharedWebGLContext,experimentalFeatures:t.experimentalFeatures});await a.recreateViewPromise,n.onReplaced?.subscribe(u=>{a.reload(u)},!1),a.onReloaded.subscribe(()=>this.requestRecalculation()),a.sounds.onChanged.subscribe(()=>this.handleSoundsChanged(),!1),a.variables.updateSignals(t.variables??{}),e.push(a)}this.playback.setup(e),this.activate()}async configure(t){await this.lock.acquire();let e=this.playback.frame,n=!1;this.startTime=t.range[0],this.endTime=t.range[1];const a=Math.max(1,t.fps);if(this.playback.fps!==a){const u=a/this.playback.fps;this.playback.fps=a,e=Math.floor(e*u),n=!0}t.size.exactlyEquals(this.size)&&t.resolutionScale===this.resolutionScale||(this.size=t.size,this.resolutionScale=t.resolutionScale,this.playback.reload({size:this.size,resolutionScale:this.resolutionScale})),t.audioOffset!==void 0&&this.audio.setOffset(t.audioOffset),this.lock.release(),n&&(this.playback.reload(),this.frame.current=e,this.requestRecalculation(),this.requestedSeek=e)}isInRange(t){return t>=0&&t<=this.playback.duration}isInUserRange(t){return t>=this.startFrame&&t<=this.endFrame}requestSeek(t){this.requestedSeek=this.clampRange(t)}requestPreviousFrame(){this.requestedSeek=this.frame.current-this.playback.speed}requestNextFrame(){this.requestedSeek=this.frame.current+this.playback.speed}requestReset(){this.canResetOnReplay=!1,this.requestedSeek=0}requestRender(){this.requestedRender=!0}requestRecalculate(t){this.canResetOnReplay=!1;const e=this.playback.onScenesRecalculated.current,n=e.indexOf(t);n>
62=0?e.slice(n).forEach(a=>a.reload()):this.playback.reload(),this.requestRecalculation()}toggleLoop(t=!this.playerState.current.loop){t!==this.playerState.current.loop&&(this.playerState.current={...this.playerState.current,loop:t})}togglePlayback(t=this.playerState.current.paused){this.audioPool.resume(),t===this.playerState.current.paused&&(this.playerState.current={...this.playerState.current,paused:!t},this.notifyStateChanged(),t&&!this.playerState.current.loop&&this.canResetOnReplay&&!this.requestedRecalculation&&this.playback.frame===this.playback.duration&&this.requestReset())}toggleAudio(t){this.playerState.current=t!==void 0?{...this.playerState.current,muted:t}:{...this.playerState.current,muted:!this.playerState.current.muted},this.notifyStateChanged()}setAudioVolume(t){const e=Tt(0,1,t);e!==this.playerState.current.volume&&(this.playerState.current={...this.playerState.current,volume:e},this.notifyStateChanged())}addAudioVolume(t){this.setAudioVolume(this.playerState.current.volume+t)}setSpeed(t){t!==this.playerState.current.speed&&(this.playback.speed=t,this.audioPool.setSpeed(t),this.playerState.current={...this.playerState.current,speed:t},this.notifyStateChanged())}setVariables(t){for(const e of this.playback.onScenesRecalculated.current)e.variables.updateSignals(t)}activate(){this.active=!0,this.removeAudioResourceListener||(this.removeAudioResourceListener=ct.addGlobalListener(this.handleAudioResourceLoaded)),this.request()}deactivate(){this.active=!1,this.removeAudioResourceListener?.(),this.removeAudioResourceListener=null,this.disarmSentenceEndFlush(),this.sharedWebGLContext.dispose(),this.requestId!==null&&(cancelAnimationFrame(this.requestId),this.requestId=null),ut.currentPlayer===this&&(ut.currentPlayer=null),ut.playersByPlaybackStatus.delete(this.status)}requestRecalculation(){this.canResetOnReplay=!1,this.requestedRecalculation=!0,this.request()}async prepare(){const t={...this.playerState.current,seek:this.requestedSeek,render:this.requestedRender};if(this.requestedSeek=-1,this.requestedRender=!1,this.requestedRecalculation){t.seek<0&&(t.seek=this.playback.frame);try{this.pendingAudioMetadataReload&&($t.disposeAll(),this.playback.reload(),this.pendingAudioMetadataReload=!1),await this.playback.recalculate(),this.duration.current=this.playback.frame;const n=[];for(const a of this.playback.onScenesRecalculated.current)n.push(...a.sounds.getSounds());await this.audioPool.setupPool(n),this.recalculated.dispatch()}catch(n){throw console.error(n),this.requestSeek(t.seek),n}finally{this.requestedRecalculation=!1}}if(this.pendingSoundUpdate){const n=this.collectSounds();this.audioPool.updateSounds(n),this.pendingSoundUpdate=!1}(!t.loop&&this.finished&&!t.paused&&t.seek<0||this.endFrame===this.startFrame)&&(this.togglePlayback(!1),t.paused=!0,t.seek=this.endFrame===this.startFrame?t.seek:this.startFrame),t.loop&&(t.seek>this.endFrame||this.finished&&!t.paused)&&this.startFrame!==this.endTime&&(t.seek=this.startFrame),await this.audioPool.prepare(this.status.time),await this.audioPool.setPaused(t.paused||this.finished),this.audioPool.setSpeed(t.speed),this.audioPool.setMuted(t.muted),this.audioPool.setVolume(t.volume);const e=t.paused||this.finished||!this.audio.isInRange(this.status.time);return await this.audio.setPaused(e)&&await this.syncAudio(-3),this.audio.setMuted(t.muted),this.audio.setVolume(t.volume),t}async run(){const t=await this.prepare(),e=this.playback.state;if(this.playback.state=t.paused?It.Paused:It.Playing,t.seek>=0||!this.isInUserRange(this.status.frame)){const n=t.seek<0?this.status.frame:t.seek,a=this.clampRange(n);this.logger.profile("seek time");const u=a>this.startFrame&&Math.abs(a-this.playback.frame)>1;u&&this.setSeeking(!0);try{await this.playback.seek(a)}finally{u&&this.setSeeking(!1)}a>this.startFrame&&(this.canResetOnReplay=!0),this.justRestartedAtSceneStart=a===this.startFrame,this.logger.profile("seek time"),await this.syncAudio(-3),this.notifySeek(a)}else{if(t.paused||t.speed===1&&this.audio.isReady()&&this.audio.isInRange(this.status.time)&&this.audio.getTime()<this.status.time)return(t.render||t.paused&&e!==It.Paused)&&await this.render.dispatch(),!t.paused&&this.status.time>this.audio.getTime()+.02&&await this.syncAudio(),void this.request();if(this.audio.isReady()&&t.speed===1&&this.audio.isInRange(this.status.time)&&!this.justRestartedAtSceneStart&&this.status.time>.5&&this.status.framesToSeconds(this.playback.frame+1)<this.audio.getTime()-.02){const n=this.status.secondsToFrames(this.audio.getTime());await this.playback.seek(n)}else this.status.frame<this.endFrame&&(await this.playback.progress(),this.playback.frame>this.startFrame&&(this.canResetOnReplay=!0),t.speed!==1&&await this.syncAudio(0,!1))}
62!t.paused&&this.playback.currentScene.slides.isWaiting()&&(this.togglePlayback(!1),t.paused=!0),await this.render.dispatch(),this.frame.current=this.playback.frame,this.playback.frame>this.startFrame+1&&(this.justRestartedAtSceneStart=!1),this.request()}request(){this.active&&(this.requestId??=requestAnimationFrame(async t=>{if(this.requestId=null,t-this.renderTime>=1e3/(this.status.fps+5)){this.renderTime=t,await this.lock.acquire();try{await this.run()}catch(e){this.logger.error(e)}this.lock.release()}else this.request()}))}armSentenceEndFlush(){if(this.sentenceEndFlushHandler!==null||typeof window>"u")return;const t=()=>{this.disarmSentenceEndFlush(),this.deferredAudioMetadataReload&&(this.deferredAudioMetadataReload=!1,this.pendingAudioMetadataReload=!0,this.requestRecalculation())};this.sentenceEndFlushHandler=t,window.addEventListener(Ps,t)}disarmSentenceEndFlush(){this.sentenceEndFlushHandler!==null&&(typeof window<"u"&&window.removeEventListener(Ps,this.sentenceEndFlushHandler),this.sentenceEndFlushHandler=null)}clampRange(t){return Tt(this.startFrame,this.endFrame,t)}collectSounds(){const t=this.playback.onScenesRecalculated.current;if(!t||t.length===0)return[];const e=[];for(const n of t)e.push(...n.sounds.getSounds());return e}handleSoundsChanged=()=>{this.pendingSoundUpdate=!0,this.request()};async syncAudio(t=0,e=!0){const n=this.status.framesToSeconds(this.playback.frame+t);this.audio.setTime(n),await this.audioPool.prepare(n),this.audioPool.setTime(n,e)}setSeeking(t){this.playerState.current.seeking!==t&&(this.playerState.current={...this.playerState.current,seeking:t},this.notifyStateChanged())}notifyStateChanged(){const t=this.playerState.current;for(const e of this.instanceStateListeners)try{e(t)}catch(n){n instanceof Error&&this.logger.error({message:"Instance state listener error",object:n})}for(const e of ut.stateListeners)try{e(t)}catch(n){n instanceof Error&&this.logger.error({message:"State listener error",object:n})}}static addStateChangeListener(t,e=!0){return ut.stateListeners.add(t),e&&ut.currentPlayer&&t(ut.currentPlayer.playerState.current),()=>{ut.stateListeners.delete(t)}}static getCurrentState(){return ut.currentPlayer?.playerState.current??null}static forPlaybackStatus(t){return ut.playersByPlaybackStatus.get(t)??null}addStateChangeListener(t,e=!0){return this.instanceStateListeners.add(t),e&&t(this.playerState.current),()=>{this.instanceStateListeners.delete(t)}}getState(){return this.playerState.current}static addSeekListener(t){return ut.seekListeners.add(t),()=>{ut.seekListeners.delete(t)}}addSeekListener(t){return this.instanceSeekListeners.add(t),()=>{this.instanceSeekListeners.delete(t)}}notifySeek(t){for(const e of this.instanceSeekListeners)try{e(t)}catch(n){this.logger.error({message:"Instance seek listener error",object:n})}for(const e of ut.seekListeners)try{e(t)}catch(n){this.logger.error({message:"Seek listener error",object:n})}}}class Ch{background=null;resolutionScale=1;colorSpace="srgb";size=v.zero;finalBuffer;currentBuffer;previousBuffer;context;currentContext;previousContext;get canvasSize(){return this.size.scale(this.resolutionScale)}constructor(){this.finalBuffer=document.createElement("canvas"),this.currentBuffer=document.createElement("canvas"),this.previousBuffer=document.createElement("canvas");const t=this.colorSpace;this.context=Qt({colorSpace:t,willReadFrequently:!0},this.finalBuffer),this.currentContext=Qt({colorSpace:t},this.currentBuffer),this.previousContext=Qt({colorSpace:t},this.previousBuffer)}configure({colorSpace:t=this.colorSpace,size:e=this.size,resolutionScale:n=this.resolutionScale,background:a=this.background}){t!==this.colorSpace&&(this.colorSpace=t,this.context=Qt({colorSpace:t},this.finalBuffer),this.currentContext=Qt({colorSpace:t},this.currentBuffer),this.previousContext=Qt({colorSpace:t},this.previousBuffer)),e.exactlyEquals(this.size)&&n===this.resolutionScale||(this.resolutionScale=n,this.size=e,this.resizeCanvas(this.context),this.resizeCanvas(this.currentContext),this.resizeCanvas(this.previousContext)),this.background=typeof a=="string"?a:a?.serialize()??null}async render(t,e){const n=!!e&&Jn(t.previousOnTop);e&&await e.render(this.previousContext),await t.render(this.currentContext);const a=this.canvasSize;this.context.clearRect(0,0,a.width,a.height),this.background&&(this.context.save(),this.context.fillStyle=this.background,this.context.fillRect(0,0,a.width,a.height),this.context.restore(
62)),e&&!n&&this.context.drawImage(this.previousBuffer,0,0),this.context.drawImage(this.currentBuffer,0,0),n&&this.context.drawImage(this.previousBuffer,0,0)}resizeCanvas(t){const e=this.canvasSize;t.canvas.width=e.width,t.canvas.height=e.height}}var Fn;(function(r){r[r.Initial=0]="Initial",r[r.Working=1]="Working",r[r.Aborting=2]="Aborting"})(Fn||(Fn={}));function Fh(r){return r}class ql extends At{constructor(t){super("project",(function(e){const n={version:new bt("version",1),shared:new At("General",{background:new xs("background",null),range:new qs("range",[0,1/0]),size:new _n("resolution",new v(2560,1920)),audioOffset:new ke("audio offset",0).setPrecision(4).setStep(.1)}),preview:new At("Preview",{fps:new ke("frame rate",30).setPresets(Tn).setRange(1),resolutionScale:new Gt("scale",En,1)}),rendering:new At("Rendering",{fps:new ke("frame rate",60).setPresets(Tn).setRange(1),resolutionScale:new Gt("scale",En,1),colorSpace:new Gt("color space",vl),exporter:new yl("exporter",e)})};return n.shared.audioOffset.disable(!e.audio),n})(t))}getFullPreviewSettings(){return{...this.shared.get(),...this.preview.get()}}getFullRenderingSettings(){return{...this.shared.get(),...this.rendering.get()}}}var On,In;(function(r){r[r.Initial=0]="Initial",r[r.Working=1]="Working",r[r.Aborting=2]="Aborting"})(On||(On={})),(function(r){r[r.Success=0]="Success",r[r.Error=1]="Error",r[r.Aborted=2]="Aborted"})(In||(In={}));function Dl(){return new At("Application Settings",{version:new bt("version",1),appearance:new At("Appearance",{color:new xs("accent color",new Ss("#33a6ff")).describe("The accent color for the user interface. (Leave empty to use the default color)"),font:new vs("legacy font",!1).describe("Use the 'JetBrains Mono' font for the user interface."),coordinates:new vs("coordinates",!0).describe("Display mouse coordinates within the preview window.")}),defaults:new At("Defaults",{background:new xs("background",null).describe("The default background color used in new projects."),size:new _n("resolution",new v(2560,1920)).describe("The default resolution used in new projects.")})})}function Nl(r){return typeof r=="function"?r:()=>r}var Bl=Nl({name:"@imaginix-inc/motion-canvas-core/default",exporters:()=>[Rs]});function zl(r,t,e,n,a,u,l=n.logger??new Ds){const p=Dl();u.attach(p);const w={name:r,...n,plugins:e,versions:t,settings:p,logger:l};return w.meta=new ql(w),w.meta.shared.set(p.defaults.get()),w.experimentalFeatures??=!1,a.attach(w.meta),w}async function Oh(r,t,e,n,a,u){const l=n.logger??new Ds,p=[Promise.resolve(Bl())];if(n.plugins)for(const b of n.plugins)p.push(ys(b,l));for(const b of n.scenes)if(b.plugins)for(const F of b.plugins)p.push(ys(F,l));for(const b of e)p.push(ys(b,l));const w=new Set,k=await Promise.all(p),E=[];let O=n;for(const b of k)b&&!w.has(b.name)&&(w.add(b.name),E.push(b),O={...O,...b.settings?.(O)??{}});const j=zl(r,t,E,O,a,u);return E.forEach(b=>b.project?.(j)),j}async function ys(r,t){if(typeof r=="string"){let e;const n=globalThis.__motion_canvas_plugin_loader__;if(n)try{const a=await n(r);if(a)return a;if(a===null)return null}catch(a){e=a}try{let a=`/@id/${r}`;const u=new URL(import.meta.url).searchParams.get("v");u&&(a+=`?v=${u}`),r=(await import(a)).default()}catch(a){return e&&console.error(e),console.error(a),t.error({message:`Failed to load plugin "${r}": ${a.message}.`,stack:a.stack,remarks:a.remarks}),null}}return r}function Ie(r,t,e){t==null&&(t=()=>{});const n=Et(),a=n.previous;n.previousOnTop=!1;const u=a?.lifecycleEvents.onBeforeRender.subscribe(t),l=n.lifecycleEvents.onBeforeRender.subscribe(r);return n.enterInitial(),()=>{n.enterAfterTransitionIn(),u?.(),l()}}async function*Ih(r=.6){const t=le(0),e=Ie(n=>{n.globalAlpha=t()});yield*t(1,r),e()}async function*qh(r=Rt.Top,t=.6){const e=Et().getRealSize().getOriginOffset(r).scale(2),n=v.createSignal(),a=v.createSignal(e),u=Ie(l=>l.translate(a.x(),a.y()),l=>l.translate(n.x(),n.y()));yield*Ce(n(e.scale(-1),t),a(v.zero,t)),u()}async function*Dh(r,t=.6){const e=Et().getRealSize().div(r.size),n=v.createSignal(r.position),a=v.createSignal(v.one.div(e)),u=v.createSignal(0),l=v.createSignal(1),p=le
62(0),w=Ie(E=>{E.globalAlpha=Re(.1,.5,0,1,p()),E.translate(n.x(),n.y()),E.scale(a.x(),a.y())},E=>{E.globalAlpha=Re(.5,.9,1,0,p()),E.translate(u.x(),u.y()),E.scale(l.x(),l.y())}),k=E=>Ee(E*E);yield*Ce(n(v.zero,t,k),u(r.position.flipped.mul(e),t,k),a(1,t,k),l(e,t,k),p(1,t,Yn)),w()}async function*Nh(r,t=.6){const e=Et().getRealSize().div(r.size),n=v.createSignal(r.position.flipped.mul(e)),a=v.createSignal(e),u=v.createSignal(0),l=v.createSignal(1),p=le(0),w=Ie(E=>{E.globalAlpha=Re(.1,.5,0,1,p()),E.translate(n.x(),n.y()),E.scale(a.x(),a.y())},E=>{E.globalAlpha=Re(.5,.9,1,0,p()),E.translate(u.x(),u.y()),E.scale(l.x(),l.y())}),k=E=>Ee(Math.sqrt(E));yield*Ce(n(v.zero,t,k),u(r.position,t,k),a(1,t,k),l(v.one.div(e),t,k),p(1,t,Yn)),w()}export{vn as $,Mh as A,Xl as B,ht as C,$t as D,Vl as E,jh as F,qs as G,_l as H,dl as I,th as J,Ql as K,fh as L,Me as M,ws as N,Wl as O,st as P,mh as Q,$l as R,Ih as S,Gl as T,Rn as U,wh as V,ce as W,Kl as X,Fs as Y,Yl as Z,ph as _,Gt as a,ks as a0,Bc as a1,ct as a2,gl as a3,rh as a4,Is as a5,pt as a6,Q as a7,ft as a8,Re as a9,eh as aA,Dn as aB,Te as aC,sh as aD,Oh as aE,Eh as aF,ah as aG,qt as aH,le as aI,oh as aJ,qh as aK,Th as aL,lh as aM,ih as aN,Hl as aa,dh as ab,Lh as ac,Pt as ad,uh as ae,Fh as af,Jn as ag,Rh as ah,Oc as ai,ut as aj,xh as ak,sl as al,ee as am,rl as an,Et as ao,Zl as ap,Ph as aq,Ic as ar,Ch as as,Hn as at,Tt as au,Fc as av,Sh as aw,q as ax,Ce as ay,kh as az,Ah as b,Nh as c,Rt as d,v as e,Bs as f,gh as g,xt as h,yh as i,bh as j,It as k,Jl as l,Ss as m,et as n,hh as o,ch as p,te as q,Dh as r,Ee as s,Yn as t,el as u,vh as v,qc as w,Sn as x,Lt as y,nh as z};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.