@kayelaa/canvas 0.2.8 → 0.2.9

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/dist/index.cjs CHANGED
@@ -1,5 +1 @@
1
- "use strict";var ye=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var qe=Object.prototype.hasOwnProperty;var be=(r,e)=>{for(var n in e)ye(r,n,{get:e[n],enumerable:!0})},Be=(r,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Xe(e))!qe.call(r,a)&&a!==n&&ye(r,a,{get:()=>e[a],enumerable:!(s=Ne(e,a))||s.enumerable});return r};var We=r=>Be(ye({},"__esModule",{value:!0}),r);var St={};be(St,{Kayla:()=>q,LEA:()=>X,default:()=>Pt});module.exports=We(St);var X={};be(X,{DeltaTweenII:()=>ie,ENVIRONMENT:()=>xe,GEmitterMemory:()=>ge,LeaEntityII:()=>O,LeaEventEmitter:()=>I,LeaGameII:()=>j,LeaRendererII:()=>W,LeaSceneII:()=>Y,LeaSerializers:()=>ke,LeaTickerII:()=>re,LeaTimeout:()=>se,LeaUtilsII:()=>T,LiaAudio:()=>N,LiaAudioSrc:()=>$,LiaOscSFX:()=>L,LiaSFXMap:()=>et,NOTE_NAMES:()=>Se,RectLeaEntity:()=>Q,Vector2:()=>F,colToRGBA:()=>je,defaultSFXConfig:()=>Ie,editRGBA:()=>Qe,generateUUID:()=>Ve,getAvoidAngle:()=>ze,getEnvironment:()=>Pe,getNormalizedColor:()=>Ye,getRayHit:()=>Ge,isInitiallyMobile:()=>rt,isMobile:()=>He,isNode:()=>D,isNote:()=>Ze,isWeb:()=>R,parseFillStyle:()=>Te,raycastAvoid:()=>nt,scaleCoord:()=>Je,setAnimInterval:()=>De,sfxHit:()=>_e,sfxJump:()=>Ae,sfxLaser:()=>Le,sfxUIClick:()=>Fe,sfxUIHover:()=>Me,shortUID:()=>tt,tinyUID:()=>ae});var I=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let s=this.#e.get(e)||[];return s.push(n),this.#e.set(e,s),this}once(e,n){let s=(...a)=>{this.off(e,s),n(...a)};return this.on(e,s),this}off(e,n){let s=this.#e.get(e);if(!s)return this;let a=s.indexOf(n);return a>=0&&s.splice(a,1),this}emit(e,...n){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw n[0];return!1}return s.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},W=class extends I{#e;#t;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;get canvas(){return this.#e}get ctx(){return this.#t}set canvas(e){this.#e=e,this.#t=e.getContext("2d"),this.updateCanvasResolution()}constructor(e,{viewportWidth:n,viewportHeight:s,cameraWidth:a,cameraHeight:l}={}){if(!R)throw new Error("Web-Only");super(),this.canvas=e,this.automatic=!0,this.#n=n??e.width,this.#r=s??e.height,this.#i=a??e.width,this.#s=l??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.#i/this.#n,n=this.#s/this.#r;this.ctx.translate(this.#i/2,this.#s/2),this.ctx.scale(e,n),this.ctx.translate(-this.#n/2,-this.#r/2)}#n=0;#r=0;#i=0;#s=0;get viewportWidth(){return this.#n}set viewportWidth(e){this.#n=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#n}get height(){return this.#r}get centerX(){return this.#n/2}get centerY(){return this.#r/2}get left(){return 0}get top(){return 0}get right(){return this.#n}get bottom(){return this.#r}get viewportHeight(){return this.#r}set viewportHeight(e){this.#r=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#i}set cameraWidth(e){this.#i=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#s}set cameraHeight(e){this.#s=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#i,this.canvas.height=this.#s}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!R)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#i,this.#s),this.emit("draw",this.ctx)}start(){if(!this.running){if(!R||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!R||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},re=class extends I{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(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(R&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new se(e,this)}createTween(e,n=()=>{}){let s=new ie(e),a=(l=0)=>{if(s.finished){this.off("tick",a);return}s.update(l)};return s.on("finish",()=>{this.off("tick",a)}),s.on("delta",l=>{n(l)}),this.on("tick",a),s}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=R&&!isFinite(this.tickInterval)?De(()=>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,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},ke;(t=>{function r(i){return i===!0?1:0}t.booleanExport=r;function e(i){return i===0?!1:i===1}t.booleanImport=e;function n(i){return`${i.x}|${i.y}`}t.vec2Export=n;function s(i){let[u,c]=i.split("|"),y=parseFloat(u),b=parseFloat(c);if(isNaN(y)||isNaN(b))throw new Error(`Invalid Vector2 string: ${i}`);return new F(y,b)}t.vec2Import=s,t.booleanMap={mapExport:r,mapImport:e};function l(i){return u=>Number(u.toFixed(i))}t.createRounder=l;function d(i=10){return{mapExport(u){return Math.round(u/i)},mapImport(u){return u*i}}}t.createLowPrecision=d;function f(i){return Math.round(i)}t.lightWeightRounder=f;function o(i=100){return{mapExport(u){return Math.round(u*i)},mapImport(u){return u/i}}}t.createPercent=o;function h(i){let u=new Map(Object.entries(i));return{mapExport:c=>u.get(c)??null,mapImport:c=>Array.from(u.entries()).find(([y,b])=>b===c)?.[0]??null}}t.createLookup=h;function p(i){let u=i*(180/Math.PI);return Math.round((u%360+360)%360)}t.radToDeg=p;function g(i){return i*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:p,mapImport:g};function v(i=10){let u=d(i);return{mapExport(c){return u.mapExport(p(c))},mapImport(c){return u.mapImport(g(c))}}}t.createLowPrecisionRadToDeg=v})(ke||={});var O=class r extends I{name="";scaleRotate=0;scale=1;constructor(e,n=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new F(n,s),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(n){this.emit("error",n)}}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(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:l}])=>{let d=Reflect.get(this,a);return l?l(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),s=Object.fromEntries(n.map(a=>{let l=Reflect.get(this,a);if(D&&typeof l=="number"){let d=l.toString().split("."),o=(d[1]?d[1].length:0)>2?Number(l.toFixed(2)):l;return[a,o]}return[a,l]}));return JSON.parse(JSON.stringify(s))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return r.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let s={};for(let a=0;a<n.length;a++){let l=e[a];if(!l)break;let[d,{mapImport:f}]=l,o=n[a];if(f&&(o=f(o)),typeof d!="string")break;try{Reflect.set(s,d,o)}catch(h){console.error(h)}}return s}},Y=class extends I{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!D&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((s,a)=>s.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof O))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 O))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},j=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,n,s=16){this.ticker=new re(s),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let l of this.scenes.values())l.paused||l.handleUpdate(a)})}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()}},T={lerp(r,e,n){return r+(e-r)*n},clamp(r,e,n){return Math.min(n,Math.max(e,r))},clamp01(r){return Math.min(1,Math.max(0,r))},easeLinear(r){return r},easeInQuad(r){return r*r},easeOutQuad(r){return 1-(1-r)*(1-r)},easeInOutQuad(r){return r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2},easeInSine(r){return 1-Math.cos(r*Math.PI/2)},easeOutSine(r){return Math.sin(r*Math.PI/2)},easeInOutSine(r){return-(Math.cos(Math.PI*r)-1)/2},easeInExpo(r){return r===0?0:Math.pow(2,10*r-10)},easeOutExpo(r){return r===1?1:1-Math.pow(2,-10*r)},easeInOutExpo(r){return r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2},smoothstep(r){return r=T.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return T.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[T.randomInt(0,r.length-1)]},createBezier(r,e,n,s){function a(f,o,h,p,g){let x=1-f;return x*x*x*o+3*x*x*f*h+3*x*f*f*p+f*f*f*g}function l(f,o,h,p,g){let x=1-f;return 3*x*x*(h-o)+6*x*f*(p-h)+3*f*f*(g-p)}function d(f){let o=f;for(let h=0;h<6;h++){let p=a(o,0,r,n,1),g=l(o,0,r,n,1);if(g===0)break;o-=(p-f)/g}return T.clamp(o,0,1)}return function(o){o=T.clamp(o,0,1);let h=d(o);return a(h,0,e,s,1)}},lengthSquared(...r){return r.reduce((e,n)=>e+n*n,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return T.normalizeRad(-r)},degToRadFlipY(r){return T.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=T.normalizeRad(r),e=T.normalizeRad(e);let n=T.normalizeRad(e-r),s=T.normalizeRad(r-e);return n<=s?1:-1}},ie=class extends I{constructor({delta:e,ms:n,easing:s}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=s??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=T.clamp(this.elapsed/this.duration,0,1),s=this.easing(n),a=this.delta*s,l=a-this.lastValue;this.lastValue=a,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},Q=class extends O{constructor(e,n=0,s=0,a=50,l=50){super(e,n,s),this.width=a,this.height=l}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)}},se=class extends I{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(s=>this._resolve=s),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,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},F=class r{constructor(e=0,n=0){this.x=e,this.y=n}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 n=Math.cos(e),s=Math.sin(e);return new r(this.x*n-this.y*s,this.x*s+this.y*n)}static from(e){return new r(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-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 r(0,0):new r(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),s=e.normalized();return n.x*s.x+n.y*s.y}lengthSquaredTo(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}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 n=this.x-e.x,s=this.y-e.y;return n*n+s*s}directionTo(e){return new r(e.x-this.x,e.y-this.y).normalized()}add(e){return new r(this.x+e.x,this.y+e.y)}addRaw(e){return new r(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new r(this.x-e.x,this.y-e.y)}scale(e){return new r(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new r(this.x,this.y)}};function Ye(r){let e=/^rgba?\(([^)]+)\)$/,n=r.match(e);if(n){let[s,a,l,d=1]=n[1].split(",").map(f=>parseFloat(f));return{r:Math.max(0,Math.min(255,Math.floor(s))),g:Math.max(0,Math.min(255,Math.floor(a))),b:Math.max(0,Math.min(255,Math.floor(l))),a:Math.max(0,Math.min(1,Math.floor(d*255)/255))}}return Te(r)}function je(r){return`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a})`}function Te(r){if(r=r.trim().toLowerCase(),r[0]==="#"){let n,s,a;if(r.length===7)n=parseInt(r.slice(1,3),16),s=parseInt(r.slice(3,5),16),a=parseInt(r.slice(5,7),16);else if(r.length===4)n=parseInt(r[1]+r[1],16),s=parseInt(r[2]+r[2],16),a=parseInt(r[3]+r[3],16);else throw new Error("Invalid hex color");return{r:n,g:s,b:a,a:1}}let e=r.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 Qe(r,{r:e,g:n,b:s,a}={}){let[l,d,f,o,h]=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??d}, ${n??f}, ${s??o}, ${a??(h||1)})`}function Je(r,e,n){return n+(r-n)*e}function Pe(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var xe=Pe(),D=xe==="node",R=xe==="web",N=class r{static unlock(){R&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=R?new AudioContext:null;static masterGain=R?this.audioCtx.createGain():null;static musicGain=R?this.audioCtx.createGain():null;static sfxGain=R?this.audioCtx.createGain():null;static{R&&(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 n=r.CACHE_NAME,s,a;if(typeof caches<"u"&&(a=await caches.open(n),s=await a.match(e)),!s){if(s=await fetch(e),!s.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,s.clone())}let l=await s.arrayBuffer(),d=await this.audioCtx.decodeAudioData(l);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=r.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,s=1,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return;let d=new $(l);d.buffer=l;let f=1-.12,o=1+.12;d.playbackRate=s??f+Math.random()*(o-f);let h=this.audioCtx.createGain();h.gain.value=n,d.tempGain=h,d.connect(h),h.connect(this.sfxGain),d.onended=()=>{d.disconnect(),h.disconnect()},d.start(),a&&this.sfsx.set(e,{source:d,gain:h})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:s=0,loopEnd:a=null,exclusive:l=!0,skipMS:d=0}={}){if(l)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let o=new $(f);o.buffer=f,o.loop=!0,typeof s=="number"&&(o.loopStart=s),typeof a=="number"&&(o.loopEnd=a);let h=this.audioCtx.createGain();h.gain.value=n,o.tempGain=h,o.playbackRate=1,o.onended=()=>{o.disconnect(),h.disconnect()},o.connect(h),h.connect(this.musicGain),o.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:o,gain:h}),p}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:s=1,loop:a=!1,loopStart:l=0,loopEnd:d=null,isMusic:f=!1,gain:o=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return null;let p=new $(h);p.loop=a,p.loopStart=l,p.loopEnd=typeof d=="number"?d:h.duration,p.playbackRate=s;let g=this.audioCtx.createGain();return g.gain.value=n,p.connect(g),p.tempGain=g,g.connect(o||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),g.disconnect()},p}catch(h){return console.error("Failed to create LiaAudioSrc:",h),null}}},Se=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Ze(r){return Se.includes(r)}var $=class{numberOfInputs;numberOfOutputs;constructor(e,n=N.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=R?n.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:n=null}={}){let s=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-s/this.playbackRate,this.source.start(0,s),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,n=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,n,s):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%s}if(this.isPlaying=!1,e>0){let s=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,s),this.output.gain.linearRampToValueAtTime(0,s+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,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=n}}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 n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,s=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,s),e}disconnect(e,n,s){e===void 0?this.output.disconnect():this.output.disconnect(e,n,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),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},L=class r{constructor(e={}){this.ctx=N.audioCtx,this.cfg=structuredClone(Ie),Object.assign(this.cfg,e)}ctx;cfg;play(e=N.sfxGain){let n=this.ctx,s=n.currentTime,a=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,s);let d=a.ampEnv;l.gain.exponentialRampToValueAtTime(d.volume,s+d.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),s+d.attack+d.decay),l.gain.exponentialRampToValueAtTime(1e-4,s+a.duration+d.release);let f=l,o;a.filter.enabled&&(o=n.createBiquadFilter(),o.type=a.filter.type,o.frequency.value=a.filter.freq,o.Q.value=a.filter.Q,o.connect(l),f=o);let h;if(a.osc.enabled){if(h=n.createOscillator(),h.type=a.osc.type,h.frequency.value=a.osc.freq,h.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let i=Math.pow(2,a.pitchEnv.amount/12);h.frequency.exponentialRampToValueAtTime(a.osc.freq*i,s+a.pitchEnv.decay)}h.connect(f),h.start(s),h.stop(s+a.duration+d.release)}let p;if(a.noise.enabled){let i=n.sampleRate*a.duration,u=n.createBuffer(1,i,n.sampleRate),c=u.getChannelData(0);for(let y=0;y<i;y++)c[y]=(Math.random()*2-1)*a.noise.level;p=n.createBufferSource(),p.buffer=u,p.connect(f),p.start(s),p.stop(s+a.duration+d.release)}let g,x;a.lfo.enabled&&h&&(g=n.createOscillator(),g.frequency.value=a.lfo.rate,x=n.createGain(),x.gain.value=a.lfo.depth,g.connect(x),a.lfo.target==="freq"?x.connect(h.frequency):a.lfo.target==="gain"?x.connect(l.gain):a.lfo.target==="filter"&&o&&x.connect(o.frequency),g.start(s),g.stop(s+a.duration)),l.connect(e);let v=[h,p,g,x,o,l],t=s+a.duration+d.release;setTimeout(()=>{v.forEach(i=>i?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),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,n,s,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:s,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),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,n,s){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:s,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,s){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:s,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},Fe=new L({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Me=new L({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Ae=new L({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}),Le=new L({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}),_e=new L({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}),et=new Map([["ui_click",Fe],["ui_hover",Me],["jump",Ae],["laser",Le],["hit",_e]]);function tt(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(r)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}function ae(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}var ge=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${Ve()}_${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,n){this.events[e]||(this.events[e]=[]),this.events[e].push(n)}off(e,n){this.events[e]&&(this.events[e]=this.events[e].filter(s=>s!==n))}_emit(e,n){this.events[e]?.forEach(s=>s(n))}send(e,n){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,n)}_receive(e,n){e?this._emit(e,n):this._emit("message",n)}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 Ve(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let r=new Uint8Array(16);return crypto.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128,[...r].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,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function De(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function Ge(r,e,n,s,a){let l=Math.cos(a),d=Math.sin(a),f=[];if(l!==0){let o=(0-r)/l,h=e+o*d;o>0&&h>=0&&h<=s&&f.push({side:"left",t:o})}if(l!==0){let o=(n-r)/l,h=e+o*d;o>0&&h>=0&&h<=s&&f.push({side:"right",t:o})}if(d!==0){let o=(0-e)/d,h=r+o*l;o>0&&h>=0&&h<=n&&f.push({side:"top",t:o})}if(d!==0){let o=(s-e)/d,h=r+o*l;o>0&&h>=0&&h<=n&&f.push({side:"bottom",t:o})}return f.length===0?null:(f.sort((o,h)=>o.t-h.t),f[0])}function ze(r,e){let n;switch(e){case"left":case"right":n=Math.PI-r;break;case"top":case"bottom":n=2*Math.PI-r;break}return(n%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function nt(r,e,n,s,a){let l=Ge(r,e,n,s,a);return l?{...l,avoidAngle:ze(a,l.side)}:null}function He(){return D?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var rt=He();var q={};be(q,{JSX:()=>Oe,KMatrix2D:()=>Ce,KaylaContext:()=>oe,KaylaFragment:()=>wt,KaylaInternals:()=>z,KaylaRect:()=>_,Layer:()=>kt,createContext:()=>lt,createElement:()=>ot,createGame:()=>it,createReassignableObject:()=>Et,createRenderer:()=>at,createScene:()=>st,createUseHook:()=>Rt,self:()=>we,setLogLevel:()=>Kt,useClick:()=>ft,useContext:()=>vt,useCurrentGame:()=>bt,useCurrentRenderer:()=>gt,useCurrentScene:()=>$e,useCurrentTicker:()=>xt,useDisposableRef:()=>Ct,useEffect:()=>le,useEntity:()=>yt,useExports:()=>de,useFiber:()=>Ke,useFiberControl:()=>Ee,useGlobalClick:()=>Ue,useGlobalPointer:()=>dt,useInitialization:()=>ue,useNextStack:()=>Re,usePaint:()=>ce,usePointer:()=>pt,useRect:()=>he,useRef:()=>ve,useSelf:()=>G,useShouldRefresh:()=>ht,useState:()=>ut,useTick:()=>mt,useViewportEffect:()=>ct});function it({width:r,height:e,updateHz:n="frames"}){return new z.KaylaGame(r,e,n==="frames"?1/0:n)}function st(r){let e=new Y(r);return new z.KaylaScene(e)}function at(r){return new z.KaylaRenderer(r)}function ot(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+ae(),{type:r,props:n}}var _;(s=>{function r(a,l){return!(a.right<l.left||a.left>l.right||a.bottom<l.top||a.top>l.bottom)}s.rawCollision=r;function e(a,l,d){let f=l*Math.PI/180,o=Math.cos(f),h=Math.sin(f),p=1/0;return o>0&&(p=Math.min(p,(d.right-a.x)/o)),o<0&&(p=Math.min(p,(d.left-a.x)/o)),h>0&&(p=Math.min(p,(d.bottom-a.y)/h)),h<0&&(p=Math.min(p,(d.top-a.y)/h)),F.from(l).scale(p)}s.getCurrToBound=e;function n(a){let{left:l,right:d,top:f,bottom:o,width:h,height:p,x:g=0,y:x=0}=a;if(h===null||p===null)throw new Error("width and height are required");let v,t;if(l!=null&&d!=null){if(Math.abs(d-l-h)>1e-6)throw new Error("left, right, and width mismatch");v=l}else g!=null?v=g-h/2:l!=null?v=l:d!=null?v=d-h:v=0;if(f!=null&&o!=null){if(Math.abs(o-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else x!=null?t=x-p/2:f!=null?t=f:o!=null?t=o-p:t=0;return{left:v,right:v+h,top:t,bottom:t+p,width:h,height:p,x:v+h/2,y:t+p/2}}s.createRawRect=n})(_||={});var z;(x=>{class r extends j{#e;#t;constructor(t,i,u){super(t,i,u),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}x.KaylaGame=r;class e extends W{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",i=>{if(this.game)for(let u of this.game.scenes.values())u.handleDraw(i)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new I,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=i=>this.onPointerAll(i,"down"),this.onPointerUp=i=>this.onPointerAll(i,"up"),this.onPointerCancel=i=>this.onPointerAll(i,"cancel"),this.onPointerMove=i=>this.onPointerAll(i,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,i){this.pointerPosUpdater(t);let u=e.getClickType(t);if(u!=="invalid"||i==="move"||i==="cancel"){t.preventDefault();let c=this.getMousePos();this.pointerEvents.emit("action",c,u,i)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,i){let u=this.canvas.getBoundingClientRect(),c=(t-u.left)/u.width,y=(i-u.top)/u.height,b=c*this.viewportWidth*this.cameraWidth/u.width,C=y*this.viewportHeight*this.cameraHeight/u.height;return new F(b,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let i=u=>{t(u,new s)};return this.on("draw",i),()=>{this.off("draw",i)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}x.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){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]=t,this.current.useStepCallIndex++}usePaint(t){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]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return ve(we)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let i=ve(null);return(i.current===null||i.current===void 0)&&(i.current=t()),i.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let i=this.current;i.onInits[this.current.useInitCallIndex]=t,i.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return G(()=>new x.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return G(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return G(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:i=>{t.setMaxChildren(i)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:i=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let c=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:i});return this.current.state[this.current.useStateCallIndex]=c,this.current.useStateCallIndex++,c}useShouldRefresh(t){let i=this.current;if(!i)throw new Error("useShouldRefresh must be called inside a component");i.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),i.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let u=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=u,this.current.useRefCallIndex++,u}useEffect(t){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]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,i){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=i}useGlobalPointer(t,i){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");i??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:i},this.current.useGlobalClickCallIndex++}usePointer(t,i){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");i??={};let u=this.current;Ue((c,y,b)=>{let C=u.entity;if(!C)return;let E=C.getRawRect(),H=_.createRawRect({x:c.x,y:c.y,width:3,height:3});_.rawCollision(E,H)&&t(c,y,b)},i)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,i,u,...c)=>{let y=t?.fc?.name||"anonymous",b=t?.key?` key=${t.key}`:"";this.logger[i](`${u} <${y}${b}>`,...c)}}}x.GlobalKayla=n;class s{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}x.KaylaEvent=s;class a{#e;#t;#n;alwaysRecall;constructor(t,i,{alwaysRecall:u=!1}={}){this.#t=t,this.#e=i??void 0,this.#n=Date.now(),this.alwaysRecall=u}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
2
- You probably wrote: const [value, setValue] = useState(...)
3
-
4
- \u2192 In Kayla write: const value = useState(...);
5
- \u2192 Then: value.get() / value.set(v) / value.add(n)`)}refreshBased(){return[this.set.bind(this),this.get()]}add(t,{recall:i}={}){this.set(this.get()+t,{recall:i})}multiply(t,{recall:i}={}){this.set(this.get()*t,{recall:i})}set(t,{recall:i=!1}={}){let u=this.#e;if(t===u)return;this.#e=t;let y=Date.now()-this.#n;i&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(i||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}x.KaylaInternalState=a;class l{#e;constructor(t){this.#e=t??void 0}#t;setSetter(t){this.#t=t}get current(){return this.#e}set current(t){this.#e=t,this.#t&&this.#t(this.#e)}}x.KaylaInternalRef=l;function d(v){return new l(v)}x.createReassignableRef=d;class f{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;lastLayer;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,i,u){if(!u)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=i,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=u.type,this.callProps=u.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalPointer=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+ae(),this.onViewportEffect=[],this.lastLayer=null}getCorrectMousePos(t){return t??=this.getAttachedRenderer().getMousePos(),this.lastLayer?.transform?this.lastLayer.transform.inverseV(t):t}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,i,u){t=this.getCorrectMousePos(t);try{for(let{handler:c,config:y}of this.onGlobalPointer)y.type??="any",y.action??="down",!(y.action!=="any"&&y.action!==u||y.type!=="any"&&y.type!==i)&&c(t,i,u)}catch(c){this.global.logger.error(c)}}resizeHook({width:t,height:i}){try{for(let u of this.onViewportEffect)u(this.getAttachedRenderer(),t,i)}catch(u){this.global.logger.error(u)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){return this.callProps.children}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalPointer;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let i=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${i} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let u=this.lastChildren.slice(0,this.maxSafeChildren),c=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=u;for(let y of c)y.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],i=this.detectedParent;for(;i;)t.push(i),i=i?.detectedParent;return t}getAllChildrenNestedFlattened(){let t=[],i=(u=[])=>{for(let c of u)t.push(c),c.lastChildren?.length&&i(c.lastChildren)};return i(this.lastChildren),t}getContextChain(){return this.getFiberChain().map(t=>t.contextInfo).filter(Boolean)}findContextValueFromInst(t){return this.getContextChain().find(i=>i.instance===t)?.value}getEntityChain(){return this.getFiberChain().map(t=>t.entity)}shouldFullRefresh(){if(this.isFirstUse||!this.watchedDeps||this.watchedDeps.length===0)return!0;for(let t=0;t<this.watchedDeps.length;t++){let i=this.watchedDeps[t],u=this.lastDepStamps[t]??0;if(i.lastChanged>u)return!0}return!1}captureDepStamps(){this.watchedDeps&&(this.lastDepStamps=this.watchedDeps.map(t=>t.lastChanged))}refresh(){if(!this.shouldFullRefresh())return;let t=this.fc?.name||"anonymous";if(!this.shouldFullRefresh()){this.global.logger.debug(`Refresh skipped <${t} key=${this.key}>`);return}this.global.logger.debug(`Refresh executed <${t} key=${this.key}> reason=${this.isFirstUse?"first":"deps-changed"}`),this.lastChildren.length>this.maxSafeChildren&&this.global.logger.warn(`High child count <${t} key=${this.key}> children=${this.lastChildren.length}`);let i;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let u=[];try{let c=this.fc(this.callProps)??[];if(c&&!Array.isArray(c)&&(c=[c]),!Array.isArray(c))throw new Error("Non array or non undefined children received.");for(let y of c)if(y.type===this.fc)throw new Error("Circular Component.");u=c}catch(c){i=c}if(this.global.restore(),this.updateChildren(u,!0),i)throw i}updateChildren(t,i){try{let u=[...t,...this.dynamicChildren],c=[],y=[];for(let b of u){let C=b.props?.key,E;C!=null&&(E=this.lastChildren.find(H=>H.key===C)),E||(E=new f(this.global,this.scene,b)),E.callProps=b.props,E.detectedParent=this,y.push(E),c.push(E)}for(let b of this.lastChildren)c.includes(b)||b.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let b of this.lastChildren)try{b.refresh()}catch(C){console.error(C)}}catch(u){console.error(u)}}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=!0),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let i=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(c=>({stamp:c.lastChanged,stateRef:c}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new o(this,this.key);for(let c of this.refs)c.current===we&&(c.current=this.entity);if(this.callProps.ref instanceof l&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof l&&(this.callProps.exportsRef.current=this.exports),this.entity&&this.entity!==this.entity&&this.global.logger.warn(`Entity name mismatch during refresh <${this.fc?.name} key=${this.key}>`),this.scene.getScene().addEntity(this.entity),i){this.onUnInits=[];for(let c of this.onInits){this.bindEvents();try{let y=c();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let c of this.onUnEffect??[])c()}catch(c){console.error(c)}let u=this.onEffect.map(c=>c()).filter(c=>c!==void 0);this.onUnEffect=u}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}}x.KaylaFiber=f;class o extends Q{#e;flags;getRawRect(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,i){super(i,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,i){return this.flags.set(t,i)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){let i=new s;if(this.#e&&this.#e.onTick)for(let u of this.#e.onTick)u(t,i);i.isPrevented()}draw(t){let i=new s;if(this.#e&&this.#e.onPaint)for(let u of this.#e.onPaint)u(t,i);i.isPrevented()||super.draw(t)}getRect(){return new h(this.getFiber())}}x.KaylaRectEntity=o;class h{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}get entity(){return this.#e.entity??null}#t(){if(!this.#e)throw new Error("No fibers found.");if(!this.entity)throw new Error("The entity does NOT exist yet.")}isCollidingWith(t){return this.#t(),this.entity.isCollidingWith(t.entity)}get setFlag(){return this.#t(),this.entity.setFlag.bind(this.entity)}get getFlag(){return this.#t(),this.entity.getFlag.bind(this.entity)}get removeFlag(){return this.#t(),this.entity.removeFlag.bind(this.entity)}isHovered(){let t=this.getRaw(),i=this.#e.getCorrectMousePos(),u=_.createRawRect({x:i.x,y:i.y,width:3,height:3});return _.rawCollision(t,u)}get pos(){return this.#t(),this.entity.pos}get x(){return this.#t(),this.pos.x}set x(t){this.#t(),this.pos.x=t}get y(){return this.#t(),this.pos.y}set y(t){this.#t(),this.pos.y=t}get width(){return this.#t(),this.entity.width}set width(t){this.#t(),this.entity.width=t}get height(){return this.#t(),this.entity.height}set height(t){this.#t(),this.entity.height=t}get z(){return this.#t(),this.entity.z}set z(t){this.#t(),this.entity.z=t}get left(){return this.#t(),this.entity.left}set left(t){this.#t(),this.entity.left=t}get right(){return this.#t(),this.entity.right}set right(t){this.#t(),this.entity.right=t}get top(){return this.#t(),this.entity.top}set top(t){this.#t(),this.entity.top=t}get bottom(){return this.#t(),this.entity.bottom}set bottom(t){this.#t(),this.entity.bottom=t}get toLocal(){return this.entity.toLocal.bind(this.entity)}get toWorld(){return this.entity.toWorld.bind(this.entity)}}x.KaylaInternalRect=h;class p{#e;#t;constructor(t){this.#r=t,this.#n=null,this.#e=new Map,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this),t.handleDraw=this.drawHandler,this.#t=null}getLayers(){return this.#e}#n;#r;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#r}getGame(){return this.#n}getOrCreateLayer(t,i=0){return this.#e.has(t)||this.#e.set(t,{name:t,z:i,visible:!0,rootFiber:null}),this.#e.get(t)}getSortedLayers(){return Array.from(this.#e.values()).filter(t=>t.visible).sort((t,i)=>t.z-i.z)}setLayerVisible(t,i){let u=this.#e.get(t);u&&(u.visible=i)}handleDraw(t){if(D)return;let i=this.getScene();if(i.paused)return;i.emit("draw",t);let u=this.getSortedLayers(),c=[];for(let b of u){if(!b.visible)continue;let C=b.rootFiber;if(!C)continue;let E=C.getAllChildrenNestedFlattened().flat().map(K=>K.entity).filter(Boolean);if(c.push(...E),t.save(),b.transform){let K=b.transform;t.setTransform(K.a,K.b,K.c,K.d,K.e,K.f)}b.blendMode&&(t.globalCompositeOperation=b.blendMode??"source-over");let H=Array.from(E).sort((K,P)=>K.z-P.z);for(let K of H)K.getFiber().lastLayer=b,K.handleDraw(t);t.restore()}let y=[...i.entities.values()].filter(b=>!c.includes(b));for(let b of y.sort((C,E)=>C.z-E.z))b.getFiber().lastLayer=null,b.handleDraw(t)}drawHandler(t){return this.handleDraw(t)}attachTo(t){t.addScene(this.#r),this.#n=t}async spawn(t){this.#t&&(this.#t.unuse(),this.#t=null);let i=this.createFiber(t);this.#t=i,await this.#n.delay(0),i.refresh()}getRoot(){return this.#t??null}createFiber(t){return new f(x.singleGlobalInstance,this,t)}detach(){this.#n&&this.#n.removeScene(this.#r)}tickHandler(){}}x.KaylaScene=p,x.singleGlobalInstance=new x.GlobalKayla})(z||={});var oe=class{#e;constructor(e){this.Provider=this.#t.bind(this),this.#e=e}get defaultValue(){return this.#e}#t({value:e=this.defaultValue,children:n}){let s=Ke();return le(()=>{s.contextInfo={instance:this,value:e}}),de(this.Provider,()=>({value:e})),n}Provider;Consumer};function lt(r){return new oe(r)}var m=z.singleGlobalInstance,ut=m.useState.bind(m),ve=m.useRef.bind(m),ht=m.useShouldRefresh.bind(m),le=m.useEffect.bind(m),ct=m.useViewportEffect.bind(m),Ue=m.useGlobalPointer.bind(m),dt=m.useGlobalPointer.bind(m),ft=m.usePointer.bind(m),pt=m.usePointer.bind(m),ue=m.useInitialization.bind(m),he=m.useRect.bind(m),mt=m.useTick.bind(m),ce=m.usePaint.bind(m),de=m.useExports.bind(m),G=m.useSelf.bind(m),Ee=m.useFiberControl.bind(m),Ke=m.useFiber.bind(m),yt=m.useEntity.bind(m),bt=m.useCurrentGame.bind(m),gt=m.useCurrentRenderer.bind(m),$e=m.useCurrentScene.bind(m),xt=m.useCurrentTicker.bind(m),vt=m.useContext.bind(m),we=Symbol("self_ref");var Re=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},wt=({children:r})=>Array.isArray(r)?[...r]:r;function Ct(r){return z.createReassignableRef(r)}function Et(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(s,a,l){return a==="reassignSelf"?d=>{e.current=d}:Reflect.get(e.current,a,l)},set(s,a,l,d){return Reflect.set(e.current,a,l,d)},has(s,a){return Reflect.has(e.current,a)},ownKeys(s){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(s,a){return Reflect.getOwnPropertyDescriptor(e.current,a)},deleteProperty(s,a){return Reflect.deleteProperty(e.current,a)}})}function Kt(r){m.logLevel=r}function Rt(r){let e=r.name||"anonymous-custom-hook";return function(s){let a=m.current;if(!a)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let l=s??{};return r.memoize!==!1?G(()=>(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,l))):(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,l))}}var Oe;(e=>e.id="kayla")(Oe||={});var kt=({name:r,z:e=0,blend:n,visible:s=!0,children:a,transform:l})=>{let d=$e(),f=Ke();return ue(()=>{let o=d.getOrCreateLayer(r,e);return o.blendMode=n,o.visible=s,o.rootFiber=f,o.transform=l??null,()=>{d.getLayers().delete(r)}}),a},Ce=class extends DOMMatrix{#e;constructor(){super(),this.#e=new DOMPoint}transformV(e){this.#e.x=e.x,this.#e.y=e.y;let n=this.#e.matrixTransform(this);return new F(n.x,n.y)}inverseV(e){let n=this.inverse();this.#e.x=e.x,this.#e.y=e.y;let s=this.#e.matrixTransform(n);return new F(s.x,s.y)}};Reflect.set(globalThis,"Kayla",q);var Tt;(n=>(n.Flex=({align:s="stretch",children:a,direction:l="row",gap:d=0,justify:f="start",wrap:o="nowrap",getHeight:h,getWidth:p,getCenterX:g,getCenterY:x,color:v})=>{let t=Ee(),i=he(),u=G(()=>({recalc(){let c=Number(d)||0,y=g(),b=x(),C=p(),E=h();i.x=y,i.y=b,i.width=C,i.height=E;let K=t.getChildrenEntities().filter(Boolean).map(w=>w.getRect()).filter(w=>w.getFlag("flex-ignored")!==!0),P=l==="row",A=P?i.width:i.height,It=P?i.height:i.width,fe=0,B=0,pe=[],J=[];K.forEach(w=>{let Z=P?w.width:w.height;fe+Z>A&&o==="wrap"?(pe.push({height:B,items:J}),J=[w],fe=Z,B=P?w.height:w.width):(J.push(w),fe+=Z+c,B=Math.max(B,P?w.height:w.width))}),pe.push({height:B,items:J});let me=0;pe.forEach((w,Z)=>{let M=w.items,V=M.reduce((k,ee)=>k+(P?ee.width:ee.height),0)+c*(M.length-1),S=0;f==="center"&&(S=(A-V)/2),f==="end"&&(S=A-V),f==="space-between"&&(S=0),f==="space-around"&&(S=(A-V)/(M.length*2)),f==="space-evenly"&&(S=(A-V)/(M.length+1)),M.forEach((k,ee)=>{k.z=i.z+1;let U=P?k.width:k.height,te=P?k.height:k.width,ne=0;s==="center"&&(ne=(w.height-te)/2),s==="end"&&(ne=w.height-te),s==="stretch"&&(P?k.height=w.height:k.width=w.height),P?(k.x=S+U/2,k.y=me+ne+te/2):(k.x=me+ne+te/2,k.y=S+U/2),f==="space-between"&&ee<M.length-1?S+=U+c+(A-V)/(M.length-1):f==="space-around"?S+=U+c+(A-V)/M.length:f==="space-evenly"?S+=U+c+(A-V)/(M.length+1):S+=U+c}),me+=w.height+c})}}));return ce((c,y)=>{y.preventDefault(),c.fillStyle=v,c.fillRect(i.left,i.top,i.width,i.height)}),le(()=>{Re(()=>{u.recalc()})}),de(n.Flex,()=>({controls:u})),a},n.GenericBox=({color:s,width:a=20,height:l=20,x:d=0,y:f=0})=>{let o=he();ue(()=>{o.width=a,o.height=l,o.x=d,o.y=f}),ce((h,p)=>{p.preventDefault(),h.fillStyle=s,h.fillRect(o.left,o.top,o.width,o.height)})}))(Tt||={});var Pt={LEA:X,Kayla:q};0&&(module.exports={Kayla,LEA});
1
+ "use strict";var be=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var qe=Object.prototype.hasOwnProperty;var ge=(r,e)=>{for(var n in e)be(r,n,{get:e[n],enumerable:!0})},Be=(r,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Xe(e))!qe.call(r,a)&&a!==n&&be(r,a,{get:()=>e[a],enumerable:!(s=Ne(e,a))||s.enumerable});return r};var We=r=>Be(be({},"__esModule",{value:!0}),r);var It={};ge(It,{Kayla:()=>q,LEA:()=>X,default:()=>Pt});module.exports=We(It);var X={};ge(X,{DeltaTweenII:()=>ie,ENVIRONMENT:()=>ve,GEmitterMemory:()=>xe,LeaEntityII:()=>O,LeaEventEmitter:()=>S,LeaGameII:()=>j,LeaRendererII:()=>W,LeaSceneII:()=>Y,LeaSerializers:()=>ke,LeaTickerII:()=>re,LeaTimeout:()=>se,LeaUtilsII:()=>T,LiaAudio:()=>N,LiaAudioSrc:()=>$,LiaOscSFX:()=>L,LiaSFXMap:()=>et,NOTE_NAMES:()=>Ie,RectLeaEntity:()=>Q,Vector2:()=>F,colToRGBA:()=>je,defaultSFXConfig:()=>Se,editRGBA:()=>Qe,generateUUID:()=>Ve,getAvoidAngle:()=>ze,getEnvironment:()=>Pe,getNormalizedColor:()=>Ye,getRayHit:()=>Ge,isInitiallyMobile:()=>rt,isMobile:()=>He,isNode:()=>D,isNote:()=>Ze,isWeb:()=>R,parseFillStyle:()=>Te,raycastAvoid:()=>nt,scaleCoord:()=>Je,setAnimInterval:()=>De,sfxHit:()=>_e,sfxJump:()=>Ae,sfxLaser:()=>Le,sfxUIClick:()=>Fe,sfxUIHover:()=>Me,shortUID:()=>tt,tinyUID:()=>ae});var S=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let s=this.#e.get(e)||[];return s.push(n),this.#e.set(e,s),this}once(e,n){let s=(...a)=>{this.off(e,s),n(...a)};return this.on(e,s),this}off(e,n){let s=this.#e.get(e);if(!s)return this;let a=s.indexOf(n);return a>=0&&s.splice(a,1),this}emit(e,...n){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw n[0];return!1}return s.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},W=class extends S{#e;#t;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;get canvas(){return this.#e}get ctx(){return this.#t}set canvas(e){this.#e=e,this.#t=e.getContext("2d"),this.updateCanvasResolution()}constructor(e,{viewportWidth:n,viewportHeight:s,cameraWidth:a,cameraHeight:l}={}){if(!R)throw new Error("Web-Only");super(),this.canvas=e,this.automatic=!0,this.#n=n??e.width,this.#r=s??e.height,this.#i=a??e.width,this.#s=l??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.#i/this.#n,n=this.#s/this.#r;this.ctx.translate(this.#i/2,this.#s/2),this.ctx.scale(e,n),this.ctx.translate(-this.#n/2,-this.#r/2)}#n=0;#r=0;#i=0;#s=0;get viewportWidth(){return this.#n}set viewportWidth(e){this.#n=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#n}get height(){return this.#r}get centerX(){return this.#n/2}get centerY(){return this.#r/2}get left(){return 0}get top(){return 0}get right(){return this.#n}get bottom(){return this.#r}get viewportHeight(){return this.#r}set viewportHeight(e){this.#r=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#i}set cameraWidth(e){this.#i=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#s}set cameraHeight(e){this.#s=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#i,this.canvas.height=this.#s}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!R)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#i,this.#s),this.emit("draw",this.ctx)}start(){if(!this.running){if(!R||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!R||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},re=class extends S{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(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(R&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new se(e,this)}createTween(e,n=()=>{}){let s=new ie(e),a=(l=0)=>{if(s.finished){this.off("tick",a);return}s.update(l)};return s.on("finish",()=>{this.off("tick",a)}),s.on("delta",l=>{n(l)}),this.on("tick",a),s}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=R&&!isFinite(this.tickInterval)?De(()=>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,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},ke;(t=>{function r(i){return i===!0?1:0}t.booleanExport=r;function e(i){return i===0?!1:i===1}t.booleanImport=e;function n(i){return`${i.x}|${i.y}`}t.vec2Export=n;function s(i){let[u,c]=i.split("|"),y=parseFloat(u),b=parseFloat(c);if(isNaN(y)||isNaN(b))throw new Error(`Invalid Vector2 string: ${i}`);return new F(y,b)}t.vec2Import=s,t.booleanMap={mapExport:r,mapImport:e};function l(i){return u=>Number(u.toFixed(i))}t.createRounder=l;function d(i=10){return{mapExport(u){return Math.round(u/i)},mapImport(u){return u*i}}}t.createLowPrecision=d;function f(i){return Math.round(i)}t.lightWeightRounder=f;function o(i=100){return{mapExport(u){return Math.round(u*i)},mapImport(u){return u/i}}}t.createPercent=o;function h(i){let u=new Map(Object.entries(i));return{mapExport:c=>u.get(c)??null,mapImport:c=>Array.from(u.entries()).find(([y,b])=>b===c)?.[0]??null}}t.createLookup=h;function p(i){let u=i*(180/Math.PI);return Math.round((u%360+360)%360)}t.radToDeg=p;function g(i){return i*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:p,mapImport:g};function v(i=10){let u=d(i);return{mapExport(c){return u.mapExport(p(c))},mapImport(c){return u.mapImport(g(c))}}}t.createLowPrecisionRadToDeg=v})(ke||={});var O=class r extends S{name="";scaleRotate=0;scale=1;constructor(e,n=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new F(n,s),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(n){this.emit("error",n)}}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(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:l}])=>{let d=Reflect.get(this,a);return l?l(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),s=Object.fromEntries(n.map(a=>{let l=Reflect.get(this,a);if(D&&typeof l=="number"){let d=l.toString().split("."),o=(d[1]?d[1].length:0)>2?Number(l.toFixed(2)):l;return[a,o]}return[a,l]}));return JSON.parse(JSON.stringify(s))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return r.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let s={};for(let a=0;a<n.length;a++){let l=e[a];if(!l)break;let[d,{mapImport:f}]=l,o=n[a];if(f&&(o=f(o)),typeof d!="string")break;try{Reflect.set(s,d,o)}catch(h){console.error(h)}}return s}},Y=class extends S{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!D&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((s,a)=>s.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof O))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 O))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},j=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,n,s=16){this.ticker=new re(s),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let l of this.scenes.values())l.paused||l.handleUpdate(a)})}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()}},T={lerp(r,e,n){return r+(e-r)*n},clamp(r,e,n){return Math.min(n,Math.max(e,r))},clamp01(r){return Math.min(1,Math.max(0,r))},easeLinear(r){return r},easeInQuad(r){return r*r},easeOutQuad(r){return 1-(1-r)*(1-r)},easeInOutQuad(r){return r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2},easeInSine(r){return 1-Math.cos(r*Math.PI/2)},easeOutSine(r){return Math.sin(r*Math.PI/2)},easeInOutSine(r){return-(Math.cos(Math.PI*r)-1)/2},easeInExpo(r){return r===0?0:Math.pow(2,10*r-10)},easeOutExpo(r){return r===1?1:1-Math.pow(2,-10*r)},easeInOutExpo(r){return r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2},smoothstep(r){return r=T.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return T.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[T.randomInt(0,r.length-1)]},createBezier(r,e,n,s){function a(f,o,h,p,g){let x=1-f;return x*x*x*o+3*x*x*f*h+3*x*f*f*p+f*f*f*g}function l(f,o,h,p,g){let x=1-f;return 3*x*x*(h-o)+6*x*f*(p-h)+3*f*f*(g-p)}function d(f){let o=f;for(let h=0;h<6;h++){let p=a(o,0,r,n,1),g=l(o,0,r,n,1);if(g===0)break;o-=(p-f)/g}return T.clamp(o,0,1)}return function(o){o=T.clamp(o,0,1);let h=d(o);return a(h,0,e,s,1)}},lengthSquared(...r){return r.reduce((e,n)=>e+n*n,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return T.normalizeRad(-r)},degToRadFlipY(r){return T.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=T.normalizeRad(r),e=T.normalizeRad(e);let n=T.normalizeRad(e-r),s=T.normalizeRad(r-e);return n<=s?1:-1}},ie=class extends S{constructor({delta:e,ms:n,easing:s}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=s??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=T.clamp(this.elapsed/this.duration,0,1),s=this.easing(n),a=this.delta*s,l=a-this.lastValue;this.lastValue=a,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},Q=class extends O{constructor(e,n=0,s=0,a=50,l=50){super(e,n,s),this.width=a,this.height=l}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)}},se=class extends S{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(s=>this._resolve=s),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,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},F=class r{constructor(e=0,n=0){this.x=e,this.y=n}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 n=Math.cos(e),s=Math.sin(e);return new r(this.x*n-this.y*s,this.x*s+this.y*n)}static from(e){return new r(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-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 r(0,0):new r(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),s=e.normalized();return n.x*s.x+n.y*s.y}lengthSquaredTo(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}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 n=this.x-e.x,s=this.y-e.y;return n*n+s*s}directionTo(e){return new r(e.x-this.x,e.y-this.y).normalized()}add(e){return new r(this.x+e.x,this.y+e.y)}addRaw(e){return new r(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new r(this.x-e.x,this.y-e.y)}scale(e){return new r(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new r(this.x,this.y)}};function Ye(r){let e=/^rgba?\(([^)]+)\)$/,n=r.match(e);if(n){let[s,a,l,d=1]=n[1].split(",").map(f=>parseFloat(f));return{r:Math.max(0,Math.min(255,Math.floor(s))),g:Math.max(0,Math.min(255,Math.floor(a))),b:Math.max(0,Math.min(255,Math.floor(l))),a:Math.max(0,Math.min(1,Math.floor(d*255)/255))}}return Te(r)}function je(r){return`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a})`}function Te(r){if(r=r.trim().toLowerCase(),r[0]==="#"){let n,s,a;if(r.length===7)n=parseInt(r.slice(1,3),16),s=parseInt(r.slice(3,5),16),a=parseInt(r.slice(5,7),16);else if(r.length===4)n=parseInt(r[1]+r[1],16),s=parseInt(r[2]+r[2],16),a=parseInt(r[3]+r[3],16);else throw new Error("Invalid hex color");return{r:n,g:s,b:a,a:1}}let e=r.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 Qe(r,{r:e,g:n,b:s,a}={}){let[l,d,f,o,h]=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??d}, ${n??f}, ${s??o}, ${a??(h||1)})`}function Je(r,e,n){return n+(r-n)*e}function Pe(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var ve=Pe(),D=ve==="node",R=ve==="web",N=class r{static unlock(){R&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=R?new AudioContext:null;static masterGain=R?this.audioCtx.createGain():null;static musicGain=R?this.audioCtx.createGain():null;static sfxGain=R?this.audioCtx.createGain():null;static{R&&(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 n=r.CACHE_NAME,s,a;if(typeof caches<"u"&&(a=await caches.open(n),s=await a.match(e)),!s){if(s=await fetch(e),!s.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,s.clone())}let l=await s.arrayBuffer(),d=await this.audioCtx.decodeAudioData(l);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=r.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,s=1,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return;let d=new $(l);d.buffer=l;let f=1-.12,o=1+.12;d.playbackRate=s??f+Math.random()*(o-f);let h=this.audioCtx.createGain();h.gain.value=n,d.tempGain=h,d.connect(h),h.connect(this.sfxGain),d.onended=()=>{d.disconnect(),h.disconnect()},d.start(),a&&this.sfsx.set(e,{source:d,gain:h})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:s=0,loopEnd:a=null,exclusive:l=!0,skipMS:d=0}={}){if(l)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let o=new $(f);o.buffer=f,o.loop=!0,typeof s=="number"&&(o.loopStart=s),typeof a=="number"&&(o.loopEnd=a);let h=this.audioCtx.createGain();h.gain.value=n,o.tempGain=h,o.playbackRate=1,o.onended=()=>{o.disconnect(),h.disconnect()},o.connect(h),h.connect(this.musicGain),o.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:o,gain:h}),p}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:s=1,loop:a=!1,loopStart:l=0,loopEnd:d=null,isMusic:f=!1,gain:o=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return null;let p=new $(h);p.loop=a,p.loopStart=l,p.loopEnd=typeof d=="number"?d:h.duration,p.playbackRate=s;let g=this.audioCtx.createGain();return g.gain.value=n,p.connect(g),p.tempGain=g,g.connect(o||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),g.disconnect()},p}catch(h){return console.error("Failed to create LiaAudioSrc:",h),null}}},Ie=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Ze(r){return Ie.includes(r)}var $=class{numberOfInputs;numberOfOutputs;constructor(e,n=N.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=R?n.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:n=null}={}){let s=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-s/this.playbackRate,this.source.start(0,s),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,n=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,n,s):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%s}if(this.isPlaying=!1,e>0){let s=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,s),this.output.gain.linearRampToValueAtTime(0,s+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,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=n}}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 n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,s=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,s),e}disconnect(e,n,s){e===void 0?this.output.disconnect():this.output.disconnect(e,n,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Se={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},L=class r{constructor(e={}){this.ctx=N.audioCtx,this.cfg=structuredClone(Se),Object.assign(this.cfg,e)}ctx;cfg;play(e=N.sfxGain){let n=this.ctx,s=n.currentTime,a=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,s);let d=a.ampEnv;l.gain.exponentialRampToValueAtTime(d.volume,s+d.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),s+d.attack+d.decay),l.gain.exponentialRampToValueAtTime(1e-4,s+a.duration+d.release);let f=l,o;a.filter.enabled&&(o=n.createBiquadFilter(),o.type=a.filter.type,o.frequency.value=a.filter.freq,o.Q.value=a.filter.Q,o.connect(l),f=o);let h;if(a.osc.enabled){if(h=n.createOscillator(),h.type=a.osc.type,h.frequency.value=a.osc.freq,h.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let i=Math.pow(2,a.pitchEnv.amount/12);h.frequency.exponentialRampToValueAtTime(a.osc.freq*i,s+a.pitchEnv.decay)}h.connect(f),h.start(s),h.stop(s+a.duration+d.release)}let p;if(a.noise.enabled){let i=n.sampleRate*a.duration,u=n.createBuffer(1,i,n.sampleRate),c=u.getChannelData(0);for(let y=0;y<i;y++)c[y]=(Math.random()*2-1)*a.noise.level;p=n.createBufferSource(),p.buffer=u,p.connect(f),p.start(s),p.stop(s+a.duration+d.release)}let g,x;a.lfo.enabled&&h&&(g=n.createOscillator(),g.frequency.value=a.lfo.rate,x=n.createGain(),x.gain.value=a.lfo.depth,g.connect(x),a.lfo.target==="freq"?x.connect(h.frequency):a.lfo.target==="gain"?x.connect(l.gain):a.lfo.target==="filter"&&o&&x.connect(o.frequency),g.start(s),g.stop(s+a.duration)),l.connect(e);let v=[h,p,g,x,o,l],t=s+a.duration+d.release;setTimeout(()=>{v.forEach(i=>i?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),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,n,s,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:s,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),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,n,s){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:s,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,s){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:s,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},Fe=new L({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Me=new L({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Ae=new L({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}),Le=new L({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}),_e=new L({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}),et=new Map([["ui_click",Fe],["ui_hover",Me],["jump",Ae],["laser",Le],["hit",_e]]);function tt(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(r)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}function ae(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}var xe=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${Ve()}_${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,n){this.events[e]||(this.events[e]=[]),this.events[e].push(n)}off(e,n){this.events[e]&&(this.events[e]=this.events[e].filter(s=>s!==n))}_emit(e,n){this.events[e]?.forEach(s=>s(n))}send(e,n){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,n)}_receive(e,n){e?this._emit(e,n):this._emit("message",n)}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 Ve(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let r=new Uint8Array(16);return crypto.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128,[...r].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,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function De(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function Ge(r,e,n,s,a){let l=Math.cos(a),d=Math.sin(a),f=[];if(l!==0){let o=(0-r)/l,h=e+o*d;o>0&&h>=0&&h<=s&&f.push({side:"left",t:o})}if(l!==0){let o=(n-r)/l,h=e+o*d;o>0&&h>=0&&h<=s&&f.push({side:"right",t:o})}if(d!==0){let o=(0-e)/d,h=r+o*l;o>0&&h>=0&&h<=n&&f.push({side:"top",t:o})}if(d!==0){let o=(s-e)/d,h=r+o*l;o>0&&h>=0&&h<=n&&f.push({side:"bottom",t:o})}return f.length===0?null:(f.sort((o,h)=>o.t-h.t),f[0])}function ze(r,e){let n;switch(e){case"left":case"right":n=Math.PI-r;break;case"top":case"bottom":n=2*Math.PI-r;break}return(n%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function nt(r,e,n,s,a){let l=Ge(r,e,n,s,a);return l?{...l,avoidAngle:ze(a,l.side)}:null}function He(){return D?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var rt=He();var q={};ge(q,{JSX:()=>Oe,KMatrix2D:()=>Ee,KaylaContext:()=>oe,KaylaFragment:()=>wt,KaylaInternals:()=>z,KaylaRect:()=>_,Layer:()=>kt,createContext:()=>lt,createElement:()=>ot,createGame:()=>it,createReassignableObject:()=>Et,createRenderer:()=>at,createScene:()=>st,createUseHook:()=>Rt,self:()=>Ce,setLogLevel:()=>Kt,useClick:()=>ft,useContext:()=>vt,useCurrentGame:()=>bt,useCurrentRenderer:()=>gt,useCurrentScene:()=>$e,useCurrentTicker:()=>xt,useDisposableRef:()=>Ct,useEffect:()=>le,useEntity:()=>yt,useExports:()=>de,useFiber:()=>Re,useFiberControl:()=>Ke,useGlobalClick:()=>Ue,useGlobalPointer:()=>dt,useInitialization:()=>ue,useNextStack:()=>fe,usePaint:()=>ce,usePointer:()=>pt,useRect:()=>he,useRef:()=>we,useSelf:()=>G,useShouldRefresh:()=>ht,useState:()=>ut,useTick:()=>mt,useViewportEffect:()=>ct});function it({width:r,height:e,updateHz:n="frames"}){return new z.KaylaGame(r,e,n==="frames"?1/0:n)}function st(r){let e=new Y(r);return new z.KaylaScene(e)}function at(r){return new z.KaylaRenderer(r)}function ot(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+ae(),{type:r,props:n}}var _;(s=>{function r(a,l){return!(a.right<l.left||a.left>l.right||a.bottom<l.top||a.top>l.bottom)}s.rawCollision=r;function e(a,l,d){let f=l*Math.PI/180,o=Math.cos(f),h=Math.sin(f),p=1/0;return o>0&&(p=Math.min(p,(d.right-a.x)/o)),o<0&&(p=Math.min(p,(d.left-a.x)/o)),h>0&&(p=Math.min(p,(d.bottom-a.y)/h)),h<0&&(p=Math.min(p,(d.top-a.y)/h)),F.from(l).scale(p)}s.getCurrToBound=e;function n(a){let{left:l,right:d,top:f,bottom:o,width:h,height:p,x:g=0,y:x=0}=a;if(h===null||p===null)throw new Error("width and height are required");let v,t;if(l!=null&&d!=null){if(Math.abs(d-l-h)>1e-6)throw new Error("left, right, and width mismatch");v=l}else g!=null?v=g-h/2:l!=null?v=l:d!=null?v=d-h:v=0;if(f!=null&&o!=null){if(Math.abs(o-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else x!=null?t=x-p/2:f!=null?t=f:o!=null?t=o-p:t=0;return{left:v,right:v+h,top:t,bottom:t+p,width:h,height:p,x:v+h/2,y:t+p/2}}s.createRawRect=n})(_||={});var z;(x=>{class r extends j{#e;#t;constructor(t,i,u){super(t,i,u),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}x.KaylaGame=r;class e extends W{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",i=>{if(this.game)for(let u of this.game.scenes.values())u.handleDraw(i)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new S,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=i=>this.onPointerAll(i,"down"),this.onPointerUp=i=>this.onPointerAll(i,"up"),this.onPointerCancel=i=>this.onPointerAll(i,"cancel"),this.onPointerMove=i=>this.onPointerAll(i,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,i){this.pointerPosUpdater(t);let u=e.getClickType(t);if(u!=="invalid"||i==="move"||i==="cancel"){t.preventDefault();let c=this.getMousePos();this.pointerEvents.emit("action",c,u,i)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,i){let u=this.canvas.getBoundingClientRect(),c=(t-u.left)/u.width,y=(i-u.top)/u.height,b=c*this.viewportWidth*this.cameraWidth/u.width,C=y*this.viewportHeight*this.cameraHeight/u.height;return new F(b,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let i=u=>{t(u,new s)};return this.on("draw",i),()=>{this.off("draw",i)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}x.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){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]=t,this.current.useStepCallIndex++}usePaint(t){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]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return we(Ce)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let i=we(null);return(i.current===null||i.current===void 0)&&(i.current=t()),i.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let i=this.current;i.onInits[this.current.useInitCallIndex]=t,i.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return G(()=>new x.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return G(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return G(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:i=>{t.setMaxChildren(i)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:i=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let c=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:i});return this.current.state[this.current.useStateCallIndex]=c,this.current.useStateCallIndex++,c}useShouldRefresh(t){let i=this.current;if(!i)throw new Error("useShouldRefresh must be called inside a component");i.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),i.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let u=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=u,this.current.useRefCallIndex++,u}useEffect(t){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]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,i){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=i}useGlobalPointer(t,i){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");i??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:i},this.current.useGlobalClickCallIndex++}usePointer(t,i){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");i??={};let u=this.current;Ue((c,y,b)=>{let C=u.entity;if(!C)return;let E=C.getRawRect(),H=_.createRawRect({x:c.x,y:c.y,width:3,height:3});_.rawCollision(E,H)&&t(c,y,b)},i)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,i,u,...c)=>{let y=t?.fc?.name||"anonymous",b=t?.key?` key=${t.key}`:"";this.logger[i](`${u} <${y}${b}>`,...c)}}}x.GlobalKayla=n;class s{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}x.KaylaEvent=s;class a{#e;#t;#n;alwaysRecall;constructor(t,i,{alwaysRecall:u=!1}={}){this.#t=t,this.#e=i??void 0,this.#n=Date.now(),this.alwaysRecall=u}get(){return this.#e}get 0(){return this.get()}1(t){this.set(t,{recall:!0})}legacy(){return[this[0],this[1].bind(this)]}add(t,{recall:i}={}){this.set(this.get()+t,{recall:i})}multiply(t,{recall:i}={}){this.set(this.get()*t,{recall:i})}set(t,{recall:i=!1}={}){let u=this.#e;if(t===u)return;this.#e=t;let y=Date.now()-this.#n;i&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(i||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}x.KaylaInternalState=a;class l{#e;constructor(t){this.#e=t??void 0}#t;setSetter(t){this.#t=t}get current(){return this.#e}set current(t){this.#e=t,this.#t&&this.#t(this.#e)}}x.KaylaInternalRef=l;function d(v){return new l(v)}x.createReassignableRef=d;class f{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;lastLayer;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,i,u){if(!u)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=i,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=u.type,this.callProps=u.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalPointer=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+ae(),this.onViewportEffect=[],this.lastLayer=null}getCorrectMousePos(t){return t??=this.getAttachedRenderer().getMousePos(),this.lastLayer?.transform?this.lastLayer.transform.inverseV(t):t}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,i,u){t=this.getCorrectMousePos(t);try{for(let{handler:c,config:y}of this.onGlobalPointer)y.type??="any",y.action??="down",!(y.action!=="any"&&y.action!==u||y.type!=="any"&&y.type!==i)&&c(t,i,u)}catch(c){this.global.logger.error(c)}}resizeHook({width:t,height:i}){try{for(let u of this.onViewportEffect)u(this.getAttachedRenderer(),t,i)}catch(u){this.global.logger.error(u)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){return this.callProps.children}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalPointer;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let i=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${i} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let u=this.lastChildren.slice(0,this.maxSafeChildren),c=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=u;for(let y of c)y.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],i=this.detectedParent;for(;i;)t.push(i),i=i?.detectedParent;return t}getAllChildrenNestedFlattened(){let t=[],i=(u=[])=>{for(let c of u)t.push(c),c.lastChildren?.length&&i(c.lastChildren)};return i(this.lastChildren),t}getContextChain(){return this.getFiberChain().map(t=>t.contextInfo).filter(Boolean)}findContextValueFromInst(t){return this.getContextChain().find(i=>i.instance===t)?.value}getEntityChain(){return this.getFiberChain().map(t=>t.entity)}shouldFullRefresh(){if(this.isFirstUse||!this.watchedDeps||this.watchedDeps.length===0)return!0;for(let t=0;t<this.watchedDeps.length;t++){let i=this.watchedDeps[t],u=this.lastDepStamps[t]??0;if(i.lastChanged>u)return!0}return!1}captureDepStamps(){this.watchedDeps&&(this.lastDepStamps=this.watchedDeps.map(t=>t.lastChanged))}refresh(){if(!this.shouldFullRefresh())return;let t=this.fc?.name||"anonymous";if(!this.shouldFullRefresh()){this.global.logger.debug(`Refresh skipped <${t} key=${this.key}>`);return}this.global.logger.debug(`Refresh executed <${t} key=${this.key}> reason=${this.isFirstUse?"first":"deps-changed"}`),this.lastChildren.length>this.maxSafeChildren&&this.global.logger.warn(`High child count <${t} key=${this.key}> children=${this.lastChildren.length}`);let i;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let u=[];try{let c=this.fc(this.callProps)??[];if(c&&!Array.isArray(c)&&(c=[c]),!Array.isArray(c))throw new Error("Non array or non undefined children received.");for(let y of c)if(y.type===this.fc)throw new Error("Circular Component.");u=c}catch(c){i=c}if(this.global.restore(),this.updateChildren(u,!0),i)throw i}updateChildren(t,i){try{let u=[...t,...this.dynamicChildren],c=[],y=[];for(let b of u){let C=b.props?.key,E;C!=null&&(E=this.lastChildren.find(H=>H.key===C)),E||(E=new f(this.global,this.scene,b)),E.callProps=b.props,E.detectedParent=this,y.push(E),c.push(E)}for(let b of this.lastChildren)c.includes(b)||b.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let b of this.lastChildren)try{b.refresh()}catch(C){console.error(C)}}catch(u){console.error(u)}}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=!0),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let i=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(c=>({stamp:c.lastChanged,stateRef:c}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new o(this,this.key);for(let c of this.refs)c.current===Ce&&(c.current=this.entity);if(this.callProps.ref instanceof l&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof l&&(this.callProps.exportsRef.current=this.exports),this.entity&&this.entity!==this.entity&&this.global.logger.warn(`Entity name mismatch during refresh <${this.fc?.name} key=${this.key}>`),this.scene.getScene().addEntity(this.entity),i){this.onUnInits=[];for(let c of this.onInits){this.bindEvents();try{let y=c();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let c of this.onUnEffect??[])c()}catch(c){console.error(c)}let u=this.onEffect.map(c=>c()).filter(c=>c!==void 0);this.onUnEffect=u}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}}x.KaylaFiber=f;class o extends Q{#e;flags;getRawRect(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,i){super(i,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,i){return this.flags.set(t,i)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){fe(()=>{let i=new s;if(this.#e&&this.#e.onTick)for(let u of this.#e.onTick)u(t,i);i.isPrevented()})}draw(t){let i=new s;if(this.#e&&this.#e.onPaint)for(let u of this.#e.onPaint)u(t,i);i.isPrevented()||super.draw(t)}getRect(){return new h(this.getFiber())}}x.KaylaRectEntity=o;class h{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}get entity(){return this.#e.entity??null}#t(){if(!this.#e)throw new Error("No fibers found.");if(!this.entity)throw new Error("The entity does NOT exist yet.")}isCollidingWith(t){return this.#t(),this.entity.isCollidingWith(t.entity)}get setFlag(){return this.#t(),this.entity.setFlag.bind(this.entity)}get getFlag(){return this.#t(),this.entity.getFlag.bind(this.entity)}get removeFlag(){return this.#t(),this.entity.removeFlag.bind(this.entity)}isHovered(){let t=this.getRaw(),i=this.#e.getCorrectMousePos(),u=_.createRawRect({x:i.x,y:i.y,width:3,height:3});return _.rawCollision(t,u)}get pos(){return this.#t(),this.entity.pos}get x(){return this.#t(),this.pos.x}set x(t){this.#t(),this.pos.x=t}get y(){return this.#t(),this.pos.y}set y(t){this.#t(),this.pos.y=t}get width(){return this.#t(),this.entity.width}set width(t){this.#t(),this.entity.width=t}get height(){return this.#t(),this.entity.height}set height(t){this.#t(),this.entity.height=t}get z(){return this.#t(),this.entity.z}set z(t){this.#t(),this.entity.z=t}get left(){return this.#t(),this.entity.left}set left(t){this.#t(),this.entity.left=t}get right(){return this.#t(),this.entity.right}set right(t){this.#t(),this.entity.right=t}get top(){return this.#t(),this.entity.top}set top(t){this.#t(),this.entity.top=t}get bottom(){return this.#t(),this.entity.bottom}set bottom(t){this.#t(),this.entity.bottom=t}get toLocal(){return this.entity.toLocal.bind(this.entity)}get toWorld(){return this.entity.toWorld.bind(this.entity)}}x.KaylaInternalRect=h;class p{#e;#t;constructor(t){this.#r=t,this.#n=null,this.#e=new Map,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this),t.handleDraw=this.drawHandler,this.#t=null}getLayers(){return this.#e}#n;#r;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#r}getGame(){return this.#n}getOrCreateLayer(t,i=0){return this.#e.has(t)||this.#e.set(t,{name:t,z:i,visible:!0,rootFiber:null}),this.#e.get(t)}getSortedLayers(){return Array.from(this.#e.values()).filter(t=>t.visible).sort((t,i)=>t.z-i.z)}setLayerVisible(t,i){let u=this.#e.get(t);u&&(u.visible=i)}handleDraw(t){if(D)return;let i=this.getScene();if(i.paused)return;i.emit("draw",t);let u=this.getSortedLayers(),c=[];for(let b of u){if(!b.visible)continue;let C=b.rootFiber;if(!C)continue;let E=C.getAllChildrenNestedFlattened().flat().map(K=>K.entity).filter(Boolean);if(c.push(...E),t.save(),b.transform){let K=b.transform;t.setTransform(K.a,K.b,K.c,K.d,K.e,K.f)}b.blendMode&&(t.globalCompositeOperation=b.blendMode??"source-over");let H=Array.from(E).sort((K,P)=>K.z-P.z);for(let K of H)K.getFiber().lastLayer=b,K.handleDraw(t);t.restore()}let y=[...i.entities.values()].filter(b=>!c.includes(b));for(let b of y.sort((C,E)=>C.z-E.z))b.getFiber().lastLayer=null,b.handleDraw(t)}drawHandler(t){return this.handleDraw(t)}attachTo(t){t.addScene(this.#r),this.#n=t}async spawn(t){this.#t&&(this.#t.unuse(),this.#t=null);let i=this.createFiber(t);this.#t=i,await this.#n.delay(0),i.refresh()}getRoot(){return this.#t??null}createFiber(t){return new f(x.singleGlobalInstance,this,t)}detach(){this.#n&&this.#n.removeScene(this.#r)}tickHandler(){}}x.KaylaScene=p,x.singleGlobalInstance=new x.GlobalKayla})(z||={});var oe=class{#e;constructor(e){this.Provider=this.#t.bind(this),this.#e=e}get defaultValue(){return this.#e}#t({value:e=this.defaultValue,children:n}){let s=Re();return le(()=>{s.contextInfo={instance:this,value:e}}),de(this.Provider,()=>({value:e})),n}Provider;Consumer};function lt(r){return new oe(r)}var m=z.singleGlobalInstance,ut=m.useState.bind(m),we=m.useRef.bind(m),ht=m.useShouldRefresh.bind(m),le=m.useEffect.bind(m),ct=m.useViewportEffect.bind(m),Ue=m.useGlobalPointer.bind(m),dt=m.useGlobalPointer.bind(m),ft=m.usePointer.bind(m),pt=m.usePointer.bind(m),ue=m.useInitialization.bind(m),he=m.useRect.bind(m),mt=m.useTick.bind(m),ce=m.usePaint.bind(m),de=m.useExports.bind(m),G=m.useSelf.bind(m),Ke=m.useFiberControl.bind(m),Re=m.useFiber.bind(m),yt=m.useEntity.bind(m),bt=m.useCurrentGame.bind(m),gt=m.useCurrentRenderer.bind(m),$e=m.useCurrentScene.bind(m),xt=m.useCurrentTicker.bind(m),vt=m.useContext.bind(m),Ce=Symbol("self_ref");var fe=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},wt=({children:r})=>Array.isArray(r)?[...r]:r;function Ct(r){return z.createReassignableRef(r)}function Et(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(s,a,l){return a==="reassignSelf"?d=>{e.current=d}:Reflect.get(e.current,a,l)},set(s,a,l,d){return Reflect.set(e.current,a,l,d)},has(s,a){return Reflect.has(e.current,a)},ownKeys(s){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(s,a){return Reflect.getOwnPropertyDescriptor(e.current,a)},deleteProperty(s,a){return Reflect.deleteProperty(e.current,a)}})}function Kt(r){m.logLevel=r}function Rt(r){let e=r.name||"anonymous-custom-hook";return function(s){let a=m.current;if(!a)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let l=s??{};return r.memoize!==!1?G(()=>(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,l))):(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,l))}}var Oe;(e=>e.id="kayla")(Oe||={});var kt=({name:r,z:e=0,blend:n,visible:s=!0,children:a,transform:l})=>{let d=$e(),f=Re();return ue(()=>{let o=d.getOrCreateLayer(r,e);return o.blendMode=n,o.visible=s,o.rootFiber=f,o.transform=l??null,()=>{d.getLayers().delete(r)}}),a},Ee=class extends DOMMatrix{#e;constructor(){super(),this.#e=new DOMPoint}transformV(e){this.#e.x=e.x,this.#e.y=e.y;let n=this.#e.matrixTransform(this);return new F(n.x,n.y)}inverseV(e){let n=this.inverse();this.#e.x=e.x,this.#e.y=e.y;let s=this.#e.matrixTransform(n);return new F(s.x,s.y)}};Reflect.set(globalThis,"Kayla",q);var Tt;(n=>(n.Flex=({align:s="stretch",children:a,direction:l="row",gap:d=0,justify:f="start",wrap:o="nowrap",getHeight:h,getWidth:p,getCenterX:g,getCenterY:x,color:v})=>{let t=Ke(),i=he(),u=G(()=>({recalc(){let c=Number(d)||0,y=g(),b=x(),C=p(),E=h();i.x=y,i.y=b,i.width=C,i.height=E;let K=t.getChildrenEntities().filter(Boolean).map(w=>w.getRect()).filter(w=>w.getFlag("flex-ignored")!==!0),P=l==="row",A=P?i.width:i.height,St=P?i.height:i.width,pe=0,B=0,me=[],J=[];K.forEach(w=>{let Z=P?w.width:w.height;pe+Z>A&&o==="wrap"?(me.push({height:B,items:J}),J=[w],pe=Z,B=P?w.height:w.width):(J.push(w),pe+=Z+c,B=Math.max(B,P?w.height:w.width))}),me.push({height:B,items:J});let ye=0;me.forEach((w,Z)=>{let M=w.items,V=M.reduce((k,ee)=>k+(P?ee.width:ee.height),0)+c*(M.length-1),I=0;f==="center"&&(I=(A-V)/2),f==="end"&&(I=A-V),f==="space-between"&&(I=0),f==="space-around"&&(I=(A-V)/(M.length*2)),f==="space-evenly"&&(I=(A-V)/(M.length+1)),M.forEach((k,ee)=>{k.z=i.z+1;let U=P?k.width:k.height,te=P?k.height:k.width,ne=0;s==="center"&&(ne=(w.height-te)/2),s==="end"&&(ne=w.height-te),s==="stretch"&&(P?k.height=w.height:k.width=w.height),P?(k.x=I+U/2,k.y=ye+ne+te/2):(k.x=ye+ne+te/2,k.y=I+U/2),f==="space-between"&&ee<M.length-1?I+=U+c+(A-V)/(M.length-1):f==="space-around"?I+=U+c+(A-V)/M.length:f==="space-evenly"?I+=U+c+(A-V)/(M.length+1):I+=U+c}),ye+=w.height+c})}}));return ce((c,y)=>{y.preventDefault(),c.fillStyle=v,c.fillRect(i.left,i.top,i.width,i.height)}),le(()=>{fe(()=>{u.recalc()})}),de(n.Flex,()=>({controls:u})),a},n.GenericBox=({color:s,width:a=20,height:l=20,x:d=0,y:f=0})=>{let o=he();ue(()=>{o.width=a,o.height=l,o.x=d,o.y=f}),ce((h,p)=>{p.preventDefault(),h.fillStyle=s,h.fillRect(o.left,o.top,o.width,o.height)})}))(Tt||={});var Pt={LEA:X,Kayla:q};0&&(module.exports={Kayla,LEA});
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { L as LEA } from './lea-BaZkxo5L.cjs';
2
- import { K as Kayla } from './kayla-internals-jEHH2NbT.cjs';
2
+ import { K as Kayla } from './kayla-internals-BTafulRl.cjs';
3
3
 
4
4
  declare const _default: {
5
5
  LEA: typeof LEA;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { L as LEA } from './lea-BaZkxo5L.js';
2
- import { K as Kayla } from './kayla-internals-BIKaIho5.js';
2
+ import { K as Kayla } from './kayla-internals-D5xAtIoY.js';
3
3
 
4
4
  declare const _default: {
5
5
  LEA: typeof LEA;
package/dist/index.js CHANGED
@@ -1,5 +1 @@
1
- var Oe=Object.defineProperty;var Ke=(r,e)=>{for(var n in e)Oe(r,n,{get:e[n],enumerable:!0})};var j={};Ke(j,{DeltaTweenII:()=>ie,ENVIRONMENT:()=>be,GEmitterMemory:()=>ye,LeaEntityII:()=>O,LeaEventEmitter:()=>I,LeaGameII:()=>W,LeaRendererII:()=>q,LeaSceneII:()=>B,LeaSerializers:()=>Re,LeaTickerII:()=>re,LeaTimeout:()=>se,LeaUtilsII:()=>T,LiaAudio:()=>N,LiaAudioSrc:()=>$,LiaOscSFX:()=>L,LiaSFXMap:()=>Ye,NOTE_NAMES:()=>Pe,RectLeaEntity:()=>Y,Vector2:()=>F,colToRGBA:()=>Xe,defaultSFXConfig:()=>Se,editRGBA:()=>qe,generateUUID:()=>_e,getAvoidAngle:()=>Ge,getEnvironment:()=>Te,getNormalizedColor:()=>Ne,getRayHit:()=>De,isInitiallyMobile:()=>Je,isMobile:()=>ze,isNode:()=>D,isNote:()=>We,isWeb:()=>R,parseFillStyle:()=>ke,raycastAvoid:()=>Qe,scaleCoord:()=>Be,setAnimInterval:()=>Ve,sfxHit:()=>Le,sfxJump:()=>Me,sfxLaser:()=>Ae,sfxUIClick:()=>Ie,sfxUIHover:()=>Fe,shortUID:()=>je,tinyUID:()=>ae});var I=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let s=this.#e.get(e)||[];return s.push(n),this.#e.set(e,s),this}once(e,n){let s=(...a)=>{this.off(e,s),n(...a)};return this.on(e,s),this}off(e,n){let s=this.#e.get(e);if(!s)return this;let a=s.indexOf(n);return a>=0&&s.splice(a,1),this}emit(e,...n){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw n[0];return!1}return s.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},q=class extends I{#e;#t;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;get canvas(){return this.#e}get ctx(){return this.#t}set canvas(e){this.#e=e,this.#t=e.getContext("2d"),this.updateCanvasResolution()}constructor(e,{viewportWidth:n,viewportHeight:s,cameraWidth:a,cameraHeight:l}={}){if(!R)throw new Error("Web-Only");super(),this.canvas=e,this.automatic=!0,this.#n=n??e.width,this.#r=s??e.height,this.#i=a??e.width,this.#s=l??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.#i/this.#n,n=this.#s/this.#r;this.ctx.translate(this.#i/2,this.#s/2),this.ctx.scale(e,n),this.ctx.translate(-this.#n/2,-this.#r/2)}#n=0;#r=0;#i=0;#s=0;get viewportWidth(){return this.#n}set viewportWidth(e){this.#n=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#n}get height(){return this.#r}get centerX(){return this.#n/2}get centerY(){return this.#r/2}get left(){return 0}get top(){return 0}get right(){return this.#n}get bottom(){return this.#r}get viewportHeight(){return this.#r}set viewportHeight(e){this.#r=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#i}set cameraWidth(e){this.#i=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#s}set cameraHeight(e){this.#s=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#i,this.canvas.height=this.#s}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!R)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#i,this.#s),this.emit("draw",this.ctx)}start(){if(!this.running){if(!R||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!R||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},re=class extends I{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(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(R&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new se(e,this)}createTween(e,n=()=>{}){let s=new ie(e),a=(l=0)=>{if(s.finished){this.off("tick",a);return}s.update(l)};return s.on("finish",()=>{this.off("tick",a)}),s.on("delta",l=>{n(l)}),this.on("tick",a),s}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=R&&!isFinite(this.tickInterval)?Ve(()=>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,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},Re;(t=>{function r(i){return i===!0?1:0}t.booleanExport=r;function e(i){return i===0?!1:i===1}t.booleanImport=e;function n(i){return`${i.x}|${i.y}`}t.vec2Export=n;function s(i){let[u,c]=i.split("|"),y=parseFloat(u),b=parseFloat(c);if(isNaN(y)||isNaN(b))throw new Error(`Invalid Vector2 string: ${i}`);return new F(y,b)}t.vec2Import=s,t.booleanMap={mapExport:r,mapImport:e};function l(i){return u=>Number(u.toFixed(i))}t.createRounder=l;function d(i=10){return{mapExport(u){return Math.round(u/i)},mapImport(u){return u*i}}}t.createLowPrecision=d;function f(i){return Math.round(i)}t.lightWeightRounder=f;function o(i=100){return{mapExport(u){return Math.round(u*i)},mapImport(u){return u/i}}}t.createPercent=o;function h(i){let u=new Map(Object.entries(i));return{mapExport:c=>u.get(c)??null,mapImport:c=>Array.from(u.entries()).find(([y,b])=>b===c)?.[0]??null}}t.createLookup=h;function p(i){let u=i*(180/Math.PI);return Math.round((u%360+360)%360)}t.radToDeg=p;function g(i){return i*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:p,mapImport:g};function v(i=10){let u=d(i);return{mapExport(c){return u.mapExport(p(c))},mapImport(c){return u.mapImport(g(c))}}}t.createLowPrecisionRadToDeg=v})(Re||={});var O=class r extends I{name="";scaleRotate=0;scale=1;constructor(e,n=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new F(n,s),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(n){this.emit("error",n)}}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(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:l}])=>{let d=Reflect.get(this,a);return l?l(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),s=Object.fromEntries(n.map(a=>{let l=Reflect.get(this,a);if(D&&typeof l=="number"){let d=l.toString().split("."),o=(d[1]?d[1].length:0)>2?Number(l.toFixed(2)):l;return[a,o]}return[a,l]}));return JSON.parse(JSON.stringify(s))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return r.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let s={};for(let a=0;a<n.length;a++){let l=e[a];if(!l)break;let[d,{mapImport:f}]=l,o=n[a];if(f&&(o=f(o)),typeof d!="string")break;try{Reflect.set(s,d,o)}catch(h){console.error(h)}}return s}},B=class extends I{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!D&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((s,a)=>s.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof O))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 O))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},W=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,n,s=16){this.ticker=new re(s),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let l of this.scenes.values())l.paused||l.handleUpdate(a)})}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()}},T={lerp(r,e,n){return r+(e-r)*n},clamp(r,e,n){return Math.min(n,Math.max(e,r))},clamp01(r){return Math.min(1,Math.max(0,r))},easeLinear(r){return r},easeInQuad(r){return r*r},easeOutQuad(r){return 1-(1-r)*(1-r)},easeInOutQuad(r){return r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2},easeInSine(r){return 1-Math.cos(r*Math.PI/2)},easeOutSine(r){return Math.sin(r*Math.PI/2)},easeInOutSine(r){return-(Math.cos(Math.PI*r)-1)/2},easeInExpo(r){return r===0?0:Math.pow(2,10*r-10)},easeOutExpo(r){return r===1?1:1-Math.pow(2,-10*r)},easeInOutExpo(r){return r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2},smoothstep(r){return r=T.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return T.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[T.randomInt(0,r.length-1)]},createBezier(r,e,n,s){function a(f,o,h,p,g){let x=1-f;return x*x*x*o+3*x*x*f*h+3*x*f*f*p+f*f*f*g}function l(f,o,h,p,g){let x=1-f;return 3*x*x*(h-o)+6*x*f*(p-h)+3*f*f*(g-p)}function d(f){let o=f;for(let h=0;h<6;h++){let p=a(o,0,r,n,1),g=l(o,0,r,n,1);if(g===0)break;o-=(p-f)/g}return T.clamp(o,0,1)}return function(o){o=T.clamp(o,0,1);let h=d(o);return a(h,0,e,s,1)}},lengthSquared(...r){return r.reduce((e,n)=>e+n*n,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return T.normalizeRad(-r)},degToRadFlipY(r){return T.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=T.normalizeRad(r),e=T.normalizeRad(e);let n=T.normalizeRad(e-r),s=T.normalizeRad(r-e);return n<=s?1:-1}},ie=class extends I{constructor({delta:e,ms:n,easing:s}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=s??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=T.clamp(this.elapsed/this.duration,0,1),s=this.easing(n),a=this.delta*s,l=a-this.lastValue;this.lastValue=a,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},Y=class extends O{constructor(e,n=0,s=0,a=50,l=50){super(e,n,s),this.width=a,this.height=l}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)}},se=class extends I{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(s=>this._resolve=s),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,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},F=class r{constructor(e=0,n=0){this.x=e,this.y=n}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 n=Math.cos(e),s=Math.sin(e);return new r(this.x*n-this.y*s,this.x*s+this.y*n)}static from(e){return new r(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-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 r(0,0):new r(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),s=e.normalized();return n.x*s.x+n.y*s.y}lengthSquaredTo(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}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 n=this.x-e.x,s=this.y-e.y;return n*n+s*s}directionTo(e){return new r(e.x-this.x,e.y-this.y).normalized()}add(e){return new r(this.x+e.x,this.y+e.y)}addRaw(e){return new r(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new r(this.x-e.x,this.y-e.y)}scale(e){return new r(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new r(this.x,this.y)}};function Ne(r){let e=/^rgba?\(([^)]+)\)$/,n=r.match(e);if(n){let[s,a,l,d=1]=n[1].split(",").map(f=>parseFloat(f));return{r:Math.max(0,Math.min(255,Math.floor(s))),g:Math.max(0,Math.min(255,Math.floor(a))),b:Math.max(0,Math.min(255,Math.floor(l))),a:Math.max(0,Math.min(1,Math.floor(d*255)/255))}}return ke(r)}function Xe(r){return`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a})`}function ke(r){if(r=r.trim().toLowerCase(),r[0]==="#"){let n,s,a;if(r.length===7)n=parseInt(r.slice(1,3),16),s=parseInt(r.slice(3,5),16),a=parseInt(r.slice(5,7),16);else if(r.length===4)n=parseInt(r[1]+r[1],16),s=parseInt(r[2]+r[2],16),a=parseInt(r[3]+r[3],16);else throw new Error("Invalid hex color");return{r:n,g:s,b:a,a:1}}let e=r.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 qe(r,{r:e,g:n,b:s,a}={}){let[l,d,f,o,h]=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??d}, ${n??f}, ${s??o}, ${a??(h||1)})`}function Be(r,e,n){return n+(r-n)*e}function Te(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var be=Te(),D=be==="node",R=be==="web",N=class r{static unlock(){R&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=R?new AudioContext:null;static masterGain=R?this.audioCtx.createGain():null;static musicGain=R?this.audioCtx.createGain():null;static sfxGain=R?this.audioCtx.createGain():null;static{R&&(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 n=r.CACHE_NAME,s,a;if(typeof caches<"u"&&(a=await caches.open(n),s=await a.match(e)),!s){if(s=await fetch(e),!s.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,s.clone())}let l=await s.arrayBuffer(),d=await this.audioCtx.decodeAudioData(l);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=r.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,s=1,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return;let d=new $(l);d.buffer=l;let f=1-.12,o=1+.12;d.playbackRate=s??f+Math.random()*(o-f);let h=this.audioCtx.createGain();h.gain.value=n,d.tempGain=h,d.connect(h),h.connect(this.sfxGain),d.onended=()=>{d.disconnect(),h.disconnect()},d.start(),a&&this.sfsx.set(e,{source:d,gain:h})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:s=0,loopEnd:a=null,exclusive:l=!0,skipMS:d=0}={}){if(l)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let o=new $(f);o.buffer=f,o.loop=!0,typeof s=="number"&&(o.loopStart=s),typeof a=="number"&&(o.loopEnd=a);let h=this.audioCtx.createGain();h.gain.value=n,o.tempGain=h,o.playbackRate=1,o.onended=()=>{o.disconnect(),h.disconnect()},o.connect(h),h.connect(this.musicGain),o.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:o,gain:h}),p}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:s=1,loop:a=!1,loopStart:l=0,loopEnd:d=null,isMusic:f=!1,gain:o=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return null;let p=new $(h);p.loop=a,p.loopStart=l,p.loopEnd=typeof d=="number"?d:h.duration,p.playbackRate=s;let g=this.audioCtx.createGain();return g.gain.value=n,p.connect(g),p.tempGain=g,g.connect(o||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),g.disconnect()},p}catch(h){return console.error("Failed to create LiaAudioSrc:",h),null}}},Pe=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function We(r){return Pe.includes(r)}var $=class{numberOfInputs;numberOfOutputs;constructor(e,n=N.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=R?n.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:n=null}={}){let s=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-s/this.playbackRate,this.source.start(0,s),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,n=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,n,s):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%s}if(this.isPlaying=!1,e>0){let s=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,s),this.output.gain.linearRampToValueAtTime(0,s+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,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=n}}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 n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,s=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,s),e}disconnect(e,n,s){e===void 0?this.output.disconnect():this.output.disconnect(e,n,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Se={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},L=class r{constructor(e={}){this.ctx=N.audioCtx,this.cfg=structuredClone(Se),Object.assign(this.cfg,e)}ctx;cfg;play(e=N.sfxGain){let n=this.ctx,s=n.currentTime,a=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,s);let d=a.ampEnv;l.gain.exponentialRampToValueAtTime(d.volume,s+d.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),s+d.attack+d.decay),l.gain.exponentialRampToValueAtTime(1e-4,s+a.duration+d.release);let f=l,o;a.filter.enabled&&(o=n.createBiquadFilter(),o.type=a.filter.type,o.frequency.value=a.filter.freq,o.Q.value=a.filter.Q,o.connect(l),f=o);let h;if(a.osc.enabled){if(h=n.createOscillator(),h.type=a.osc.type,h.frequency.value=a.osc.freq,h.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let i=Math.pow(2,a.pitchEnv.amount/12);h.frequency.exponentialRampToValueAtTime(a.osc.freq*i,s+a.pitchEnv.decay)}h.connect(f),h.start(s),h.stop(s+a.duration+d.release)}let p;if(a.noise.enabled){let i=n.sampleRate*a.duration,u=n.createBuffer(1,i,n.sampleRate),c=u.getChannelData(0);for(let y=0;y<i;y++)c[y]=(Math.random()*2-1)*a.noise.level;p=n.createBufferSource(),p.buffer=u,p.connect(f),p.start(s),p.stop(s+a.duration+d.release)}let g,x;a.lfo.enabled&&h&&(g=n.createOscillator(),g.frequency.value=a.lfo.rate,x=n.createGain(),x.gain.value=a.lfo.depth,g.connect(x),a.lfo.target==="freq"?x.connect(h.frequency):a.lfo.target==="gain"?x.connect(l.gain):a.lfo.target==="filter"&&o&&x.connect(o.frequency),g.start(s),g.stop(s+a.duration)),l.connect(e);let v=[h,p,g,x,o,l],t=s+a.duration+d.release;setTimeout(()=>{v.forEach(i=>i?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),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,n,s,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:s,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),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,n,s){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:s,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,s){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:s,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},Ie=new L({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Fe=new L({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Me=new L({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 L({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}),Le=new L({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}),Ye=new Map([["ui_click",Ie],["ui_hover",Fe],["jump",Me],["laser",Ae],["hit",Le]]);function je(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(r)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}function ae(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}var ye=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${_e()}_${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,n){this.events[e]||(this.events[e]=[]),this.events[e].push(n)}off(e,n){this.events[e]&&(this.events[e]=this.events[e].filter(s=>s!==n))}_emit(e,n){this.events[e]?.forEach(s=>s(n))}send(e,n){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,n)}_receive(e,n){e?this._emit(e,n):this._emit("message",n)}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 _e(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let r=new Uint8Array(16);return crypto.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128,[...r].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,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function Ve(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function De(r,e,n,s,a){let l=Math.cos(a),d=Math.sin(a),f=[];if(l!==0){let o=(0-r)/l,h=e+o*d;o>0&&h>=0&&h<=s&&f.push({side:"left",t:o})}if(l!==0){let o=(n-r)/l,h=e+o*d;o>0&&h>=0&&h<=s&&f.push({side:"right",t:o})}if(d!==0){let o=(0-e)/d,h=r+o*l;o>0&&h>=0&&h<=n&&f.push({side:"top",t:o})}if(d!==0){let o=(s-e)/d,h=r+o*l;o>0&&h>=0&&h<=n&&f.push({side:"bottom",t:o})}return f.length===0?null:(f.sort((o,h)=>o.t-h.t),f[0])}function Ge(r,e){let n;switch(e){case"left":case"right":n=Math.PI-r;break;case"top":case"bottom":n=2*Math.PI-r;break}return(n%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function Qe(r,e,n,s,a){let l=De(r,e,n,s,a);return l?{...l,avoidAngle:Ge(a,l.side)}:null}function ze(){return D?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var Je=ze();var Q={};Ke(Q,{JSX:()=>$e,KMatrix2D:()=>ve,KaylaContext:()=>oe,KaylaFragment:()=>yt,KaylaInternals:()=>z,KaylaRect:()=>_,Layer:()=>wt,createContext:()=>rt,createElement:()=>nt,createGame:()=>Ze,createReassignableObject:()=>gt,createRenderer:()=>tt,createScene:()=>et,createUseHook:()=>vt,self:()=>xe,setLogLevel:()=>xt,useClick:()=>lt,useContext:()=>mt,useCurrentGame:()=>dt,useCurrentRenderer:()=>ft,useCurrentScene:()=>Ue,useCurrentTicker:()=>pt,useDisposableRef:()=>bt,useEffect:()=>le,useEntity:()=>ct,useExports:()=>de,useFiber:()=>Ce,useFiberControl:()=>we,useGlobalClick:()=>He,useGlobalPointer:()=>ot,useInitialization:()=>ue,useNextStack:()=>Ee,usePaint:()=>ce,usePointer:()=>ut,useRect:()=>he,useRef:()=>ge,useSelf:()=>G,useShouldRefresh:()=>st,useState:()=>it,useTick:()=>ht,useViewportEffect:()=>at});function Ze({width:r,height:e,updateHz:n="frames"}){return new z.KaylaGame(r,e,n==="frames"?1/0:n)}function et(r){let e=new B(r);return new z.KaylaScene(e)}function tt(r){return new z.KaylaRenderer(r)}function nt(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+ae(),{type:r,props:n}}var _;(s=>{function r(a,l){return!(a.right<l.left||a.left>l.right||a.bottom<l.top||a.top>l.bottom)}s.rawCollision=r;function e(a,l,d){let f=l*Math.PI/180,o=Math.cos(f),h=Math.sin(f),p=1/0;return o>0&&(p=Math.min(p,(d.right-a.x)/o)),o<0&&(p=Math.min(p,(d.left-a.x)/o)),h>0&&(p=Math.min(p,(d.bottom-a.y)/h)),h<0&&(p=Math.min(p,(d.top-a.y)/h)),F.from(l).scale(p)}s.getCurrToBound=e;function n(a){let{left:l,right:d,top:f,bottom:o,width:h,height:p,x:g=0,y:x=0}=a;if(h===null||p===null)throw new Error("width and height are required");let v,t;if(l!=null&&d!=null){if(Math.abs(d-l-h)>1e-6)throw new Error("left, right, and width mismatch");v=l}else g!=null?v=g-h/2:l!=null?v=l:d!=null?v=d-h:v=0;if(f!=null&&o!=null){if(Math.abs(o-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else x!=null?t=x-p/2:f!=null?t=f:o!=null?t=o-p:t=0;return{left:v,right:v+h,top:t,bottom:t+p,width:h,height:p,x:v+h/2,y:t+p/2}}s.createRawRect=n})(_||={});var z;(x=>{class r extends W{#e;#t;constructor(t,i,u){super(t,i,u),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}x.KaylaGame=r;class e extends q{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",i=>{if(this.game)for(let u of this.game.scenes.values())u.handleDraw(i)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new I,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=i=>this.onPointerAll(i,"down"),this.onPointerUp=i=>this.onPointerAll(i,"up"),this.onPointerCancel=i=>this.onPointerAll(i,"cancel"),this.onPointerMove=i=>this.onPointerAll(i,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,i){this.pointerPosUpdater(t);let u=e.getClickType(t);if(u!=="invalid"||i==="move"||i==="cancel"){t.preventDefault();let c=this.getMousePos();this.pointerEvents.emit("action",c,u,i)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,i){let u=this.canvas.getBoundingClientRect(),c=(t-u.left)/u.width,y=(i-u.top)/u.height,b=c*this.viewportWidth*this.cameraWidth/u.width,C=y*this.viewportHeight*this.cameraHeight/u.height;return new F(b,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let i=u=>{t(u,new s)};return this.on("draw",i),()=>{this.off("draw",i)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}x.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){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]=t,this.current.useStepCallIndex++}usePaint(t){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]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return ge(xe)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let i=ge(null);return(i.current===null||i.current===void 0)&&(i.current=t()),i.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let i=this.current;i.onInits[this.current.useInitCallIndex]=t,i.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return G(()=>new x.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return G(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return G(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:i=>{t.setMaxChildren(i)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:i=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let c=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:i});return this.current.state[this.current.useStateCallIndex]=c,this.current.useStateCallIndex++,c}useShouldRefresh(t){let i=this.current;if(!i)throw new Error("useShouldRefresh must be called inside a component");i.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),i.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let u=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=u,this.current.useRefCallIndex++,u}useEffect(t){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]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,i){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=i}useGlobalPointer(t,i){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");i??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:i},this.current.useGlobalClickCallIndex++}usePointer(t,i){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");i??={};let u=this.current;He((c,y,b)=>{let C=u.entity;if(!C)return;let E=C.getRawRect(),H=_.createRawRect({x:c.x,y:c.y,width:3,height:3});_.rawCollision(E,H)&&t(c,y,b)},i)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,i,u,...c)=>{let y=t?.fc?.name||"anonymous",b=t?.key?` key=${t.key}`:"";this.logger[i](`${u} <${y}${b}>`,...c)}}}x.GlobalKayla=n;class s{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}x.KaylaEvent=s;class a{#e;#t;#n;alwaysRecall;constructor(t,i,{alwaysRecall:u=!1}={}){this.#t=t,this.#e=i??void 0,this.#n=Date.now(),this.alwaysRecall=u}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
2
- You probably wrote: const [value, setValue] = useState(...)
3
-
4
- \u2192 In Kayla write: const value = useState(...);
5
- \u2192 Then: value.get() / value.set(v) / value.add(n)`)}refreshBased(){return[this.set.bind(this),this.get()]}add(t,{recall:i}={}){this.set(this.get()+t,{recall:i})}multiply(t,{recall:i}={}){this.set(this.get()*t,{recall:i})}set(t,{recall:i=!1}={}){let u=this.#e;if(t===u)return;this.#e=t;let y=Date.now()-this.#n;i&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(i||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}x.KaylaInternalState=a;class l{#e;constructor(t){this.#e=t??void 0}#t;setSetter(t){this.#t=t}get current(){return this.#e}set current(t){this.#e=t,this.#t&&this.#t(this.#e)}}x.KaylaInternalRef=l;function d(v){return new l(v)}x.createReassignableRef=d;class f{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;lastLayer;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,i,u){if(!u)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=i,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=u.type,this.callProps=u.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalPointer=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+ae(),this.onViewportEffect=[],this.lastLayer=null}getCorrectMousePos(t){return t??=this.getAttachedRenderer().getMousePos(),this.lastLayer?.transform?this.lastLayer.transform.inverseV(t):t}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,i,u){t=this.getCorrectMousePos(t);try{for(let{handler:c,config:y}of this.onGlobalPointer)y.type??="any",y.action??="down",!(y.action!=="any"&&y.action!==u||y.type!=="any"&&y.type!==i)&&c(t,i,u)}catch(c){this.global.logger.error(c)}}resizeHook({width:t,height:i}){try{for(let u of this.onViewportEffect)u(this.getAttachedRenderer(),t,i)}catch(u){this.global.logger.error(u)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){return this.callProps.children}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalPointer;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let i=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${i} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let u=this.lastChildren.slice(0,this.maxSafeChildren),c=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=u;for(let y of c)y.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],i=this.detectedParent;for(;i;)t.push(i),i=i?.detectedParent;return t}getAllChildrenNestedFlattened(){let t=[],i=(u=[])=>{for(let c of u)t.push(c),c.lastChildren?.length&&i(c.lastChildren)};return i(this.lastChildren),t}getContextChain(){return this.getFiberChain().map(t=>t.contextInfo).filter(Boolean)}findContextValueFromInst(t){return this.getContextChain().find(i=>i.instance===t)?.value}getEntityChain(){return this.getFiberChain().map(t=>t.entity)}shouldFullRefresh(){if(this.isFirstUse||!this.watchedDeps||this.watchedDeps.length===0)return!0;for(let t=0;t<this.watchedDeps.length;t++){let i=this.watchedDeps[t],u=this.lastDepStamps[t]??0;if(i.lastChanged>u)return!0}return!1}captureDepStamps(){this.watchedDeps&&(this.lastDepStamps=this.watchedDeps.map(t=>t.lastChanged))}refresh(){if(!this.shouldFullRefresh())return;let t=this.fc?.name||"anonymous";if(!this.shouldFullRefresh()){this.global.logger.debug(`Refresh skipped <${t} key=${this.key}>`);return}this.global.logger.debug(`Refresh executed <${t} key=${this.key}> reason=${this.isFirstUse?"first":"deps-changed"}`),this.lastChildren.length>this.maxSafeChildren&&this.global.logger.warn(`High child count <${t} key=${this.key}> children=${this.lastChildren.length}`);let i;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let u=[];try{let c=this.fc(this.callProps)??[];if(c&&!Array.isArray(c)&&(c=[c]),!Array.isArray(c))throw new Error("Non array or non undefined children received.");for(let y of c)if(y.type===this.fc)throw new Error("Circular Component.");u=c}catch(c){i=c}if(this.global.restore(),this.updateChildren(u,!0),i)throw i}updateChildren(t,i){try{let u=[...t,...this.dynamicChildren],c=[],y=[];for(let b of u){let C=b.props?.key,E;C!=null&&(E=this.lastChildren.find(H=>H.key===C)),E||(E=new f(this.global,this.scene,b)),E.callProps=b.props,E.detectedParent=this,y.push(E),c.push(E)}for(let b of this.lastChildren)c.includes(b)||b.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let b of this.lastChildren)try{b.refresh()}catch(C){console.error(C)}}catch(u){console.error(u)}}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=!0),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let i=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(c=>({stamp:c.lastChanged,stateRef:c}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new o(this,this.key);for(let c of this.refs)c.current===xe&&(c.current=this.entity);if(this.callProps.ref instanceof l&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof l&&(this.callProps.exportsRef.current=this.exports),this.entity&&this.entity!==this.entity&&this.global.logger.warn(`Entity name mismatch during refresh <${this.fc?.name} key=${this.key}>`),this.scene.getScene().addEntity(this.entity),i){this.onUnInits=[];for(let c of this.onInits){this.bindEvents();try{let y=c();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let c of this.onUnEffect??[])c()}catch(c){console.error(c)}let u=this.onEffect.map(c=>c()).filter(c=>c!==void 0);this.onUnEffect=u}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}}x.KaylaFiber=f;class o extends Y{#e;flags;getRawRect(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,i){super(i,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,i){return this.flags.set(t,i)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){let i=new s;if(this.#e&&this.#e.onTick)for(let u of this.#e.onTick)u(t,i);i.isPrevented()}draw(t){let i=new s;if(this.#e&&this.#e.onPaint)for(let u of this.#e.onPaint)u(t,i);i.isPrevented()||super.draw(t)}getRect(){return new h(this.getFiber())}}x.KaylaRectEntity=o;class h{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}get entity(){return this.#e.entity??null}#t(){if(!this.#e)throw new Error("No fibers found.");if(!this.entity)throw new Error("The entity does NOT exist yet.")}isCollidingWith(t){return this.#t(),this.entity.isCollidingWith(t.entity)}get setFlag(){return this.#t(),this.entity.setFlag.bind(this.entity)}get getFlag(){return this.#t(),this.entity.getFlag.bind(this.entity)}get removeFlag(){return this.#t(),this.entity.removeFlag.bind(this.entity)}isHovered(){let t=this.getRaw(),i=this.#e.getCorrectMousePos(),u=_.createRawRect({x:i.x,y:i.y,width:3,height:3});return _.rawCollision(t,u)}get pos(){return this.#t(),this.entity.pos}get x(){return this.#t(),this.pos.x}set x(t){this.#t(),this.pos.x=t}get y(){return this.#t(),this.pos.y}set y(t){this.#t(),this.pos.y=t}get width(){return this.#t(),this.entity.width}set width(t){this.#t(),this.entity.width=t}get height(){return this.#t(),this.entity.height}set height(t){this.#t(),this.entity.height=t}get z(){return this.#t(),this.entity.z}set z(t){this.#t(),this.entity.z=t}get left(){return this.#t(),this.entity.left}set left(t){this.#t(),this.entity.left=t}get right(){return this.#t(),this.entity.right}set right(t){this.#t(),this.entity.right=t}get top(){return this.#t(),this.entity.top}set top(t){this.#t(),this.entity.top=t}get bottom(){return this.#t(),this.entity.bottom}set bottom(t){this.#t(),this.entity.bottom=t}get toLocal(){return this.entity.toLocal.bind(this.entity)}get toWorld(){return this.entity.toWorld.bind(this.entity)}}x.KaylaInternalRect=h;class p{#e;#t;constructor(t){this.#r=t,this.#n=null,this.#e=new Map,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this),t.handleDraw=this.drawHandler,this.#t=null}getLayers(){return this.#e}#n;#r;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#r}getGame(){return this.#n}getOrCreateLayer(t,i=0){return this.#e.has(t)||this.#e.set(t,{name:t,z:i,visible:!0,rootFiber:null}),this.#e.get(t)}getSortedLayers(){return Array.from(this.#e.values()).filter(t=>t.visible).sort((t,i)=>t.z-i.z)}setLayerVisible(t,i){let u=this.#e.get(t);u&&(u.visible=i)}handleDraw(t){if(D)return;let i=this.getScene();if(i.paused)return;i.emit("draw",t);let u=this.getSortedLayers(),c=[];for(let b of u){if(!b.visible)continue;let C=b.rootFiber;if(!C)continue;let E=C.getAllChildrenNestedFlattened().flat().map(K=>K.entity).filter(Boolean);if(c.push(...E),t.save(),b.transform){let K=b.transform;t.setTransform(K.a,K.b,K.c,K.d,K.e,K.f)}b.blendMode&&(t.globalCompositeOperation=b.blendMode??"source-over");let H=Array.from(E).sort((K,P)=>K.z-P.z);for(let K of H)K.getFiber().lastLayer=b,K.handleDraw(t);t.restore()}let y=[...i.entities.values()].filter(b=>!c.includes(b));for(let b of y.sort((C,E)=>C.z-E.z))b.getFiber().lastLayer=null,b.handleDraw(t)}drawHandler(t){return this.handleDraw(t)}attachTo(t){t.addScene(this.#r),this.#n=t}async spawn(t){this.#t&&(this.#t.unuse(),this.#t=null);let i=this.createFiber(t);this.#t=i,await this.#n.delay(0),i.refresh()}getRoot(){return this.#t??null}createFiber(t){return new f(x.singleGlobalInstance,this,t)}detach(){this.#n&&this.#n.removeScene(this.#r)}tickHandler(){}}x.KaylaScene=p,x.singleGlobalInstance=new x.GlobalKayla})(z||={});var oe=class{#e;constructor(e){this.Provider=this.#t.bind(this),this.#e=e}get defaultValue(){return this.#e}#t({value:e=this.defaultValue,children:n}){let s=Ce();return le(()=>{s.contextInfo={instance:this,value:e}}),de(this.Provider,()=>({value:e})),n}Provider;Consumer};function rt(r){return new oe(r)}var m=z.singleGlobalInstance,it=m.useState.bind(m),ge=m.useRef.bind(m),st=m.useShouldRefresh.bind(m),le=m.useEffect.bind(m),at=m.useViewportEffect.bind(m),He=m.useGlobalPointer.bind(m),ot=m.useGlobalPointer.bind(m),lt=m.usePointer.bind(m),ut=m.usePointer.bind(m),ue=m.useInitialization.bind(m),he=m.useRect.bind(m),ht=m.useTick.bind(m),ce=m.usePaint.bind(m),de=m.useExports.bind(m),G=m.useSelf.bind(m),we=m.useFiberControl.bind(m),Ce=m.useFiber.bind(m),ct=m.useEntity.bind(m),dt=m.useCurrentGame.bind(m),ft=m.useCurrentRenderer.bind(m),Ue=m.useCurrentScene.bind(m),pt=m.useCurrentTicker.bind(m),mt=m.useContext.bind(m),xe=Symbol("self_ref");var Ee=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},yt=({children:r})=>Array.isArray(r)?[...r]:r;function bt(r){return z.createReassignableRef(r)}function gt(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(s,a,l){return a==="reassignSelf"?d=>{e.current=d}:Reflect.get(e.current,a,l)},set(s,a,l,d){return Reflect.set(e.current,a,l,d)},has(s,a){return Reflect.has(e.current,a)},ownKeys(s){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(s,a){return Reflect.getOwnPropertyDescriptor(e.current,a)},deleteProperty(s,a){return Reflect.deleteProperty(e.current,a)}})}function xt(r){m.logLevel=r}function vt(r){let e=r.name||"anonymous-custom-hook";return function(s){let a=m.current;if(!a)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let l=s??{};return r.memoize!==!1?G(()=>(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,l))):(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,l))}}var $e;(e=>e.id="kayla")($e||={});var wt=({name:r,z:e=0,blend:n,visible:s=!0,children:a,transform:l})=>{let d=Ue(),f=Ce();return ue(()=>{let o=d.getOrCreateLayer(r,e);return o.blendMode=n,o.visible=s,o.rootFiber=f,o.transform=l??null,()=>{d.getLayers().delete(r)}}),a},ve=class extends DOMMatrix{#e;constructor(){super(),this.#e=new DOMPoint}transformV(e){this.#e.x=e.x,this.#e.y=e.y;let n=this.#e.matrixTransform(this);return new F(n.x,n.y)}inverseV(e){let n=this.inverse();this.#e.x=e.x,this.#e.y=e.y;let s=this.#e.matrixTransform(n);return new F(s.x,s.y)}};Reflect.set(globalThis,"Kayla",Q);var Ct;(n=>(n.Flex=({align:s="stretch",children:a,direction:l="row",gap:d=0,justify:f="start",wrap:o="nowrap",getHeight:h,getWidth:p,getCenterX:g,getCenterY:x,color:v})=>{let t=we(),i=he(),u=G(()=>({recalc(){let c=Number(d)||0,y=g(),b=x(),C=p(),E=h();i.x=y,i.y=b,i.width=C,i.height=E;let K=t.getChildrenEntities().filter(Boolean).map(w=>w.getRect()).filter(w=>w.getFlag("flex-ignored")!==!0),P=l==="row",A=P?i.width:i.height,Et=P?i.height:i.width,fe=0,X=0,pe=[],J=[];K.forEach(w=>{let Z=P?w.width:w.height;fe+Z>A&&o==="wrap"?(pe.push({height:X,items:J}),J=[w],fe=Z,X=P?w.height:w.width):(J.push(w),fe+=Z+c,X=Math.max(X,P?w.height:w.width))}),pe.push({height:X,items:J});let me=0;pe.forEach((w,Z)=>{let M=w.items,V=M.reduce((k,ee)=>k+(P?ee.width:ee.height),0)+c*(M.length-1),S=0;f==="center"&&(S=(A-V)/2),f==="end"&&(S=A-V),f==="space-between"&&(S=0),f==="space-around"&&(S=(A-V)/(M.length*2)),f==="space-evenly"&&(S=(A-V)/(M.length+1)),M.forEach((k,ee)=>{k.z=i.z+1;let U=P?k.width:k.height,te=P?k.height:k.width,ne=0;s==="center"&&(ne=(w.height-te)/2),s==="end"&&(ne=w.height-te),s==="stretch"&&(P?k.height=w.height:k.width=w.height),P?(k.x=S+U/2,k.y=me+ne+te/2):(k.x=me+ne+te/2,k.y=S+U/2),f==="space-between"&&ee<M.length-1?S+=U+c+(A-V)/(M.length-1):f==="space-around"?S+=U+c+(A-V)/M.length:f==="space-evenly"?S+=U+c+(A-V)/(M.length+1):S+=U+c}),me+=w.height+c})}}));return ce((c,y)=>{y.preventDefault(),c.fillStyle=v,c.fillRect(i.left,i.top,i.width,i.height)}),le(()=>{Ee(()=>{u.recalc()})}),de(n.Flex,()=>({controls:u})),a},n.GenericBox=({color:s,width:a=20,height:l=20,x:d=0,y:f=0})=>{let o=he();ue(()=>{o.width=a,o.height=l,o.x=d,o.y=f}),ce((h,p)=>{p.preventDefault(),h.fillStyle=s,h.fillRect(o.left,o.top,o.width,o.height)})}))(Ct||={});var Pt={LEA:j,Kayla:Q};export{Q as Kayla,j as LEA,Pt as default};
1
+ var Oe=Object.defineProperty;var Ke=(r,e)=>{for(var n in e)Oe(r,n,{get:e[n],enumerable:!0})};var j={};Ke(j,{DeltaTweenII:()=>ie,ENVIRONMENT:()=>ge,GEmitterMemory:()=>be,LeaEntityII:()=>O,LeaEventEmitter:()=>S,LeaGameII:()=>W,LeaRendererII:()=>q,LeaSceneII:()=>B,LeaSerializers:()=>Re,LeaTickerII:()=>re,LeaTimeout:()=>se,LeaUtilsII:()=>T,LiaAudio:()=>N,LiaAudioSrc:()=>$,LiaOscSFX:()=>L,LiaSFXMap:()=>Ye,NOTE_NAMES:()=>Pe,RectLeaEntity:()=>Y,Vector2:()=>F,colToRGBA:()=>Xe,defaultSFXConfig:()=>Ie,editRGBA:()=>qe,generateUUID:()=>_e,getAvoidAngle:()=>Ge,getEnvironment:()=>Te,getNormalizedColor:()=>Ne,getRayHit:()=>De,isInitiallyMobile:()=>Je,isMobile:()=>ze,isNode:()=>D,isNote:()=>We,isWeb:()=>R,parseFillStyle:()=>ke,raycastAvoid:()=>Qe,scaleCoord:()=>Be,setAnimInterval:()=>Ve,sfxHit:()=>Le,sfxJump:()=>Me,sfxLaser:()=>Ae,sfxUIClick:()=>Se,sfxUIHover:()=>Fe,shortUID:()=>je,tinyUID:()=>ae});var S=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let s=this.#e.get(e)||[];return s.push(n),this.#e.set(e,s),this}once(e,n){let s=(...a)=>{this.off(e,s),n(...a)};return this.on(e,s),this}off(e,n){let s=this.#e.get(e);if(!s)return this;let a=s.indexOf(n);return a>=0&&s.splice(a,1),this}emit(e,...n){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw n[0];return!1}return s.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},q=class extends S{#e;#t;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;get canvas(){return this.#e}get ctx(){return this.#t}set canvas(e){this.#e=e,this.#t=e.getContext("2d"),this.updateCanvasResolution()}constructor(e,{viewportWidth:n,viewportHeight:s,cameraWidth:a,cameraHeight:l}={}){if(!R)throw new Error("Web-Only");super(),this.canvas=e,this.automatic=!0,this.#n=n??e.width,this.#r=s??e.height,this.#i=a??e.width,this.#s=l??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.#i/this.#n,n=this.#s/this.#r;this.ctx.translate(this.#i/2,this.#s/2),this.ctx.scale(e,n),this.ctx.translate(-this.#n/2,-this.#r/2)}#n=0;#r=0;#i=0;#s=0;get viewportWidth(){return this.#n}set viewportWidth(e){this.#n=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#n}get height(){return this.#r}get centerX(){return this.#n/2}get centerY(){return this.#r/2}get left(){return 0}get top(){return 0}get right(){return this.#n}get bottom(){return this.#r}get viewportHeight(){return this.#r}set viewportHeight(e){this.#r=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#i}set cameraWidth(e){this.#i=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#s}set cameraHeight(e){this.#s=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#i,this.canvas.height=this.#s}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!R)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#i,this.#s),this.emit("draw",this.ctx)}start(){if(!this.running){if(!R||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!R||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},re=class extends S{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(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(R&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new se(e,this)}createTween(e,n=()=>{}){let s=new ie(e),a=(l=0)=>{if(s.finished){this.off("tick",a);return}s.update(l)};return s.on("finish",()=>{this.off("tick",a)}),s.on("delta",l=>{n(l)}),this.on("tick",a),s}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=R&&!isFinite(this.tickInterval)?Ve(()=>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,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},Re;(t=>{function r(i){return i===!0?1:0}t.booleanExport=r;function e(i){return i===0?!1:i===1}t.booleanImport=e;function n(i){return`${i.x}|${i.y}`}t.vec2Export=n;function s(i){let[u,c]=i.split("|"),y=parseFloat(u),b=parseFloat(c);if(isNaN(y)||isNaN(b))throw new Error(`Invalid Vector2 string: ${i}`);return new F(y,b)}t.vec2Import=s,t.booleanMap={mapExport:r,mapImport:e};function l(i){return u=>Number(u.toFixed(i))}t.createRounder=l;function d(i=10){return{mapExport(u){return Math.round(u/i)},mapImport(u){return u*i}}}t.createLowPrecision=d;function f(i){return Math.round(i)}t.lightWeightRounder=f;function o(i=100){return{mapExport(u){return Math.round(u*i)},mapImport(u){return u/i}}}t.createPercent=o;function h(i){let u=new Map(Object.entries(i));return{mapExport:c=>u.get(c)??null,mapImport:c=>Array.from(u.entries()).find(([y,b])=>b===c)?.[0]??null}}t.createLookup=h;function p(i){let u=i*(180/Math.PI);return Math.round((u%360+360)%360)}t.radToDeg=p;function g(i){return i*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:p,mapImport:g};function v(i=10){let u=d(i);return{mapExport(c){return u.mapExport(p(c))},mapImport(c){return u.mapImport(g(c))}}}t.createLowPrecisionRadToDeg=v})(Re||={});var O=class r extends S{name="";scaleRotate=0;scale=1;constructor(e,n=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new F(n,s),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(n){this.emit("error",n)}}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(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:l}])=>{let d=Reflect.get(this,a);return l?l(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),s=Object.fromEntries(n.map(a=>{let l=Reflect.get(this,a);if(D&&typeof l=="number"){let d=l.toString().split("."),o=(d[1]?d[1].length:0)>2?Number(l.toFixed(2)):l;return[a,o]}return[a,l]}));return JSON.parse(JSON.stringify(s))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return r.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,n){if(!e||!Array.isArray(n))return n;let s={};for(let a=0;a<n.length;a++){let l=e[a];if(!l)break;let[d,{mapImport:f}]=l,o=n[a];if(f&&(o=f(o)),typeof d!="string")break;try{Reflect.set(s,d,o)}catch(h){console.error(h)}}return s}},B=class extends S{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!D&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((s,a)=>s.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof O))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 O))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},W=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,n,s=16){this.ticker=new re(s),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let l of this.scenes.values())l.paused||l.handleUpdate(a)})}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()}},T={lerp(r,e,n){return r+(e-r)*n},clamp(r,e,n){return Math.min(n,Math.max(e,r))},clamp01(r){return Math.min(1,Math.max(0,r))},easeLinear(r){return r},easeInQuad(r){return r*r},easeOutQuad(r){return 1-(1-r)*(1-r)},easeInOutQuad(r){return r<.5?2*r*r:1-Math.pow(-2*r+2,2)/2},easeInSine(r){return 1-Math.cos(r*Math.PI/2)},easeOutSine(r){return Math.sin(r*Math.PI/2)},easeInOutSine(r){return-(Math.cos(Math.PI*r)-1)/2},easeInExpo(r){return r===0?0:Math.pow(2,10*r-10)},easeOutExpo(r){return r===1?1:1-Math.pow(2,-10*r)},easeInOutExpo(r){return r===0?0:r===1?1:r<.5?Math.pow(2,20*r-10)/2:(2-Math.pow(2,-20*r+10))/2},smoothstep(r){return r=T.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return T.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[T.randomInt(0,r.length-1)]},createBezier(r,e,n,s){function a(f,o,h,p,g){let x=1-f;return x*x*x*o+3*x*x*f*h+3*x*f*f*p+f*f*f*g}function l(f,o,h,p,g){let x=1-f;return 3*x*x*(h-o)+6*x*f*(p-h)+3*f*f*(g-p)}function d(f){let o=f;for(let h=0;h<6;h++){let p=a(o,0,r,n,1),g=l(o,0,r,n,1);if(g===0)break;o-=(p-f)/g}return T.clamp(o,0,1)}return function(o){o=T.clamp(o,0,1);let h=d(o);return a(h,0,e,s,1)}},lengthSquared(...r){return r.reduce((e,n)=>e+n*n,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return T.normalizeRad(-r)},degToRadFlipY(r){return T.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=T.normalizeRad(r),e=T.normalizeRad(e);let n=T.normalizeRad(e-r),s=T.normalizeRad(r-e);return n<=s?1:-1}},ie=class extends S{constructor({delta:e,ms:n,easing:s}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=s??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=T.clamp(this.elapsed/this.duration,0,1),s=this.easing(n),a=this.delta*s,l=a-this.lastValue;this.lastValue=a,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},Y=class extends O{constructor(e,n=0,s=0,a=50,l=50){super(e,n,s),this.width=a,this.height=l}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)}},se=class extends S{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(s=>this._resolve=s),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,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},F=class r{constructor(e=0,n=0){this.x=e,this.y=n}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 n=Math.cos(e),s=Math.sin(e);return new r(this.x*n-this.y*s,this.x*s+this.y*n)}static from(e){return new r(Math.cos(e),Math.sin(e))}isEmpty(){return Math.abs(this.x)<.01&&Math.abs(this.y)<.01}get angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-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 r(0,0):new r(this.x/e,this.y/e)}consume(e){let n=this.length;n<=e?(this.x=0,this.y=0):this.overwite(this.scale((n-e)/n))}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let n=this.dot(e);return this.subtract(e.scale(2*n))}dotNormalized(e){let n=this.normalized(),s=e.normalized();return n.x*s.x+n.y*s.y}lengthSquaredTo(e){let n=this.x-e.x,s=this.y-e.y;return n*n+s*s}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 n=this.x-e.x,s=this.y-e.y;return n*n+s*s}directionTo(e){return new r(e.x-this.x,e.y-this.y).normalized()}add(e){return new r(this.x+e.x,this.y+e.y)}addRaw(e){return new r(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new r(this.x-e.x,this.y-e.y)}scale(e){return new r(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new r(this.x,this.y)}};function Ne(r){let e=/^rgba?\(([^)]+)\)$/,n=r.match(e);if(n){let[s,a,l,d=1]=n[1].split(",").map(f=>parseFloat(f));return{r:Math.max(0,Math.min(255,Math.floor(s))),g:Math.max(0,Math.min(255,Math.floor(a))),b:Math.max(0,Math.min(255,Math.floor(l))),a:Math.max(0,Math.min(1,Math.floor(d*255)/255))}}return ke(r)}function Xe(r){return`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a})`}function ke(r){if(r=r.trim().toLowerCase(),r[0]==="#"){let n,s,a;if(r.length===7)n=parseInt(r.slice(1,3),16),s=parseInt(r.slice(3,5),16),a=parseInt(r.slice(5,7),16);else if(r.length===4)n=parseInt(r[1]+r[1],16),s=parseInt(r[2]+r[2],16),a=parseInt(r[3]+r[3],16);else throw new Error("Invalid hex color");return{r:n,g:s,b:a,a:1}}let e=r.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 qe(r,{r:e,g:n,b:s,a}={}){let[l,d,f,o,h]=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??d}, ${n??f}, ${s??o}, ${a??(h||1)})`}function Be(r,e,n){return n+(r-n)*e}function Te(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var ge=Te(),D=ge==="node",R=ge==="web",N=class r{static unlock(){R&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=R?new AudioContext:null;static masterGain=R?this.audioCtx.createGain():null;static musicGain=R?this.audioCtx.createGain():null;static sfxGain=R?this.audioCtx.createGain():null;static{R&&(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 n=r.CACHE_NAME,s,a;if(typeof caches<"u"&&(a=await caches.open(n),s=await a.match(e)),!s){if(s=await fetch(e),!s.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,s.clone())}let l=await s.arrayBuffer(),d=await this.audioCtx.decodeAudioData(l);return this.audioBufferCache.set(e,d),d}static async getOnlyDownloadedCache(e){let n=r.CACHE_NAME;return await(await caches.open(n)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,n=.2,s=1,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return;let d=new $(l);d.buffer=l;let f=1-.12,o=1+.12;d.playbackRate=s??f+Math.random()*(o-f);let h=this.audioCtx.createGain();h.gain.value=n,d.tempGain=h,d.connect(h),h.connect(this.sfxGain),d.onended=()=>{d.disconnect(),h.disconnect()},d.start(),a&&this.sfsx.set(e,{source:d,gain:h})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:s=0,loopEnd:a=null,exclusive:l=!0,skipMS:d=0}={}){if(l)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let o=new $(f);o.buffer=f,o.loop=!0,typeof s=="number"&&(o.loopStart=s),typeof a=="number"&&(o.loopEnd=a);let h=this.audioCtx.createGain();h.gain.value=n,o.tempGain=h,o.playbackRate=1,o.onended=()=>{o.disconnect(),h.disconnect()},o.connect(h),h.connect(this.musicGain),o.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:o,gain:h}),p}static stopLoop(e){let n=this.loops.get(e);n&&(n.source.stop(),n.source.notIndependent||(n.source.disconnect(),n.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:n=1,speed:s=1,loop:a=!1,loopStart:l=0,loopEnd:d=null,isMusic:f=!1,gain:o=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return null;let p=new $(h);p.loop=a,p.loopStart=l,p.loopEnd=typeof d=="number"?d:h.duration,p.playbackRate=s;let g=this.audioCtx.createGain();return g.gain.value=n,p.connect(g),p.tempGain=g,g.connect(o||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),g.disconnect()},p}catch(h){return console.error("Failed to create LiaAudioSrc:",h),null}}},Pe=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function We(r){return Pe.includes(r)}var $=class{numberOfInputs;numberOfOutputs;constructor(e,n=N.audioCtx){this.context=n,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=R?n.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:n=null}={}){let s=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-s/this.playbackRate,this.source.start(0,s),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,n=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,n,s):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%s}if(this.isPlaying=!1,e>0){let s=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,s),this.output.gain.linearRampToValueAtTime(0,s+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,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=n}}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 n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,s=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,s),e}disconnect(e,n,s){e===void 0?this.output.disconnect():this.output.disconnect(e,n,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),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},L=class r{constructor(e={}){this.ctx=N.audioCtx,this.cfg=structuredClone(Ie),Object.assign(this.cfg,e)}ctx;cfg;play(e=N.sfxGain){let n=this.ctx,s=n.currentTime,a=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,s);let d=a.ampEnv;l.gain.exponentialRampToValueAtTime(d.volume,s+d.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),s+d.attack+d.decay),l.gain.exponentialRampToValueAtTime(1e-4,s+a.duration+d.release);let f=l,o;a.filter.enabled&&(o=n.createBiquadFilter(),o.type=a.filter.type,o.frequency.value=a.filter.freq,o.Q.value=a.filter.Q,o.connect(l),f=o);let h;if(a.osc.enabled){if(h=n.createOscillator(),h.type=a.osc.type,h.frequency.value=a.osc.freq,h.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let i=Math.pow(2,a.pitchEnv.amount/12);h.frequency.exponentialRampToValueAtTime(a.osc.freq*i,s+a.pitchEnv.decay)}h.connect(f),h.start(s),h.stop(s+a.duration+d.release)}let p;if(a.noise.enabled){let i=n.sampleRate*a.duration,u=n.createBuffer(1,i,n.sampleRate),c=u.getChannelData(0);for(let y=0;y<i;y++)c[y]=(Math.random()*2-1)*a.noise.level;p=n.createBufferSource(),p.buffer=u,p.connect(f),p.start(s),p.stop(s+a.duration+d.release)}let g,x;a.lfo.enabled&&h&&(g=n.createOscillator(),g.frequency.value=a.lfo.rate,x=n.createGain(),x.gain.value=a.lfo.depth,g.connect(x),a.lfo.target==="freq"?x.connect(h.frequency):a.lfo.target==="gain"?x.connect(l.gain):a.lfo.target==="filter"&&o&&x.connect(o.frequency),g.start(s),g.stop(s+a.duration)),l.connect(e);let v=[h,p,g,x,o,l],t=s+a.duration+d.release;setTimeout(()=>{v.forEach(i=>i?.disconnect())},(t-n.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,n){return Object.assign(this.cfg[e],n),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,n,s,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:s,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),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,n,s){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:s,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,s){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:s,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},Se=new L({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Fe=new L({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Me=new L({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 L({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}),Le=new L({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}),Ye=new Map([["ui_click",Se],["ui_hover",Fe],["jump",Me],["laser",Ae],["hit",Le]]);function je(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(r)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}function ae(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),s=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}var be=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${_e()}_${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,n){this.events[e]||(this.events[e]=[]),this.events[e].push(n)}off(e,n){this.events[e]&&(this.events[e]=this.events[e].filter(s=>s!==n))}_emit(e,n){this.events[e]?.forEach(s=>s(n))}send(e,n){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,n)}_receive(e,n){e?this._emit(e,n):this._emit("message",n)}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 _e(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let r=new Uint8Array(16);return crypto.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128,[...r].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,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function Ve(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function De(r,e,n,s,a){let l=Math.cos(a),d=Math.sin(a),f=[];if(l!==0){let o=(0-r)/l,h=e+o*d;o>0&&h>=0&&h<=s&&f.push({side:"left",t:o})}if(l!==0){let o=(n-r)/l,h=e+o*d;o>0&&h>=0&&h<=s&&f.push({side:"right",t:o})}if(d!==0){let o=(0-e)/d,h=r+o*l;o>0&&h>=0&&h<=n&&f.push({side:"top",t:o})}if(d!==0){let o=(s-e)/d,h=r+o*l;o>0&&h>=0&&h<=n&&f.push({side:"bottom",t:o})}return f.length===0?null:(f.sort((o,h)=>o.t-h.t),f[0])}function Ge(r,e){let n;switch(e){case"left":case"right":n=Math.PI-r;break;case"top":case"bottom":n=2*Math.PI-r;break}return(n%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function Qe(r,e,n,s,a){let l=De(r,e,n,s,a);return l?{...l,avoidAngle:Ge(a,l.side)}:null}function ze(){return D?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var Je=ze();var Q={};Ke(Q,{JSX:()=>$e,KMatrix2D:()=>we,KaylaContext:()=>oe,KaylaFragment:()=>yt,KaylaInternals:()=>z,KaylaRect:()=>_,Layer:()=>wt,createContext:()=>rt,createElement:()=>nt,createGame:()=>Ze,createReassignableObject:()=>gt,createRenderer:()=>tt,createScene:()=>et,createUseHook:()=>vt,self:()=>ve,setLogLevel:()=>xt,useClick:()=>lt,useContext:()=>mt,useCurrentGame:()=>dt,useCurrentRenderer:()=>ft,useCurrentScene:()=>Ue,useCurrentTicker:()=>pt,useDisposableRef:()=>bt,useEffect:()=>le,useEntity:()=>ct,useExports:()=>de,useFiber:()=>Ee,useFiberControl:()=>Ce,useGlobalClick:()=>He,useGlobalPointer:()=>ot,useInitialization:()=>ue,useNextStack:()=>fe,usePaint:()=>ce,usePointer:()=>ut,useRect:()=>he,useRef:()=>xe,useSelf:()=>G,useShouldRefresh:()=>st,useState:()=>it,useTick:()=>ht,useViewportEffect:()=>at});function Ze({width:r,height:e,updateHz:n="frames"}){return new z.KaylaGame(r,e,n==="frames"?1/0:n)}function et(r){let e=new B(r);return new z.KaylaScene(e)}function tt(r){return new z.KaylaRenderer(r)}function nt(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+ae(),{type:r,props:n}}var _;(s=>{function r(a,l){return!(a.right<l.left||a.left>l.right||a.bottom<l.top||a.top>l.bottom)}s.rawCollision=r;function e(a,l,d){let f=l*Math.PI/180,o=Math.cos(f),h=Math.sin(f),p=1/0;return o>0&&(p=Math.min(p,(d.right-a.x)/o)),o<0&&(p=Math.min(p,(d.left-a.x)/o)),h>0&&(p=Math.min(p,(d.bottom-a.y)/h)),h<0&&(p=Math.min(p,(d.top-a.y)/h)),F.from(l).scale(p)}s.getCurrToBound=e;function n(a){let{left:l,right:d,top:f,bottom:o,width:h,height:p,x:g=0,y:x=0}=a;if(h===null||p===null)throw new Error("width and height are required");let v,t;if(l!=null&&d!=null){if(Math.abs(d-l-h)>1e-6)throw new Error("left, right, and width mismatch");v=l}else g!=null?v=g-h/2:l!=null?v=l:d!=null?v=d-h:v=0;if(f!=null&&o!=null){if(Math.abs(o-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else x!=null?t=x-p/2:f!=null?t=f:o!=null?t=o-p:t=0;return{left:v,right:v+h,top:t,bottom:t+p,width:h,height:p,x:v+h/2,y:t+p/2}}s.createRawRect=n})(_||={});var z;(x=>{class r extends W{#e;#t;constructor(t,i,u){super(t,i,u),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}x.KaylaGame=r;class e extends q{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",i=>{if(this.game)for(let u of this.game.scenes.values())u.handleDraw(i)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new S,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=i=>this.onPointerAll(i,"down"),this.onPointerUp=i=>this.onPointerAll(i,"up"),this.onPointerCancel=i=>this.onPointerAll(i,"cancel"),this.onPointerMove=i=>this.onPointerAll(i,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,i){this.pointerPosUpdater(t);let u=e.getClickType(t);if(u!=="invalid"||i==="move"||i==="cancel"){t.preventDefault();let c=this.getMousePos();this.pointerEvents.emit("action",c,u,i)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,i){let u=this.canvas.getBoundingClientRect(),c=(t-u.left)/u.width,y=(i-u.top)/u.height,b=c*this.viewportWidth*this.cameraWidth/u.width,C=y*this.viewportHeight*this.cameraHeight/u.height;return new F(b,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let i=u=>{t(u,new s)};return this.on("draw",i),()=>{this.off("draw",i)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}x.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){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]=t,this.current.useStepCallIndex++}usePaint(t){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]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return xe(ve)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let i=xe(null);return(i.current===null||i.current===void 0)&&(i.current=t()),i.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let i=this.current;i.onInits[this.current.useInitCallIndex]=t,i.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return G(()=>new x.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return G(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return G(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:i=>{t.setMaxChildren(i)},getMaxChildren:()=>t.getMaxChildren(),get maxSafeChildren(){return t.maxSafeChildren},get key(){return t.key},get getChildrenEntities(){return t.getChildrenEntities.bind(t)},get getEntityChain(){return t.getEntityChain.bind(t)},get getFiberChain(){return t.getFiberChain.bind(t)}}))}useCurrentTicker(){if(!this.current)throw new Error("Hook 'useCurrentTicker' must be executed in the top level scope of a component.");return this.current.getAttachedGame().ticker}useCurrentRenderer(){if(!this.current)throw new Error("Hook 'useCurrentRenderer' must be executed in the top level scope of a component.");return this.current.getAttachedGame().mainRenderer}useCurrentGame(){if(!this.current)throw new Error("Hook 'useCurrentGame' must be executed in the top level scope of a component.");return this.current.getAttachedGame()}useCurrentScene(){if(!this.current)throw new Error("Hook 'useCurrentScene' must be executed in the top level scope of a component.");return this.current.scene}useState(t,{alwaysRecall:i=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let c=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:i});return this.current.state[this.current.useStateCallIndex]=c,this.current.useStateCallIndex++,c}useShouldRefresh(t){let i=this.current;if(!i)throw new Error("useShouldRefresh must be called inside a component");i.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),i.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let u=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=u,this.current.useRefCallIndex++,u}useEffect(t){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]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,i){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=i}useGlobalPointer(t,i){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");i??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:i},this.current.useGlobalClickCallIndex++}usePointer(t,i){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");i??={};let u=this.current;He((c,y,b)=>{let C=u.entity;if(!C)return;let E=C.getRawRect(),H=_.createRawRect({x:c.x,y:c.y,width:3,height:3});_.rawCollision(E,H)&&t(c,y,b)},i)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,i,u,...c)=>{let y=t?.fc?.name||"anonymous",b=t?.key?` key=${t.key}`:"";this.logger[i](`${u} <${y}${b}>`,...c)}}}x.GlobalKayla=n;class s{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}x.KaylaEvent=s;class a{#e;#t;#n;alwaysRecall;constructor(t,i,{alwaysRecall:u=!1}={}){this.#t=t,this.#e=i??void 0,this.#n=Date.now(),this.alwaysRecall=u}get(){return this.#e}get 0(){return this.get()}1(t){this.set(t,{recall:!0})}legacy(){return[this[0],this[1].bind(this)]}add(t,{recall:i}={}){this.set(this.get()+t,{recall:i})}multiply(t,{recall:i}={}){this.set(this.get()*t,{recall:i})}set(t,{recall:i=!1}={}){let u=this.#e;if(t===u)return;this.#e=t;let y=Date.now()-this.#n;i&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(i||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}x.KaylaInternalState=a;class l{#e;constructor(t){this.#e=t??void 0}#t;setSetter(t){this.#t=t}get current(){return this.#e}set current(t){this.#e=t,this.#t&&this.#t(this.#e)}}x.KaylaInternalRef=l;function d(v){return new l(v)}x.createReassignableRef=d;class f{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;lastLayer;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,i,u){if(!u)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=i,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=u.type,this.callProps=u.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalPointer=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+ae(),this.onViewportEffect=[],this.lastLayer=null}getCorrectMousePos(t){return t??=this.getAttachedRenderer().getMousePos(),this.lastLayer?.transform?this.lastLayer.transform.inverseV(t):t}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,i,u){t=this.getCorrectMousePos(t);try{for(let{handler:c,config:y}of this.onGlobalPointer)y.type??="any",y.action??="down",!(y.action!=="any"&&y.action!==u||y.type!=="any"&&y.type!==i)&&c(t,i,u)}catch(c){this.global.logger.error(c)}}resizeHook({width:t,height:i}){try{for(let u of this.onViewportEffect)u(this.getAttachedRenderer(),t,i)}catch(u){this.global.logger.error(u)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){return this.callProps.children}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalPointer;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let i=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${i} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let u=this.lastChildren.slice(0,this.maxSafeChildren),c=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=u;for(let y of c)y.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],i=this.detectedParent;for(;i;)t.push(i),i=i?.detectedParent;return t}getAllChildrenNestedFlattened(){let t=[],i=(u=[])=>{for(let c of u)t.push(c),c.lastChildren?.length&&i(c.lastChildren)};return i(this.lastChildren),t}getContextChain(){return this.getFiberChain().map(t=>t.contextInfo).filter(Boolean)}findContextValueFromInst(t){return this.getContextChain().find(i=>i.instance===t)?.value}getEntityChain(){return this.getFiberChain().map(t=>t.entity)}shouldFullRefresh(){if(this.isFirstUse||!this.watchedDeps||this.watchedDeps.length===0)return!0;for(let t=0;t<this.watchedDeps.length;t++){let i=this.watchedDeps[t],u=this.lastDepStamps[t]??0;if(i.lastChanged>u)return!0}return!1}captureDepStamps(){this.watchedDeps&&(this.lastDepStamps=this.watchedDeps.map(t=>t.lastChanged))}refresh(){if(!this.shouldFullRefresh())return;let t=this.fc?.name||"anonymous";if(!this.shouldFullRefresh()){this.global.logger.debug(`Refresh skipped <${t} key=${this.key}>`);return}this.global.logger.debug(`Refresh executed <${t} key=${this.key}> reason=${this.isFirstUse?"first":"deps-changed"}`),this.lastChildren.length>this.maxSafeChildren&&this.global.logger.warn(`High child count <${t} key=${this.key}> children=${this.lastChildren.length}`);let i;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let u=[];try{let c=this.fc(this.callProps)??[];if(c&&!Array.isArray(c)&&(c=[c]),!Array.isArray(c))throw new Error("Non array or non undefined children received.");for(let y of c)if(y.type===this.fc)throw new Error("Circular Component.");u=c}catch(c){i=c}if(this.global.restore(),this.updateChildren(u,!0),i)throw i}updateChildren(t,i){try{let u=[...t,...this.dynamicChildren],c=[],y=[];for(let b of u){let C=b.props?.key,E;C!=null&&(E=this.lastChildren.find(H=>H.key===C)),E||(E=new f(this.global,this.scene,b)),E.callProps=b.props,E.detectedParent=this,y.push(E),c.push(E)}for(let b of this.lastChildren)c.includes(b)||b.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let b of this.lastChildren)try{b.refresh()}catch(C){console.error(C)}}catch(u){console.error(u)}}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=!0),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let i=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(c=>({stamp:c.lastChanged,stateRef:c}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new o(this,this.key);for(let c of this.refs)c.current===ve&&(c.current=this.entity);if(this.callProps.ref instanceof l&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof l&&(this.callProps.exportsRef.current=this.exports),this.entity&&this.entity!==this.entity&&this.global.logger.warn(`Entity name mismatch during refresh <${this.fc?.name} key=${this.key}>`),this.scene.getScene().addEntity(this.entity),i){this.onUnInits=[];for(let c of this.onInits){this.bindEvents();try{let y=c();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let c of this.onUnEffect??[])c()}catch(c){console.error(c)}let u=this.onEffect.map(c=>c()).filter(c=>c!==void 0);this.onUnEffect=u}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}}x.KaylaFiber=f;class o extends Y{#e;flags;getRawRect(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,i){super(i,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,i){return this.flags.set(t,i)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){fe(()=>{let i=new s;if(this.#e&&this.#e.onTick)for(let u of this.#e.onTick)u(t,i);i.isPrevented()})}draw(t){let i=new s;if(this.#e&&this.#e.onPaint)for(let u of this.#e.onPaint)u(t,i);i.isPrevented()||super.draw(t)}getRect(){return new h(this.getFiber())}}x.KaylaRectEntity=o;class h{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return _.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}get entity(){return this.#e.entity??null}#t(){if(!this.#e)throw new Error("No fibers found.");if(!this.entity)throw new Error("The entity does NOT exist yet.")}isCollidingWith(t){return this.#t(),this.entity.isCollidingWith(t.entity)}get setFlag(){return this.#t(),this.entity.setFlag.bind(this.entity)}get getFlag(){return this.#t(),this.entity.getFlag.bind(this.entity)}get removeFlag(){return this.#t(),this.entity.removeFlag.bind(this.entity)}isHovered(){let t=this.getRaw(),i=this.#e.getCorrectMousePos(),u=_.createRawRect({x:i.x,y:i.y,width:3,height:3});return _.rawCollision(t,u)}get pos(){return this.#t(),this.entity.pos}get x(){return this.#t(),this.pos.x}set x(t){this.#t(),this.pos.x=t}get y(){return this.#t(),this.pos.y}set y(t){this.#t(),this.pos.y=t}get width(){return this.#t(),this.entity.width}set width(t){this.#t(),this.entity.width=t}get height(){return this.#t(),this.entity.height}set height(t){this.#t(),this.entity.height=t}get z(){return this.#t(),this.entity.z}set z(t){this.#t(),this.entity.z=t}get left(){return this.#t(),this.entity.left}set left(t){this.#t(),this.entity.left=t}get right(){return this.#t(),this.entity.right}set right(t){this.#t(),this.entity.right=t}get top(){return this.#t(),this.entity.top}set top(t){this.#t(),this.entity.top=t}get bottom(){return this.#t(),this.entity.bottom}set bottom(t){this.#t(),this.entity.bottom=t}get toLocal(){return this.entity.toLocal.bind(this.entity)}get toWorld(){return this.entity.toWorld.bind(this.entity)}}x.KaylaInternalRect=h;class p{#e;#t;constructor(t){this.#r=t,this.#n=null,this.#e=new Map,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this),t.handleDraw=this.drawHandler,this.#t=null}getLayers(){return this.#e}#n;#r;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#r}getGame(){return this.#n}getOrCreateLayer(t,i=0){return this.#e.has(t)||this.#e.set(t,{name:t,z:i,visible:!0,rootFiber:null}),this.#e.get(t)}getSortedLayers(){return Array.from(this.#e.values()).filter(t=>t.visible).sort((t,i)=>t.z-i.z)}setLayerVisible(t,i){let u=this.#e.get(t);u&&(u.visible=i)}handleDraw(t){if(D)return;let i=this.getScene();if(i.paused)return;i.emit("draw",t);let u=this.getSortedLayers(),c=[];for(let b of u){if(!b.visible)continue;let C=b.rootFiber;if(!C)continue;let E=C.getAllChildrenNestedFlattened().flat().map(K=>K.entity).filter(Boolean);if(c.push(...E),t.save(),b.transform){let K=b.transform;t.setTransform(K.a,K.b,K.c,K.d,K.e,K.f)}b.blendMode&&(t.globalCompositeOperation=b.blendMode??"source-over");let H=Array.from(E).sort((K,P)=>K.z-P.z);for(let K of H)K.getFiber().lastLayer=b,K.handleDraw(t);t.restore()}let y=[...i.entities.values()].filter(b=>!c.includes(b));for(let b of y.sort((C,E)=>C.z-E.z))b.getFiber().lastLayer=null,b.handleDraw(t)}drawHandler(t){return this.handleDraw(t)}attachTo(t){t.addScene(this.#r),this.#n=t}async spawn(t){this.#t&&(this.#t.unuse(),this.#t=null);let i=this.createFiber(t);this.#t=i,await this.#n.delay(0),i.refresh()}getRoot(){return this.#t??null}createFiber(t){return new f(x.singleGlobalInstance,this,t)}detach(){this.#n&&this.#n.removeScene(this.#r)}tickHandler(){}}x.KaylaScene=p,x.singleGlobalInstance=new x.GlobalKayla})(z||={});var oe=class{#e;constructor(e){this.Provider=this.#t.bind(this),this.#e=e}get defaultValue(){return this.#e}#t({value:e=this.defaultValue,children:n}){let s=Ee();return le(()=>{s.contextInfo={instance:this,value:e}}),de(this.Provider,()=>({value:e})),n}Provider;Consumer};function rt(r){return new oe(r)}var m=z.singleGlobalInstance,it=m.useState.bind(m),xe=m.useRef.bind(m),st=m.useShouldRefresh.bind(m),le=m.useEffect.bind(m),at=m.useViewportEffect.bind(m),He=m.useGlobalPointer.bind(m),ot=m.useGlobalPointer.bind(m),lt=m.usePointer.bind(m),ut=m.usePointer.bind(m),ue=m.useInitialization.bind(m),he=m.useRect.bind(m),ht=m.useTick.bind(m),ce=m.usePaint.bind(m),de=m.useExports.bind(m),G=m.useSelf.bind(m),Ce=m.useFiberControl.bind(m),Ee=m.useFiber.bind(m),ct=m.useEntity.bind(m),dt=m.useCurrentGame.bind(m),ft=m.useCurrentRenderer.bind(m),Ue=m.useCurrentScene.bind(m),pt=m.useCurrentTicker.bind(m),mt=m.useContext.bind(m),ve=Symbol("self_ref");var fe=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},yt=({children:r})=>Array.isArray(r)?[...r]:r;function bt(r){return z.createReassignableRef(r)}function gt(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(s,a,l){return a==="reassignSelf"?d=>{e.current=d}:Reflect.get(e.current,a,l)},set(s,a,l,d){return Reflect.set(e.current,a,l,d)},has(s,a){return Reflect.has(e.current,a)},ownKeys(s){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(s,a){return Reflect.getOwnPropertyDescriptor(e.current,a)},deleteProperty(s,a){return Reflect.deleteProperty(e.current,a)}})}function xt(r){m.logLevel=r}function vt(r){let e=r.name||"anonymous-custom-hook";return function(s){let a=m.current;if(!a)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let l=s??{};return r.memoize!==!1?G(()=>(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,l))):(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,l))}}var $e;(e=>e.id="kayla")($e||={});var wt=({name:r,z:e=0,blend:n,visible:s=!0,children:a,transform:l})=>{let d=Ue(),f=Ee();return ue(()=>{let o=d.getOrCreateLayer(r,e);return o.blendMode=n,o.visible=s,o.rootFiber=f,o.transform=l??null,()=>{d.getLayers().delete(r)}}),a},we=class extends DOMMatrix{#e;constructor(){super(),this.#e=new DOMPoint}transformV(e){this.#e.x=e.x,this.#e.y=e.y;let n=this.#e.matrixTransform(this);return new F(n.x,n.y)}inverseV(e){let n=this.inverse();this.#e.x=e.x,this.#e.y=e.y;let s=this.#e.matrixTransform(n);return new F(s.x,s.y)}};Reflect.set(globalThis,"Kayla",Q);var Ct;(n=>(n.Flex=({align:s="stretch",children:a,direction:l="row",gap:d=0,justify:f="start",wrap:o="nowrap",getHeight:h,getWidth:p,getCenterX:g,getCenterY:x,color:v})=>{let t=Ce(),i=he(),u=G(()=>({recalc(){let c=Number(d)||0,y=g(),b=x(),C=p(),E=h();i.x=y,i.y=b,i.width=C,i.height=E;let K=t.getChildrenEntities().filter(Boolean).map(w=>w.getRect()).filter(w=>w.getFlag("flex-ignored")!==!0),P=l==="row",A=P?i.width:i.height,Et=P?i.height:i.width,pe=0,X=0,me=[],J=[];K.forEach(w=>{let Z=P?w.width:w.height;pe+Z>A&&o==="wrap"?(me.push({height:X,items:J}),J=[w],pe=Z,X=P?w.height:w.width):(J.push(w),pe+=Z+c,X=Math.max(X,P?w.height:w.width))}),me.push({height:X,items:J});let ye=0;me.forEach((w,Z)=>{let M=w.items,V=M.reduce((k,ee)=>k+(P?ee.width:ee.height),0)+c*(M.length-1),I=0;f==="center"&&(I=(A-V)/2),f==="end"&&(I=A-V),f==="space-between"&&(I=0),f==="space-around"&&(I=(A-V)/(M.length*2)),f==="space-evenly"&&(I=(A-V)/(M.length+1)),M.forEach((k,ee)=>{k.z=i.z+1;let U=P?k.width:k.height,te=P?k.height:k.width,ne=0;s==="center"&&(ne=(w.height-te)/2),s==="end"&&(ne=w.height-te),s==="stretch"&&(P?k.height=w.height:k.width=w.height),P?(k.x=I+U/2,k.y=ye+ne+te/2):(k.x=ye+ne+te/2,k.y=I+U/2),f==="space-between"&&ee<M.length-1?I+=U+c+(A-V)/(M.length-1):f==="space-around"?I+=U+c+(A-V)/M.length:f==="space-evenly"?I+=U+c+(A-V)/(M.length+1):I+=U+c}),ye+=w.height+c})}}));return ce((c,y)=>{y.preventDefault(),c.fillStyle=v,c.fillRect(i.left,i.top,i.width,i.height)}),le(()=>{fe(()=>{u.recalc()})}),de(n.Flex,()=>({controls:u})),a},n.GenericBox=({color:s,width:a=20,height:l=20,x:d=0,y:f=0})=>{let o=he();ue(()=>{o.width=a,o.height=l,o.x=d,o.y=f}),ce((h,p)=>{p.preventDefault(),h.fillStyle=s,h.fillRect(o.left,o.top,o.width,o.height)})}))(Ct||={});var Pt={LEA:j,Kayla:Q};export{Q as Kayla,j as LEA,Pt as default};