@kayelaa/canvas 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,6 +15,8 @@ It's a **very thin declarative layer** on top of LEA — all performance-critica
15
15
 
16
16
  Made by **Kayelaa Cagara** (@LianeKayee39 on X / GitHub) in Calamba, Philippines.
17
17
 
18
+ **This Documentation might be INACCURATE! Always visit the .d.ts files to verify.**
19
+
18
20
  ## Quick Start — Fully Typed Version (copy-paste this)
19
21
 
20
22
  ```ts
@@ -274,7 +276,7 @@ These rules are **not suggestions**. Breaking them causes serious performance pr
274
276
 
275
277
  ### useSelf — Your main stable god-object (use this for almost everything)
276
278
 
277
- ```ts
279
+ ```typescript
278
280
  const self = useSelf(() => ({
279
281
  // This object never gets recreated — mutate it freely
280
282
  health: 100,
@@ -312,9 +314,9 @@ const self = useSelf(() => {
312
314
  const entity = useEntity();
313
315
 
314
316
  useTick(() => {
315
- entity.x += 5; // move right
316
- entity.z = entity.y; // sort by Y position (higher = drawn later)
317
- entity.width = 64; // resize dynamically
317
+ entity.current.x += 5; // move right
318
+ entity.current.z = entity.current.y; // sort by Y position (higher = drawn later)
319
+ entity.current.width = 64; // resize dynamically
318
320
  });
319
321
  ```
320
322
 
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var $=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Ie=Object.prototype.hasOwnProperty;var L=(n,e)=>{for(var t in e)$(n,t,{get:e[t],enumerable:!0})},Ke=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Se(e))!Ie.call(n,s)&&s!==t&&$(n,s,{get:()=>e[s],enumerable:!(r=Te(e,s))||r.enumerable});return n};var Re=n=>Ke($({},"__esModule",{value:!0}),n);var Ne={};L(Ne,{Kayla:()=>B,LEA:()=>O,default:()=>Ge});module.exports=Re(Ne);var O={};L(O,{DeltaTweenII:()=>N,ENVIRONMENT:()=>j,GEmitterMemory:()=>W,LeaEntityII:()=>K,LeaEventEmitter:()=>w,LeaGameII:()=>A,LeaRendererII:()=>M,LeaSceneII:()=>_,LeaSerializers:()=>J,LeaTickerII:()=>G,LeaTimeout:()=>z,LeaUtilsII:()=>g,LiaAudio:()=>R,LiaAudioSrc:()=>I,LiaOscSFX:()=>C,LiaSFXMap:()=>Fe,NOTE_NAMES:()=>te,RectLeaEntity:()=>F,Vector2:()=>S,colToRGBA:()=>Pe,defaultSFXConfig:()=>ne,editRGBA:()=>Me,generateUUID:()=>ue,getAvoidAngle:()=>he,getEnvironment:()=>ee,getNormalizedColor:()=>ke,getRayHit:()=>ce,isInitiallyMobile:()=>Le,isMobile:()=>pe,isNode:()=>V,isNote:()=>Ae,isWeb:()=>v,parseFillStyle:()=>Z,raycastAvoid:()=>De,scaleCoord:()=>_e,setAnimInterval:()=>le,sfxHit:()=>oe,sfxJump:()=>ie,sfxLaser:()=>ae,sfxUIClick:()=>re,sfxUIHover:()=>se,shortUID:()=>Ve,tinyUID:()=>Y});var w=class{#e=new Map;constructor(){this.#e=new Map}on(e,t){let r=this.#e.get(e)||[];return r.push(t),this.#e.set(e,r),this}once(e,t){let r=(...s)=>{this.off(e,r),t(...s)};return this.on(e,r),this}off(e,t){let r=this.#e.get(e);if(!r)return this;let s=r.indexOf(t);return s>=0&&r.splice(s,1),this}emit(e,...t){let r=this.#e.get(e);if(!r||r.length===0){if(e==="error")throw t[0];return!1}return r.slice().forEach(s=>s(...t)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},M=class extends w{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:t,viewportHeight:r,cameraWidth:s,cameraHeight:u}={}){if(!v)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=t??e.width,this.#t=r??e.height,this.#n=s??e.width,this.#r=u??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,t=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,t),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!v)return;let e=performance.now(),t=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=t,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!v||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!v||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},G=class extends w{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),t=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,this.#e+=t*1e3,this.emit("tick",t)}createTimeout(e){return new z(e,this)}createTween(e,t=()=>{}){let r=new N(e),s=(u=0)=>{if(r.finished){this.off("tick",s);return}r.update(u)};return r.on("finish",()=>{this.off("tick",s)}),r.on("delta",u=>{t(u)}),this.on("tick",s),r}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=v&&!isFinite(this.tickInterval)?le(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,t=0){return .5+.5*Math.sin((this.now()%e/e+t)*2*Math.PI)}},J;(l=>{function n(f){return f===!0?1:0}l.booleanExport=n;function e(f){return f===0?!1:f===1}l.booleanImport=e;function t(f){return`${f.x}|${f.y}`}l.vec2Export=t;function r(f){let[m,b]=f.split("|"),E=parseFloat(m),D=parseFloat(b);if(isNaN(E)||isNaN(D))throw new Error(`Invalid Vector2 string: ${f}`);return new S(E,D)}l.vec2Import=r,l.booleanMap={mapExport:n,mapImport:e};function u(f){return m=>Number(m.toFixed(f))}l.createRounder=u;function c(f=10){return{mapExport(m){return Math.round(m/f)},mapImport(m){return m*f}}}l.createLowPrecision=c;function h(f){return Math.round(f)}l.lightWeightRounder=h;function a(f=100){return{mapExport(m){return Math.round(m*f)},mapImport(m){return m/f}}}l.createPercent=a;function o(f){let m=new Map(Object.entries(f));return{mapExport:b=>m.get(b)??null,mapImport:b=>Array.from(m.entries()).find(([E,D])=>D===b)?.[0]??null}}l.createLookup=o;function d(f){let m=f*(180/Math.PI);return Math.round((m%360+360)%360)}l.radToDeg=d;function y(f){return f*(Math.PI/180)}l.degToRad=y,l.angleRadToDeg={mapExport:d,mapImport:y};function p(f=10){let m=c(f);return{mapExport(b){return m.mapExport(d(b))},mapImport(b){return m.mapImport(y(b))}}}l.createLowPrecisionRadToDeg=p})(J||={});var K=class n extends w{name="";scaleRotate=0;scale=1;constructor(e,t=0,r=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new S(t,r),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(t){this.emit("error",t)}}handleDraw(e){if(!(V||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(t){this.emit("error",t)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([s,{mapExport:u}])=>{let c=Reflect.get(this,s);return u?u(c):c});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],t=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(s=>!this.nonSerializableProperties.includes(s)&&!e.includes(s.toString())),r=Object.fromEntries(t.map(s=>{let u=Reflect.get(this,s);if(V&&typeof u=="number"){let c=u.toString().split("."),a=(c[1]?c[1].length:0)>2?Number(u.toFixed(2)):u;return[s,a]}return[s,u]}));return JSON.parse(JSON.stringify(r))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return n.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,t){if(!e||!Array.isArray(t))return t;let r={};for(let s=0;s<t.length;s++){let u=e[s];if(!u)break;let[c,{mapImport:h}]=u,a=t[s];if(h&&(a=h(a)),typeof c!="string")break;try{Reflect.set(r,c,a)}catch(o){console.error(o)}}return r}},_=class extends w{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let t of this.entities.values())t.handleUpdate(e)}}handleDraw(e){if(!V&&!this.paused){this.emit("draw",e);for(let t of[...this.entities.values()].sort((r,s)=>r.z-s.z))t.handleDraw(e)}}addEntity(e){if(!(e instanceof K))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof K))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},A=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,t,r=16){this.ticker=new G(r),this.scenes=new Map,this.width=e,this.height=t,this.ticker.on("tick",s=>{for(let u of this.scenes.values())u.paused||u.handleUpdate(s)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},g={lerp(n,e,t){return n+(e-n)*t},clamp(n,e,t){return Math.min(t,Math.max(e,n))},clamp01(n){return Math.min(1,Math.max(0,n))},easeLinear(n){return n},easeInQuad(n){return n*n},easeOutQuad(n){return 1-(1-n)*(1-n)},easeInOutQuad(n){return n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2},easeInSine(n){return 1-Math.cos(n*Math.PI/2)},easeOutSine(n){return Math.sin(n*Math.PI/2)},easeInOutSine(n){return-(Math.cos(Math.PI*n)-1)/2},easeInExpo(n){return n===0?0:Math.pow(2,10*n-10)},easeOutExpo(n){return n===1?1:1-Math.pow(2,-10*n)},easeInOutExpo(n){return n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2},smoothstep(n){return n=g.clamp(n,0,1),n*n*(3-2*n)},randomLerp(n,e){return g.lerp(n,e,Math.random())},randomInt(n,e){return Math.floor(Math.random()*(e-n+1))+n},randomArrayValue(n){return n[g.randomInt(0,n.length-1)]},createBezier(n,e,t,r){function s(h,a,o,d,y){let i=1-h;return i*i*i*a+3*i*i*h*o+3*i*h*h*d+h*h*h*y}function u(h,a,o,d,y){let i=1-h;return 3*i*i*(o-a)+6*i*h*(d-o)+3*h*h*(y-d)}function c(h){let a=h;for(let o=0;o<6;o++){let d=s(a,0,n,t,1),y=u(a,0,n,t,1);if(y===0)break;a-=(d-h)/y}return g.clamp(a,0,1)}return function(a){a=g.clamp(a,0,1);let o=c(a);return s(o,0,e,r,1)}},lengthSquared(...n){return n.reduce((e,t)=>e+t*t,0)},normalizeRad(n){let e=2*Math.PI;return n=n%e,n<0&&(n+=e),n},angleInvertY(n){return g.normalizeRad(-n)},degToRadFlipY(n){return g.angleInvertY(n*Math.PI/180)},minimalAngularDirection(n,e){n=g.normalizeRad(n),e=g.normalizeRad(e);let t=g.normalizeRad(e-n),r=g.normalizeRad(n-e);return t<=r?1:-1}},N=class extends w{constructor({delta:e,ms:t,easing:r}){super(),this.delta=e,this.duration=t,this.elapsed=0,this.easing=r??(s=>s),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let t=g.clamp(this.elapsed/this.duration,0,1),r=this.easing(t),s=this.delta*r,u=s-this.lastValue;this.lastValue=s,this.emit("delta",u),t>=1&&(this.finished=!0,this.emit("finish",void 0))}},F=class extends K{constructor(e,t=0,r=0,s=50,u=50){super(e,t,r),this.width=s,this.height=u}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},z=class extends w{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,t=null){super(),this.duration=e,this.ticker=t,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(r=>this._resolve=r),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,t){return this.promise.then(e,t)}after(e,t){return this.promise.then(e,t)}},S=class n{constructor(e=0,t=0){this.x=e,this.y=t}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let t=Math.cos(e),r=Math.sin(e);return new n(this.x*t-this.y*r,this.x*r+this.y*t)}static from(e){return new n(Math.cos(e),Math.sin(e))}get angle(){return Math.atan2(this.y,this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new n(0,0):new n(this.x/e,this.y/e)}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let t=this.dot(e);return this.subtract(e.scale(2*t))}dotNormalized(e){let t=this.normalized(),r=e.normalized();return t.x*r.x+t.y*r.y}lengthSquaredTo(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}directionTo(e){return new n(e.x-this.x,e.y-this.y).normalized()}add(e){return new n(this.x+e.x,this.y+e.y)}addRaw(e){return new n(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new n(this.x-e.x,this.y-e.y)}scale(e){return new n(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new n(this.x,this.y)}};function ke(n){let e=/^rgba?\(([^)]+)\)$/,t=n.match(e);if(t){let[r,s,u,c=1]=t[1].split(",").map(h=>parseFloat(h));return{r:Math.max(0,Math.min(255,Math.floor(r))),g:Math.max(0,Math.min(255,Math.floor(s))),b:Math.max(0,Math.min(255,Math.floor(u))),a:Math.max(0,Math.min(1,Math.floor(c*255)/255))}}return Z(n)}function Pe(n){return`rgba(${n.r}, ${n.g}, ${n.b}, ${n.a})`}function Z(n){if(n=n.trim().toLowerCase(),n[0]==="#"){let t,r,s;if(n.length===7)t=parseInt(n.slice(1,3),16),r=parseInt(n.slice(3,5),16),s=parseInt(n.slice(5,7),16);else if(n.length===4)t=parseInt(n[1]+n[1],16),r=parseInt(n[2]+n[2],16),s=parseInt(n[3]+n[3],16);else throw new Error("Invalid hex color");return{r:t,g:r,b:s,a:1}}let e=n.match(/^rgba?\s*\(\s*(\d+)[, ]\s*(\d+)[, ]\s*(\d+)(?:[, ]\s*([\d.]+))?\s*\)$/);if(e)return{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3]),a:e[4]!==void 0?parseFloat(e[4]):1};throw new Error("Unsupported fillStyle format")}function Me(n,{r:e,g:t,b:r,a:s}={}){let[u,c,h,a,o]=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??c}, ${t??h}, ${r??a}, ${s??(o||1)})`}function _e(n,e,t){return t+(n-t)*e}function ee(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var j=ee(),V=j==="node",v=j==="web",R=class n{static unlock(){v&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=v?new AudioContext:null;static masterGain=v?this.audioCtx.createGain():null;static musicGain=v?this.audioCtx.createGain():null;static sfxGain=v?this.audioCtx.createGain():null;static{v&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let t=n.CACHE_NAME,r,s;if(typeof caches<"u"&&(s=await caches.open(t),r=await s.match(e)),!r){if(r=await fetch(e),!r.ok)throw new Error(`Failed to fetch ${e}`);s&&await s.put(e,r.clone())}let u=await r.arrayBuffer(),c=await this.audioCtx.decodeAudioData(u);return this.audioBufferCache.set(e,c),c}static async getOnlyDownloadedCache(e){let t=n.CACHE_NAME;return await(await caches.open(t)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,t=.2,r=1,s=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let u=this.getCached(e);if(!u)return;let c=new I(u);c.buffer=u;let h=1-.12,a=1+.12;c.playbackRate=r??h+Math.random()*(a-h);let o=this.audioCtx.createGain();o.gain.value=t,c.tempGain=o,c.connect(o),o.connect(this.sfxGain),c.onended=()=>{c.disconnect(),o.disconnect()},c.start(),s&&this.sfsx.set(e,{source:c,gain:o})}catch(u){console.error(u)}}static async playLoop(e,t=1,{loopStart:r=0,loopEnd:s=null,exclusive:u=!0,skipMS:c=0}={}){if(u)for(let y of this.loops.keys())this.stopLoop(y);this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return;let a=new I(h);a.buffer=h,a.loop=!0,typeof r=="number"&&(a.loopStart=r),typeof s=="number"&&(a.loopEnd=s);let o=this.audioCtx.createGain();o.gain.value=t,a.tempGain=o,a.playbackRate=1,a.onended=()=>{a.disconnect(),o.disconnect()},a.connect(o),o.connect(this.musicGain),a.start(0,c/1e3);let d=++this.loopIdCounter;return this.loops.set(d,{source:a,gain:o}),d}static stopLoop(e){let t=this.loops.get(e);t&&(t.source.stop(),t.source.notIndependent||(t.source.disconnect(),t.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:t=1,speed:r=1,loop:s=!1,loopStart:u=0,loopEnd:c=null,isMusic:h=!1,gain:a=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return null;let d=new I(o);d.loop=s,d.loopStart=u,d.loopEnd=typeof c=="number"?c:o.duration,d.playbackRate=r;let y=this.audioCtx.createGain();return y.gain.value=t,d.connect(y),d.tempGain=y,y.connect(a||(h?this.musicGain:this.sfxGain)),d.onended=()=>{d.disconnect(),y.disconnect()},d}catch(o){return console.error("Failed to create LiaAudioSrc:",o),null}}},te=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Ae(n){return te.includes(n)}var I=class{numberOfInputs;numberOfOutputs;constructor(e,t=R.audioCtx){this.context=t,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=v?t.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:t=null}={}){let r=t!==null?t:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-r/this.playbackRate,this.source.start(0,r),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,t=0,r){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-t/this.playbackRate,r!==void 0?this.source.start(this.context.currentTime+e,t,r):this.source.start(this.context.currentTime+e,t),this.pauseTime=t,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let t=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let r=this.loopEnd-this.loopStart;t=this.loopStart+(t-this.loopStart)%r}if(this.isPlaying=!1,e>0){let r=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,r),this.output.gain.linearRampToValueAtTime(0,r+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let t=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=t,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,t=0,r=0){if("value"in e)this.output.connect(e,t);else return this.output.connect(e,t,r),e}disconnect(e,t,r){e===void 0?this.output.disconnect():this.output.disconnect(e,t,r)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let t=this.context.currentTime+e;this.source.stop(t),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},ne={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},C=class n{constructor(e={}){this.ctx=R.audioCtx,this.cfg=structuredClone(ne),Object.assign(this.cfg,e)}ctx;cfg;play(e=R.sfxGain){let t=this.ctx,r=t.currentTime,s=this.cfg,u=t.createGain();u.gain.setValueAtTime(1e-4,r);let c=s.ampEnv;u.gain.exponentialRampToValueAtTime(c.volume,r+c.attack),u.gain.exponentialRampToValueAtTime(Math.max(1e-4,c.sustain*c.volume),r+c.attack+c.decay),u.gain.exponentialRampToValueAtTime(1e-4,r+s.duration+c.release);let h=u,a;s.filter.enabled&&(a=t.createBiquadFilter(),a.type=s.filter.type,a.frequency.value=s.filter.freq,a.Q.value=s.filter.Q,a.connect(u),h=a);let o;if(s.osc.enabled){if(o=t.createOscillator(),o.type=s.osc.type,o.frequency.value=s.osc.freq,o.detune.value=s.osc.detune,s.pitchEnv.amount!==0){let f=Math.pow(2,s.pitchEnv.amount/12);o.frequency.exponentialRampToValueAtTime(s.osc.freq*f,r+s.pitchEnv.decay)}o.connect(h),o.start(r),o.stop(r+s.duration+c.release)}let d;if(s.noise.enabled){let f=t.sampleRate*s.duration,m=t.createBuffer(1,f,t.sampleRate),b=m.getChannelData(0);for(let E=0;E<f;E++)b[E]=(Math.random()*2-1)*s.noise.level;d=t.createBufferSource(),d.buffer=m,d.connect(h),d.start(r),d.stop(r+s.duration+c.release)}let y,i;s.lfo.enabled&&o&&(y=t.createOscillator(),y.frequency.value=s.lfo.rate,i=t.createGain(),i.gain.value=s.lfo.depth,y.connect(i),s.lfo.target==="freq"?i.connect(o.frequency):s.lfo.target==="gain"?i.connect(u.gain):s.lfo.target==="filter"&&a&&i.connect(a.frequency),y.start(r),y.stop(r+s.duration)),u.connect(e);let p=[o,d,y,i,a,u],l=r+s.duration+c.release;setTimeout(()=>{p.forEach(f=>f?.disconnect())},(l-t.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,t){return Object.assign(this.cfg[e],t),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,t,r,s){return Object.assign(this.cfg.ampEnv,{attack:e,decay:t,sustain:r,release:s}),this}setPitchEnv(e,t){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:t}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,t,r){return Object.assign(this.cfg.filter,{type:e,freq:t,Q:r,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,t,r){return Object.assign(this.cfg.lfo,{target:e,rate:t,depth:r,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new n(structuredClone(this.cfg))}},re=new C({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),se=new C({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),ie=new C({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),ae=new C({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),oe=new C({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2}),Fe=new Map([["ui_click",re],["ui_hover",se],["jump",ie],["laser",ae],["hit",oe]]);function Ve(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(n)),r=Array.from(t).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}function Y(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(4)),r=Array.from(t).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}var W=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${ue()}_${Date.now()}`}connect(e){e&&(this.peer=e,e.peer=this,this.connected=!0,e.connected=!0),this._emit("open")}isConnected(){return this.connected&&!!this.peer}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(r=>r!==t))}_emit(e,t){this.events[e]?.forEach(r=>r(t))}send(e,t){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,t)}_receive(e,t){e?this._emit(e,t):this._emit("message",t)}close(){if(this.connected=!1,this.peer){let e=this.peer;this.peer=null,e.peer=null,e.connected=!1,e._emit("close")}this._emit("close")}getKey(){return this.key}};function ue(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let n=new Uint8Array(16);return crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,[...n].map(e=>e.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5")}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function le(n){let e=!0;function t(){e&&(n(),requestAnimationFrame(t))}return requestAnimationFrame(t),{clear:()=>e=!1}}function ce(n,e,t,r,s){let u=Math.cos(s),c=Math.sin(s),h=[];if(u!==0){let a=(0-n)/u,o=e+a*c;a>0&&o>=0&&o<=r&&h.push({side:"left",t:a})}if(u!==0){let a=(t-n)/u,o=e+a*c;a>0&&o>=0&&o<=r&&h.push({side:"right",t:a})}if(c!==0){let a=(0-e)/c,o=n+a*u;a>0&&o>=0&&o<=t&&h.push({side:"top",t:a})}if(c!==0){let a=(r-e)/c,o=n+a*u;a>0&&o>=0&&o<=t&&h.push({side:"bottom",t:a})}return h.length===0?null:(h.sort((a,o)=>a.t-o.t),h[0])}function he(n,e){let t;switch(e){case"left":case"right":t=Math.PI-n;break;case"top":case"bottom":t=2*Math.PI-n;break}return(t%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function De(n,e,t,r,s){let u=ce(n,e,t,r,s);return u?{...u,avoidAngle:he(s,u.side)}:null}function pe(){return V?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var Le=pe();var B={};L(B,{Kayla:()=>q,KaylaFragment:()=>Ee,KaylaInternals:()=>T,UI:()=>Ce,createElement:()=>ye,createGame:()=>fe,createRenderer:()=>me,createScene:()=>de,self:()=>P,useDisposableRef:()=>we,useEffect:()=>X,useEntity:()=>ve,useExports:()=>xe,useNextStack:()=>Q,usePaint:()=>U,useRef:()=>k,useSelf:()=>ge,useState:()=>H,useTick:()=>be});var q={};L(q,{KaylaFragment:()=>Ee,KaylaInternals:()=>T,createElement:()=>ye,createGame:()=>fe,createRenderer:()=>me,createScene:()=>de,self:()=>P,useDisposableRef:()=>we,useEffect:()=>X,useEntity:()=>ve,useExports:()=>xe,useNextStack:()=>Q,usePaint:()=>U,useRef:()=>k,useSelf:()=>ge,useState:()=>H,useTick:()=>be});function fe({width:n,height:e,updateHz:t="frames"}){return new T.KaylaGame(n,e,t==="frames"?1/0:t)}function de(n){let e=new _(n);return new T.KaylaScene(e)}function me(n){return new T.KaylaRenderer(n)}function ye(n,e){return{type:n,props:e}}var T;(d=>{class n extends A{#e;#t;constructor(i,p,l){super(i,p,l),this.#e=new Set,this.#t=!1}get started(){return this.#t}start(){if(!this.#t){for(let i of this.#e)i.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let i of this.#e)i.stop();this.#t=!1,super.stop()}}addRenderer(i){this.#e.has(i)||(this.#e.add(i),this.#t&&i.start(),i.game=this)}deleteRenderer(i){this.#e.has(i)&&(this.#e.delete(i),this.#t&&i.stop(),delete i.game)}}d.KaylaGame=n;class e extends M{game;pointerX;pointerY;#e;constructor(i){super(i),this.useDraw=this.useDraw.bind(this),this.on("draw",p=>{if(this.game)for(let l of this.game.scenes.values())l.handleDraw(p)}),this.pointerX=0,this.pointerY=0,this.#e=this.#t.bind(this)}#t(i){this.pointerX=i.clientX,this.pointerY=i.clientY}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.#e)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.#e)}pointerPosToWorldPos(i,p){let l=this.canvas.getBoundingClientRect(),f=(i-l.left)/l.width,m=(p-l.top)/l.height,b=f*this.viewportWidth*this.cameraWidth/l.width,E=m*this.viewportHeight*this.cameraHeight/l.height;return new S(b,E)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(i){let p=l=>{i(l,new r)};return this.on("draw",p),()=>{this.off("draw",p)}}attachTo(i){i.addRenderer(this),this.game=i}detach(){this.game&&this.game.deleteRenderer(this)}}d.KaylaRenderer=e;class t{current;saves;constructor(){this.saves=[]}useTick(i){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=i,this.current.useStepCallIndex++}usePaint(i){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=i,this.current.useDrawCallIndex++}useEntity(){return k(P)}useSelf(i){let p=k(null);return(p.current===null||p.current===void 0)&&(p.current=i()),p.current}useState(i,{alwaysRecall:p=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let f=this.current.state[this.current.useStateCallIndex]??new s(this.current,i,{alwaysRecall:p});return this.current.state[this.current.useStateCallIndex]=f,this.current.useStateCallIndex++,f}useRef(i){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let l=this.current.refs[this.current.useRefCallIndex]??new u(this.current,i??null);return this.current.refs[this.current.useRefCallIndex]=l,this.current.useRefCallIndex++,l}useEffect(i){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=i,this.current.useEffectCallIndex++}useExports(i,p){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=p}save(){this.saves.push({current:this.current})}restore(){let i=this.saves.pop();if(!i)throw new Error("Cannot restore without saving.");this.current=i.current}}d.GlobalKayla=t;class r{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}d.KaylaEvent=r;class s{#e;#t;#n;alwaysRecall;constructor(i,p,{alwaysRecall:l=!1}={}){this.#t=i,this.#e=p??void 0,this.#n=Date.now(),this.alwaysRecall=l}get(){return this.#e}add(i,{recall:p}={}){this.set(this.get()+i,{recall:p})}multiply(i,{recall:p}={}){this.set(this.get()*i,{recall:p})}set(i,{recall:p=!1}={}){let l=this.#e;i!==l&&(this.#e=i,(p||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now())}get value(){return this.#e}get lastChanged(){return this.#n}}d.KaylaState=s;class u{#e;#t;constructor(i,p){this.#t=i,this.#e=p??void 0}get current(){return this.#e}set current(i){this.#e=i}}d.KaylaRef=u;class c{state;refs;global;callProps;scene;exports;constructor(i,p,l){if(!l)throw new Error("Empty element");this.scene=p,this.state=[],this.refs=[],this.fc=l.type,this.callProps=l.props??{},this.global=i,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[]}get key(){return this.callProps.key}set key(i){this.callProps.key=i}get children(){return this.callProps.children}set children(i){this.callProps.children=i}entity;onExport=()=>({});onEffect;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;lastStateDeps;refresh(){let i;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0;let p=[];try{let l=this.fc(this.callProps)??[];if(l&&!Array.isArray(l)&&(l=[l]),!Array.isArray(l))throw new Error("Non array or non undefined children received.");p=l}catch(l){i=l}this.useStateCallIndex=0,this.useRefCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.global.restore();try{let l=0,f=[];for(let m of p){let b=this.lastChildren.at(l)??new c(this.global,this.scene,m);this.lastChildren[l]=b,f.push(b),l++}for(let m of this.lastChildren.filter(b=>!f.includes(b))){let b=this.lastChildren.indexOf(m);b!==1&&this.lastChildren.splice(b,1),m.unuse()}for(let m of this.lastChildren)try{m.refresh()}catch(b){console.error(b)}Q(()=>{this.use()})}catch(l){console.error(l)}if(i)throw i}lastChildren;isFirstUse=!0;use(){try{let i=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(i=this.onEffectDeps.some((p,l)=>{let f=this.lastStateDeps.at(l);if(f){let m=p.lastChanged,b=f.stamp;return m>b}})),i||this.isFirstUse){this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(l=>({stamp:l.lastChanged,stateRef:l}))),this.key??=this.fc.name+"_"+Y(),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new h(this,this.key);for(let l of this.refs)l.current===P&&(l.current=this.entity);this.callProps.ref instanceof u&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof u&&(this.callProps.exportsRef.current=this.exports),this.scene.getScene().addEntity(this.entity);let p=this.onEffect.map(l=>l()).filter(l=>l!==void 0);this.onUnEffect=p}}catch(i){throw i}}unuse(){try{for(let i of this.onUnEffect)i()}catch(i){console.error(i)}this.scene.getScene().removeEntity(this.entity)}}d.KaylaInternalComponent=c;class h extends F{#e;constructor(i,p){super(p,0,0,0,0),this.#e=i}update(i){let p=new r;if(this.#e.onTick)for(let l of this.#e.onTick)l(i,p);p.isPrevented()}draw(i){let p=new r;if(this.#e.onPaint)for(let l of this.#e.onPaint)l(i,p);p.isPrevented()||super.draw(i)}}d.KaylaRectEntity=h;class a{constructor(i){this.#t=i,this.#e=null,i.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getScene(){return this.#t}drawHandler(i){return this.#t.handleDraw(i)}attachTo(i){i.addScene(this.#t),this.#e=i}spawn(i){new c(d.singleGlobalInstance,this,i).refresh()}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}d.KaylaScene=a,d.singleGlobalInstance=new d.GlobalKayla})(T||={});var x=T.singleGlobalInstance,H=x.useState.bind(x),k=x.useRef.bind(x),X=x.useEffect.bind(x),be=x.useTick.bind(x),U=x.usePaint.bind(x),xe=x.useExports.bind(x),ge=x.useSelf.bind(x),ve=x.useEntity.bind(x),P=Symbol("self_ref");var Q=n=>{Promise.resolve(1).then(()=>n())},Ee=({children:n})=>Array.isArray(n)?[...n]:n;function we(n){return new T.KaylaRef(null,n)}Reflect.set(globalThis,"Kayla",q);var Ce;(e=>e.UIComponent=({x:t,y:r,width:s,height:u,children:c})=>{let h=k(P),a=H(!1);return X(()=>{if(a.get()===!0)return;a.set(!0);let o=h.current;o.width=s,o.height=u,o.x=t,o.y=r}),U(o=>{o.fillStyle="rgba(0, 0, 0, 0.5)",o.fillRect(t,r,s,u)}),c??[]})(Ce||={});var Ge={LEA:O,Kayla:B};0&&(module.exports={Kayla,LEA});
1
+ "use strict";var H=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var X=(n,e)=>{for(var t in e)H(n,t,{get:e[t],enumerable:!0})},me=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fe(e))!de.call(n,s)&&s!==t&&H(n,s,{get:()=>e[s],enumerable:!(r=pe(e,s))||r.enumerable});return n};var ye=n=>me(H({},"__esModule",{value:!0}),n);var Ne={};X(Ne,{Kayla:()=>P,LEA:()=>D,default:()=>Ge});module.exports=ye(Ne);var D={};X(D,{DeltaTweenII:()=>O,ENVIRONMENT:()=>q,GEmitterMemory:()=>U,LeaEntityII:()=>I,LeaEventEmitter:()=>w,LeaGameII:()=>F,LeaRendererII:()=>M,LeaSceneII:()=>A,LeaSerializers:()=>Y,LeaTickerII:()=>N,LeaTimeout:()=>z,LeaUtilsII:()=>v,LiaAudio:()=>k,LiaAudioSrc:()=>K,LiaOscSFX:()=>T,LiaSFXMap:()=>we,NOTE_NAMES:()=>Z,RectLeaEntity:()=>_,Vector2:()=>C,colToRGBA:()=>xe,defaultSFXConfig:()=>ee,editRGBA:()=>ge,generateUUID:()=>ae,getAvoidAngle:()=>ce,getEnvironment:()=>J,getNormalizedColor:()=>be,getRayHit:()=>ue,isInitiallyMobile:()=>Se,isMobile:()=>le,isNode:()=>L,isNote:()=>Ee,isWeb:()=>E,parseFillStyle:()=>Q,raycastAvoid:()=>Ce,scaleCoord:()=>ve,setAnimInterval:()=>oe,sfxHit:()=>ie,sfxJump:()=>re,sfxLaser:()=>se,sfxUIClick:()=>te,sfxUIHover:()=>ne,shortUID:()=>Te,tinyUID:()=>B});var w=class{#e=new Map;constructor(){this.#e=new Map}on(e,t){let r=this.#e.get(e)||[];return r.push(t),this.#e.set(e,r),this}once(e,t){let r=(...s)=>{this.off(e,r),t(...s)};return this.on(e,r),this}off(e,t){let r=this.#e.get(e);if(!r)return this;let s=r.indexOf(t);return s>=0&&r.splice(s,1),this}emit(e,...t){let r=this.#e.get(e);if(!r||r.length===0){if(e==="error")throw t[0];return!1}return r.slice().forEach(s=>s(...t)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},M=class extends w{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:t,viewportHeight:r,cameraWidth:s,cameraHeight:o}={}){if(!E)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=t??e.width,this.#t=r??e.height,this.#n=s??e.width,this.#r=o??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,t=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,t),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!E)return;let e=performance.now(),t=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=t,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},N=class extends w{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),t=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,this.#e+=t*1e3,this.emit("tick",t)}createTimeout(e){return new z(e,this)}createTween(e,t=()=>{}){let r=new O(e),s=(o=0)=>{if(r.finished){this.off("tick",s);return}r.update(o)};return r.on("finish",()=>{this.off("tick",s)}),r.on("delta",o=>{t(o)}),this.on("tick",s),r}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=E&&!isFinite(this.tickInterval)?oe(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,t=0){return .5+.5*Math.sin((this.now()%e/e+t)*2*Math.PI)}},Y;(p=>{function n(a){return a===!0?1:0}p.booleanExport=n;function e(a){return a===0?!1:a===1}p.booleanImport=e;function t(a){return`${a.x}|${a.y}`}p.vec2Export=t;function r(a){let[f,b]=a.split("|"),x=parseFloat(f),R=parseFloat(b);if(isNaN(x)||isNaN(R))throw new Error(`Invalid Vector2 string: ${a}`);return new C(x,R)}p.vec2Import=r,p.booleanMap={mapExport:n,mapImport:e};function o(a){return f=>Number(f.toFixed(a))}p.createRounder=o;function l(a=10){return{mapExport(f){return Math.round(f/a)},mapImport(f){return f*a}}}p.createLowPrecision=l;function h(a){return Math.round(a)}p.lightWeightRounder=h;function u(a=100){return{mapExport(f){return Math.round(f*a)},mapImport(f){return f/a}}}p.createPercent=u;function c(a){let f=new Map(Object.entries(a));return{mapExport:b=>f.get(b)??null,mapImport:b=>Array.from(f.entries()).find(([x,R])=>R===b)?.[0]??null}}p.createLookup=c;function d(a){let f=a*(180/Math.PI);return Math.round((f%360+360)%360)}p.radToDeg=d;function y(a){return a*(Math.PI/180)}p.degToRad=y,p.angleRadToDeg={mapExport:d,mapImport:y};function i(a=10){let f=l(a);return{mapExport(b){return f.mapExport(d(b))},mapImport(b){return f.mapImport(y(b))}}}p.createLowPrecisionRadToDeg=i})(Y||={});var I=class n extends w{name="";scaleRotate=0;scale=1;constructor(e,t=0,r=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new C(t,r),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(t){this.emit("error",t)}}handleDraw(e){if(!(L||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(t){this.emit("error",t)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([s,{mapExport:o}])=>{let l=Reflect.get(this,s);return o?o(l):l});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],t=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(s=>!this.nonSerializableProperties.includes(s)&&!e.includes(s.toString())),r=Object.fromEntries(t.map(s=>{let o=Reflect.get(this,s);if(L&&typeof o=="number"){let l=o.toString().split("."),u=(l[1]?l[1].length:0)>2?Number(o.toFixed(2)):o;return[s,u]}return[s,o]}));return JSON.parse(JSON.stringify(r))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return n.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,t){if(!e||!Array.isArray(t))return t;let r={};for(let s=0;s<t.length;s++){let o=e[s];if(!o)break;let[l,{mapImport:h}]=o,u=t[s];if(h&&(u=h(u)),typeof l!="string")break;try{Reflect.set(r,l,u)}catch(c){console.error(c)}}return r}},A=class extends w{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let t of this.entities.values())t.handleUpdate(e)}}handleDraw(e){if(!L&&!this.paused){this.emit("draw",e);for(let t of[...this.entities.values()].sort((r,s)=>r.z-s.z))t.handleDraw(e)}}addEntity(e){if(!(e instanceof I))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof I))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},F=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,t,r=16){this.ticker=new N(r),this.scenes=new Map,this.width=e,this.height=t,this.ticker.on("tick",s=>{for(let o of this.scenes.values())o.paused||o.handleUpdate(s)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},v={lerp(n,e,t){return n+(e-n)*t},clamp(n,e,t){return Math.min(t,Math.max(e,n))},clamp01(n){return Math.min(1,Math.max(0,n))},easeLinear(n){return n},easeInQuad(n){return n*n},easeOutQuad(n){return 1-(1-n)*(1-n)},easeInOutQuad(n){return n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2},easeInSine(n){return 1-Math.cos(n*Math.PI/2)},easeOutSine(n){return Math.sin(n*Math.PI/2)},easeInOutSine(n){return-(Math.cos(Math.PI*n)-1)/2},easeInExpo(n){return n===0?0:Math.pow(2,10*n-10)},easeOutExpo(n){return n===1?1:1-Math.pow(2,-10*n)},easeInOutExpo(n){return n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2},smoothstep(n){return n=v.clamp(n,0,1),n*n*(3-2*n)},randomLerp(n,e){return v.lerp(n,e,Math.random())},randomInt(n,e){return Math.floor(Math.random()*(e-n+1))+n},randomArrayValue(n){return n[v.randomInt(0,n.length-1)]},createBezier(n,e,t,r){function s(h,u,c,d,y){let m=1-h;return m*m*m*u+3*m*m*h*c+3*m*h*h*d+h*h*h*y}function o(h,u,c,d,y){let m=1-h;return 3*m*m*(c-u)+6*m*h*(d-c)+3*h*h*(y-d)}function l(h){let u=h;for(let c=0;c<6;c++){let d=s(u,0,n,t,1),y=o(u,0,n,t,1);if(y===0)break;u-=(d-h)/y}return v.clamp(u,0,1)}return function(u){u=v.clamp(u,0,1);let c=l(u);return s(c,0,e,r,1)}},lengthSquared(...n){return n.reduce((e,t)=>e+t*t,0)},normalizeRad(n){let e=2*Math.PI;return n=n%e,n<0&&(n+=e),n},angleInvertY(n){return v.normalizeRad(-n)},degToRadFlipY(n){return v.angleInvertY(n*Math.PI/180)},minimalAngularDirection(n,e){n=v.normalizeRad(n),e=v.normalizeRad(e);let t=v.normalizeRad(e-n),r=v.normalizeRad(n-e);return t<=r?1:-1}},O=class extends w{constructor({delta:e,ms:t,easing:r}){super(),this.delta=e,this.duration=t,this.elapsed=0,this.easing=r??(s=>s),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let t=v.clamp(this.elapsed/this.duration,0,1),r=this.easing(t),s=this.delta*r,o=s-this.lastValue;this.lastValue=s,this.emit("delta",o),t>=1&&(this.finished=!0,this.emit("finish",void 0))}},_=class extends I{constructor(e,t=0,r=0,s=50,o=50){super(e,t,r),this.width=s,this.height=o}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},z=class extends w{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,t=null){super(),this.duration=e,this.ticker=t,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(r=>this._resolve=r),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,t){return this.promise.then(e,t)}after(e,t){return this.promise.then(e,t)}},C=class n{constructor(e=0,t=0){this.x=e,this.y=t}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let t=Math.cos(e),r=Math.sin(e);return new n(this.x*t-this.y*r,this.x*r+this.y*t)}static from(e){return new n(Math.cos(e),Math.sin(e))}get angle(){return Math.atan2(this.y,this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new n(0,0):new n(this.x/e,this.y/e)}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let t=this.dot(e);return this.subtract(e.scale(2*t))}dotNormalized(e){let t=this.normalized(),r=e.normalized();return t.x*r.x+t.y*r.y}lengthSquaredTo(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}directionTo(e){return new n(e.x-this.x,e.y-this.y).normalized()}add(e){return new n(this.x+e.x,this.y+e.y)}addRaw(e){return new n(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new n(this.x-e.x,this.y-e.y)}scale(e){return new n(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new n(this.x,this.y)}};function be(n){let e=/^rgba?\(([^)]+)\)$/,t=n.match(e);if(t){let[r,s,o,l=1]=t[1].split(",").map(h=>parseFloat(h));return{r:Math.max(0,Math.min(255,Math.floor(r))),g:Math.max(0,Math.min(255,Math.floor(s))),b:Math.max(0,Math.min(255,Math.floor(o))),a:Math.max(0,Math.min(1,Math.floor(l*255)/255))}}return Q(n)}function xe(n){return`rgba(${n.r}, ${n.g}, ${n.b}, ${n.a})`}function Q(n){if(n=n.trim().toLowerCase(),n[0]==="#"){let t,r,s;if(n.length===7)t=parseInt(n.slice(1,3),16),r=parseInt(n.slice(3,5),16),s=parseInt(n.slice(5,7),16);else if(n.length===4)t=parseInt(n[1]+n[1],16),r=parseInt(n[2]+n[2],16),s=parseInt(n[3]+n[3],16);else throw new Error("Invalid hex color");return{r:t,g:r,b:s,a:1}}let e=n.match(/^rgba?\s*\(\s*(\d+)[, ]\s*(\d+)[, ]\s*(\d+)(?:[, ]\s*([\d.]+))?\s*\)$/);if(e)return{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3]),a:e[4]!==void 0?parseFloat(e[4]):1};throw new Error("Unsupported fillStyle format")}function ge(n,{r:e,g:t,b:r,a:s}={}){let[o,l,h,u,c]=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??l}, ${t??h}, ${r??u}, ${s??(c||1)})`}function ve(n,e,t){return t+(n-t)*e}function J(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var q=J(),L=q==="node",E=q==="web",k=class n{static unlock(){E&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=E?new AudioContext:null;static masterGain=E?this.audioCtx.createGain():null;static musicGain=E?this.audioCtx.createGain():null;static sfxGain=E?this.audioCtx.createGain():null;static{E&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let t=n.CACHE_NAME,r,s;if(typeof caches<"u"&&(s=await caches.open(t),r=await s.match(e)),!r){if(r=await fetch(e),!r.ok)throw new Error(`Failed to fetch ${e}`);s&&await s.put(e,r.clone())}let o=await r.arrayBuffer(),l=await this.audioCtx.decodeAudioData(o);return this.audioBufferCache.set(e,l),l}static async getOnlyDownloadedCache(e){let t=n.CACHE_NAME;return await(await caches.open(t)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,t=.2,r=1,s=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return;let l=new K(o);l.buffer=o;let h=1-.12,u=1+.12;l.playbackRate=r??h+Math.random()*(u-h);let c=this.audioCtx.createGain();c.gain.value=t,l.tempGain=c,l.connect(c),c.connect(this.sfxGain),l.onended=()=>{l.disconnect(),c.disconnect()},l.start(),s&&this.sfsx.set(e,{source:l,gain:c})}catch(o){console.error(o)}}static async playLoop(e,t=1,{loopStart:r=0,loopEnd:s=null,exclusive:o=!0,skipMS:l=0}={}){if(o)for(let y of this.loops.keys())this.stopLoop(y);this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return;let u=new K(h);u.buffer=h,u.loop=!0,typeof r=="number"&&(u.loopStart=r),typeof s=="number"&&(u.loopEnd=s);let c=this.audioCtx.createGain();c.gain.value=t,u.tempGain=c,u.playbackRate=1,u.onended=()=>{u.disconnect(),c.disconnect()},u.connect(c),c.connect(this.musicGain),u.start(0,l/1e3);let d=++this.loopIdCounter;return this.loops.set(d,{source:u,gain:c}),d}static stopLoop(e){let t=this.loops.get(e);t&&(t.source.stop(),t.source.notIndependent||(t.source.disconnect(),t.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:t=1,speed:r=1,loop:s=!1,loopStart:o=0,loopEnd:l=null,isMusic:h=!1,gain:u=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return null;let d=new K(c);d.loop=s,d.loopStart=o,d.loopEnd=typeof l=="number"?l:c.duration,d.playbackRate=r;let y=this.audioCtx.createGain();return y.gain.value=t,d.connect(y),d.tempGain=y,y.connect(u||(h?this.musicGain:this.sfxGain)),d.onended=()=>{d.disconnect(),y.disconnect()},d}catch(c){return console.error("Failed to create LiaAudioSrc:",c),null}}},Z=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Ee(n){return Z.includes(n)}var K=class{numberOfInputs;numberOfOutputs;constructor(e,t=k.audioCtx){this.context=t,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=E?t.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:t=null}={}){let r=t!==null?t:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-r/this.playbackRate,this.source.start(0,r),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,t=0,r){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-t/this.playbackRate,r!==void 0?this.source.start(this.context.currentTime+e,t,r):this.source.start(this.context.currentTime+e,t),this.pauseTime=t,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let t=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let r=this.loopEnd-this.loopStart;t=this.loopStart+(t-this.loopStart)%r}if(this.isPlaying=!1,e>0){let r=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,r),this.output.gain.linearRampToValueAtTime(0,r+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let t=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=t,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,t=0,r=0){if("value"in e)this.output.connect(e,t);else return this.output.connect(e,t,r),e}disconnect(e,t,r){e===void 0?this.output.disconnect():this.output.disconnect(e,t,r)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let t=this.context.currentTime+e;this.source.stop(t),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},ee={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},T=class n{constructor(e={}){this.ctx=k.audioCtx,this.cfg=structuredClone(ee),Object.assign(this.cfg,e)}ctx;cfg;play(e=k.sfxGain){let t=this.ctx,r=t.currentTime,s=this.cfg,o=t.createGain();o.gain.setValueAtTime(1e-4,r);let l=s.ampEnv;o.gain.exponentialRampToValueAtTime(l.volume,r+l.attack),o.gain.exponentialRampToValueAtTime(Math.max(1e-4,l.sustain*l.volume),r+l.attack+l.decay),o.gain.exponentialRampToValueAtTime(1e-4,r+s.duration+l.release);let h=o,u;s.filter.enabled&&(u=t.createBiquadFilter(),u.type=s.filter.type,u.frequency.value=s.filter.freq,u.Q.value=s.filter.Q,u.connect(o),h=u);let c;if(s.osc.enabled){if(c=t.createOscillator(),c.type=s.osc.type,c.frequency.value=s.osc.freq,c.detune.value=s.osc.detune,s.pitchEnv.amount!==0){let a=Math.pow(2,s.pitchEnv.amount/12);c.frequency.exponentialRampToValueAtTime(s.osc.freq*a,r+s.pitchEnv.decay)}c.connect(h),c.start(r),c.stop(r+s.duration+l.release)}let d;if(s.noise.enabled){let a=t.sampleRate*s.duration,f=t.createBuffer(1,a,t.sampleRate),b=f.getChannelData(0);for(let x=0;x<a;x++)b[x]=(Math.random()*2-1)*s.noise.level;d=t.createBufferSource(),d.buffer=f,d.connect(h),d.start(r),d.stop(r+s.duration+l.release)}let y,m;s.lfo.enabled&&c&&(y=t.createOscillator(),y.frequency.value=s.lfo.rate,m=t.createGain(),m.gain.value=s.lfo.depth,y.connect(m),s.lfo.target==="freq"?m.connect(c.frequency):s.lfo.target==="gain"?m.connect(o.gain):s.lfo.target==="filter"&&u&&m.connect(u.frequency),y.start(r),y.stop(r+s.duration)),o.connect(e);let i=[c,d,y,m,u,o],p=r+s.duration+l.release;setTimeout(()=>{i.forEach(a=>a?.disconnect())},(p-t.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,t){return Object.assign(this.cfg[e],t),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,t,r,s){return Object.assign(this.cfg.ampEnv,{attack:e,decay:t,sustain:r,release:s}),this}setPitchEnv(e,t){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:t}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,t,r){return Object.assign(this.cfg.filter,{type:e,freq:t,Q:r,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,t,r){return Object.assign(this.cfg.lfo,{target:e,rate:t,depth:r,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new n(structuredClone(this.cfg))}},te=new T({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),ne=new T({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),re=new T({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),se=new T({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),ie=new T({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2}),we=new Map([["ui_click",te],["ui_hover",ne],["jump",re],["laser",se],["hit",ie]]);function Te(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(n)),r=Array.from(t).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}function B(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(4)),r=Array.from(t).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}var U=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${ae()}_${Date.now()}`}connect(e){e&&(this.peer=e,e.peer=this,this.connected=!0,e.connected=!0),this._emit("open")}isConnected(){return this.connected&&!!this.peer}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(r=>r!==t))}_emit(e,t){this.events[e]?.forEach(r=>r(t))}send(e,t){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,t)}_receive(e,t){e?this._emit(e,t):this._emit("message",t)}close(){if(this.connected=!1,this.peer){let e=this.peer;this.peer=null,e.peer=null,e.connected=!1,e._emit("close")}this._emit("close")}getKey(){return this.key}};function ae(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let n=new Uint8Array(16);return crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,[...n].map(e=>e.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5")}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function oe(n){let e=!0;function t(){e&&(n(),requestAnimationFrame(t))}return requestAnimationFrame(t),{clear:()=>e=!1}}function ue(n,e,t,r,s){let o=Math.cos(s),l=Math.sin(s),h=[];if(o!==0){let u=(0-n)/o,c=e+u*l;u>0&&c>=0&&c<=r&&h.push({side:"left",t:u})}if(o!==0){let u=(t-n)/o,c=e+u*l;u>0&&c>=0&&c<=r&&h.push({side:"right",t:u})}if(l!==0){let u=(0-e)/l,c=n+u*o;u>0&&c>=0&&c<=t&&h.push({side:"top",t:u})}if(l!==0){let u=(r-e)/l,c=n+u*o;u>0&&c>=0&&c<=t&&h.push({side:"bottom",t:u})}return h.length===0?null:(h.sort((u,c)=>u.t-c.t),h[0])}function ce(n,e){let t;switch(e){case"left":case"right":t=Math.PI-n;break;case"top":case"bottom":t=2*Math.PI-n;break}return(t%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function Ce(n,e,t,r,s){let o=ue(n,e,t,r,s);return o?{...o,avoidAngle:ce(s,o.side)}:null}function le(){return L?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var Se=le();var P={};X(P,{KaylaFragment:()=>_e,KaylaInternals:()=>S,createElement:()=>ke,createGame:()=>Re,createReassignableObject:()=>De,createRenderer:()=>Ie,createScene:()=>Ke,self:()=>G,useDisposableRef:()=>Le,useEffect:()=>W,useEntity:()=>Fe,useExports:()=>Me,useNextStack:()=>he,usePaint:()=>j,useRef:()=>V,useSelf:()=>Ae,useState:()=>$,useTick:()=>Pe});function Re({width:n,height:e,updateHz:t="frames"}){return new S.KaylaGame(n,e,t==="frames"?1/0:t)}function Ke(n){let e=new A(n);return new S.KaylaScene(e)}function Ie(n){return new S.KaylaRenderer(n)}function ke(n,e){return{type:n,props:e}}var S;(y=>{class n extends F{#e;#t;constructor(i,p,a){super(i,p,a),this.#e=new Set,this.#t=!1}get started(){return this.#t}start(){if(!this.#t){for(let i of this.#e)i.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let i of this.#e)i.stop();this.#t=!1,super.stop()}}addRenderer(i){this.#e.has(i)||(this.#e.add(i),this.#t&&i.start(),i.game=this)}deleteRenderer(i){this.#e.has(i)&&(this.#e.delete(i),this.#t&&i.stop(),delete i.game)}}y.KaylaGame=n;class e extends M{game;pointerX;pointerY;#e;constructor(i){super(i),this.useDraw=this.useDraw.bind(this),this.on("draw",p=>{if(this.game)for(let a of this.game.scenes.values())a.handleDraw(p)}),this.pointerX=0,this.pointerY=0,this.#e=this.#t.bind(this)}#t(i){this.pointerX=i.clientX,this.pointerY=i.clientY}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.#e)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.#e)}pointerPosToWorldPos(i,p){let a=this.canvas.getBoundingClientRect(),f=(i-a.left)/a.width,b=(p-a.top)/a.height,x=f*this.viewportWidth*this.cameraWidth/a.width,R=b*this.viewportHeight*this.cameraHeight/a.height;return new C(x,R)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(i){let p=a=>{i(a,new r)};return this.on("draw",p),()=>{this.off("draw",p)}}attachTo(i){i.addRenderer(this),this.game=i}detach(){this.game&&this.game.deleteRenderer(this)}}y.KaylaRenderer=e;class t{current;saves;constructor(){this.saves=[]}useTick(i){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=i,this.current.useStepCallIndex++}usePaint(i){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=i,this.current.useDrawCallIndex++}useEntity(){return V(G)}useSelf(i){let p=V(null);return(p.current===null||p.current===void 0)&&(p.current=i()),p.current}useState(i,{alwaysRecall:p=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let f=this.current.state[this.current.useStateCallIndex]??new s(this.current,i,{alwaysRecall:p});return this.current.state[this.current.useStateCallIndex]=f,this.current.useStateCallIndex++,f}useRef(i){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let a=this.current.refs[this.current.useRefCallIndex]??l(i??null);return this.current.refs[this.current.useRefCallIndex]=a,this.current.useRefCallIndex++,a}useEffect(i){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=i,this.current.useEffectCallIndex++}useExports(i,p){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=p}save(){this.saves.push({current:this.current})}restore(){let i=this.saves.pop();if(!i)throw new Error("Cannot restore without saving.");this.current=i.current}}y.GlobalKayla=t;class r{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}y.KaylaEvent=r;class s{#e;#t;#n;alwaysRecall;constructor(i,p,{alwaysRecall:a=!1}={}){this.#t=i,this.#e=p??void 0,this.#n=Date.now(),this.alwaysRecall=a}get(){return this.#e}add(i,{recall:p}={}){this.set(this.get()+i,{recall:p})}multiply(i,{recall:p}={}){this.set(this.get()*i,{recall:p})}set(i,{recall:p=!1}={}){let a=this.#e;i!==a&&(this.#e=i,(p||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now())}get value(){return this.#e}get lastChanged(){return this.#n}}y.KaylaState=s;class o{#e;constructor(i){this.#e=i??void 0}#t;setSetter(i){this.#t=i}get current(){return this.#e}set current(i){this.#e=i,this.#t&&this.#t(this.#e)}}y.KaylaInternalRef=o;function l(m){return new o(m)}y.createReassignableRef=l;class h{state;refs;global;callProps;scene;exports;constructor(i,p,a){if(!a)throw new Error("Empty element");this.scene=p,this.state=[],this.refs=[],this.fc=a.type,this.callProps=a.props??{},this.global=i,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[]}get key(){return this.callProps.key}set key(i){this.callProps.key=i}get children(){return this.callProps.children}set children(i){this.callProps.children=i}entity;onExport=()=>({});onEffect;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;lastStateDeps;refresh(){let i;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0;let p=[];try{let a=this.fc(this.callProps)??[];if(a&&!Array.isArray(a)&&(a=[a]),!Array.isArray(a))throw new Error("Non array or non undefined children received.");p=a}catch(a){i=a}this.useStateCallIndex=0,this.useRefCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.global.restore();try{let a=0,f=[];for(let b of p){let x=this.lastChildren.at(a)??new h(this.global,this.scene,b);this.lastChildren[a]=x,f.push(x),a++}for(let b of this.lastChildren.filter(x=>!f.includes(x))){let x=this.lastChildren.indexOf(b);x!==1&&this.lastChildren.splice(x,1),b.unuse()}for(let b of this.lastChildren)try{b.refresh()}catch(x){console.error(x)}he(()=>{this.use()})}catch(a){console.error(a)}if(i)throw i}lastChildren;isFirstUse=!0;use(){try{let i=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(i=this.onEffectDeps.some((p,a)=>{let f=this.lastStateDeps.at(a);if(f){let b=p.lastChanged,x=f.stamp;return b>x}})),i||this.isFirstUse){this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(a=>({stamp:a.lastChanged,stateRef:a}))),this.key??=this.fc.name+"_"+B(),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new u(this,this.key);for(let a of this.refs)a.current===G&&(a.current=this.entity);this.callProps.ref instanceof o&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof o&&(this.callProps.exportsRef.current=this.exports),this.scene.getScene().addEntity(this.entity);let p=this.onEffect.map(a=>a()).filter(a=>a!==void 0);this.onUnEffect=p}}catch(i){throw i}}unuse(){try{for(let i of this.onUnEffect)i()}catch(i){console.error(i)}this.scene.getScene().removeEntity(this.entity)}}y.KaylaFiber=h;class u extends _{#e;constructor(i,p){super(p,0,0,0,0),this.#e=i}update(i){let p=new r;if(this.#e.onTick)for(let a of this.#e.onTick)a(i,p);p.isPrevented()}draw(i){let p=new r;if(this.#e.onPaint)for(let a of this.#e.onPaint)a(i,p);p.isPrevented()||super.draw(i)}}y.KaylaRectEntity=u;class c{constructor(i){this.#t=i,this.#e=null,i.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getScene(){return this.#t}drawHandler(i){return this.#t.handleDraw(i)}attachTo(i){i.addScene(this.#t),this.#e=i}spawn(i){new h(y.singleGlobalInstance,this,i).refresh()}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}y.KaylaScene=c,y.singleGlobalInstance=new y.GlobalKayla})(S||={});var g=S.singleGlobalInstance,$=g.useState.bind(g),V=g.useRef.bind(g),W=g.useEffect.bind(g),Pe=g.useTick.bind(g),j=g.usePaint.bind(g),Me=g.useExports.bind(g),Ae=g.useSelf.bind(g),Fe=g.useEntity.bind(g),G=Symbol("self_ref");var he=n=>{Promise.resolve(1).then(()=>n())},_e=({children:n})=>Array.isArray(n)?[...n]:n;function Le(n){return S.createReassignableRef(n)}function De(n){if(typeof n!="object"||typeof n=="function"||n===null)return n;let e={current:n};return new Proxy({},{get(r,s,o){return s==="reassignSelf"?l=>{e.current=l}:Reflect.get(e.current,s,o)},set(r,s,o,l){return Reflect.set(e.current,s,o,l)},has(r,s){return Reflect.has(e.current,s)},ownKeys(r){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(r,s){return Reflect.getOwnPropertyDescriptor(e.current,s)},deleteProperty(r,s){return Reflect.deleteProperty(e.current,s)}})}Reflect.set(globalThis,"Kayla",P);var Ve;(e=>e.UIComponent=({x:t,y:r,width:s,height:o,children:l})=>{let h=V(G),u=$(!1);return W(()=>{if(u.get()===!0)return;u.set(!0);let c=h.current;c.width=s,c.height=o,c.x=t,c.y=r}),j(c=>{c.fillStyle="rgba(0, 0, 0, 0.5)",c.fillRect(t,r,s,o)}),l??[]})(Ve||={});var Ge={LEA:D,Kayla:P};0&&(module.exports={Kayla,LEA});
package/dist/index.d.cts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { L as LEA } from './lea-DvxsutSf.cjs';
2
- import { K as Kayla } from './kayla-eZdx9UI6.cjs';
3
- import './kayla-internals-DvV9K1wf.cjs';
2
+ import { K as Kayla } from './kayla-internals-k7GMYD9t.cjs';
4
3
 
5
4
  declare const _default: {
6
5
  LEA: typeof LEA;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { L as LEA } from './lea-DvxsutSf.js';
2
- import { K as Kayla } from './kayla-DmdtbuQf.js';
3
- import './kayla-internals-ClSuOWZb.js';
2
+ import { K as Kayla } from './kayla-internals-KKhcrA30.js';
4
3
 
5
4
  declare const _default: {
6
5
  LEA: typeof LEA;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var Ce=Object.defineProperty;var U=(n,e)=>{for(var t in e)Ce(n,t,{get:e[t],enumerable:!0})};var W={};U(W,{DeltaTweenII:()=>G,ENVIRONMENT:()=>B,GEmitterMemory:()=>q,LeaEntityII:()=>K,LeaEventEmitter:()=>w,LeaGameII:()=>A,LeaRendererII:()=>M,LeaSceneII:()=>_,LeaSerializers:()=>Q,LeaTickerII:()=>L,LeaTimeout:()=>N,LeaUtilsII:()=>g,LiaAudio:()=>R,LiaAudioSrc:()=>I,LiaOscSFX:()=>C,LiaSFXMap:()=>ke,NOTE_NAMES:()=>ee,RectLeaEntity:()=>F,Vector2:()=>S,colToRGBA:()=>Se,defaultSFXConfig:()=>te,editRGBA:()=>Ie,generateUUID:()=>oe,getAvoidAngle:()=>ce,getEnvironment:()=>Z,getNormalizedColor:()=>Te,getRayHit:()=>le,isInitiallyMobile:()=>_e,isMobile:()=>he,isNode:()=>V,isNote:()=>Re,isWeb:()=>v,parseFillStyle:()=>J,raycastAvoid:()=>Me,scaleCoord:()=>Ke,setAnimInterval:()=>ue,sfxHit:()=>ae,sfxJump:()=>se,sfxLaser:()=>ie,sfxUIClick:()=>ne,sfxUIHover:()=>re,shortUID:()=>Pe,tinyUID:()=>$});var w=class{#e=new Map;constructor(){this.#e=new Map}on(e,t){let r=this.#e.get(e)||[];return r.push(t),this.#e.set(e,r),this}once(e,t){let r=(...i)=>{this.off(e,r),t(...i)};return this.on(e,r),this}off(e,t){let r=this.#e.get(e);if(!r)return this;let i=r.indexOf(t);return i>=0&&r.splice(i,1),this}emit(e,...t){let r=this.#e.get(e);if(!r||r.length===0){if(e==="error")throw t[0];return!1}return r.slice().forEach(i=>i(...t)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},M=class extends w{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:t,viewportHeight:r,cameraWidth:i,cameraHeight:u}={}){if(!v)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=t??e.width,this.#t=r??e.height,this.#n=i??e.width,this.#r=u??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,t=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,t),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!v)return;let e=performance.now(),t=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=t,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!v||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!v||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},L=class extends w{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),t=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,this.#e+=t*1e3,this.emit("tick",t)}createTimeout(e){return new N(e,this)}createTween(e,t=()=>{}){let r=new G(e),i=(u=0)=>{if(r.finished){this.off("tick",i);return}r.update(u)};return r.on("finish",()=>{this.off("tick",i)}),r.on("delta",u=>{t(u)}),this.on("tick",i),r}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=v&&!isFinite(this.tickInterval)?ue(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,t=0){return .5+.5*Math.sin((this.now()%e/e+t)*2*Math.PI)}},Q;(l=>{function n(f){return f===!0?1:0}l.booleanExport=n;function e(f){return f===0?!1:f===1}l.booleanImport=e;function t(f){return`${f.x}|${f.y}`}l.vec2Export=t;function r(f){let[m,b]=f.split("|"),E=parseFloat(m),D=parseFloat(b);if(isNaN(E)||isNaN(D))throw new Error(`Invalid Vector2 string: ${f}`);return new S(E,D)}l.vec2Import=r,l.booleanMap={mapExport:n,mapImport:e};function u(f){return m=>Number(m.toFixed(f))}l.createRounder=u;function c(f=10){return{mapExport(m){return Math.round(m/f)},mapImport(m){return m*f}}}l.createLowPrecision=c;function h(f){return Math.round(f)}l.lightWeightRounder=h;function a(f=100){return{mapExport(m){return Math.round(m*f)},mapImport(m){return m/f}}}l.createPercent=a;function o(f){let m=new Map(Object.entries(f));return{mapExport:b=>m.get(b)??null,mapImport:b=>Array.from(m.entries()).find(([E,D])=>D===b)?.[0]??null}}l.createLookup=o;function d(f){let m=f*(180/Math.PI);return Math.round((m%360+360)%360)}l.radToDeg=d;function y(f){return f*(Math.PI/180)}l.degToRad=y,l.angleRadToDeg={mapExport:d,mapImport:y};function p(f=10){let m=c(f);return{mapExport(b){return m.mapExport(d(b))},mapImport(b){return m.mapImport(y(b))}}}l.createLowPrecisionRadToDeg=p})(Q||={});var K=class n extends w{name="";scaleRotate=0;scale=1;constructor(e,t=0,r=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new S(t,r),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(t){this.emit("error",t)}}handleDraw(e){if(!(V||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(t){this.emit("error",t)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([i,{mapExport:u}])=>{let c=Reflect.get(this,i);return u?u(c):c});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],t=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(i=>!this.nonSerializableProperties.includes(i)&&!e.includes(i.toString())),r=Object.fromEntries(t.map(i=>{let u=Reflect.get(this,i);if(V&&typeof u=="number"){let c=u.toString().split("."),a=(c[1]?c[1].length:0)>2?Number(u.toFixed(2)):u;return[i,a]}return[i,u]}));return JSON.parse(JSON.stringify(r))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return n.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,t){if(!e||!Array.isArray(t))return t;let r={};for(let i=0;i<t.length;i++){let u=e[i];if(!u)break;let[c,{mapImport:h}]=u,a=t[i];if(h&&(a=h(a)),typeof c!="string")break;try{Reflect.set(r,c,a)}catch(o){console.error(o)}}return r}},_=class extends w{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let t of this.entities.values())t.handleUpdate(e)}}handleDraw(e){if(!V&&!this.paused){this.emit("draw",e);for(let t of[...this.entities.values()].sort((r,i)=>r.z-i.z))t.handleDraw(e)}}addEntity(e){if(!(e instanceof K))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof K))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},A=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,t,r=16){this.ticker=new L(r),this.scenes=new Map,this.width=e,this.height=t,this.ticker.on("tick",i=>{for(let u of this.scenes.values())u.paused||u.handleUpdate(i)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},g={lerp(n,e,t){return n+(e-n)*t},clamp(n,e,t){return Math.min(t,Math.max(e,n))},clamp01(n){return Math.min(1,Math.max(0,n))},easeLinear(n){return n},easeInQuad(n){return n*n},easeOutQuad(n){return 1-(1-n)*(1-n)},easeInOutQuad(n){return n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2},easeInSine(n){return 1-Math.cos(n*Math.PI/2)},easeOutSine(n){return Math.sin(n*Math.PI/2)},easeInOutSine(n){return-(Math.cos(Math.PI*n)-1)/2},easeInExpo(n){return n===0?0:Math.pow(2,10*n-10)},easeOutExpo(n){return n===1?1:1-Math.pow(2,-10*n)},easeInOutExpo(n){return n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2},smoothstep(n){return n=g.clamp(n,0,1),n*n*(3-2*n)},randomLerp(n,e){return g.lerp(n,e,Math.random())},randomInt(n,e){return Math.floor(Math.random()*(e-n+1))+n},randomArrayValue(n){return n[g.randomInt(0,n.length-1)]},createBezier(n,e,t,r){function i(h,a,o,d,y){let s=1-h;return s*s*s*a+3*s*s*h*o+3*s*h*h*d+h*h*h*y}function u(h,a,o,d,y){let s=1-h;return 3*s*s*(o-a)+6*s*h*(d-o)+3*h*h*(y-d)}function c(h){let a=h;for(let o=0;o<6;o++){let d=i(a,0,n,t,1),y=u(a,0,n,t,1);if(y===0)break;a-=(d-h)/y}return g.clamp(a,0,1)}return function(a){a=g.clamp(a,0,1);let o=c(a);return i(o,0,e,r,1)}},lengthSquared(...n){return n.reduce((e,t)=>e+t*t,0)},normalizeRad(n){let e=2*Math.PI;return n=n%e,n<0&&(n+=e),n},angleInvertY(n){return g.normalizeRad(-n)},degToRadFlipY(n){return g.angleInvertY(n*Math.PI/180)},minimalAngularDirection(n,e){n=g.normalizeRad(n),e=g.normalizeRad(e);let t=g.normalizeRad(e-n),r=g.normalizeRad(n-e);return t<=r?1:-1}},G=class extends w{constructor({delta:e,ms:t,easing:r}){super(),this.delta=e,this.duration=t,this.elapsed=0,this.easing=r??(i=>i),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let t=g.clamp(this.elapsed/this.duration,0,1),r=this.easing(t),i=this.delta*r,u=i-this.lastValue;this.lastValue=i,this.emit("delta",u),t>=1&&(this.finished=!0,this.emit("finish",void 0))}},F=class extends K{constructor(e,t=0,r=0,i=50,u=50){super(e,t,r),this.width=i,this.height=u}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},N=class extends w{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,t=null){super(),this.duration=e,this.ticker=t,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(r=>this._resolve=r),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,t){return this.promise.then(e,t)}after(e,t){return this.promise.then(e,t)}},S=class n{constructor(e=0,t=0){this.x=e,this.y=t}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let t=Math.cos(e),r=Math.sin(e);return new n(this.x*t-this.y*r,this.x*r+this.y*t)}static from(e){return new n(Math.cos(e),Math.sin(e))}get angle(){return Math.atan2(this.y,this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new n(0,0):new n(this.x/e,this.y/e)}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let t=this.dot(e);return this.subtract(e.scale(2*t))}dotNormalized(e){let t=this.normalized(),r=e.normalized();return t.x*r.x+t.y*r.y}lengthSquaredTo(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}directionTo(e){return new n(e.x-this.x,e.y-this.y).normalized()}add(e){return new n(this.x+e.x,this.y+e.y)}addRaw(e){return new n(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new n(this.x-e.x,this.y-e.y)}scale(e){return new n(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new n(this.x,this.y)}};function Te(n){let e=/^rgba?\(([^)]+)\)$/,t=n.match(e);if(t){let[r,i,u,c=1]=t[1].split(",").map(h=>parseFloat(h));return{r:Math.max(0,Math.min(255,Math.floor(r))),g:Math.max(0,Math.min(255,Math.floor(i))),b:Math.max(0,Math.min(255,Math.floor(u))),a:Math.max(0,Math.min(1,Math.floor(c*255)/255))}}return J(n)}function Se(n){return`rgba(${n.r}, ${n.g}, ${n.b}, ${n.a})`}function J(n){if(n=n.trim().toLowerCase(),n[0]==="#"){let t,r,i;if(n.length===7)t=parseInt(n.slice(1,3),16),r=parseInt(n.slice(3,5),16),i=parseInt(n.slice(5,7),16);else if(n.length===4)t=parseInt(n[1]+n[1],16),r=parseInt(n[2]+n[2],16),i=parseInt(n[3]+n[3],16);else throw new Error("Invalid hex color");return{r:t,g:r,b:i,a:1}}let e=n.match(/^rgba?\s*\(\s*(\d+)[, ]\s*(\d+)[, ]\s*(\d+)(?:[, ]\s*([\d.]+))?\s*\)$/);if(e)return{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3]),a:e[4]!==void 0?parseFloat(e[4]):1};throw new Error("Unsupported fillStyle format")}function Ie(n,{r:e,g:t,b:r,a:i}={}){let[u,c,h,a,o]=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??c}, ${t??h}, ${r??a}, ${i??(o||1)})`}function Ke(n,e,t){return t+(n-t)*e}function Z(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var B=Z(),V=B==="node",v=B==="web",R=class n{static unlock(){v&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=v?new AudioContext:null;static masterGain=v?this.audioCtx.createGain():null;static musicGain=v?this.audioCtx.createGain():null;static sfxGain=v?this.audioCtx.createGain():null;static{v&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let t=n.CACHE_NAME,r,i;if(typeof caches<"u"&&(i=await caches.open(t),r=await i.match(e)),!r){if(r=await fetch(e),!r.ok)throw new Error(`Failed to fetch ${e}`);i&&await i.put(e,r.clone())}let u=await r.arrayBuffer(),c=await this.audioCtx.decodeAudioData(u);return this.audioBufferCache.set(e,c),c}static async getOnlyDownloadedCache(e){let t=n.CACHE_NAME;return await(await caches.open(t)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,t=.2,r=1,i=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let u=this.getCached(e);if(!u)return;let c=new I(u);c.buffer=u;let h=1-.12,a=1+.12;c.playbackRate=r??h+Math.random()*(a-h);let o=this.audioCtx.createGain();o.gain.value=t,c.tempGain=o,c.connect(o),o.connect(this.sfxGain),c.onended=()=>{c.disconnect(),o.disconnect()},c.start(),i&&this.sfsx.set(e,{source:c,gain:o})}catch(u){console.error(u)}}static async playLoop(e,t=1,{loopStart:r=0,loopEnd:i=null,exclusive:u=!0,skipMS:c=0}={}){if(u)for(let y of this.loops.keys())this.stopLoop(y);this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return;let a=new I(h);a.buffer=h,a.loop=!0,typeof r=="number"&&(a.loopStart=r),typeof i=="number"&&(a.loopEnd=i);let o=this.audioCtx.createGain();o.gain.value=t,a.tempGain=o,a.playbackRate=1,a.onended=()=>{a.disconnect(),o.disconnect()},a.connect(o),o.connect(this.musicGain),a.start(0,c/1e3);let d=++this.loopIdCounter;return this.loops.set(d,{source:a,gain:o}),d}static stopLoop(e){let t=this.loops.get(e);t&&(t.source.stop(),t.source.notIndependent||(t.source.disconnect(),t.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:t=1,speed:r=1,loop:i=!1,loopStart:u=0,loopEnd:c=null,isMusic:h=!1,gain:a=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return null;let d=new I(o);d.loop=i,d.loopStart=u,d.loopEnd=typeof c=="number"?c:o.duration,d.playbackRate=r;let y=this.audioCtx.createGain();return y.gain.value=t,d.connect(y),d.tempGain=y,y.connect(a||(h?this.musicGain:this.sfxGain)),d.onended=()=>{d.disconnect(),y.disconnect()},d}catch(o){return console.error("Failed to create LiaAudioSrc:",o),null}}},ee=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Re(n){return ee.includes(n)}var I=class{numberOfInputs;numberOfOutputs;constructor(e,t=R.audioCtx){this.context=t,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=v?t.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:t=null}={}){let r=t!==null?t:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-r/this.playbackRate,this.source.start(0,r),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,t=0,r){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-t/this.playbackRate,r!==void 0?this.source.start(this.context.currentTime+e,t,r):this.source.start(this.context.currentTime+e,t),this.pauseTime=t,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let t=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let r=this.loopEnd-this.loopStart;t=this.loopStart+(t-this.loopStart)%r}if(this.isPlaying=!1,e>0){let r=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,r),this.output.gain.linearRampToValueAtTime(0,r+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let t=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=t,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,t=0,r=0){if("value"in e)this.output.connect(e,t);else return this.output.connect(e,t,r),e}disconnect(e,t,r){e===void 0?this.output.disconnect():this.output.disconnect(e,t,r)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let t=this.context.currentTime+e;this.source.stop(t),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},te={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},C=class n{constructor(e={}){this.ctx=R.audioCtx,this.cfg=structuredClone(te),Object.assign(this.cfg,e)}ctx;cfg;play(e=R.sfxGain){let t=this.ctx,r=t.currentTime,i=this.cfg,u=t.createGain();u.gain.setValueAtTime(1e-4,r);let c=i.ampEnv;u.gain.exponentialRampToValueAtTime(c.volume,r+c.attack),u.gain.exponentialRampToValueAtTime(Math.max(1e-4,c.sustain*c.volume),r+c.attack+c.decay),u.gain.exponentialRampToValueAtTime(1e-4,r+i.duration+c.release);let h=u,a;i.filter.enabled&&(a=t.createBiquadFilter(),a.type=i.filter.type,a.frequency.value=i.filter.freq,a.Q.value=i.filter.Q,a.connect(u),h=a);let o;if(i.osc.enabled){if(o=t.createOscillator(),o.type=i.osc.type,o.frequency.value=i.osc.freq,o.detune.value=i.osc.detune,i.pitchEnv.amount!==0){let f=Math.pow(2,i.pitchEnv.amount/12);o.frequency.exponentialRampToValueAtTime(i.osc.freq*f,r+i.pitchEnv.decay)}o.connect(h),o.start(r),o.stop(r+i.duration+c.release)}let d;if(i.noise.enabled){let f=t.sampleRate*i.duration,m=t.createBuffer(1,f,t.sampleRate),b=m.getChannelData(0);for(let E=0;E<f;E++)b[E]=(Math.random()*2-1)*i.noise.level;d=t.createBufferSource(),d.buffer=m,d.connect(h),d.start(r),d.stop(r+i.duration+c.release)}let y,s;i.lfo.enabled&&o&&(y=t.createOscillator(),y.frequency.value=i.lfo.rate,s=t.createGain(),s.gain.value=i.lfo.depth,y.connect(s),i.lfo.target==="freq"?s.connect(o.frequency):i.lfo.target==="gain"?s.connect(u.gain):i.lfo.target==="filter"&&a&&s.connect(a.frequency),y.start(r),y.stop(r+i.duration)),u.connect(e);let p=[o,d,y,s,a,u],l=r+i.duration+c.release;setTimeout(()=>{p.forEach(f=>f?.disconnect())},(l-t.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,t){return Object.assign(this.cfg[e],t),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,t,r,i){return Object.assign(this.cfg.ampEnv,{attack:e,decay:t,sustain:r,release:i}),this}setPitchEnv(e,t){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:t}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,t,r){return Object.assign(this.cfg.filter,{type:e,freq:t,Q:r,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,t,r){return Object.assign(this.cfg.lfo,{target:e,rate:t,depth:r,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new n(structuredClone(this.cfg))}},ne=new C({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),re=new C({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),se=new C({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),ie=new C({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),ae=new C({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2}),ke=new Map([["ui_click",ne],["ui_hover",re],["jump",se],["laser",ie],["hit",ae]]);function Pe(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(n)),r=Array.from(t).map(i=>i.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}function $(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(4)),r=Array.from(t).map(i=>i.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}var q=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${oe()}_${Date.now()}`}connect(e){e&&(this.peer=e,e.peer=this,this.connected=!0,e.connected=!0),this._emit("open")}isConnected(){return this.connected&&!!this.peer}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(r=>r!==t))}_emit(e,t){this.events[e]?.forEach(r=>r(t))}send(e,t){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,t)}_receive(e,t){e?this._emit(e,t):this._emit("message",t)}close(){if(this.connected=!1,this.peer){let e=this.peer;this.peer=null,e.peer=null,e.connected=!1,e._emit("close")}this._emit("close")}getKey(){return this.key}};function oe(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let n=new Uint8Array(16);return crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,[...n].map(e=>e.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5")}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function ue(n){let e=!0;function t(){e&&(n(),requestAnimationFrame(t))}return requestAnimationFrame(t),{clear:()=>e=!1}}function le(n,e,t,r,i){let u=Math.cos(i),c=Math.sin(i),h=[];if(u!==0){let a=(0-n)/u,o=e+a*c;a>0&&o>=0&&o<=r&&h.push({side:"left",t:a})}if(u!==0){let a=(t-n)/u,o=e+a*c;a>0&&o>=0&&o<=r&&h.push({side:"right",t:a})}if(c!==0){let a=(0-e)/c,o=n+a*u;a>0&&o>=0&&o<=t&&h.push({side:"top",t:a})}if(c!==0){let a=(r-e)/c,o=n+a*u;a>0&&o>=0&&o<=t&&h.push({side:"bottom",t:a})}return h.length===0?null:(h.sort((a,o)=>a.t-o.t),h[0])}function ce(n,e){let t;switch(e){case"left":case"right":t=Math.PI-n;break;case"top":case"bottom":t=2*Math.PI-n;break}return(t%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function Me(n,e,t,r,i){let u=le(n,e,t,r,i);return u?{...u,avoidAngle:ce(i,u.side)}:null}function he(){return V?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var _e=he();var Y={};U(Y,{Kayla:()=>X,KaylaFragment:()=>ve,KaylaInternals:()=>T,UI:()=>we,createElement:()=>me,createGame:()=>pe,createRenderer:()=>de,createScene:()=>fe,self:()=>P,useDisposableRef:()=>Ee,useEffect:()=>O,useEntity:()=>ge,useExports:()=>be,useNextStack:()=>j,usePaint:()=>H,useRef:()=>k,useSelf:()=>xe,useState:()=>z,useTick:()=>ye});var X={};U(X,{KaylaFragment:()=>ve,KaylaInternals:()=>T,createElement:()=>me,createGame:()=>pe,createRenderer:()=>de,createScene:()=>fe,self:()=>P,useDisposableRef:()=>Ee,useEffect:()=>O,useEntity:()=>ge,useExports:()=>be,useNextStack:()=>j,usePaint:()=>H,useRef:()=>k,useSelf:()=>xe,useState:()=>z,useTick:()=>ye});function pe({width:n,height:e,updateHz:t="frames"}){return new T.KaylaGame(n,e,t==="frames"?1/0:t)}function fe(n){let e=new _(n);return new T.KaylaScene(e)}function de(n){return new T.KaylaRenderer(n)}function me(n,e){return{type:n,props:e}}var T;(d=>{class n extends A{#e;#t;constructor(s,p,l){super(s,p,l),this.#e=new Set,this.#t=!1}get started(){return this.#t}start(){if(!this.#t){for(let s of this.#e)s.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let s of this.#e)s.stop();this.#t=!1,super.stop()}}addRenderer(s){this.#e.has(s)||(this.#e.add(s),this.#t&&s.start(),s.game=this)}deleteRenderer(s){this.#e.has(s)&&(this.#e.delete(s),this.#t&&s.stop(),delete s.game)}}d.KaylaGame=n;class e extends M{game;pointerX;pointerY;#e;constructor(s){super(s),this.useDraw=this.useDraw.bind(this),this.on("draw",p=>{if(this.game)for(let l of this.game.scenes.values())l.handleDraw(p)}),this.pointerX=0,this.pointerY=0,this.#e=this.#t.bind(this)}#t(s){this.pointerX=s.clientX,this.pointerY=s.clientY}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.#e)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.#e)}pointerPosToWorldPos(s,p){let l=this.canvas.getBoundingClientRect(),f=(s-l.left)/l.width,m=(p-l.top)/l.height,b=f*this.viewportWidth*this.cameraWidth/l.width,E=m*this.viewportHeight*this.cameraHeight/l.height;return new S(b,E)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(s){let p=l=>{s(l,new r)};return this.on("draw",p),()=>{this.off("draw",p)}}attachTo(s){s.addRenderer(this),this.game=s}detach(){this.game&&this.game.deleteRenderer(this)}}d.KaylaRenderer=e;class t{current;saves;constructor(){this.saves=[]}useTick(s){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=s,this.current.useStepCallIndex++}usePaint(s){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=s,this.current.useDrawCallIndex++}useEntity(){return k(P)}useSelf(s){let p=k(null);return(p.current===null||p.current===void 0)&&(p.current=s()),p.current}useState(s,{alwaysRecall:p=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let f=this.current.state[this.current.useStateCallIndex]??new i(this.current,s,{alwaysRecall:p});return this.current.state[this.current.useStateCallIndex]=f,this.current.useStateCallIndex++,f}useRef(s){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let l=this.current.refs[this.current.useRefCallIndex]??new u(this.current,s??null);return this.current.refs[this.current.useRefCallIndex]=l,this.current.useRefCallIndex++,l}useEffect(s){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=s,this.current.useEffectCallIndex++}useExports(s,p){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=p}save(){this.saves.push({current:this.current})}restore(){let s=this.saves.pop();if(!s)throw new Error("Cannot restore without saving.");this.current=s.current}}d.GlobalKayla=t;class r{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}d.KaylaEvent=r;class i{#e;#t;#n;alwaysRecall;constructor(s,p,{alwaysRecall:l=!1}={}){this.#t=s,this.#e=p??void 0,this.#n=Date.now(),this.alwaysRecall=l}get(){return this.#e}add(s,{recall:p}={}){this.set(this.get()+s,{recall:p})}multiply(s,{recall:p}={}){this.set(this.get()*s,{recall:p})}set(s,{recall:p=!1}={}){let l=this.#e;s!==l&&(this.#e=s,(p||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now())}get value(){return this.#e}get lastChanged(){return this.#n}}d.KaylaState=i;class u{#e;#t;constructor(s,p){this.#t=s,this.#e=p??void 0}get current(){return this.#e}set current(s){this.#e=s}}d.KaylaRef=u;class c{state;refs;global;callProps;scene;exports;constructor(s,p,l){if(!l)throw new Error("Empty element");this.scene=p,this.state=[],this.refs=[],this.fc=l.type,this.callProps=l.props??{},this.global=s,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[]}get key(){return this.callProps.key}set key(s){this.callProps.key=s}get children(){return this.callProps.children}set children(s){this.callProps.children=s}entity;onExport=()=>({});onEffect;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;lastStateDeps;refresh(){let s;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0;let p=[];try{let l=this.fc(this.callProps)??[];if(l&&!Array.isArray(l)&&(l=[l]),!Array.isArray(l))throw new Error("Non array or non undefined children received.");p=l}catch(l){s=l}this.useStateCallIndex=0,this.useRefCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.global.restore();try{let l=0,f=[];for(let m of p){let b=this.lastChildren.at(l)??new c(this.global,this.scene,m);this.lastChildren[l]=b,f.push(b),l++}for(let m of this.lastChildren.filter(b=>!f.includes(b))){let b=this.lastChildren.indexOf(m);b!==1&&this.lastChildren.splice(b,1),m.unuse()}for(let m of this.lastChildren)try{m.refresh()}catch(b){console.error(b)}j(()=>{this.use()})}catch(l){console.error(l)}if(s)throw s}lastChildren;isFirstUse=!0;use(){try{let s=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(s=this.onEffectDeps.some((p,l)=>{let f=this.lastStateDeps.at(l);if(f){let m=p.lastChanged,b=f.stamp;return m>b}})),s||this.isFirstUse){this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(l=>({stamp:l.lastChanged,stateRef:l}))),this.key??=this.fc.name+"_"+$(),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new h(this,this.key);for(let l of this.refs)l.current===P&&(l.current=this.entity);this.callProps.ref instanceof u&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof u&&(this.callProps.exportsRef.current=this.exports),this.scene.getScene().addEntity(this.entity);let p=this.onEffect.map(l=>l()).filter(l=>l!==void 0);this.onUnEffect=p}}catch(s){throw s}}unuse(){try{for(let s of this.onUnEffect)s()}catch(s){console.error(s)}this.scene.getScene().removeEntity(this.entity)}}d.KaylaInternalComponent=c;class h extends F{#e;constructor(s,p){super(p,0,0,0,0),this.#e=s}update(s){let p=new r;if(this.#e.onTick)for(let l of this.#e.onTick)l(s,p);p.isPrevented()}draw(s){let p=new r;if(this.#e.onPaint)for(let l of this.#e.onPaint)l(s,p);p.isPrevented()||super.draw(s)}}d.KaylaRectEntity=h;class a{constructor(s){this.#t=s,this.#e=null,s.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getScene(){return this.#t}drawHandler(s){return this.#t.handleDraw(s)}attachTo(s){s.addScene(this.#t),this.#e=s}spawn(s){new c(d.singleGlobalInstance,this,s).refresh()}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}d.KaylaScene=a,d.singleGlobalInstance=new d.GlobalKayla})(T||={});var x=T.singleGlobalInstance,z=x.useState.bind(x),k=x.useRef.bind(x),O=x.useEffect.bind(x),ye=x.useTick.bind(x),H=x.usePaint.bind(x),be=x.useExports.bind(x),xe=x.useSelf.bind(x),ge=x.useEntity.bind(x),P=Symbol("self_ref");var j=n=>{Promise.resolve(1).then(()=>n())},ve=({children:n})=>Array.isArray(n)?[...n]:n;function Ee(n){return new T.KaylaRef(null,n)}Reflect.set(globalThis,"Kayla",X);var we;(e=>e.UIComponent=({x:t,y:r,width:i,height:u,children:c})=>{let h=k(P),a=z(!1);return O(()=>{if(a.get()===!0)return;a.set(!0);let o=h.current;o.width=i,o.height=u,o.x=t,o.y=r}),H(o=>{o.fillStyle="rgba(0, 0, 0, 0.5)",o.fillRect(t,r,i,u)}),c??[]})(we||={});var De={LEA:W,Kayla:Y};export{Y as Kayla,W as LEA,De as default};
1
+ var he=Object.defineProperty;var W=(n,e)=>{for(var t in e)he(n,t,{get:e[t],enumerable:!0})};var z={};W(z,{DeltaTweenII:()=>N,ENVIRONMENT:()=>X,GEmitterMemory:()=>H,LeaEntityII:()=>I,LeaEventEmitter:()=>w,LeaGameII:()=>A,LeaRendererII:()=>P,LeaSceneII:()=>M,LeaSerializers:()=>j,LeaTickerII:()=>G,LeaTimeout:()=>O,LeaUtilsII:()=>v,LiaAudio:()=>k,LiaAudioSrc:()=>K,LiaOscSFX:()=>T,LiaSFXMap:()=>be,NOTE_NAMES:()=>J,RectLeaEntity:()=>F,Vector2:()=>C,colToRGBA:()=>fe,defaultSFXConfig:()=>Z,editRGBA:()=>de,generateUUID:()=>ie,getAvoidAngle:()=>ue,getEnvironment:()=>Q,getNormalizedColor:()=>pe,getRayHit:()=>oe,isInitiallyMobile:()=>ve,isMobile:()=>ce,isNode:()=>_,isNote:()=>ye,isWeb:()=>E,parseFillStyle:()=>Y,raycastAvoid:()=>ge,scaleCoord:()=>me,setAnimInterval:()=>ae,sfxHit:()=>se,sfxJump:()=>ne,sfxLaser:()=>re,sfxUIClick:()=>ee,sfxUIHover:()=>te,shortUID:()=>xe,tinyUID:()=>U});var w=class{#e=new Map;constructor(){this.#e=new Map}on(e,t){let r=this.#e.get(e)||[];return r.push(t),this.#e.set(e,r),this}once(e,t){let r=(...s)=>{this.off(e,r),t(...s)};return this.on(e,r),this}off(e,t){let r=this.#e.get(e);if(!r)return this;let s=r.indexOf(t);return s>=0&&r.splice(s,1),this}emit(e,...t){let r=this.#e.get(e);if(!r||r.length===0){if(e==="error")throw t[0];return!1}return r.slice().forEach(s=>s(...t)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},P=class extends w{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:t,viewportHeight:r,cameraWidth:s,cameraHeight:o}={}){if(!E)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=t??e.width,this.#t=r??e.height,this.#n=s??e.width,this.#r=o??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,t=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,t),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!E)return;let e=performance.now(),t=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=t,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},G=class extends w{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),t=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,this.#e+=t*1e3,this.emit("tick",t)}createTimeout(e){return new O(e,this)}createTween(e,t=()=>{}){let r=new N(e),s=(o=0)=>{if(r.finished){this.off("tick",s);return}r.update(o)};return r.on("finish",()=>{this.off("tick",s)}),r.on("delta",o=>{t(o)}),this.on("tick",s),r}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=E&&!isFinite(this.tickInterval)?ae(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,t=0){return .5+.5*Math.sin((this.now()%e/e+t)*2*Math.PI)}},j;(p=>{function n(a){return a===!0?1:0}p.booleanExport=n;function e(a){return a===0?!1:a===1}p.booleanImport=e;function t(a){return`${a.x}|${a.y}`}p.vec2Export=t;function r(a){let[f,b]=a.split("|"),x=parseFloat(f),R=parseFloat(b);if(isNaN(x)||isNaN(R))throw new Error(`Invalid Vector2 string: ${a}`);return new C(x,R)}p.vec2Import=r,p.booleanMap={mapExport:n,mapImport:e};function o(a){return f=>Number(f.toFixed(a))}p.createRounder=o;function l(a=10){return{mapExport(f){return Math.round(f/a)},mapImport(f){return f*a}}}p.createLowPrecision=l;function h(a){return Math.round(a)}p.lightWeightRounder=h;function u(a=100){return{mapExport(f){return Math.round(f*a)},mapImport(f){return f/a}}}p.createPercent=u;function c(a){let f=new Map(Object.entries(a));return{mapExport:b=>f.get(b)??null,mapImport:b=>Array.from(f.entries()).find(([x,R])=>R===b)?.[0]??null}}p.createLookup=c;function d(a){let f=a*(180/Math.PI);return Math.round((f%360+360)%360)}p.radToDeg=d;function y(a){return a*(Math.PI/180)}p.degToRad=y,p.angleRadToDeg={mapExport:d,mapImport:y};function i(a=10){let f=l(a);return{mapExport(b){return f.mapExport(d(b))},mapImport(b){return f.mapImport(y(b))}}}p.createLowPrecisionRadToDeg=i})(j||={});var I=class n extends w{name="";scaleRotate=0;scale=1;constructor(e,t=0,r=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new C(t,r),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(t){this.emit("error",t)}}handleDraw(e){if(!(_||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(t){this.emit("error",t)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([s,{mapExport:o}])=>{let l=Reflect.get(this,s);return o?o(l):l});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],t=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(s=>!this.nonSerializableProperties.includes(s)&&!e.includes(s.toString())),r=Object.fromEntries(t.map(s=>{let o=Reflect.get(this,s);if(_&&typeof o=="number"){let l=o.toString().split("."),u=(l[1]?l[1].length:0)>2?Number(o.toFixed(2)):o;return[s,u]}return[s,o]}));return JSON.parse(JSON.stringify(r))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return n.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,t){if(!e||!Array.isArray(t))return t;let r={};for(let s=0;s<t.length;s++){let o=e[s];if(!o)break;let[l,{mapImport:h}]=o,u=t[s];if(h&&(u=h(u)),typeof l!="string")break;try{Reflect.set(r,l,u)}catch(c){console.error(c)}}return r}},M=class extends w{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let t of this.entities.values())t.handleUpdate(e)}}handleDraw(e){if(!_&&!this.paused){this.emit("draw",e);for(let t of[...this.entities.values()].sort((r,s)=>r.z-s.z))t.handleDraw(e)}}addEntity(e){if(!(e instanceof I))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof I))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},A=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,t,r=16){this.ticker=new G(r),this.scenes=new Map,this.width=e,this.height=t,this.ticker.on("tick",s=>{for(let o of this.scenes.values())o.paused||o.handleUpdate(s)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},v={lerp(n,e,t){return n+(e-n)*t},clamp(n,e,t){return Math.min(t,Math.max(e,n))},clamp01(n){return Math.min(1,Math.max(0,n))},easeLinear(n){return n},easeInQuad(n){return n*n},easeOutQuad(n){return 1-(1-n)*(1-n)},easeInOutQuad(n){return n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2},easeInSine(n){return 1-Math.cos(n*Math.PI/2)},easeOutSine(n){return Math.sin(n*Math.PI/2)},easeInOutSine(n){return-(Math.cos(Math.PI*n)-1)/2},easeInExpo(n){return n===0?0:Math.pow(2,10*n-10)},easeOutExpo(n){return n===1?1:1-Math.pow(2,-10*n)},easeInOutExpo(n){return n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2},smoothstep(n){return n=v.clamp(n,0,1),n*n*(3-2*n)},randomLerp(n,e){return v.lerp(n,e,Math.random())},randomInt(n,e){return Math.floor(Math.random()*(e-n+1))+n},randomArrayValue(n){return n[v.randomInt(0,n.length-1)]},createBezier(n,e,t,r){function s(h,u,c,d,y){let m=1-h;return m*m*m*u+3*m*m*h*c+3*m*h*h*d+h*h*h*y}function o(h,u,c,d,y){let m=1-h;return 3*m*m*(c-u)+6*m*h*(d-c)+3*h*h*(y-d)}function l(h){let u=h;for(let c=0;c<6;c++){let d=s(u,0,n,t,1),y=o(u,0,n,t,1);if(y===0)break;u-=(d-h)/y}return v.clamp(u,0,1)}return function(u){u=v.clamp(u,0,1);let c=l(u);return s(c,0,e,r,1)}},lengthSquared(...n){return n.reduce((e,t)=>e+t*t,0)},normalizeRad(n){let e=2*Math.PI;return n=n%e,n<0&&(n+=e),n},angleInvertY(n){return v.normalizeRad(-n)},degToRadFlipY(n){return v.angleInvertY(n*Math.PI/180)},minimalAngularDirection(n,e){n=v.normalizeRad(n),e=v.normalizeRad(e);let t=v.normalizeRad(e-n),r=v.normalizeRad(n-e);return t<=r?1:-1}},N=class extends w{constructor({delta:e,ms:t,easing:r}){super(),this.delta=e,this.duration=t,this.elapsed=0,this.easing=r??(s=>s),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let t=v.clamp(this.elapsed/this.duration,0,1),r=this.easing(t),s=this.delta*r,o=s-this.lastValue;this.lastValue=s,this.emit("delta",o),t>=1&&(this.finished=!0,this.emit("finish",void 0))}},F=class extends I{constructor(e,t=0,r=0,s=50,o=50){super(e,t,r),this.width=s,this.height=o}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},O=class extends w{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,t=null){super(),this.duration=e,this.ticker=t,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(r=>this._resolve=r),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,t){return this.promise.then(e,t)}after(e,t){return this.promise.then(e,t)}},C=class n{constructor(e=0,t=0){this.x=e,this.y=t}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let t=Math.cos(e),r=Math.sin(e);return new n(this.x*t-this.y*r,this.x*r+this.y*t)}static from(e){return new n(Math.cos(e),Math.sin(e))}get angle(){return Math.atan2(this.y,this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new n(0,0):new n(this.x/e,this.y/e)}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let t=this.dot(e);return this.subtract(e.scale(2*t))}dotNormalized(e){let t=this.normalized(),r=e.normalized();return t.x*r.x+t.y*r.y}lengthSquaredTo(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}directionTo(e){return new n(e.x-this.x,e.y-this.y).normalized()}add(e){return new n(this.x+e.x,this.y+e.y)}addRaw(e){return new n(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new n(this.x-e.x,this.y-e.y)}scale(e){return new n(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new n(this.x,this.y)}};function pe(n){let e=/^rgba?\(([^)]+)\)$/,t=n.match(e);if(t){let[r,s,o,l=1]=t[1].split(",").map(h=>parseFloat(h));return{r:Math.max(0,Math.min(255,Math.floor(r))),g:Math.max(0,Math.min(255,Math.floor(s))),b:Math.max(0,Math.min(255,Math.floor(o))),a:Math.max(0,Math.min(1,Math.floor(l*255)/255))}}return Y(n)}function fe(n){return`rgba(${n.r}, ${n.g}, ${n.b}, ${n.a})`}function Y(n){if(n=n.trim().toLowerCase(),n[0]==="#"){let t,r,s;if(n.length===7)t=parseInt(n.slice(1,3),16),r=parseInt(n.slice(3,5),16),s=parseInt(n.slice(5,7),16);else if(n.length===4)t=parseInt(n[1]+n[1],16),r=parseInt(n[2]+n[2],16),s=parseInt(n[3]+n[3],16);else throw new Error("Invalid hex color");return{r:t,g:r,b:s,a:1}}let e=n.match(/^rgba?\s*\(\s*(\d+)[, ]\s*(\d+)[, ]\s*(\d+)(?:[, ]\s*([\d.]+))?\s*\)$/);if(e)return{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3]),a:e[4]!==void 0?parseFloat(e[4]):1};throw new Error("Unsupported fillStyle format")}function de(n,{r:e,g:t,b:r,a:s}={}){let[o,l,h,u,c]=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??l}, ${t??h}, ${r??u}, ${s??(c||1)})`}function me(n,e,t){return t+(n-t)*e}function Q(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var X=Q(),_=X==="node",E=X==="web",k=class n{static unlock(){E&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=E?new AudioContext:null;static masterGain=E?this.audioCtx.createGain():null;static musicGain=E?this.audioCtx.createGain():null;static sfxGain=E?this.audioCtx.createGain():null;static{E&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let t=n.CACHE_NAME,r,s;if(typeof caches<"u"&&(s=await caches.open(t),r=await s.match(e)),!r){if(r=await fetch(e),!r.ok)throw new Error(`Failed to fetch ${e}`);s&&await s.put(e,r.clone())}let o=await r.arrayBuffer(),l=await this.audioCtx.decodeAudioData(o);return this.audioBufferCache.set(e,l),l}static async getOnlyDownloadedCache(e){let t=n.CACHE_NAME;return await(await caches.open(t)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,t=.2,r=1,s=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return;let l=new K(o);l.buffer=o;let h=1-.12,u=1+.12;l.playbackRate=r??h+Math.random()*(u-h);let c=this.audioCtx.createGain();c.gain.value=t,l.tempGain=c,l.connect(c),c.connect(this.sfxGain),l.onended=()=>{l.disconnect(),c.disconnect()},l.start(),s&&this.sfsx.set(e,{source:l,gain:c})}catch(o){console.error(o)}}static async playLoop(e,t=1,{loopStart:r=0,loopEnd:s=null,exclusive:o=!0,skipMS:l=0}={}){if(o)for(let y of this.loops.keys())this.stopLoop(y);this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return;let u=new K(h);u.buffer=h,u.loop=!0,typeof r=="number"&&(u.loopStart=r),typeof s=="number"&&(u.loopEnd=s);let c=this.audioCtx.createGain();c.gain.value=t,u.tempGain=c,u.playbackRate=1,u.onended=()=>{u.disconnect(),c.disconnect()},u.connect(c),c.connect(this.musicGain),u.start(0,l/1e3);let d=++this.loopIdCounter;return this.loops.set(d,{source:u,gain:c}),d}static stopLoop(e){let t=this.loops.get(e);t&&(t.source.stop(),t.source.notIndependent||(t.source.disconnect(),t.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:t=1,speed:r=1,loop:s=!1,loopStart:o=0,loopEnd:l=null,isMusic:h=!1,gain:u=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return null;let d=new K(c);d.loop=s,d.loopStart=o,d.loopEnd=typeof l=="number"?l:c.duration,d.playbackRate=r;let y=this.audioCtx.createGain();return y.gain.value=t,d.connect(y),d.tempGain=y,y.connect(u||(h?this.musicGain:this.sfxGain)),d.onended=()=>{d.disconnect(),y.disconnect()},d}catch(c){return console.error("Failed to create LiaAudioSrc:",c),null}}},J=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function ye(n){return J.includes(n)}var K=class{numberOfInputs;numberOfOutputs;constructor(e,t=k.audioCtx){this.context=t,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=E?t.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:t=null}={}){let r=t!==null?t:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-r/this.playbackRate,this.source.start(0,r),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,t=0,r){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-t/this.playbackRate,r!==void 0?this.source.start(this.context.currentTime+e,t,r):this.source.start(this.context.currentTime+e,t),this.pauseTime=t,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let t=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let r=this.loopEnd-this.loopStart;t=this.loopStart+(t-this.loopStart)%r}if(this.isPlaying=!1,e>0){let r=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,r),this.output.gain.linearRampToValueAtTime(0,r+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let t=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=t,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,t=0,r=0){if("value"in e)this.output.connect(e,t);else return this.output.connect(e,t,r),e}disconnect(e,t,r){e===void 0?this.output.disconnect():this.output.disconnect(e,t,r)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let t=this.context.currentTime+e;this.source.stop(t),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Z={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},T=class n{constructor(e={}){this.ctx=k.audioCtx,this.cfg=structuredClone(Z),Object.assign(this.cfg,e)}ctx;cfg;play(e=k.sfxGain){let t=this.ctx,r=t.currentTime,s=this.cfg,o=t.createGain();o.gain.setValueAtTime(1e-4,r);let l=s.ampEnv;o.gain.exponentialRampToValueAtTime(l.volume,r+l.attack),o.gain.exponentialRampToValueAtTime(Math.max(1e-4,l.sustain*l.volume),r+l.attack+l.decay),o.gain.exponentialRampToValueAtTime(1e-4,r+s.duration+l.release);let h=o,u;s.filter.enabled&&(u=t.createBiquadFilter(),u.type=s.filter.type,u.frequency.value=s.filter.freq,u.Q.value=s.filter.Q,u.connect(o),h=u);let c;if(s.osc.enabled){if(c=t.createOscillator(),c.type=s.osc.type,c.frequency.value=s.osc.freq,c.detune.value=s.osc.detune,s.pitchEnv.amount!==0){let a=Math.pow(2,s.pitchEnv.amount/12);c.frequency.exponentialRampToValueAtTime(s.osc.freq*a,r+s.pitchEnv.decay)}c.connect(h),c.start(r),c.stop(r+s.duration+l.release)}let d;if(s.noise.enabled){let a=t.sampleRate*s.duration,f=t.createBuffer(1,a,t.sampleRate),b=f.getChannelData(0);for(let x=0;x<a;x++)b[x]=(Math.random()*2-1)*s.noise.level;d=t.createBufferSource(),d.buffer=f,d.connect(h),d.start(r),d.stop(r+s.duration+l.release)}let y,m;s.lfo.enabled&&c&&(y=t.createOscillator(),y.frequency.value=s.lfo.rate,m=t.createGain(),m.gain.value=s.lfo.depth,y.connect(m),s.lfo.target==="freq"?m.connect(c.frequency):s.lfo.target==="gain"?m.connect(o.gain):s.lfo.target==="filter"&&u&&m.connect(u.frequency),y.start(r),y.stop(r+s.duration)),o.connect(e);let i=[c,d,y,m,u,o],p=r+s.duration+l.release;setTimeout(()=>{i.forEach(a=>a?.disconnect())},(p-t.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,t){return Object.assign(this.cfg[e],t),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,t,r,s){return Object.assign(this.cfg.ampEnv,{attack:e,decay:t,sustain:r,release:s}),this}setPitchEnv(e,t){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:t}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,t,r){return Object.assign(this.cfg.filter,{type:e,freq:t,Q:r,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,t,r){return Object.assign(this.cfg.lfo,{target:e,rate:t,depth:r,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new n(structuredClone(this.cfg))}},ee=new T({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),te=new T({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),ne=new T({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),re=new T({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),se=new T({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2}),be=new Map([["ui_click",ee],["ui_hover",te],["jump",ne],["laser",re],["hit",se]]);function xe(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(n)),r=Array.from(t).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}function U(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(4)),r=Array.from(t).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}var H=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${ie()}_${Date.now()}`}connect(e){e&&(this.peer=e,e.peer=this,this.connected=!0,e.connected=!0),this._emit("open")}isConnected(){return this.connected&&!!this.peer}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(r=>r!==t))}_emit(e,t){this.events[e]?.forEach(r=>r(t))}send(e,t){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,t)}_receive(e,t){e?this._emit(e,t):this._emit("message",t)}close(){if(this.connected=!1,this.peer){let e=this.peer;this.peer=null,e.peer=null,e.connected=!1,e._emit("close")}this._emit("close")}getKey(){return this.key}};function ie(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let n=new Uint8Array(16);return crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,[...n].map(e=>e.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5")}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function ae(n){let e=!0;function t(){e&&(n(),requestAnimationFrame(t))}return requestAnimationFrame(t),{clear:()=>e=!1}}function oe(n,e,t,r,s){let o=Math.cos(s),l=Math.sin(s),h=[];if(o!==0){let u=(0-n)/o,c=e+u*l;u>0&&c>=0&&c<=r&&h.push({side:"left",t:u})}if(o!==0){let u=(t-n)/o,c=e+u*l;u>0&&c>=0&&c<=r&&h.push({side:"right",t:u})}if(l!==0){let u=(0-e)/l,c=n+u*o;u>0&&c>=0&&c<=t&&h.push({side:"top",t:u})}if(l!==0){let u=(r-e)/l,c=n+u*o;u>0&&c>=0&&c<=t&&h.push({side:"bottom",t:u})}return h.length===0?null:(h.sort((u,c)=>u.t-c.t),h[0])}function ue(n,e){let t;switch(e){case"left":case"right":t=Math.PI-n;break;case"top":case"bottom":t=2*Math.PI-n;break}return(t%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function ge(n,e,t,r,s){let o=oe(n,e,t,r,s);return o?{...o,avoidAngle:ue(s,o.side)}:null}function ce(){return _?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var ve=ce();var V={};W(V,{KaylaFragment:()=>ke,KaylaInternals:()=>S,createElement:()=>Ce,createGame:()=>Ee,createReassignableObject:()=>Me,createRenderer:()=>Te,createScene:()=>we,self:()=>D,useDisposableRef:()=>Pe,useEffect:()=>B,useEntity:()=>Ie,useExports:()=>Re,useNextStack:()=>le,usePaint:()=>$,useRef:()=>L,useSelf:()=>Ke,useState:()=>q,useTick:()=>Se});function Ee({width:n,height:e,updateHz:t="frames"}){return new S.KaylaGame(n,e,t==="frames"?1/0:t)}function we(n){let e=new M(n);return new S.KaylaScene(e)}function Te(n){return new S.KaylaRenderer(n)}function Ce(n,e){return{type:n,props:e}}var S;(y=>{class n extends A{#e;#t;constructor(i,p,a){super(i,p,a),this.#e=new Set,this.#t=!1}get started(){return this.#t}start(){if(!this.#t){for(let i of this.#e)i.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let i of this.#e)i.stop();this.#t=!1,super.stop()}}addRenderer(i){this.#e.has(i)||(this.#e.add(i),this.#t&&i.start(),i.game=this)}deleteRenderer(i){this.#e.has(i)&&(this.#e.delete(i),this.#t&&i.stop(),delete i.game)}}y.KaylaGame=n;class e extends P{game;pointerX;pointerY;#e;constructor(i){super(i),this.useDraw=this.useDraw.bind(this),this.on("draw",p=>{if(this.game)for(let a of this.game.scenes.values())a.handleDraw(p)}),this.pointerX=0,this.pointerY=0,this.#e=this.#t.bind(this)}#t(i){this.pointerX=i.clientX,this.pointerY=i.clientY}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.#e)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.#e)}pointerPosToWorldPos(i,p){let a=this.canvas.getBoundingClientRect(),f=(i-a.left)/a.width,b=(p-a.top)/a.height,x=f*this.viewportWidth*this.cameraWidth/a.width,R=b*this.viewportHeight*this.cameraHeight/a.height;return new C(x,R)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(i){let p=a=>{i(a,new r)};return this.on("draw",p),()=>{this.off("draw",p)}}attachTo(i){i.addRenderer(this),this.game=i}detach(){this.game&&this.game.deleteRenderer(this)}}y.KaylaRenderer=e;class t{current;saves;constructor(){this.saves=[]}useTick(i){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=i,this.current.useStepCallIndex++}usePaint(i){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=i,this.current.useDrawCallIndex++}useEntity(){return L(D)}useSelf(i){let p=L(null);return(p.current===null||p.current===void 0)&&(p.current=i()),p.current}useState(i,{alwaysRecall:p=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let f=this.current.state[this.current.useStateCallIndex]??new s(this.current,i,{alwaysRecall:p});return this.current.state[this.current.useStateCallIndex]=f,this.current.useStateCallIndex++,f}useRef(i){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let a=this.current.refs[this.current.useRefCallIndex]??l(i??null);return this.current.refs[this.current.useRefCallIndex]=a,this.current.useRefCallIndex++,a}useEffect(i){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=i,this.current.useEffectCallIndex++}useExports(i,p){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=p}save(){this.saves.push({current:this.current})}restore(){let i=this.saves.pop();if(!i)throw new Error("Cannot restore without saving.");this.current=i.current}}y.GlobalKayla=t;class r{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}y.KaylaEvent=r;class s{#e;#t;#n;alwaysRecall;constructor(i,p,{alwaysRecall:a=!1}={}){this.#t=i,this.#e=p??void 0,this.#n=Date.now(),this.alwaysRecall=a}get(){return this.#e}add(i,{recall:p}={}){this.set(this.get()+i,{recall:p})}multiply(i,{recall:p}={}){this.set(this.get()*i,{recall:p})}set(i,{recall:p=!1}={}){let a=this.#e;i!==a&&(this.#e=i,(p||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now())}get value(){return this.#e}get lastChanged(){return this.#n}}y.KaylaState=s;class o{#e;constructor(i){this.#e=i??void 0}#t;setSetter(i){this.#t=i}get current(){return this.#e}set current(i){this.#e=i,this.#t&&this.#t(this.#e)}}y.KaylaInternalRef=o;function l(m){return new o(m)}y.createReassignableRef=l;class h{state;refs;global;callProps;scene;exports;constructor(i,p,a){if(!a)throw new Error("Empty element");this.scene=p,this.state=[],this.refs=[],this.fc=a.type,this.callProps=a.props??{},this.global=i,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[]}get key(){return this.callProps.key}set key(i){this.callProps.key=i}get children(){return this.callProps.children}set children(i){this.callProps.children=i}entity;onExport=()=>({});onEffect;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;lastStateDeps;refresh(){let i;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0;let p=[];try{let a=this.fc(this.callProps)??[];if(a&&!Array.isArray(a)&&(a=[a]),!Array.isArray(a))throw new Error("Non array or non undefined children received.");p=a}catch(a){i=a}this.useStateCallIndex=0,this.useRefCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.global.restore();try{let a=0,f=[];for(let b of p){let x=this.lastChildren.at(a)??new h(this.global,this.scene,b);this.lastChildren[a]=x,f.push(x),a++}for(let b of this.lastChildren.filter(x=>!f.includes(x))){let x=this.lastChildren.indexOf(b);x!==1&&this.lastChildren.splice(x,1),b.unuse()}for(let b of this.lastChildren)try{b.refresh()}catch(x){console.error(x)}le(()=>{this.use()})}catch(a){console.error(a)}if(i)throw i}lastChildren;isFirstUse=!0;use(){try{let i=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(i=this.onEffectDeps.some((p,a)=>{let f=this.lastStateDeps.at(a);if(f){let b=p.lastChanged,x=f.stamp;return b>x}})),i||this.isFirstUse){this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(a=>({stamp:a.lastChanged,stateRef:a}))),this.key??=this.fc.name+"_"+U(),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new u(this,this.key);for(let a of this.refs)a.current===D&&(a.current=this.entity);this.callProps.ref instanceof o&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof o&&(this.callProps.exportsRef.current=this.exports),this.scene.getScene().addEntity(this.entity);let p=this.onEffect.map(a=>a()).filter(a=>a!==void 0);this.onUnEffect=p}}catch(i){throw i}}unuse(){try{for(let i of this.onUnEffect)i()}catch(i){console.error(i)}this.scene.getScene().removeEntity(this.entity)}}y.KaylaFiber=h;class u extends F{#e;constructor(i,p){super(p,0,0,0,0),this.#e=i}update(i){let p=new r;if(this.#e.onTick)for(let a of this.#e.onTick)a(i,p);p.isPrevented()}draw(i){let p=new r;if(this.#e.onPaint)for(let a of this.#e.onPaint)a(i,p);p.isPrevented()||super.draw(i)}}y.KaylaRectEntity=u;class c{constructor(i){this.#t=i,this.#e=null,i.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getScene(){return this.#t}drawHandler(i){return this.#t.handleDraw(i)}attachTo(i){i.addScene(this.#t),this.#e=i}spawn(i){new h(y.singleGlobalInstance,this,i).refresh()}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}y.KaylaScene=c,y.singleGlobalInstance=new y.GlobalKayla})(S||={});var g=S.singleGlobalInstance,q=g.useState.bind(g),L=g.useRef.bind(g),B=g.useEffect.bind(g),Se=g.useTick.bind(g),$=g.usePaint.bind(g),Re=g.useExports.bind(g),Ke=g.useSelf.bind(g),Ie=g.useEntity.bind(g),D=Symbol("self_ref");var le=n=>{Promise.resolve(1).then(()=>n())},ke=({children:n})=>Array.isArray(n)?[...n]:n;function Pe(n){return S.createReassignableRef(n)}function Me(n){if(typeof n!="object"||typeof n=="function"||n===null)return n;let e={current:n};return new Proxy({},{get(r,s,o){return s==="reassignSelf"?l=>{e.current=l}:Reflect.get(e.current,s,o)},set(r,s,o,l){return Reflect.set(e.current,s,o,l)},has(r,s){return Reflect.has(e.current,s)},ownKeys(r){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(r,s){return Reflect.getOwnPropertyDescriptor(e.current,s)},deleteProperty(r,s){return Reflect.deleteProperty(e.current,s)}})}Reflect.set(globalThis,"Kayla",V);var Ae;(e=>e.UIComponent=({x:t,y:r,width:s,height:o,children:l})=>{let h=L(D),u=q(!1);return B(()=>{if(u.get()===!0)return;u.set(!0);let c=h.current;c.width=s,c.height=o,c.x=t,c.y=r}),$(c=>{c.fillStyle="rgba(0, 0, 0, 0.5)",c.fillRect(t,r,s,o)}),l??[]})(Ae||={});var Ve={LEA:z,Kayla:V};export{V as Kayla,z as LEA,Ve as default};
@@ -1 +1 @@
1
- "use strict";var G=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var $=(n,e)=>{for(var t in e)G(n,t,{get:e[t],enumerable:!0})},te=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Z(e))!ee.call(n,i)&&i!==t&&G(n,i,{get:()=>e[i],enumerable:!(r=J(e,i))||r.enumerable});return n};var ne=n=>te(G({},"__esModule",{value:!0}),n);var ve={};$(ve,{Fragment:()=>ge,jsx:()=>be,jsxDEV:()=>xe,jsxs:()=>Q});module.exports=ne(ve);var B={};$(B,{KaylaFragment:()=>q,KaylaInternals:()=>T,createElement:()=>L,createGame:()=>ue,createRenderer:()=>ce,createScene:()=>le,self:()=>P,useDisposableRef:()=>me,useEffect:()=>X,useEntity:()=>de,useExports:()=>pe,useNextStack:()=>Y,usePaint:()=>U,useRef:()=>k,useSelf:()=>fe,useState:()=>H,useTick:()=>he});var w=class{#e=new Map;constructor(){this.#e=new Map}on(e,t){let r=this.#e.get(e)||[];return r.push(t),this.#e.set(e,r),this}once(e,t){let r=(...i)=>{this.off(e,r),t(...i)};return this.on(e,r),this}off(e,t){let r=this.#e.get(e);if(!r)return this;let i=r.indexOf(t);return i>=0&&r.splice(i,1),this}emit(e,...t){let r=this.#e.get(e);if(!r||r.length===0){if(e==="error")throw t[0];return!1}return r.slice().forEach(i=>i(...t)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},F=class extends w{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:t,viewportHeight:r,cameraWidth:i,cameraHeight:o}={}){if(!v)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=t??e.width,this.#t=r??e.height,this.#n=i??e.width,this.#r=o??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,t=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,t),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!v)return;let e=performance.now(),t=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=t,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!v||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!v||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},N=class extends w{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),t=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,this.#e+=t*1e3,this.emit("tick",t)}createTimeout(e){return new O(e,this)}createTween(e,t=()=>{}){let r=new z(e),i=(o=0)=>{if(r.finished){this.off("tick",i);return}r.update(o)};return r.on("finish",()=>{this.off("tick",i)}),r.on("delta",o=>{t(o)}),this.on("tick",i),r}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=v&&!isFinite(this.tickInterval)?ae(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,t=0){return .5+.5*Math.sin((this.now()%e/e+t)*2*Math.PI)}},re;(a=>{function n(h){return h===!0?1:0}a.booleanExport=n;function e(h){return h===0?!1:h===1}a.booleanImport=e;function t(h){return`${h.x}|${h.y}`}a.vec2Export=t;function r(h){let[m,b]=h.split("|"),E=parseFloat(m),M=parseFloat(b);if(isNaN(E)||isNaN(M))throw new Error(`Invalid Vector2 string: ${h}`);return new S(E,M)}a.vec2Import=r,a.booleanMap={mapExport:n,mapImport:e};function o(h){return m=>Number(m.toFixed(h))}a.createRounder=o;function p(h=10){return{mapExport(m){return Math.round(m/h)},mapImport(m){return m*h}}}a.createLowPrecision=p;function f(h){return Math.round(h)}a.lightWeightRounder=f;function l(h=100){return{mapExport(m){return Math.round(m*h)},mapImport(m){return m/h}}}a.createPercent=l;function u(h){let m=new Map(Object.entries(h));return{mapExport:b=>m.get(b)??null,mapImport:b=>Array.from(m.entries()).find(([E,M])=>M===b)?.[0]??null}}a.createLookup=u;function d(h){let m=h*(180/Math.PI);return Math.round((m%360+360)%360)}a.radToDeg=d;function y(h){return h*(Math.PI/180)}a.degToRad=y,a.angleRadToDeg={mapExport:d,mapImport:y};function c(h=10){let m=p(h);return{mapExport(b){return m.mapExport(d(b))},mapImport(b){return m.mapImport(y(b))}}}a.createLowPrecisionRadToDeg=c})(re||={});var K=class n extends w{name="";scaleRotate=0;scale=1;constructor(e,t=0,r=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new S(t,r),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(t){this.emit("error",t)}}handleDraw(e){if(!(D||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(t){this.emit("error",t)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([i,{mapExport:o}])=>{let p=Reflect.get(this,i);return o?o(p):p});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],t=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(i=>!this.nonSerializableProperties.includes(i)&&!e.includes(i.toString())),r=Object.fromEntries(t.map(i=>{let o=Reflect.get(this,i);if(D&&typeof o=="number"){let p=o.toString().split("."),l=(p[1]?p[1].length:0)>2?Number(o.toFixed(2)):o;return[i,l]}return[i,o]}));return JSON.parse(JSON.stringify(r))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return n.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,t){if(!e||!Array.isArray(t))return t;let r={};for(let i=0;i<t.length;i++){let o=e[i];if(!o)break;let[p,{mapImport:f}]=o,l=t[i];if(f&&(l=f(l)),typeof p!="string")break;try{Reflect.set(r,p,l)}catch(u){console.error(u)}}return r}},_=class extends w{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let t of this.entities.values())t.handleUpdate(e)}}handleDraw(e){if(!D&&!this.paused){this.emit("draw",e);for(let t of[...this.entities.values()].sort((r,i)=>r.z-i.z))t.handleDraw(e)}}addEntity(e){if(!(e instanceof K))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof K))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},A=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,t,r=16){this.ticker=new N(r),this.scenes=new Map,this.width=e,this.height=t,this.ticker.on("tick",i=>{for(let o of this.scenes.values())o.paused||o.handleUpdate(i)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},g={lerp(n,e,t){return n+(e-n)*t},clamp(n,e,t){return Math.min(t,Math.max(e,n))},clamp01(n){return Math.min(1,Math.max(0,n))},easeLinear(n){return n},easeInQuad(n){return n*n},easeOutQuad(n){return 1-(1-n)*(1-n)},easeInOutQuad(n){return n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2},easeInSine(n){return 1-Math.cos(n*Math.PI/2)},easeOutSine(n){return Math.sin(n*Math.PI/2)},easeInOutSine(n){return-(Math.cos(Math.PI*n)-1)/2},easeInExpo(n){return n===0?0:Math.pow(2,10*n-10)},easeOutExpo(n){return n===1?1:1-Math.pow(2,-10*n)},easeInOutExpo(n){return n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2},smoothstep(n){return n=g.clamp(n,0,1),n*n*(3-2*n)},randomLerp(n,e){return g.lerp(n,e,Math.random())},randomInt(n,e){return Math.floor(Math.random()*(e-n+1))+n},randomArrayValue(n){return n[g.randomInt(0,n.length-1)]},createBezier(n,e,t,r){function i(f,l,u,d,y){let s=1-f;return s*s*s*l+3*s*s*f*u+3*s*f*f*d+f*f*f*y}function o(f,l,u,d,y){let s=1-f;return 3*s*s*(u-l)+6*s*f*(d-u)+3*f*f*(y-d)}function p(f){let l=f;for(let u=0;u<6;u++){let d=i(l,0,n,t,1),y=o(l,0,n,t,1);if(y===0)break;l-=(d-f)/y}return g.clamp(l,0,1)}return function(l){l=g.clamp(l,0,1);let u=p(l);return i(u,0,e,r,1)}},lengthSquared(...n){return n.reduce((e,t)=>e+t*t,0)},normalizeRad(n){let e=2*Math.PI;return n=n%e,n<0&&(n+=e),n},angleInvertY(n){return g.normalizeRad(-n)},degToRadFlipY(n){return g.angleInvertY(n*Math.PI/180)},minimalAngularDirection(n,e){n=g.normalizeRad(n),e=g.normalizeRad(e);let t=g.normalizeRad(e-n),r=g.normalizeRad(n-e);return t<=r?1:-1}},z=class extends w{constructor({delta:e,ms:t,easing:r}){super(),this.delta=e,this.duration=t,this.elapsed=0,this.easing=r??(i=>i),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let t=g.clamp(this.elapsed/this.duration,0,1),r=this.easing(t),i=this.delta*r,o=i-this.lastValue;this.lastValue=i,this.emit("delta",o),t>=1&&(this.finished=!0,this.emit("finish",void 0))}},V=class extends K{constructor(e,t=0,r=0,i=50,o=50){super(e,t,r),this.width=i,this.height=o}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},O=class extends w{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,t=null){super(),this.duration=e,this.ticker=t,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(r=>this._resolve=r),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,t){return this.promise.then(e,t)}after(e,t){return this.promise.then(e,t)}},S=class n{constructor(e=0,t=0){this.x=e,this.y=t}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let t=Math.cos(e),r=Math.sin(e);return new n(this.x*t-this.y*r,this.x*r+this.y*t)}static from(e){return new n(Math.cos(e),Math.sin(e))}get angle(){return Math.atan2(this.y,this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new n(0,0):new n(this.x/e,this.y/e)}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let t=this.dot(e);return this.subtract(e.scale(2*t))}dotNormalized(e){let t=this.normalized(),r=e.normalized();return t.x*r.x+t.y*r.y}lengthSquaredTo(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}directionTo(e){return new n(e.x-this.x,e.y-this.y).normalized()}add(e){return new n(this.x+e.x,this.y+e.y)}addRaw(e){return new n(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new n(this.x-e.x,this.y-e.y)}scale(e){return new n(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new n(this.x,this.y)}};function se(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var W=se(),D=W==="node",v=W==="web",R=class n{static unlock(){v&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=v?new AudioContext:null;static masterGain=v?this.audioCtx.createGain():null;static musicGain=v?this.audioCtx.createGain():null;static sfxGain=v?this.audioCtx.createGain():null;static{v&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let t=n.CACHE_NAME,r,i;if(typeof caches<"u"&&(i=await caches.open(t),r=await i.match(e)),!r){if(r=await fetch(e),!r.ok)throw new Error(`Failed to fetch ${e}`);i&&await i.put(e,r.clone())}let o=await r.arrayBuffer(),p=await this.audioCtx.decodeAudioData(o);return this.audioBufferCache.set(e,p),p}static async getOnlyDownloadedCache(e){let t=n.CACHE_NAME;return await(await caches.open(t)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,t=.2,r=1,i=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return;let p=new I(o);p.buffer=o;let f=1-.12,l=1+.12;p.playbackRate=r??f+Math.random()*(l-f);let u=this.audioCtx.createGain();u.gain.value=t,p.tempGain=u,p.connect(u),u.connect(this.sfxGain),p.onended=()=>{p.disconnect(),u.disconnect()},p.start(),i&&this.sfsx.set(e,{source:p,gain:u})}catch(o){console.error(o)}}static async playLoop(e,t=1,{loopStart:r=0,loopEnd:i=null,exclusive:o=!0,skipMS:p=0}={}){if(o)for(let y of this.loops.keys())this.stopLoop(y);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let l=new I(f);l.buffer=f,l.loop=!0,typeof r=="number"&&(l.loopStart=r),typeof i=="number"&&(l.loopEnd=i);let u=this.audioCtx.createGain();u.gain.value=t,l.tempGain=u,l.playbackRate=1,l.onended=()=>{l.disconnect(),u.disconnect()},l.connect(u),u.connect(this.musicGain),l.start(0,p/1e3);let d=++this.loopIdCounter;return this.loops.set(d,{source:l,gain:u}),d}static stopLoop(e){let t=this.loops.get(e);t&&(t.source.stop(),t.source.notIndependent||(t.source.disconnect(),t.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:t=1,speed:r=1,loop:i=!1,loopStart:o=0,loopEnd:p=null,isMusic:f=!1,gain:l=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let u=this.getCached(e);if(!u)return null;let d=new I(u);d.loop=i,d.loopStart=o,d.loopEnd=typeof p=="number"?p:u.duration,d.playbackRate=r;let y=this.audioCtx.createGain();return y.gain.value=t,d.connect(y),d.tempGain=y,y.connect(l||(f?this.musicGain:this.sfxGain)),d.onended=()=>{d.disconnect(),y.disconnect()},d}catch(u){return console.error("Failed to create LiaAudioSrc:",u),null}}};var I=class{numberOfInputs;numberOfOutputs;constructor(e,t=R.audioCtx){this.context=t,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=v?t.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:t=null}={}){let r=t!==null?t:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-r/this.playbackRate,this.source.start(0,r),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,t=0,r){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-t/this.playbackRate,r!==void 0?this.source.start(this.context.currentTime+e,t,r):this.source.start(this.context.currentTime+e,t),this.pauseTime=t,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let t=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let r=this.loopEnd-this.loopStart;t=this.loopStart+(t-this.loopStart)%r}if(this.isPlaying=!1,e>0){let r=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,r),this.output.gain.linearRampToValueAtTime(0,r+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let t=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=t,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,t=0,r=0){if("value"in e)this.output.connect(e,t);else return this.output.connect(e,t,r),e}disconnect(e,t,r){e===void 0?this.output.disconnect():this.output.disconnect(e,t,r)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let t=this.context.currentTime+e;this.source.stop(t),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},ie={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},C=class n{constructor(e={}){this.ctx=R.audioCtx,this.cfg=structuredClone(ie),Object.assign(this.cfg,e)}ctx;cfg;play(e=R.sfxGain){let t=this.ctx,r=t.currentTime,i=this.cfg,o=t.createGain();o.gain.setValueAtTime(1e-4,r);let p=i.ampEnv;o.gain.exponentialRampToValueAtTime(p.volume,r+p.attack),o.gain.exponentialRampToValueAtTime(Math.max(1e-4,p.sustain*p.volume),r+p.attack+p.decay),o.gain.exponentialRampToValueAtTime(1e-4,r+i.duration+p.release);let f=o,l;i.filter.enabled&&(l=t.createBiquadFilter(),l.type=i.filter.type,l.frequency.value=i.filter.freq,l.Q.value=i.filter.Q,l.connect(o),f=l);let u;if(i.osc.enabled){if(u=t.createOscillator(),u.type=i.osc.type,u.frequency.value=i.osc.freq,u.detune.value=i.osc.detune,i.pitchEnv.amount!==0){let h=Math.pow(2,i.pitchEnv.amount/12);u.frequency.exponentialRampToValueAtTime(i.osc.freq*h,r+i.pitchEnv.decay)}u.connect(f),u.start(r),u.stop(r+i.duration+p.release)}let d;if(i.noise.enabled){let h=t.sampleRate*i.duration,m=t.createBuffer(1,h,t.sampleRate),b=m.getChannelData(0);for(let E=0;E<h;E++)b[E]=(Math.random()*2-1)*i.noise.level;d=t.createBufferSource(),d.buffer=m,d.connect(f),d.start(r),d.stop(r+i.duration+p.release)}let y,s;i.lfo.enabled&&u&&(y=t.createOscillator(),y.frequency.value=i.lfo.rate,s=t.createGain(),s.gain.value=i.lfo.depth,y.connect(s),i.lfo.target==="freq"?s.connect(u.frequency):i.lfo.target==="gain"?s.connect(o.gain):i.lfo.target==="filter"&&l&&s.connect(l.frequency),y.start(r),y.stop(r+i.duration)),o.connect(e);let c=[u,d,y,s,l,o],a=r+i.duration+p.release;setTimeout(()=>{c.forEach(h=>h?.disconnect())},(a-t.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,t){return Object.assign(this.cfg[e],t),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,t,r,i){return Object.assign(this.cfg.ampEnv,{attack:e,decay:t,sustain:r,release:i}),this}setPitchEnv(e,t){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:t}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,t,r){return Object.assign(this.cfg.filter,{type:e,freq:t,Q:r,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,t,r){return Object.assign(this.cfg.lfo,{target:e,rate:t,depth:r,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new n(structuredClone(this.cfg))}},we=new C({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Ce=new C({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Te=new C({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),Se=new C({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),Ie=new C({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function j(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(4)),r=Array.from(t).map(i=>i.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}function ae(n){let e=!0;function t(){e&&(n(),requestAnimationFrame(t))}return requestAnimationFrame(t),{clear:()=>e=!1}}function oe(){return D?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var Ke=oe();function ue({width:n,height:e,updateHz:t="frames"}){return new T.KaylaGame(n,e,t==="frames"?1/0:t)}function le(n){let e=new _(n);return new T.KaylaScene(e)}function ce(n){return new T.KaylaRenderer(n)}function L(n,e){return{type:n,props:e}}var T;(d=>{class n extends A{#e;#t;constructor(s,c,a){super(s,c,a),this.#e=new Set,this.#t=!1}get started(){return this.#t}start(){if(!this.#t){for(let s of this.#e)s.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let s of this.#e)s.stop();this.#t=!1,super.stop()}}addRenderer(s){this.#e.has(s)||(this.#e.add(s),this.#t&&s.start(),s.game=this)}deleteRenderer(s){this.#e.has(s)&&(this.#e.delete(s),this.#t&&s.stop(),delete s.game)}}d.KaylaGame=n;class e extends F{game;pointerX;pointerY;#e;constructor(s){super(s),this.useDraw=this.useDraw.bind(this),this.on("draw",c=>{if(this.game)for(let a of this.game.scenes.values())a.handleDraw(c)}),this.pointerX=0,this.pointerY=0,this.#e=this.#t.bind(this)}#t(s){this.pointerX=s.clientX,this.pointerY=s.clientY}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.#e)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.#e)}pointerPosToWorldPos(s,c){let a=this.canvas.getBoundingClientRect(),h=(s-a.left)/a.width,m=(c-a.top)/a.height,b=h*this.viewportWidth*this.cameraWidth/a.width,E=m*this.viewportHeight*this.cameraHeight/a.height;return new S(b,E)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(s){let c=a=>{s(a,new r)};return this.on("draw",c),()=>{this.off("draw",c)}}attachTo(s){s.addRenderer(this),this.game=s}detach(){this.game&&this.game.deleteRenderer(this)}}d.KaylaRenderer=e;class t{current;saves;constructor(){this.saves=[]}useTick(s){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=s,this.current.useStepCallIndex++}usePaint(s){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=s,this.current.useDrawCallIndex++}useEntity(){return k(P)}useSelf(s){let c=k(null);return(c.current===null||c.current===void 0)&&(c.current=s()),c.current}useState(s,{alwaysRecall:c=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let h=this.current.state[this.current.useStateCallIndex]??new i(this.current,s,{alwaysRecall:c});return this.current.state[this.current.useStateCallIndex]=h,this.current.useStateCallIndex++,h}useRef(s){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let a=this.current.refs[this.current.useRefCallIndex]??new o(this.current,s??null);return this.current.refs[this.current.useRefCallIndex]=a,this.current.useRefCallIndex++,a}useEffect(s){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=s,this.current.useEffectCallIndex++}useExports(s,c){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=c}save(){this.saves.push({current:this.current})}restore(){let s=this.saves.pop();if(!s)throw new Error("Cannot restore without saving.");this.current=s.current}}d.GlobalKayla=t;class r{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}d.KaylaEvent=r;class i{#e;#t;#n;alwaysRecall;constructor(s,c,{alwaysRecall:a=!1}={}){this.#t=s,this.#e=c??void 0,this.#n=Date.now(),this.alwaysRecall=a}get(){return this.#e}add(s,{recall:c}={}){this.set(this.get()+s,{recall:c})}multiply(s,{recall:c}={}){this.set(this.get()*s,{recall:c})}set(s,{recall:c=!1}={}){let a=this.#e;s!==a&&(this.#e=s,(c||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now())}get value(){return this.#e}get lastChanged(){return this.#n}}d.KaylaState=i;class o{#e;#t;constructor(s,c){this.#t=s,this.#e=c??void 0}get current(){return this.#e}set current(s){this.#e=s}}d.KaylaRef=o;class p{state;refs;global;callProps;scene;exports;constructor(s,c,a){if(!a)throw new Error("Empty element");this.scene=c,this.state=[],this.refs=[],this.fc=a.type,this.callProps=a.props??{},this.global=s,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[]}get key(){return this.callProps.key}set key(s){this.callProps.key=s}get children(){return this.callProps.children}set children(s){this.callProps.children=s}entity;onExport=()=>({});onEffect;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;lastStateDeps;refresh(){let s;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0;let c=[];try{let a=this.fc(this.callProps)??[];if(a&&!Array.isArray(a)&&(a=[a]),!Array.isArray(a))throw new Error("Non array or non undefined children received.");c=a}catch(a){s=a}this.useStateCallIndex=0,this.useRefCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.global.restore();try{let a=0,h=[];for(let m of c){let b=this.lastChildren.at(a)??new p(this.global,this.scene,m);this.lastChildren[a]=b,h.push(b),a++}for(let m of this.lastChildren.filter(b=>!h.includes(b))){let b=this.lastChildren.indexOf(m);b!==1&&this.lastChildren.splice(b,1),m.unuse()}for(let m of this.lastChildren)try{m.refresh()}catch(b){console.error(b)}Y(()=>{this.use()})}catch(a){console.error(a)}if(s)throw s}lastChildren;isFirstUse=!0;use(){try{let s=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(s=this.onEffectDeps.some((c,a)=>{let h=this.lastStateDeps.at(a);if(h){let m=c.lastChanged,b=h.stamp;return m>b}})),s||this.isFirstUse){this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(a=>({stamp:a.lastChanged,stateRef:a}))),this.key??=this.fc.name+"_"+j(),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new f(this,this.key);for(let a of this.refs)a.current===P&&(a.current=this.entity);this.callProps.ref instanceof o&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof o&&(this.callProps.exportsRef.current=this.exports),this.scene.getScene().addEntity(this.entity);let c=this.onEffect.map(a=>a()).filter(a=>a!==void 0);this.onUnEffect=c}}catch(s){throw s}}unuse(){try{for(let s of this.onUnEffect)s()}catch(s){console.error(s)}this.scene.getScene().removeEntity(this.entity)}}d.KaylaInternalComponent=p;class f extends V{#e;constructor(s,c){super(c,0,0,0,0),this.#e=s}update(s){let c=new r;if(this.#e.onTick)for(let a of this.#e.onTick)a(s,c);c.isPrevented()}draw(s){let c=new r;if(this.#e.onPaint)for(let a of this.#e.onPaint)a(s,c);c.isPrevented()||super.draw(s)}}d.KaylaRectEntity=f;class l{constructor(s){this.#t=s,this.#e=null,s.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getScene(){return this.#t}drawHandler(s){return this.#t.handleDraw(s)}attachTo(s){s.addScene(this.#t),this.#e=s}spawn(s){new p(d.singleGlobalInstance,this,s).refresh()}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}d.KaylaScene=l,d.singleGlobalInstance=new d.GlobalKayla})(T||={});var x=T.singleGlobalInstance,H=x.useState.bind(x),k=x.useRef.bind(x),X=x.useEffect.bind(x),he=x.useTick.bind(x),U=x.usePaint.bind(x),pe=x.useExports.bind(x),fe=x.useSelf.bind(x),de=x.useEntity.bind(x),P=Symbol("self_ref");var Y=n=>{Promise.resolve(1).then(()=>n())},q=({children:n})=>Array.isArray(n)?[...n]:n;function me(n){return new T.KaylaRef(null,n)}Reflect.set(globalThis,"Kayla",B);var ye;(e=>e.UIComponent=({x:t,y:r,width:i,height:o,children:p})=>{let f=k(P),l=H(!1);return X(()=>{if(l.get()===!0)return;l.set(!0);let u=f.current;u.width=i,u.height=o,u.x=t,u.y=r}),U(u=>{u.fillStyle="rgba(0, 0, 0, 0.5)",u.fillRect(t,r,i,o)}),p??[]})(ye||={});function be(n,e,...t){if(typeof n=="string")throw new Error("Cannot use intrinsic elements.");return L(n,{...e,children:e.children??t})}function Q(n,e,...t){if(typeof n=="string")throw new Error("Cannot use intrinsic elements.");return L(n,{...e,children:e.children??t})}function xe(n,e){return Q(n,e)}var ge=q;0&&(module.exports={Fragment,jsx,jsxDEV,jsxs});
1
+ "use strict";var G=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var $=(n,e)=>{for(var t in e)G(n,t,{get:e[t],enumerable:!0})},te=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Z(e))!ee.call(n,s)&&s!==t&&G(n,s,{get:()=>e[s],enumerable:!(r=J(e,s))||r.enumerable});return n};var ne=n=>te(G({},"__esModule",{value:!0}),n);var we={};$(we,{Fragment:()=>Ee,jsx:()=>ge,jsxDEV:()=>ve,jsxs:()=>Q});module.exports=ne(we);var B={};$(B,{KaylaFragment:()=>q,KaylaInternals:()=>C,createElement:()=>V,createGame:()=>le,createReassignableObject:()=>be,createRenderer:()=>he,createScene:()=>ce,self:()=>M,useDisposableRef:()=>ye,useEffect:()=>X,useEntity:()=>me,useExports:()=>fe,useNextStack:()=>Y,usePaint:()=>U,useRef:()=>P,useSelf:()=>de,useState:()=>H,useTick:()=>pe});var w=class{#e=new Map;constructor(){this.#e=new Map}on(e,t){let r=this.#e.get(e)||[];return r.push(t),this.#e.set(e,r),this}once(e,t){let r=(...s)=>{this.off(e,r),t(...s)};return this.on(e,r),this}off(e,t){let r=this.#e.get(e);if(!r)return this;let s=r.indexOf(t);return s>=0&&r.splice(s,1),this}emit(e,...t){let r=this.#e.get(e);if(!r||r.length===0){if(e==="error")throw t[0];return!1}return r.slice().forEach(s=>s(...t)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},F=class extends w{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:t,viewportHeight:r,cameraWidth:s,cameraHeight:o}={}){if(!E)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=t??e.width,this.#t=r??e.height,this.#n=s??e.width,this.#r=o??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,t=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,t),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!E)return;let e=performance.now(),t=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=t,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},N=class extends w{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),t=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,this.#e+=t*1e3,this.emit("tick",t)}createTimeout(e){return new z(e,this)}createTween(e,t=()=>{}){let r=new O(e),s=(o=0)=>{if(r.finished){this.off("tick",s);return}r.update(o)};return r.on("finish",()=>{this.off("tick",s)}),r.on("delta",o=>{t(o)}),this.on("tick",s),r}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=E&&!isFinite(this.tickInterval)?ae(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,t=0){return .5+.5*Math.sin((this.now()%e/e+t)*2*Math.PI)}},re;(c=>{function n(a){return a===!0?1:0}c.booleanExport=n;function e(a){return a===0?!1:a===1}c.booleanImport=e;function t(a){return`${a.x}|${a.y}`}c.vec2Export=t;function r(a){let[f,b]=a.split("|"),x=parseFloat(f),S=parseFloat(b);if(isNaN(x)||isNaN(S))throw new Error(`Invalid Vector2 string: ${a}`);return new R(x,S)}c.vec2Import=r,c.booleanMap={mapExport:n,mapImport:e};function o(a){return f=>Number(f.toFixed(a))}c.createRounder=o;function h(a=10){return{mapExport(f){return Math.round(f/a)},mapImport(f){return f*a}}}c.createLowPrecision=h;function p(a){return Math.round(a)}c.lightWeightRounder=p;function l(a=100){return{mapExport(f){return Math.round(f*a)},mapImport(f){return f/a}}}c.createPercent=l;function u(a){let f=new Map(Object.entries(a));return{mapExport:b=>f.get(b)??null,mapImport:b=>Array.from(f.entries()).find(([x,S])=>S===b)?.[0]??null}}c.createLookup=u;function d(a){let f=a*(180/Math.PI);return Math.round((f%360+360)%360)}c.radToDeg=d;function y(a){return a*(Math.PI/180)}c.degToRad=y,c.angleRadToDeg={mapExport:d,mapImport:y};function i(a=10){let f=h(a);return{mapExport(b){return f.mapExport(d(b))},mapImport(b){return f.mapImport(y(b))}}}c.createLowPrecisionRadToDeg=i})(re||={});var I=class n extends w{name="";scaleRotate=0;scale=1;constructor(e,t=0,r=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new R(t,r),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(t){this.emit("error",t)}}handleDraw(e){if(!(D||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(t){this.emit("error",t)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([s,{mapExport:o}])=>{let h=Reflect.get(this,s);return o?o(h):h});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],t=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(s=>!this.nonSerializableProperties.includes(s)&&!e.includes(s.toString())),r=Object.fromEntries(t.map(s=>{let o=Reflect.get(this,s);if(D&&typeof o=="number"){let h=o.toString().split("."),l=(h[1]?h[1].length:0)>2?Number(o.toFixed(2)):o;return[s,l]}return[s,o]}));return JSON.parse(JSON.stringify(r))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return n.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,t){if(!e||!Array.isArray(t))return t;let r={};for(let s=0;s<t.length;s++){let o=e[s];if(!o)break;let[h,{mapImport:p}]=o,l=t[s];if(p&&(l=p(l)),typeof h!="string")break;try{Reflect.set(r,h,l)}catch(u){console.error(u)}}return r}},A=class extends w{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let t of this.entities.values())t.handleUpdate(e)}}handleDraw(e){if(!D&&!this.paused){this.emit("draw",e);for(let t of[...this.entities.values()].sort((r,s)=>r.z-s.z))t.handleDraw(e)}}addEntity(e){if(!(e instanceof I))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof I))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},_=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,t,r=16){this.ticker=new N(r),this.scenes=new Map,this.width=e,this.height=t,this.ticker.on("tick",s=>{for(let o of this.scenes.values())o.paused||o.handleUpdate(s)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},v={lerp(n,e,t){return n+(e-n)*t},clamp(n,e,t){return Math.min(t,Math.max(e,n))},clamp01(n){return Math.min(1,Math.max(0,n))},easeLinear(n){return n},easeInQuad(n){return n*n},easeOutQuad(n){return 1-(1-n)*(1-n)},easeInOutQuad(n){return n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2},easeInSine(n){return 1-Math.cos(n*Math.PI/2)},easeOutSine(n){return Math.sin(n*Math.PI/2)},easeInOutSine(n){return-(Math.cos(Math.PI*n)-1)/2},easeInExpo(n){return n===0?0:Math.pow(2,10*n-10)},easeOutExpo(n){return n===1?1:1-Math.pow(2,-10*n)},easeInOutExpo(n){return n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2},smoothstep(n){return n=v.clamp(n,0,1),n*n*(3-2*n)},randomLerp(n,e){return v.lerp(n,e,Math.random())},randomInt(n,e){return Math.floor(Math.random()*(e-n+1))+n},randomArrayValue(n){return n[v.randomInt(0,n.length-1)]},createBezier(n,e,t,r){function s(p,l,u,d,y){let m=1-p;return m*m*m*l+3*m*m*p*u+3*m*p*p*d+p*p*p*y}function o(p,l,u,d,y){let m=1-p;return 3*m*m*(u-l)+6*m*p*(d-u)+3*p*p*(y-d)}function h(p){let l=p;for(let u=0;u<6;u++){let d=s(l,0,n,t,1),y=o(l,0,n,t,1);if(y===0)break;l-=(d-p)/y}return v.clamp(l,0,1)}return function(l){l=v.clamp(l,0,1);let u=h(l);return s(u,0,e,r,1)}},lengthSquared(...n){return n.reduce((e,t)=>e+t*t,0)},normalizeRad(n){let e=2*Math.PI;return n=n%e,n<0&&(n+=e),n},angleInvertY(n){return v.normalizeRad(-n)},degToRadFlipY(n){return v.angleInvertY(n*Math.PI/180)},minimalAngularDirection(n,e){n=v.normalizeRad(n),e=v.normalizeRad(e);let t=v.normalizeRad(e-n),r=v.normalizeRad(n-e);return t<=r?1:-1}},O=class extends w{constructor({delta:e,ms:t,easing:r}){super(),this.delta=e,this.duration=t,this.elapsed=0,this.easing=r??(s=>s),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let t=v.clamp(this.elapsed/this.duration,0,1),r=this.easing(t),s=this.delta*r,o=s-this.lastValue;this.lastValue=s,this.emit("delta",o),t>=1&&(this.finished=!0,this.emit("finish",void 0))}},L=class extends I{constructor(e,t=0,r=0,s=50,o=50){super(e,t,r),this.width=s,this.height=o}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},z=class extends w{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,t=null){super(),this.duration=e,this.ticker=t,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(r=>this._resolve=r),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,t){return this.promise.then(e,t)}after(e,t){return this.promise.then(e,t)}},R=class n{constructor(e=0,t=0){this.x=e,this.y=t}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let t=Math.cos(e),r=Math.sin(e);return new n(this.x*t-this.y*r,this.x*r+this.y*t)}static from(e){return new n(Math.cos(e),Math.sin(e))}get angle(){return Math.atan2(this.y,this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new n(0,0):new n(this.x/e,this.y/e)}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let t=this.dot(e);return this.subtract(e.scale(2*t))}dotNormalized(e){let t=this.normalized(),r=e.normalized();return t.x*r.x+t.y*r.y}lengthSquaredTo(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}directionTo(e){return new n(e.x-this.x,e.y-this.y).normalized()}add(e){return new n(this.x+e.x,this.y+e.y)}addRaw(e){return new n(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new n(this.x-e.x,this.y-e.y)}scale(e){return new n(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new n(this.x,this.y)}};function se(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var j=se(),D=j==="node",E=j==="web",k=class n{static unlock(){E&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=E?new AudioContext:null;static masterGain=E?this.audioCtx.createGain():null;static musicGain=E?this.audioCtx.createGain():null;static sfxGain=E?this.audioCtx.createGain():null;static{E&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let t=n.CACHE_NAME,r,s;if(typeof caches<"u"&&(s=await caches.open(t),r=await s.match(e)),!r){if(r=await fetch(e),!r.ok)throw new Error(`Failed to fetch ${e}`);s&&await s.put(e,r.clone())}let o=await r.arrayBuffer(),h=await this.audioCtx.decodeAudioData(o);return this.audioBufferCache.set(e,h),h}static async getOnlyDownloadedCache(e){let t=n.CACHE_NAME;return await(await caches.open(t)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,t=.2,r=1,s=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return;let h=new K(o);h.buffer=o;let p=1-.12,l=1+.12;h.playbackRate=r??p+Math.random()*(l-p);let u=this.audioCtx.createGain();u.gain.value=t,h.tempGain=u,h.connect(u),u.connect(this.sfxGain),h.onended=()=>{h.disconnect(),u.disconnect()},h.start(),s&&this.sfsx.set(e,{source:h,gain:u})}catch(o){console.error(o)}}static async playLoop(e,t=1,{loopStart:r=0,loopEnd:s=null,exclusive:o=!0,skipMS:h=0}={}){if(o)for(let y of this.loops.keys())this.stopLoop(y);this.audioBufferCache.has(e)||await this.preLoad(e);let p=this.getCached(e);if(!p)return;let l=new K(p);l.buffer=p,l.loop=!0,typeof r=="number"&&(l.loopStart=r),typeof s=="number"&&(l.loopEnd=s);let u=this.audioCtx.createGain();u.gain.value=t,l.tempGain=u,l.playbackRate=1,l.onended=()=>{l.disconnect(),u.disconnect()},l.connect(u),u.connect(this.musicGain),l.start(0,h/1e3);let d=++this.loopIdCounter;return this.loops.set(d,{source:l,gain:u}),d}static stopLoop(e){let t=this.loops.get(e);t&&(t.source.stop(),t.source.notIndependent||(t.source.disconnect(),t.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:t=1,speed:r=1,loop:s=!1,loopStart:o=0,loopEnd:h=null,isMusic:p=!1,gain:l=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let u=this.getCached(e);if(!u)return null;let d=new K(u);d.loop=s,d.loopStart=o,d.loopEnd=typeof h=="number"?h:u.duration,d.playbackRate=r;let y=this.audioCtx.createGain();return y.gain.value=t,d.connect(y),d.tempGain=y,y.connect(l||(p?this.musicGain:this.sfxGain)),d.onended=()=>{d.disconnect(),y.disconnect()},d}catch(u){return console.error("Failed to create LiaAudioSrc:",u),null}}};var K=class{numberOfInputs;numberOfOutputs;constructor(e,t=k.audioCtx){this.context=t,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=E?t.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:t=null}={}){let r=t!==null?t:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-r/this.playbackRate,this.source.start(0,r),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,t=0,r){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-t/this.playbackRate,r!==void 0?this.source.start(this.context.currentTime+e,t,r):this.source.start(this.context.currentTime+e,t),this.pauseTime=t,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let t=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let r=this.loopEnd-this.loopStart;t=this.loopStart+(t-this.loopStart)%r}if(this.isPlaying=!1,e>0){let r=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,r),this.output.gain.linearRampToValueAtTime(0,r+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let t=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=t,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,t=0,r=0){if("value"in e)this.output.connect(e,t);else return this.output.connect(e,t,r),e}disconnect(e,t,r){e===void 0?this.output.disconnect():this.output.disconnect(e,t,r)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let t=this.context.currentTime+e;this.source.stop(t),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},ie={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},T=class n{constructor(e={}){this.ctx=k.audioCtx,this.cfg=structuredClone(ie),Object.assign(this.cfg,e)}ctx;cfg;play(e=k.sfxGain){let t=this.ctx,r=t.currentTime,s=this.cfg,o=t.createGain();o.gain.setValueAtTime(1e-4,r);let h=s.ampEnv;o.gain.exponentialRampToValueAtTime(h.volume,r+h.attack),o.gain.exponentialRampToValueAtTime(Math.max(1e-4,h.sustain*h.volume),r+h.attack+h.decay),o.gain.exponentialRampToValueAtTime(1e-4,r+s.duration+h.release);let p=o,l;s.filter.enabled&&(l=t.createBiquadFilter(),l.type=s.filter.type,l.frequency.value=s.filter.freq,l.Q.value=s.filter.Q,l.connect(o),p=l);let u;if(s.osc.enabled){if(u=t.createOscillator(),u.type=s.osc.type,u.frequency.value=s.osc.freq,u.detune.value=s.osc.detune,s.pitchEnv.amount!==0){let a=Math.pow(2,s.pitchEnv.amount/12);u.frequency.exponentialRampToValueAtTime(s.osc.freq*a,r+s.pitchEnv.decay)}u.connect(p),u.start(r),u.stop(r+s.duration+h.release)}let d;if(s.noise.enabled){let a=t.sampleRate*s.duration,f=t.createBuffer(1,a,t.sampleRate),b=f.getChannelData(0);for(let x=0;x<a;x++)b[x]=(Math.random()*2-1)*s.noise.level;d=t.createBufferSource(),d.buffer=f,d.connect(p),d.start(r),d.stop(r+s.duration+h.release)}let y,m;s.lfo.enabled&&u&&(y=t.createOscillator(),y.frequency.value=s.lfo.rate,m=t.createGain(),m.gain.value=s.lfo.depth,y.connect(m),s.lfo.target==="freq"?m.connect(u.frequency):s.lfo.target==="gain"?m.connect(o.gain):s.lfo.target==="filter"&&l&&m.connect(l.frequency),y.start(r),y.stop(r+s.duration)),o.connect(e);let i=[u,d,y,m,l,o],c=r+s.duration+h.release;setTimeout(()=>{i.forEach(a=>a?.disconnect())},(c-t.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,t){return Object.assign(this.cfg[e],t),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,t,r,s){return Object.assign(this.cfg.ampEnv,{attack:e,decay:t,sustain:r,release:s}),this}setPitchEnv(e,t){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:t}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,t,r){return Object.assign(this.cfg.filter,{type:e,freq:t,Q:r,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,t,r){return Object.assign(this.cfg.lfo,{target:e,rate:t,depth:r,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new n(structuredClone(this.cfg))}},Ce=new T({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Se=new T({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Re=new T({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),Ke=new T({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),Ie=new T({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function W(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(4)),r=Array.from(t).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}function ae(n){let e=!0;function t(){e&&(n(),requestAnimationFrame(t))}return requestAnimationFrame(t),{clear:()=>e=!1}}function oe(){return D?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var ke=oe();function le({width:n,height:e,updateHz:t="frames"}){return new C.KaylaGame(n,e,t==="frames"?1/0:t)}function ce(n){let e=new A(n);return new C.KaylaScene(e)}function he(n){return new C.KaylaRenderer(n)}function V(n,e){return{type:n,props:e}}var C;(y=>{class n extends _{#e;#t;constructor(i,c,a){super(i,c,a),this.#e=new Set,this.#t=!1}get started(){return this.#t}start(){if(!this.#t){for(let i of this.#e)i.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let i of this.#e)i.stop();this.#t=!1,super.stop()}}addRenderer(i){this.#e.has(i)||(this.#e.add(i),this.#t&&i.start(),i.game=this)}deleteRenderer(i){this.#e.has(i)&&(this.#e.delete(i),this.#t&&i.stop(),delete i.game)}}y.KaylaGame=n;class e extends F{game;pointerX;pointerY;#e;constructor(i){super(i),this.useDraw=this.useDraw.bind(this),this.on("draw",c=>{if(this.game)for(let a of this.game.scenes.values())a.handleDraw(c)}),this.pointerX=0,this.pointerY=0,this.#e=this.#t.bind(this)}#t(i){this.pointerX=i.clientX,this.pointerY=i.clientY}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.#e)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.#e)}pointerPosToWorldPos(i,c){let a=this.canvas.getBoundingClientRect(),f=(i-a.left)/a.width,b=(c-a.top)/a.height,x=f*this.viewportWidth*this.cameraWidth/a.width,S=b*this.viewportHeight*this.cameraHeight/a.height;return new R(x,S)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(i){let c=a=>{i(a,new r)};return this.on("draw",c),()=>{this.off("draw",c)}}attachTo(i){i.addRenderer(this),this.game=i}detach(){this.game&&this.game.deleteRenderer(this)}}y.KaylaRenderer=e;class t{current;saves;constructor(){this.saves=[]}useTick(i){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=i,this.current.useStepCallIndex++}usePaint(i){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=i,this.current.useDrawCallIndex++}useEntity(){return P(M)}useSelf(i){let c=P(null);return(c.current===null||c.current===void 0)&&(c.current=i()),c.current}useState(i,{alwaysRecall:c=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let f=this.current.state[this.current.useStateCallIndex]??new s(this.current,i,{alwaysRecall:c});return this.current.state[this.current.useStateCallIndex]=f,this.current.useStateCallIndex++,f}useRef(i){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let a=this.current.refs[this.current.useRefCallIndex]??h(i??null);return this.current.refs[this.current.useRefCallIndex]=a,this.current.useRefCallIndex++,a}useEffect(i){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=i,this.current.useEffectCallIndex++}useExports(i,c){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=c}save(){this.saves.push({current:this.current})}restore(){let i=this.saves.pop();if(!i)throw new Error("Cannot restore without saving.");this.current=i.current}}y.GlobalKayla=t;class r{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}y.KaylaEvent=r;class s{#e;#t;#n;alwaysRecall;constructor(i,c,{alwaysRecall:a=!1}={}){this.#t=i,this.#e=c??void 0,this.#n=Date.now(),this.alwaysRecall=a}get(){return this.#e}add(i,{recall:c}={}){this.set(this.get()+i,{recall:c})}multiply(i,{recall:c}={}){this.set(this.get()*i,{recall:c})}set(i,{recall:c=!1}={}){let a=this.#e;i!==a&&(this.#e=i,(c||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now())}get value(){return this.#e}get lastChanged(){return this.#n}}y.KaylaState=s;class o{#e;constructor(i){this.#e=i??void 0}#t;setSetter(i){this.#t=i}get current(){return this.#e}set current(i){this.#e=i,this.#t&&this.#t(this.#e)}}y.KaylaInternalRef=o;function h(m){return new o(m)}y.createReassignableRef=h;class p{state;refs;global;callProps;scene;exports;constructor(i,c,a){if(!a)throw new Error("Empty element");this.scene=c,this.state=[],this.refs=[],this.fc=a.type,this.callProps=a.props??{},this.global=i,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[]}get key(){return this.callProps.key}set key(i){this.callProps.key=i}get children(){return this.callProps.children}set children(i){this.callProps.children=i}entity;onExport=()=>({});onEffect;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;lastStateDeps;refresh(){let i;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0;let c=[];try{let a=this.fc(this.callProps)??[];if(a&&!Array.isArray(a)&&(a=[a]),!Array.isArray(a))throw new Error("Non array or non undefined children received.");c=a}catch(a){i=a}this.useStateCallIndex=0,this.useRefCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.global.restore();try{let a=0,f=[];for(let b of c){let x=this.lastChildren.at(a)??new p(this.global,this.scene,b);this.lastChildren[a]=x,f.push(x),a++}for(let b of this.lastChildren.filter(x=>!f.includes(x))){let x=this.lastChildren.indexOf(b);x!==1&&this.lastChildren.splice(x,1),b.unuse()}for(let b of this.lastChildren)try{b.refresh()}catch(x){console.error(x)}Y(()=>{this.use()})}catch(a){console.error(a)}if(i)throw i}lastChildren;isFirstUse=!0;use(){try{let i=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(i=this.onEffectDeps.some((c,a)=>{let f=this.lastStateDeps.at(a);if(f){let b=c.lastChanged,x=f.stamp;return b>x}})),i||this.isFirstUse){this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(a=>({stamp:a.lastChanged,stateRef:a}))),this.key??=this.fc.name+"_"+W(),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new l(this,this.key);for(let a of this.refs)a.current===M&&(a.current=this.entity);this.callProps.ref instanceof o&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof o&&(this.callProps.exportsRef.current=this.exports),this.scene.getScene().addEntity(this.entity);let c=this.onEffect.map(a=>a()).filter(a=>a!==void 0);this.onUnEffect=c}}catch(i){throw i}}unuse(){try{for(let i of this.onUnEffect)i()}catch(i){console.error(i)}this.scene.getScene().removeEntity(this.entity)}}y.KaylaFiber=p;class l extends L{#e;constructor(i,c){super(c,0,0,0,0),this.#e=i}update(i){let c=new r;if(this.#e.onTick)for(let a of this.#e.onTick)a(i,c);c.isPrevented()}draw(i){let c=new r;if(this.#e.onPaint)for(let a of this.#e.onPaint)a(i,c);c.isPrevented()||super.draw(i)}}y.KaylaRectEntity=l;class u{constructor(i){this.#t=i,this.#e=null,i.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getScene(){return this.#t}drawHandler(i){return this.#t.handleDraw(i)}attachTo(i){i.addScene(this.#t),this.#e=i}spawn(i){new p(y.singleGlobalInstance,this,i).refresh()}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}y.KaylaScene=u,y.singleGlobalInstance=new y.GlobalKayla})(C||={});var g=C.singleGlobalInstance,H=g.useState.bind(g),P=g.useRef.bind(g),X=g.useEffect.bind(g),pe=g.useTick.bind(g),U=g.usePaint.bind(g),fe=g.useExports.bind(g),de=g.useSelf.bind(g),me=g.useEntity.bind(g),M=Symbol("self_ref");var Y=n=>{Promise.resolve(1).then(()=>n())},q=({children:n})=>Array.isArray(n)?[...n]:n;function ye(n){return C.createReassignableRef(n)}function be(n){if(typeof n!="object"||typeof n=="function"||n===null)return n;let e={current:n};return new Proxy({},{get(r,s,o){return s==="reassignSelf"?h=>{e.current=h}:Reflect.get(e.current,s,o)},set(r,s,o,h){return Reflect.set(e.current,s,o,h)},has(r,s){return Reflect.has(e.current,s)},ownKeys(r){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(r,s){return Reflect.getOwnPropertyDescriptor(e.current,s)},deleteProperty(r,s){return Reflect.deleteProperty(e.current,s)}})}Reflect.set(globalThis,"Kayla",B);var xe;(e=>e.UIComponent=({x:t,y:r,width:s,height:o,children:h})=>{let p=P(M),l=H(!1);return X(()=>{if(l.get()===!0)return;l.set(!0);let u=p.current;u.width=s,u.height=o,u.x=t,u.y=r}),U(u=>{u.fillStyle="rgba(0, 0, 0, 0.5)",u.fillRect(t,r,s,o)}),h??[]})(xe||={});function ge(n,e,...t){if(typeof n=="string")throw new Error("Cannot use intrinsic elements.");return V(n,{...e,children:e.children??t})}function Q(n,e,...t){if(typeof n=="string")throw new Error("Cannot use intrinsic elements.");return V(n,{...e,children:e.children??t})}function ve(n,e){return Q(n,e)}var Ee=q;0&&(module.exports={Fragment,jsx,jsxDEV,jsxs});