@kayelaa/canvas 0.1.14 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kayla.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var N=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var be=Object.prototype.hasOwnProperty;var W=(r,e)=>{for(var t in e)N(r,t,{get:e[t],enumerable:!0})},ge=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ye(e))!be.call(r,i)&&i!==t&&N(r,i,{get:()=>e[i],enumerable:!(s=me(e,i))||s.enumerable});return r};var xe=r=>ge(N({},"__esModule",{value:!0}),r);var Re={};W(Re,{Kayla:()=>H,KaylaFragment:()=>le,KaylaInternals:()=>S,UI:()=>pe,createElement:()=>ee,createGame:()=>Q,createReassignableObject:()=>ce,createRenderer:()=>Z,createScene:()=>J,createUseHook:()=>de,self:()=>P,setLogLevel:()=>fe,useDisposableRef:()=>he,useEffect:()=>G,useEntity:()=>ue,useExports:()=>ie,useFiber:()=>oe,useFiberControl:()=>ae,useInitialization:()=>ne,useNextStack:()=>B,usePaint:()=>U,useRect:()=>re,useRef:()=>I,useSelf:()=>k,useShouldRefresh:()=>te,useState:()=>$,useTick:()=>se});module.exports=xe(Re);var H={};W(H,{KaylaFragment:()=>le,KaylaInternals:()=>S,createElement:()=>ee,createGame:()=>Q,createReassignableObject:()=>ce,createRenderer:()=>Z,createScene:()=>J,createUseHook:()=>de,self:()=>P,setLogLevel:()=>fe,useDisposableRef:()=>he,useEffect:()=>G,useEntity:()=>ue,useExports:()=>ie,useFiber:()=>oe,useFiberControl:()=>ae,useInitialization:()=>ne,useNextStack:()=>B,usePaint:()=>U,useRect:()=>re,useRef:()=>I,useSelf:()=>k,useShouldRefresh:()=>te,useState:()=>$,useTick:()=>se});var T=class{#e=new Map;constructor(){this.#e=new Map}on(e,t){let s=this.#e.get(e)||[];return s.push(t),this.#e.set(e,s),this}once(e,t){let s=(...i)=>{this.off(e,s),t(...i)};return this.on(e,s),this}off(e,t){let s=this.#e.get(e);if(!s)return this;let i=s.indexOf(t);return i>=0&&s.splice(i,1),this}emit(e,...t){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw t[0];return!1}return s.slice().forEach(i=>i(...t)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},_=class extends T{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:t,viewportHeight:s,cameraWidth:i,cameraHeight:u}={}){if(!E)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=t??e.width,this.#t=s??e.height,this.#n=i??e.width,this.#r=u??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,t=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,t),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!E)return;let e=performance.now(),t=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=t,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},O=class extends T{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),t=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,this.#e+=t*1e3,this.emit("tick",t)}createTimeout(e){return new q(e,this)}createTween(e,t=()=>{}){let s=new X(e),i=(u=0)=>{if(s.finished){this.off("tick",i);return}s.update(u)};return s.on("finish",()=>{this.off("tick",i)}),s.on("delta",u=>{t(u)}),this.on("tick",i),s}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=E&&!isFinite(this.tickInterval)?Ce(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,t=0){return .5+.5*Math.sin((this.now()%e/e+t)*2*Math.PI)}},ve;(n=>{function r(a){return a===!0?1:0}n.booleanExport=r;function e(a){return a===0?!1:a===1}n.booleanImport=e;function t(a){return`${a.x}|${a.y}`}n.vec2Export=t;function s(a){let[o,l]=a.split("|"),g=parseFloat(o),x=parseFloat(l);if(isNaN(g)||isNaN(x))throw new Error(`Invalid Vector2 string: ${a}`);return new K(g,x)}n.vec2Import=s,n.booleanMap={mapExport:r,mapImport:e};function u(a){return o=>Number(o.toFixed(a))}n.createRounder=u;function f(a=10){return{mapExport(o){return Math.round(o/a)},mapImport(o){return o*a}}}n.createLowPrecision=f;function d(a){return Math.round(a)}n.lightWeightRounder=d;function c(a=100){return{mapExport(o){return Math.round(o*a)},mapImport(o){return o/a}}}n.createPercent=c;function h(a){let o=new Map(Object.entries(a));return{mapExport:l=>o.get(l)??null,mapImport:l=>Array.from(o.entries()).find(([g,x])=>x===l)?.[0]??null}}n.createLookup=h;function p(a){let o=a*(180/Math.PI);return Math.round((o%360+360)%360)}n.radToDeg=p;function y(a){return a*(Math.PI/180)}n.degToRad=y,n.angleRadToDeg={mapExport:p,mapImport:y};function v(a=10){let o=f(a);return{mapExport(l){return o.mapExport(p(l))},mapImport(l){return o.mapImport(y(l))}}}n.createLowPrecisionRadToDeg=v})(ve||={});var M=class r extends T{name="";scaleRotate=0;scale=1;constructor(e,t=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new K(t,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(t){this.emit("error",t)}}handleDraw(e){if(!(z||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(t){this.emit("error",t)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([i,{mapExport:u}])=>{let f=Reflect.get(this,i);return u?u(f):f});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],t=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(i=>!this.nonSerializableProperties.includes(i)&&!e.includes(i.toString())),s=Object.fromEntries(t.map(i=>{let u=Reflect.get(this,i);if(z&&typeof u=="number"){let f=u.toString().split("."),c=(f[1]?f[1].length:0)>2?Number(u.toFixed(2)):u;return[i,c]}return[i,u]}));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,t){if(!e||!Array.isArray(t))return t;let s={};for(let i=0;i<t.length;i++){let u=e[i];if(!u)break;let[f,{mapImport:d}]=u,c=t[i];if(d&&(c=d(c)),typeof f!="string")break;try{Reflect.set(s,f,c)}catch(h){console.error(h)}}return s}},L=class extends T{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let t of this.entities.values())t.handleUpdate(e)}}handleDraw(e){if(!z&&!this.paused){this.emit("draw",e);for(let t of[...this.entities.values()].sort((s,i)=>s.z-i.z))t.handleDraw(e)}}addEntity(e){if(!(e instanceof M))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 M))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},D=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,t,s=16){this.ticker=new O(s),this.scenes=new Map,this.width=e,this.height=t,this.ticker.on("tick",i=>{for(let u of this.scenes.values())u.paused||u.handleUpdate(i)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},w={lerp(r,e,t){return r+(e-r)*t},clamp(r,e,t){return Math.min(t,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=w.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return w.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[w.randomInt(0,r.length-1)]},createBezier(r,e,t,s){function i(d,c,h,p,y){let b=1-d;return b*b*b*c+3*b*b*d*h+3*b*d*d*p+d*d*d*y}function u(d,c,h,p,y){let b=1-d;return 3*b*b*(h-c)+6*b*d*(p-h)+3*d*d*(y-p)}function f(d){let c=d;for(let h=0;h<6;h++){let p=i(c,0,r,t,1),y=u(c,0,r,t,1);if(y===0)break;c-=(p-d)/y}return w.clamp(c,0,1)}return function(c){c=w.clamp(c,0,1);let h=f(c);return i(h,0,e,s,1)}},lengthSquared(...r){return r.reduce((e,t)=>e+t*t,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return w.normalizeRad(-r)},degToRadFlipY(r){return w.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=w.normalizeRad(r),e=w.normalizeRad(e);let t=w.normalizeRad(e-r),s=w.normalizeRad(r-e);return t<=s?1:-1}},X=class extends T{constructor({delta:e,ms:t,easing:s}){super(),this.delta=e,this.duration=t,this.elapsed=0,this.easing=s??(i=>i),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let t=w.clamp(this.elapsed/this.duration,0,1),s=this.easing(t),i=this.delta*s,u=i-this.lastValue;this.lastValue=i,this.emit("delta",u),t>=1&&(this.finished=!0,this.emit("finish",void 0))}},V=class extends M{constructor(e,t=0,s=0,i=50,u=50){super(e,t,s),this.width=i,this.height=u}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},q=class extends T{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,t=null){super(),this.duration=e,this.ticker=t,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(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,t){return this.promise.then(e,t)}after(e,t){return this.promise.then(e,t)}},K=class r{constructor(e=0,t=0){this.x=e,this.y=t}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let t=Math.cos(e),s=Math.sin(e);return new r(this.x*t-this.y*s,this.x*s+this.y*t)}static from(e){return new r(Math.cos(e),Math.sin(e))}get angle(){return Math.atan2(this.y,this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new r(0,0):new r(this.x/e,this.y/e)}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let t=this.dot(e);return this.subtract(e.scale(2*t))}dotNormalized(e){let t=this.normalized(),s=e.normalized();return t.x*s.x+t.y*s.y}lengthSquaredTo(e){let t=this.x-e.x,s=this.y-e.y;return t*t+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 t=this.x-e.x,s=this.y-e.y;return t*t+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 we(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var j=we(),z=j==="node",E=j==="web",A=class r{static unlock(){E&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=E?new AudioContext:null;static masterGain=E?this.audioCtx.createGain():null;static musicGain=E?this.audioCtx.createGain():null;static sfxGain=E?this.audioCtx.createGain():null;static{E&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let t=r.CACHE_NAME,s,i;if(typeof caches<"u"&&(i=await caches.open(t),s=await i.match(e)),!s){if(s=await fetch(e),!s.ok)throw new Error(`Failed to fetch ${e}`);i&&await i.put(e,s.clone())}let u=await s.arrayBuffer(),f=await this.audioCtx.decodeAudioData(u);return this.audioBufferCache.set(e,f),f}static async getOnlyDownloadedCache(e){let t=r.CACHE_NAME;return await(await caches.open(t)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,t=.2,s=1,i=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let u=this.getCached(e);if(!u)return;let f=new F(u);f.buffer=u;let d=1-.12,c=1+.12;f.playbackRate=s??d+Math.random()*(c-d);let h=this.audioCtx.createGain();h.gain.value=t,f.tempGain=h,f.connect(h),h.connect(this.sfxGain),f.onended=()=>{f.disconnect(),h.disconnect()},f.start(),i&&this.sfsx.set(e,{source:f,gain:h})}catch(u){console.error(u)}}static async playLoop(e,t=1,{loopStart:s=0,loopEnd:i=null,exclusive:u=!0,skipMS:f=0}={}){if(u)for(let y of this.loops.keys())this.stopLoop(y);this.audioBufferCache.has(e)||await this.preLoad(e);let d=this.getCached(e);if(!d)return;let c=new F(d);c.buffer=d,c.loop=!0,typeof s=="number"&&(c.loopStart=s),typeof i=="number"&&(c.loopEnd=i);let h=this.audioCtx.createGain();h.gain.value=t,c.tempGain=h,c.playbackRate=1,c.onended=()=>{c.disconnect(),h.disconnect()},c.connect(h),h.connect(this.musicGain),c.start(0,f/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:c,gain:h}),p}static stopLoop(e){let t=this.loops.get(e);t&&(t.source.stop(),t.source.notIndependent||(t.source.disconnect(),t.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:t=1,speed:s=1,loop:i=!1,loopStart:u=0,loopEnd:f=null,isMusic:d=!1,gain:c=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return null;let p=new F(h);p.loop=i,p.loopStart=u,p.loopEnd=typeof f=="number"?f:h.duration,p.playbackRate=s;let y=this.audioCtx.createGain();return y.gain.value=t,p.connect(y),p.tempGain=y,y.connect(c||(d?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),y.disconnect()},p}catch(h){return console.error("Failed to create LiaAudioSrc:",h),null}}};var F=class{numberOfInputs;numberOfOutputs;constructor(e,t=A.audioCtx){this.context=t,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=E?t.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:t=null}={}){let s=t!==null?t:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-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,t=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-t/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,t,s):this.source.start(this.context.currentTime+e,t),this.pauseTime=t,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let t=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;t=this.loopStart+(t-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=t,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let t=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=t,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,t=0,s=0){if("value"in e)this.output.connect(e,t);else return this.output.connect(e,t,s),e}disconnect(e,t,s){e===void 0?this.output.disconnect():this.output.disconnect(e,t,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let t=this.context.currentTime+e;this.source.stop(t),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Ee={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},R=class r{constructor(e={}){this.ctx=A.audioCtx,this.cfg=structuredClone(Ee),Object.assign(this.cfg,e)}ctx;cfg;play(e=A.sfxGain){let t=this.ctx,s=t.currentTime,i=this.cfg,u=t.createGain();u.gain.setValueAtTime(1e-4,s);let f=i.ampEnv;u.gain.exponentialRampToValueAtTime(f.volume,s+f.attack),u.gain.exponentialRampToValueAtTime(Math.max(1e-4,f.sustain*f.volume),s+f.attack+f.decay),u.gain.exponentialRampToValueAtTime(1e-4,s+i.duration+f.release);let d=u,c;i.filter.enabled&&(c=t.createBiquadFilter(),c.type=i.filter.type,c.frequency.value=i.filter.freq,c.Q.value=i.filter.Q,c.connect(u),d=c);let h;if(i.osc.enabled){if(h=t.createOscillator(),h.type=i.osc.type,h.frequency.value=i.osc.freq,h.detune.value=i.osc.detune,i.pitchEnv.amount!==0){let a=Math.pow(2,i.pitchEnv.amount/12);h.frequency.exponentialRampToValueAtTime(i.osc.freq*a,s+i.pitchEnv.decay)}h.connect(d),h.start(s),h.stop(s+i.duration+f.release)}let p;if(i.noise.enabled){let a=t.sampleRate*i.duration,o=t.createBuffer(1,a,t.sampleRate),l=o.getChannelData(0);for(let g=0;g<a;g++)l[g]=(Math.random()*2-1)*i.noise.level;p=t.createBufferSource(),p.buffer=o,p.connect(d),p.start(s),p.stop(s+i.duration+f.release)}let y,b;i.lfo.enabled&&h&&(y=t.createOscillator(),y.frequency.value=i.lfo.rate,b=t.createGain(),b.gain.value=i.lfo.depth,y.connect(b),i.lfo.target==="freq"?b.connect(h.frequency):i.lfo.target==="gain"?b.connect(u.gain):i.lfo.target==="filter"&&c&&b.connect(c.frequency),y.start(s),y.stop(s+i.duration)),u.connect(e);let v=[h,p,y,b,c,u],n=s+i.duration+f.release;setTimeout(()=>{v.forEach(a=>a?.disconnect())},(n-t.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,t){return Object.assign(this.cfg[e],t),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,t,s,i){return Object.assign(this.cfg.ampEnv,{attack:e,decay:t,sustain:s,release:i}),this}setPitchEnv(e,t){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:t}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,t,s){return Object.assign(this.cfg.filter,{type:e,freq:t,Q:s,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,t,s){return Object.assign(this.cfg.lfo,{target:e,rate:t,depth:s,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},ke=new R({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Ie=new R({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Pe=new R({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}),Fe=new R({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}),Me=new R({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function Y(r=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(4)),s=Array.from(t).map(i=>i.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}function Ce(r){let e=!0;function t(){e&&(r(),requestAnimationFrame(t))}return requestAnimationFrame(t),{clear:()=>e=!1}}function Te(){return z?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var Ae=Te();function Q({width:r,height:e,updateHz:t="frames"}){return new S.KaylaGame(r,e,t==="frames"?1/0:t)}function J(r){let e=new L(r);return new S.KaylaScene(e)}function Z(r){return new S.KaylaRenderer(r)}function ee(r,e){return{type:r,props:e}}var S;(b=>{class r extends D{#e;#t;constructor(n,a,o){super(n,a,o),this.#e=new Set,this.#t=!1}get started(){return this.#t}start(){if(!this.#t){for(let n of this.#e)n.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let n of this.#e)n.stop();this.#t=!1,super.stop()}}addRenderer(n){this.#e.has(n)||(this.#e.add(n),this.#t&&n.start(),n.game=this)}deleteRenderer(n){this.#e.has(n)&&(this.#e.delete(n),this.#t&&n.stop(),delete n.game)}}b.KaylaGame=r;class e extends _{game;pointerX;pointerY;#e;constructor(n){super(n),this.useDraw=this.useDraw.bind(this),this.on("draw",a=>{if(this.game)for(let o of this.game.scenes.values())o.handleDraw(a)}),this.pointerX=0,this.pointerY=0,this.#e=this.#t.bind(this)}#t(n){this.pointerX=n.clientX,this.pointerY=n.clientY}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.#e)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.#e)}pointerPosToWorldPos(n,a){let o=this.canvas.getBoundingClientRect(),l=(n-o.left)/o.width,g=(a-o.top)/o.height,x=l*this.viewportWidth*this.cameraWidth/o.width,C=g*this.viewportHeight*this.cameraHeight/o.height;return new K(x,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(n){let a=o=>{n(o,new s)};return this.on("draw",a),()=>{this.off("draw",a)}}attachTo(n){n.addRenderer(this),this.game=n}detach(){this.game&&this.game.deleteRenderer(this)}}b.KaylaRenderer=e;class t{current;saves;constructor(){this.saves=[]}useTick(n){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]=n,this.current.useStepCallIndex++}usePaint(n){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]=n,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return I(P)}useSelf(n){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let a=I(null);return(a.current===null||a.current===void 0)&&(a.current=n()),a.current}useInitialization(n){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let a=this.current;a.onInit=n}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return k(()=>new b.KaylaRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return k(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let n=this.current;return k(()=>({refresh:()=>n.refresh(),get childrenCount(){return n.lastChildren.length},setMaxChildren:a=>{n.setMaxChildren(a)},getMaxChildren:()=>n.getMaxChildren(),get maxSafeChildren(){return n.maxSafeChildren}}))}useState(n,{alwaysRecall:a=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let l=this.current.state[this.current.useStateCallIndex]??new i(this.current,n,{alwaysRecall:a});return this.current.state[this.current.useStateCallIndex]=l,this.current.useStateCallIndex++,l}useShouldRefresh(n){let a=this.current;if(!a)throw new Error("useShouldRefresh must be called inside a component");a.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),a.watchedDeps=n}useRef(n){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let o=this.current.refs[this.current.useRefCallIndex]??f(n??null);return this.current.refs[this.current.useRefCallIndex]=o,this.current.useRefCallIndex++,o}useEffect(n){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]=n,this.current.useEffectCallIndex++}useExports(n,a){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=a}save(){this.saves.push({current:this.current})}restore(){let n=this.saves.pop();if(!n)throw new Error("Cannot restore without saving.");this.current=n.current}logLevel="warn";logger={debug:(...n)=>{this.logLevel==="debug"&&console.debug(...n)},info:(...n)=>{this.logLevel>="info"&&console.info(...n)},warn:(...n)=>{this.logLevel>="warn"&&console.warn(...n)},error:(...n)=>console.error(...n),withFiber:(n,a,o,...l)=>{let g=n?.fc?.name||"anonymous",x=n?.key?` key=${n.key}`:"";this.logger[a](`${o} <${g}${x}>`,...l)}}}b.GlobalKayla=t;class s{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}b.KaylaEvent=s;class i{#e;#t;#n;alwaysRecall;constructor(n,a,{alwaysRecall:o=!1}={}){this.#t=n,this.#e=a??void 0,this.#n=Date.now(),this.alwaysRecall=o}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
1
+ "use strict";var ye=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var lt=Object.prototype.hasOwnProperty;var ge=(r,e)=>{for(var n in e)ye(r,n,{get:e[n],enumerable:!0})},ht=(r,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ut(e))!lt.call(r,s)&&s!==n&&ye(r,s,{get:()=>e[s],enumerable:!(i=ot(e,s))||i.enumerable});return r};var ct=r=>ht(ye({},"__esModule",{value:!0}),r);var vt={};ge(vt,{Kayla:()=>de,KaylaContext:()=>B,KaylaFragment:()=>Ze,KaylaInternals:()=>L,KaylaRect:()=>F,LEA:()=>ae,UI:()=>it,createContext:()=>Ue,createElement:()=>$e,createGame:()=>Ve,createReassignableObject:()=>tt,createRenderer:()=>ze,createScene:()=>He,createUseHook:()=>rt,self:()=>ue,setLogLevel:()=>nt,useClick:()=>Xe,useContext:()=>Je,useCurrentGame:()=>We,useCurrentRenderer:()=>Ye,useCurrentScene:()=>je,useCurrentTicker:()=>Qe,useDisposableRef:()=>et,useEffect:()=>le,useEntity:()=>Be,useExports:()=>Q,useFiber:()=>Ce,useFiberControl:()=>he,useGlobalClick:()=>ve,useInitialization:()=>W,useNextStack:()=>ce,usePaint:()=>j,useRect:()=>Y,useRef:()=>oe,useSelf:()=>_,useShouldRefresh:()=>Oe,useState:()=>Ne,useTick:()=>qe});module.exports=ct(vt);var de={};ge(de,{KaylaContext:()=>B,KaylaFragment:()=>Ze,KaylaInternals:()=>L,KaylaRect:()=>F,createContext:()=>Ue,createElement:()=>$e,createGame:()=>Ve,createReassignableObject:()=>tt,createRenderer:()=>ze,createScene:()=>He,createUseHook:()=>rt,self:()=>ue,setLogLevel:()=>nt,useClick:()=>Xe,useContext:()=>Je,useCurrentGame:()=>We,useCurrentRenderer:()=>Ye,useCurrentScene:()=>je,useCurrentTicker:()=>Qe,useDisposableRef:()=>et,useEffect:()=>le,useEntity:()=>Be,useExports:()=>Q,useFiber:()=>Ce,useFiberControl:()=>he,useGlobalClick:()=>ve,useInitialization:()=>W,useNextStack:()=>ce,usePaint:()=>j,useRect:()=>Y,useRef:()=>oe,useSelf:()=>_,useShouldRefresh:()=>Oe,useState:()=>Ne,useTick:()=>qe});var ae={};ge(ae,{DeltaTweenII:()=>ie,ENVIRONMENT:()=>xe,GEmitterMemory:()=>be,LeaEntityII:()=>H,LeaEventEmitter:()=>K,LeaGameII:()=>O,LeaRendererII:()=>U,LeaSceneII:()=>N,LeaSerializers:()=>Ee,LeaTickerII:()=>re,LeaTimeout:()=>se,LeaUtilsII:()=>k,LiaAudio:()=>z,LiaAudioSrc:()=>V,LiaOscSFX:()=>A,LiaSFXMap:()=>gt,NOTE_NAMES:()=>Te,RectLeaEntity:()=>X,Vector2:()=>M,colToRGBA:()=>ft,defaultSFXConfig:()=>Ke,editRGBA:()=>pt,generateUUID:()=>Ae,getAvoidAngle:()=>De,getEnvironment:()=>ke,getNormalizedColor:()=>dt,getRayHit:()=>Le,isInitiallyMobile:()=>wt,isMobile:()=>Ge,isNode:()=>q,isNote:()=>yt,isWeb:()=>E,parseFillStyle:()=>Re,raycastAvoid:()=>xt,scaleCoord:()=>mt,setAnimInterval:()=>_e,sfxHit:()=>Me,sfxJump:()=>Fe,sfxLaser:()=>Pe,sfxUIClick:()=>Se,sfxUIHover:()=>Ie,shortUID:()=>bt,tinyUID:()=>we});var K=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let i=this.#e.get(e)||[];return i.push(n),this.#e.set(e,i),this}once(e,n){let i=(...s)=>{this.off(e,i),n(...s)};return this.on(e,i),this}off(e,n){let i=this.#e.get(e);if(!i)return this;let s=i.indexOf(n);return s>=0&&i.splice(s,1),this}emit(e,...n){let i=this.#e.get(e);if(!i||i.length===0){if(e==="error")throw n[0];return!1}return i.slice().forEach(s=>s(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},U=class extends K{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:n,viewportHeight:i,cameraWidth:s,cameraHeight:o}={}){if(!E)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=n??e.width,this.#t=i??e.height,this.#n=s??e.width,this.#r=o??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,n=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,n),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!E)return;let e=performance.now(),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.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},re=class extends K{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,!(E&&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 i=new ie(e),s=(o=0)=>{if(i.finished){this.off("tick",s);return}i.update(o)};return i.on("finish",()=>{this.off("tick",s)}),i.on("delta",o=>{n(o)}),this.on("tick",s),i}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=E&&!isFinite(this.tickInterval)?_e(()=>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)}},Ee;(t=>{function r(a){return a===!0?1:0}t.booleanExport=r;function e(a){return a===0?!1:a===1}t.booleanImport=e;function n(a){return`${a.x}|${a.y}`}t.vec2Export=n;function i(a){let[h,c]=a.split("|"),g=parseFloat(h),w=parseFloat(c);if(isNaN(g)||isNaN(w))throw new Error(`Invalid Vector2 string: ${a}`);return new M(g,w)}t.vec2Import=i,t.booleanMap={mapExport:r,mapImport:e};function o(a){return h=>Number(h.toFixed(a))}t.createRounder=o;function d(a=10){return{mapExport(h){return Math.round(h/a)},mapImport(h){return h*a}}}t.createLowPrecision=d;function f(a){return Math.round(a)}t.lightWeightRounder=f;function u(a=100){return{mapExport(h){return Math.round(h*a)},mapImport(h){return h/a}}}t.createPercent=u;function l(a){let h=new Map(Object.entries(a));return{mapExport:c=>h.get(c)??null,mapImport:c=>Array.from(h.entries()).find(([g,w])=>w===c)?.[0]??null}}t.createLookup=l;function p(a){let h=a*(180/Math.PI);return Math.round((h%360+360)%360)}t.radToDeg=p;function y(a){return a*(Math.PI/180)}t.degToRad=y,t.angleRadToDeg={mapExport:p,mapImport:y};function x(a=10){let h=d(a);return{mapExport(c){return h.mapExport(p(c))},mapImport(c){return h.mapImport(y(c))}}}t.createLowPrecisionRadToDeg=x})(Ee||={});var H=class r extends K{name="";scaleRotate=0;scale=1;constructor(e,n=0,i=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new M(n,i),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(!(q||!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(([s,{mapExport:o}])=>{let d=Reflect.get(this,s);return o?o(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(s=>!this.nonSerializableProperties.includes(s)&&!e.includes(s.toString())),i=Object.fromEntries(n.map(s=>{let o=Reflect.get(this,s);if(q&&typeof o=="number"){let d=o.toString().split("."),u=(d[1]?d[1].length:0)>2?Number(o.toFixed(2)):o;return[s,u]}return[s,o]}));return JSON.parse(JSON.stringify(i))}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 i={};for(let s=0;s<n.length;s++){let o=e[s];if(!o)break;let[d,{mapImport:f}]=o,u=n[s];if(f&&(u=f(u)),typeof d!="string")break;try{Reflect.set(i,d,u)}catch(l){console.error(l)}}return i}},N=class extends K{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(!q&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((i,s)=>i.z-s.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof H))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 H))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},O=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,i=16){this.ticker=new re(i),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",s=>{for(let o of this.scenes.values())o.paused||o.handleUpdate(s)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},k={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=k.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return k.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[k.randomInt(0,r.length-1)]},createBezier(r,e,n,i){function s(f,u,l,p,y){let b=1-f;return b*b*b*u+3*b*b*f*l+3*b*f*f*p+f*f*f*y}function o(f,u,l,p,y){let b=1-f;return 3*b*b*(l-u)+6*b*f*(p-l)+3*f*f*(y-p)}function d(f){let u=f;for(let l=0;l<6;l++){let p=s(u,0,r,n,1),y=o(u,0,r,n,1);if(y===0)break;u-=(p-f)/y}return k.clamp(u,0,1)}return function(u){u=k.clamp(u,0,1);let l=d(u);return s(l,0,e,i,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 k.normalizeRad(-r)},degToRadFlipY(r){return k.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=k.normalizeRad(r),e=k.normalizeRad(e);let n=k.normalizeRad(e-r),i=k.normalizeRad(r-e);return n<=i?1:-1}},ie=class extends K{constructor({delta:e,ms:n,easing:i}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=i??(s=>s),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=k.clamp(this.elapsed/this.duration,0,1),i=this.easing(n),s=this.delta*i,o=s-this.lastValue;this.lastValue=s,this.emit("delta",o),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},X=class extends H{constructor(e,n=0,i=0,s=50,o=50){super(e,n,i),this.width=s,this.height=o}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},se=class extends K{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(i=>this._resolve=i),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)}},M=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),i=Math.sin(e);return new r(this.x*n-this.y*i,this.x*i+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(),i=e.normalized();return n.x*i.x+n.y*i.y}lengthSquaredTo(e){let n=this.x-e.x,i=this.y-e.y;return n*n+i*i}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,i=this.y-e.y;return n*n+i*i}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 dt(r){let e=/^rgba?\(([^)]+)\)$/,n=r.match(e);if(n){let[i,s,o,d=1]=n[1].split(",").map(f=>parseFloat(f));return{r:Math.max(0,Math.min(255,Math.floor(i))),g:Math.max(0,Math.min(255,Math.floor(s))),b:Math.max(0,Math.min(255,Math.floor(o))),a:Math.max(0,Math.min(1,Math.floor(d*255)/255))}}return Re(r)}function ft(r){return`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a})`}function Re(r){if(r=r.trim().toLowerCase(),r[0]==="#"){let n,i,s;if(r.length===7)n=parseInt(r.slice(1,3),16),i=parseInt(r.slice(3,5),16),s=parseInt(r.slice(5,7),16);else if(r.length===4)n=parseInt(r[1]+r[1],16),i=parseInt(r[2]+r[2],16),s=parseInt(r[3]+r[3],16);else throw new Error("Invalid hex color");return{r:n,g:i,b:s,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 pt(r,{r:e,g:n,b:i,a:s}={}){let[o,d,f,u,l]=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??d}, ${n??f}, ${i??u}, ${s??(l||1)})`}function mt(r,e,n){return n+(r-n)*e}function ke(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var xe=ke(),q=xe==="node",E=xe==="web",z=class r{static unlock(){E&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=E?new AudioContext:null;static masterGain=E?this.audioCtx.createGain():null;static musicGain=E?this.audioCtx.createGain():null;static sfxGain=E?this.audioCtx.createGain():null;static{E&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,i,s;if(typeof caches<"u"&&(s=await caches.open(n),i=await s.match(e)),!i){if(i=await fetch(e),!i.ok)throw new Error(`Failed to fetch ${e}`);s&&await s.put(e,i.clone())}let o=await i.arrayBuffer(),d=await this.audioCtx.decodeAudioData(o);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,i=1,s=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return;let d=new V(o);d.buffer=o;let f=1-.12,u=1+.12;d.playbackRate=i??f+Math.random()*(u-f);let l=this.audioCtx.createGain();l.gain.value=n,d.tempGain=l,d.connect(l),l.connect(this.sfxGain),d.onended=()=>{d.disconnect(),l.disconnect()},d.start(),s&&this.sfsx.set(e,{source:d,gain:l})}catch(o){console.error(o)}}static async playLoop(e,n=1,{loopStart:i=0,loopEnd:s=null,exclusive:o=!0,skipMS:d=0}={}){if(o)for(let y of this.loops.keys())this.stopLoop(y);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let u=new V(f);u.buffer=f,u.loop=!0,typeof i=="number"&&(u.loopStart=i),typeof s=="number"&&(u.loopEnd=s);let l=this.audioCtx.createGain();l.gain.value=n,u.tempGain=l,u.playbackRate=1,u.onended=()=>{u.disconnect(),l.disconnect()},u.connect(l),l.connect(this.musicGain),u.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:u,gain:l}),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:i=1,loop:s=!1,loopStart:o=0,loopEnd:d=null,isMusic:f=!1,gain:u=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return null;let p=new V(l);p.loop=s,p.loopStart=o,p.loopEnd=typeof d=="number"?d:l.duration,p.playbackRate=i;let y=this.audioCtx.createGain();return y.gain.value=n,p.connect(y),p.tempGain=y,y.connect(u||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),y.disconnect()},p}catch(l){return console.error("Failed to create LiaAudioSrc:",l),null}}},Te=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function yt(r){return Te.includes(r)}var V=class{numberOfInputs;numberOfOutputs;constructor(e,n=z.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=E?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 i=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-i/this.playbackRate,this.source.start(0,i),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,i){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,i!==void 0?this.source.start(this.context.currentTime+e,n,i):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 i=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%i}if(this.isPlaying=!1,e>0){let i=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,i),this.output.gain.linearRampToValueAtTime(0,i+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,i=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,i),e}disconnect(e,n,i){e===void 0?this.output.disconnect():this.output.disconnect(e,n,i)}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},Ke={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},A=class r{constructor(e={}){this.ctx=z.audioCtx,this.cfg=structuredClone(Ke),Object.assign(this.cfg,e)}ctx;cfg;play(e=z.sfxGain){let n=this.ctx,i=n.currentTime,s=this.cfg,o=n.createGain();o.gain.setValueAtTime(1e-4,i);let d=s.ampEnv;o.gain.exponentialRampToValueAtTime(d.volume,i+d.attack),o.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),i+d.attack+d.decay),o.gain.exponentialRampToValueAtTime(1e-4,i+s.duration+d.release);let f=o,u;s.filter.enabled&&(u=n.createBiquadFilter(),u.type=s.filter.type,u.frequency.value=s.filter.freq,u.Q.value=s.filter.Q,u.connect(o),f=u);let l;if(s.osc.enabled){if(l=n.createOscillator(),l.type=s.osc.type,l.frequency.value=s.osc.freq,l.detune.value=s.osc.detune,s.pitchEnv.amount!==0){let a=Math.pow(2,s.pitchEnv.amount/12);l.frequency.exponentialRampToValueAtTime(s.osc.freq*a,i+s.pitchEnv.decay)}l.connect(f),l.start(i),l.stop(i+s.duration+d.release)}let p;if(s.noise.enabled){let a=n.sampleRate*s.duration,h=n.createBuffer(1,a,n.sampleRate),c=h.getChannelData(0);for(let g=0;g<a;g++)c[g]=(Math.random()*2-1)*s.noise.level;p=n.createBufferSource(),p.buffer=h,p.connect(f),p.start(i),p.stop(i+s.duration+d.release)}let y,b;s.lfo.enabled&&l&&(y=n.createOscillator(),y.frequency.value=s.lfo.rate,b=n.createGain(),b.gain.value=s.lfo.depth,y.connect(b),s.lfo.target==="freq"?b.connect(l.frequency):s.lfo.target==="gain"?b.connect(o.gain):s.lfo.target==="filter"&&u&&b.connect(u.frequency),y.start(i),y.stop(i+s.duration)),o.connect(e);let x=[l,p,y,b,u,o],t=i+s.duration+d.release;setTimeout(()=>{x.forEach(a=>a?.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,i,s){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:i,release:s}),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,i){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:i,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,i){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:i,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},Se=new A({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Ie=new A({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Fe=new A({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}),Pe=new A({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}),Me=new A({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}),gt=new Map([["ui_click",Se],["ui_hover",Ie],["jump",Fe],["laser",Pe],["hit",Me]]);function bt(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(r)),i=Array.from(n).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+i).slice(0,r)}function we(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),i=Array.from(n).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+i).slice(0,r)}var be=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${Ae()}_${Date.now()}`}connect(e){e&&(this.peer=e,e.peer=this,this.connected=!0,e.connected=!0),this._emit("open")}isConnected(){return this.connected&&!!this.peer}on(e,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(i=>i!==n))}_emit(e,n){this.events[e]?.forEach(i=>i(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 Ae(){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 _e(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function Le(r,e,n,i,s){let o=Math.cos(s),d=Math.sin(s),f=[];if(o!==0){let u=(0-r)/o,l=e+u*d;u>0&&l>=0&&l<=i&&f.push({side:"left",t:u})}if(o!==0){let u=(n-r)/o,l=e+u*d;u>0&&l>=0&&l<=i&&f.push({side:"right",t:u})}if(d!==0){let u=(0-e)/d,l=r+u*o;u>0&&l>=0&&l<=n&&f.push({side:"top",t:u})}if(d!==0){let u=(i-e)/d,l=r+u*o;u>0&&l>=0&&l<=n&&f.push({side:"bottom",t:u})}return f.length===0?null:(f.sort((u,l)=>u.t-l.t),f[0])}function De(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 xt(r,e,n,i,s){let o=Le(r,e,n,i,s);return o?{...o,avoidAngle:De(s,o.side)}:null}function Ge(){return q?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var wt=Ge();function Ve({width:r,height:e,updateHz:n="frames"}){return new L.KaylaGame(r,e,n==="frames"?1/0:n)}function He(r){let e=new N(r);return new L.KaylaScene(e)}function ze(r){return new L.KaylaRenderer(r)}function $e(r,e){return{type:r,props:e}}var F;(i=>{function r(s,o){return!(s.right<o.left||s.left>o.right||s.bottom<o.top||s.top>o.bottom)}i.rawCollision=r;function e(s,o,d){let f=o*Math.PI/180,u=Math.cos(f),l=Math.sin(f),p=1/0;return u>0&&(p=Math.min(p,(d.right-s.x)/u)),u<0&&(p=Math.min(p,(d.left-s.x)/u)),l>0&&(p=Math.min(p,(d.bottom-s.y)/l)),l<0&&(p=Math.min(p,(d.top-s.y)/l)),M.from(o).scale(p)}i.getCurrToBound=e;function n(s){let{left:o,right:d,top:f,bottom:u,width:l,height:p,x:y=0,y:b=0}=s;if(l===null||p===null)throw new Error("width and height are required");let x,t;if(o!=null&&d!=null){if(Math.abs(d-o-l)>1e-6)throw new Error("left, right, and width mismatch");x=o}else y!=null?x=y-l/2:o!=null?x=o:d!=null?x=d-l:x=0;if(f!=null&&u!=null){if(Math.abs(u-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else b!=null?t=b-p/2:f!=null?t=f:u!=null?t=u-p:t=0;return{left:x,right:x+l,top:t,bottom:t+p,width:l,height:p,x:x+l/2,y:t+p/2}}i.createRawRect=n})(F||={});var L;(b=>{class r extends O{#e;#t;constructor(t,a,h){super(t,a,h),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)}}b.KaylaGame=r;class e extends U{game;pointerX;pointerY;pointerEvents;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",a=>{if(this.game)for(let h of this.game.scenes.values())h.handleDraw(a)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new K,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=this.onPointerDown.bind(this)}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerDown(t){this.pointerPosUpdater(t);let a=e.getClickType(t);if(a!=="invalid"){t.preventDefault();let h=this.getMousePos();this.pointerEvents.emit("down",h,a)}}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)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown)}pointerPosToWorldPos(t,a){let h=this.canvas.getBoundingClientRect(),c=(t-h.left)/h.width,g=(a-h.top)/h.height,w=c*this.viewportWidth*this.cameraWidth/h.width,C=g*this.viewportHeight*this.cameraHeight/h.height;return new M(w,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let a=h=>{t(h,new i)};return this.on("draw",a),()=>{this.off("draw",a)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}b.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 oe(ue)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let a=oe(null);return(a.current===null||a.current===void 0)&&(a.current=t()),a.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let a=this.current;a.onInit=t}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return _(()=>new b.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return _(()=>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 _(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:a=>{t.setMaxChildren(a)},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:a=!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 s(this.current,t,{alwaysRecall:a});return this.current.state[this.current.useStateCallIndex]=c,this.current.useStateCallIndex++,c}useShouldRefresh(t){let a=this.current;if(!a)throw new Error("useShouldRefresh must be called inside a component");a.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),a.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let h=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=h,this.current.useRefCallIndex++,h}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++}useExports(t,a){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=a}useGlobalClick(t){if(!this.current)throw new Error("Hook 'useGlobalClick' must be executed in the top level scope of a component.");this.current.onGlobalClick[this.current.useGlobalClickCallIndex]=t,this.current.useGlobalClickCallIndex++}useClick(t){if(!this.current)throw new Error("Hook 'useClick' must be executed in the top level scope of a component.");let a=this.current;ve((h,c)=>{let g=a.entity;if(!g)return;let w=g.getRawRect(),C=F.createRawRect({x:h.x,y:h.y,width:3,height:3});F.rawCollision(w,C)&&t(h,c)})}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,a,h,...c)=>{let g=t?.fc?.name||"anonymous",w=t?.key?` key=${t.key}`:"";this.logger[a](`${h} <${g}${w}>`,...c)}}}b.GlobalKayla=n;class i{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}b.KaylaEvent=i;class s{#e;#t;#n;alwaysRecall;constructor(t,a,{alwaysRecall:h=!1}={}){this.#t=t,this.#e=a??void 0,this.#n=Date.now(),this.alwaysRecall=h}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
2
2
  You probably wrote: const [value, setValue] = useState(...)
3
3
 
4
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(n,{recall:a}={}){this.set(this.get()+n,{recall:a})}multiply(n,{recall:a}={}){this.set(this.get()*n,{recall:a})}set(n,{recall:a=!1}={}){let o=this.#e;if(n===o)return;this.#e=n;let g=Date.now()-this.#n;a&&g<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${g}ms`),(a||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}b.KaylaInternalState=i;class u{#e;constructor(n){this.#e=n??void 0}#t;setSetter(n){this.#t=n}get current(){return this.#e}set current(n){this.#e=n,this.#t&&this.#t(this.#e)}}b.KaylaInternalRef=u;function f(v){return new u(v)}b.createReassignableRef=f;class d{state;refs;global;callProps;scene;exports;get childrenCount(){return this.lastChildren.length}maxSafeChildren;constructor(n,a,o){if(!o)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=a,this.state=[],this.refs=[],this.fc=o.type,this.callProps=o.props??{},this.global=n,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[]}get key(){return this.callProps.key}set key(n){this.callProps.key=n}get children(){return this.callProps.children}set children(n){this.callProps.children=n}entity;onExport=()=>({});onEffect;onInit;onUnInit;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];setMaxChildren(n){if(this.maxSafeChildren=Math.max(0,n),this.global.logger.debug(`Max children limit updated to ${n} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let a=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${a} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let o=this.lastChildren.slice(0,this.maxSafeChildren),l=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=o;for(let g of l)g.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}shouldFullRefresh(){if(this.isFirstUse||!this.watchedDeps||this.watchedDeps.length===0)return!0;for(let n=0;n<this.watchedDeps.length;n++){let a=this.watchedDeps[n],o=this.lastDepStamps[n]??0;if(a.lastChanged>o)return!0}return!1}captureDepStamps(){this.watchedDeps&&(this.lastDepStamps=this.watchedDeps.map(n=>n.lastChanged))}refresh(){if(!this.shouldFullRefresh())return;let n=this.fc?.name||"anonymous";if(!this.shouldFullRefresh()){this.global.logger.debug(`Refresh skipped <${n} key=${this.key}>`);return}this.global.logger.debug(`Refresh executed <${n} key=${this.key}> reason=${this.isFirstUse?"first":"deps-changed"}`),this.lastChildren.length>this.maxSafeChildren&&this.global.logger.warn(`High child count <${n} key=${this.key}> children=${this.lastChildren.length}`);let a;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0;let o=[];try{let l=this.fc(this.callProps)??[];if(l&&!Array.isArray(l)&&(l=[l]),!Array.isArray(l))throw new Error("Non array or non undefined children received.");o=l}catch(l){a=l}this.useStateCallIndex=0,this.useRefCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.global.restore();try{let l=0,g=[];for(let x of o){let C=this.lastChildren.at(l)??new d(this.global,this.scene,x);this.lastChildren[l]=C,g.push(C),l++}for(let x of this.lastChildren.filter(C=>!g.includes(C))){let C=this.lastChildren.indexOf(x);C!==1&&this.lastChildren.splice(C,1),x.unuse()}for(let x of this.lastChildren)try{x.refresh()}catch(C){console.error(C)}this.captureDepStamps(),B(()=>{this.use()})}catch(l){console.error(l)}if(a)throw a}lastChildren;isFirstUse=!0;use(){try{let n=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(n=this.onEffectDeps.some((a,o)=>{let l=this.lastStateDeps.at(o);if(l){let g=a.lastChanged,x=l.stamp;return g>x}})),n||this.isFirstUse){this.global.logger.debug(`Effects re-registered <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let a=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(l=>({stamp:l.lastChanged,stateRef:l}))),this.key??=this.fc.name+"_"+Y(),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new c(this,this.key);for(let l of this.refs)l.current===P&&(l.current=this.entity);if(this.callProps.ref instanceof u&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof u&&(this.callProps.exportsRef.current=this.exports),this.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),a&&this.onInit)try{let l=this.onInit();typeof l=="function"&&(this.onUnInit=l)}catch(l){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",l),l}try{for(let l of this.onUnEffect??[])l()}catch(l){console.error(l)}let o=this.onEffect.map(l=>l()).filter(l=>l!==void 0);this.onUnEffect=o}}catch(n){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,n),n}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.watchedDeps=void 0,this.lastDepStamps=[];try{this.onUnInit&&this.onUnInit();for(let n of this.onUnEffect)n()}catch(n){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,n)}this.scene.getScene().removeEntity(this.entity);for(let n of this.lastChildren)n.unuse();this.lastChildren.length=0}}b.KaylaFiber=d;class c extends V{#e;constructor(n,a){super(a,0,0,0,0),this.#e=n}update(n){let a=new s;if(this.#e.onTick)for(let o of this.#e.onTick)o(n,a);a.isPrevented()}draw(n){let a=new s;if(this.#e.onPaint)for(let o of this.#e.onPaint)o(n,a);a.isPrevented()||super.draw(n)}}b.KaylaRectEntity=c;class h{#e;constructor(n){this.#e=n}get entity(){return this.#e.entity??null}isCollidingWith(n){return this.entity.isCollidingWith(n.entity)}get pos(){return this.entity.pos}get x(){return this.pos.x}set x(n){this.pos.x=n}get y(){return this.pos.y}set y(n){this.pos.y=n}get width(){return this.entity.width}set width(n){this.entity.width=n}get height(){return this.entity.height}set height(n){this.entity.height=n}get z(){return this.entity.z}set z(n){this.entity.z=n}}b.KaylaRect=h;class p{constructor(n){this.#t=n,this.#e=null,n.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getScene(){return this.#t}drawHandler(n){return this.#t.handleDraw(n)}attachTo(n){n.addScene(this.#t),this.#e=n}spawn(n){new d(b.singleGlobalInstance,this,n).refresh()}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}b.KaylaScene=p,b.singleGlobalInstance=new b.GlobalKayla})(S||={});var m=S.singleGlobalInstance,$=m.useState.bind(m),I=m.useRef.bind(m),te=m.useShouldRefresh.bind(m),G=m.useEffect.bind(m),ne=m.useInitialization.bind(m),re=m.useRect.bind(m),se=m.useTick.bind(m),U=m.usePaint.bind(m),ie=m.useExports.bind(m),k=m.useSelf.bind(m),ae=m.useFiberControl.bind(m),oe=m.useFiber.bind(m),ue=m.useEntity.bind(m),P=Symbol("self_ref");var B=r=>{Promise.resolve(1).then(()=>r())},le=({children:r})=>Array.isArray(r)?[...r]:r;function he(r){return S.createReassignableRef(r)}function ce(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(s,i,u){return i==="reassignSelf"?f=>{e.current=f}:Reflect.get(e.current,i,u)},set(s,i,u,f){return Reflect.set(e.current,i,u,f)},has(s,i){return Reflect.has(e.current,i)},ownKeys(s){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(s,i){return Reflect.getOwnPropertyDescriptor(e.current,i)},deleteProperty(s,i){return Reflect.deleteProperty(e.current,i)}})}function fe(r){m.logLevel=r}function de(r){let e=r.name||"anonymous-custom-hook";return function(s){let i=m.current;if(!i)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let u=s??{};return r.memoize!==!1?k(()=>(i.global.logLevel==="debug"&&i.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${i.fc?.name||"anonymous"} key=${i.key||"no-key"}>`),r.onUse(i,m,u))):(i.global.logLevel==="debug"&&i.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${i.fc?.name||"anonymous"} key=${i.key||"no-key"}>`),r.onUse(i,m,u))}}Reflect.set(globalThis,"Kayla",H);var pe;(e=>e.UIComponent=({x:t,y:s,width:i,height:u,children:f})=>{let d=I(P),c=$(!1);return G(()=>{if(c.get()===!0)return;c.set(!0);let h=d.current;h.width=i,h.height=u,h.x=t,h.y=s}),U(h=>{h.fillStyle="rgba(0, 0, 0, 0.5)",h.fillRect(t,s,i,u)}),f??[]})(pe||={});0&&(module.exports={Kayla,KaylaFragment,KaylaInternals,UI,createElement,createGame,createReassignableObject,createRenderer,createScene,createUseHook,self,setLogLevel,useDisposableRef,useEffect,useEntity,useExports,useFiber,useFiberControl,useInitialization,useNextStack,usePaint,useRect,useRef,useSelf,useShouldRefresh,useState,useTick});
5
+ \u2192 Then: value.get() / value.set(v) / value.add(n)`)}refreshBased(){return[this.set.bind(this),this.get()]}add(t,{recall:a}={}){this.set(this.get()+t,{recall:a})}multiply(t,{recall:a}={}){this.set(this.get()*t,{recall:a})}set(t,{recall:a=!1}={}){let h=this.#e;if(t===h)return;this.#e=t;let g=Date.now()-this.#n;a&&g<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${g}ms`),(a||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}b.KaylaInternalState=s;class o{#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)}}b.KaylaInternalRef=o;function d(x){return new o(x)}b.createReassignableRef=d;class f{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;get childrenCount(){return this.lastChildren.length}maxSafeChildren;constructor(t,a,h){if(!h)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=a,this.state=[],this.refs=[],this.fc=h.type,this.callProps=h.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalClick=[],this.pointerHook=this.pointerHook.bind(this),this.contextInfo=null,this.detectedParent=null}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,a){try{for(let h of this.onGlobalClick)h(t,a)}catch(h){this.global.logger.error(h)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&t.pointerEvents.on("down",this.pointerHook)}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&t.pointerEvents.off("down",this.pointerHook)}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;onGlobalClick;onInit;onUnInit;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=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 a=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${a} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let h=this.lastChildren.slice(0,this.maxSafeChildren),c=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=h;for(let g of c)g.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],a=this.detectedParent;for(;a;)t.push(a),a=a?.detectedParent;return t}getContextChain(){return this.getFiberChain().map(t=>t.contextInfo).filter(Boolean)}findContextValueFromInst(t){return this.getContextChain().find(a=>a.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 a=this.watchedDeps[t],h=this.lastDepStamps[t]??0;if(a.lastChanged>h)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 a;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0;let h=[];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 g of c)if(g.type===this.fc)throw new Error("Circular Component.");h=c}catch(c){a=c}this.useStateCallIndex=0,this.useRefCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0,this.global.restore();try{let c=0,g=[];for(let w of h){let C=this.lastChildren.at(c)??new f(this.global,this.scene,w);this.lastChildren[c]=C,C.detectedParent=this,g.push(C),c++}this.captureDepStamps(),this.use();for(let w of this.lastChildren.filter(C=>!g.includes(C))){let C=this.lastChildren.indexOf(w);C!==1&&this.lastChildren.splice(C,1),w.unuse()}for(let w of this.lastChildren)try{w.refresh()}catch(C){console.error(C)}}catch(c){console.error(c)}if(a)throw a}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=this.onEffectDeps.some((a,h)=>{let c=this.lastStateDeps.at(h);if(c){let g=a.lastChanged,w=c.stamp;return g>w}})),t||this.isFirstUse){this.key??=this.fc.name+"_"+we(),this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let a=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 u(this,this.key);for(let c of this.refs)c.current===ue&&(c.current=this.entity);if(this.callProps.ref instanceof o&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof o&&(this.callProps.exportsRef.current=this.exports),this.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),a&&this.onInit){this.bindEvents();try{let c=this.onInit();typeof c=="function"&&(this.onUnInit=c)}catch(c){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",c),c}}try{for(let c of this.onUnEffect??[])c()}catch(c){console.error(c)}let h=this.onEffect.map(c=>c()).filter(c=>c!==void 0);this.onUnEffect=h}}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.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{this.onUnInit&&this.onUnInit();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}}b.KaylaFiber=f;class u extends X{#e;flags;getRawRect(){return F.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,a){super(a,0,0,0,0),this.#e=t,this.flags=new Map}setFlag(t,a){return this.flags.set(t,a)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){let a=new i;if(this.#e&&this.#e.onTick)for(let h of this.#e.onTick)h(t,a);a.isPrevented()}draw(t){let a=new i;if(this.#e&&this.#e.onPaint)for(let h of this.#e.onPaint)h(t,a);a.isPrevented()||super.draw(t)}getRect(){return new l(this.getFiber())}}b.KaylaRectEntity=u;class l{#e;constructor(t){this.#e=t}getRaw(){return F.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(),a=this.#e.getAttachedRenderer().getMousePos(),h=F.createRawRect({x:a.x,y:a.y,width:3,height:3});return F.rawCollision(t,h)}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)}}b.KaylaInternalRect=l;class p{constructor(t){this.#t=t,this.#e=null,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#t}getGame(){return this.#e}drawHandler(t){return this.#t.handleDraw(t)}attachTo(t){t.addScene(this.#t),this.#e=t}async spawn(t){let a=this.createFiber(t);await this.#e.delay(0),a.refresh()}createFiber(t){return new f(b.singleGlobalInstance,this,t)}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}b.KaylaScene=p,b.singleGlobalInstance=new b.GlobalKayla})(L||={});var B=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 i=Ce();return W(()=>{i.contextInfo={instance:this,value:e}}),Q(this.Provider,()=>({value:e})),n}Provider;Consumer};function Ue(r){return new B(r)}var m=L.singleGlobalInstance,Ne=m.useState.bind(m),oe=m.useRef.bind(m),Oe=m.useShouldRefresh.bind(m),le=m.useEffect.bind(m),ve=m.useGlobalClick.bind(m),Xe=m.useClick.bind(m),W=m.useInitialization.bind(m),Y=m.useRect.bind(m),qe=m.useTick.bind(m),j=m.usePaint.bind(m),Q=m.useExports.bind(m),_=m.useSelf.bind(m),he=m.useFiberControl.bind(m),Ce=m.useFiber.bind(m),Be=m.useEntity.bind(m),We=m.useCurrentGame.bind(m),Ye=m.useCurrentRenderer.bind(m),je=m.useCurrentScene.bind(m),Qe=m.useCurrentTicker.bind(m),Je=m.useContext.bind(m),ue=Symbol("self_ref");var ce=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},Ze=({children:r})=>Array.isArray(r)?[...r]:r;function et(r){return L.createReassignableRef(r)}function tt(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(i,s,o){return s==="reassignSelf"?d=>{e.current=d}:Reflect.get(e.current,s,o)},set(i,s,o,d){return Reflect.set(e.current,s,o,d)},has(i,s){return Reflect.has(e.current,s)},ownKeys(i){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(i,s){return Reflect.getOwnPropertyDescriptor(e.current,s)},deleteProperty(i,s){return Reflect.deleteProperty(e.current,s)}})}function nt(r){m.logLevel=r}function rt(r){let e=r.name||"anonymous-custom-hook";return function(i){let s=m.current;if(!s)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let o=i??{};return r.memoize!==!1?_(()=>(s.global.logLevel==="debug"&&s.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${s.fc?.name||"anonymous"} key=${s.key||"no-key"}>`),r.onUse(s,m,o))):(s.global.logLevel==="debug"&&s.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${s.fc?.name||"anonymous"} key=${s.key||"no-key"}>`),r.onUse(s,m,o))}}Reflect.set(globalThis,"Kayla",de);var it;(n=>(n.Flex=({align:i="stretch",children:s,direction:o="row",gap:d=0,justify:f="start",wrap:u="nowrap",getHeight:l,getWidth:p,getCenterX:y,getCenterY:b,color:x})=>{let t=he(),a=Y(),h=_(()=>({recalc(){let c=Number(d)||0,g=y(),w=b(),C=p(),st=l();a.x=g,a.y=w,a.width=C,a.height=st;let at=t.getChildrenEntities().filter(Boolean).map(v=>v.getRect()).filter(v=>v.getFlag("flex-ignored")!==!0),S=o==="row",P=S?a.width:a.height,Et=S?a.height:a.width,fe=0,$=0,pe=[],J=[];at.forEach(v=>{let Z=S?v.width:v.height;fe+Z>P&&u==="wrap"?(pe.push({height:$,items:J}),J=[v],fe=Z,$=S?v.height:v.width):(J.push(v),fe+=Z+c,$=Math.max($,S?v.height:v.width))}),pe.push({height:$,items:J});let me=0;pe.forEach((v,Z)=>{let I=v.items,D=I.reduce((R,ee)=>R+(S?ee.width:ee.height),0)+c*(I.length-1),T=0;f==="center"&&(T=(P-D)/2),f==="end"&&(T=P-D),f==="space-between"&&(T=0),f==="space-around"&&(T=(P-D)/(I.length*2)),f==="space-evenly"&&(T=(P-D)/(I.length+1)),I.forEach((R,ee)=>{R.z=a.z+1;let G=S?R.width:R.height,te=S?R.height:R.width,ne=0;i==="center"&&(ne=(v.height-te)/2),i==="end"&&(ne=v.height-te),i==="stretch"&&(S?R.height=v.height:R.width=v.height),S?(R.x=T+G/2,R.y=me+ne+te/2):(R.x=me+ne+te/2,R.y=T+G/2),f==="space-between"&&ee<I.length-1?T+=G+c+(P-D)/(I.length-1):f==="space-around"?T+=G+c+(P-D)/I.length:f==="space-evenly"?T+=G+c+(P-D)/(I.length+1):T+=G+c}),me+=v.height+c})}}));return j((c,g)=>{g.preventDefault(),c.fillStyle=x,c.fillRect(a.left,a.top,a.width,a.height)}),le(()=>{ce(()=>{h.recalc()})}),Q(n.Flex,()=>({controls:h})),s},n.GenericBox=({color:i,width:s=20,height:o=20,x:d=0,y:f=0})=>{let u=Y();W(()=>{u.width=s,u.height=o,u.x=d,u.y=f}),j((l,p)=>{p.preventDefault(),l.fillStyle=i,l.fillRect(u.left,u.top,u.width,u.height)})}))(it||={});0&&(module.exports={Kayla,KaylaContext,KaylaFragment,KaylaInternals,KaylaRect,LEA,UI,createContext,createElement,createGame,createReassignableObject,createRenderer,createScene,createUseHook,self,setLogLevel,useClick,useContext,useCurrentGame,useCurrentRenderer,useCurrentScene,useCurrentTicker,useDisposableRef,useEffect,useEntity,useExports,useFiber,useFiberControl,useGlobalClick,useInitialization,useNextStack,usePaint,useRect,useRef,useSelf,useShouldRefresh,useState,useTick});
package/dist/kayla.d.cts CHANGED
@@ -1,16 +1,35 @@
1
- import { F as FCProps, a as FC } from './kayla-internals-DVENIMGb.cjs';
2
- export { E as ExportsOfFC, b as FCExports, J as JSX, K as Kayla, c as KaylaCustomHookConfig, d as KaylaElement, e as KaylaElementRef, f as KaylaExportables, g as KaylaExports, h as KaylaFiberControl, i as KaylaFragment, j as KaylaGame, k as KaylaInternals, l as KaylaRect, m as KaylaRef, n as KaylaRenderer, o as KaylaScene, p as KaylaState, P as PropOfFC, R as Reassignable, U as UnsafeKaylaFiber, q as createElement, r as createGame, s as createReassignableObject, t as createRenderer, u as createScene, v as createUseHook, w as self, x as setLogLevel, y as useDisposableRef, z as useEffect, A as useEntity, B as useExports, C as useFiber, D as useFiberControl, G as useInitialization, H as useNextStack, I as usePaint, L as useRect, M as useRef, N as useSelf, O as useShouldRefresh, Q as useState, S as useTick } from './kayla-internals-DVENIMGb.cjs';
3
- import './lea-DvxsutSf.cjs';
1
+ import { F as FCProps, a as FCExports, b as FC } from './kayla-internals-CudoMM3W.cjs';
2
+ export { E as ExportsOfFC, J as JSX, K as Kayla, c as KaylaClickType, d as KaylaContext, e as KaylaCustomHookConfig, f as KaylaElement, g as KaylaElementRef, h as KaylaExportables, i as KaylaExports, j as KaylaFiberControl, k as KaylaFragment, l as KaylaGame, m as KaylaInternals, n as KaylaRect, o as KaylaRef, p as KaylaRenderer, q as KaylaScene, r as KaylaState, P as PropOfFC, R as Reassignable, U as UnsafeKaylaFiber, s as createContext, t as createElement, u as createGame, v as createReassignableObject, w as createRenderer, x as createScene, y as createUseHook, z as self, A as setLogLevel, B as useClick, C as useContext, D as useCurrentGame, G as useCurrentRenderer, H as useCurrentScene, I as useCurrentTicker, L as useDisposableRef, M as useEffect, N as useEntity, O as useExports, Q as useFiber, S as useFiberControl, T as useGlobalClick, V as useInitialization, W as useNextStack, X as usePaint, Y as useRect, Z as useRef, _ as useSelf, $ as useShouldRefresh, a0 as useState, a1 as useTick } from './kayla-internals-CudoMM3W.cjs';
3
+ export { L as LEA } from './lea-k7IGP_-W.cjs';
4
4
 
5
5
  declare namespace UI {
6
- interface UIProps extends FCProps {
7
- x: number;
8
- y: number;
9
- width: number;
10
- height: number;
11
- onClick?: () => void;
6
+ interface FlexProps extends FCProps {
7
+ direction?: "row" | "column";
8
+ align?: "stretch" | "start" | "end" | "center" | "baseline";
9
+ justify?: "start" | "end" | "center" | "space-between" | "space-around" | "space-evenly";
10
+ wrap?: "wrap" | "nowrap" | "wrap-reverse";
11
+ gap?: number;
12
+ getHeight(): number;
13
+ getWidth(): number;
14
+ getCenterX(): number;
15
+ getCenterY(): number;
16
+ color: string;
12
17
  }
13
- const UIComponent: FC<UIProps>;
18
+ interface FlexControls {
19
+ recalc(): void;
20
+ }
21
+ interface FlexExports extends FCExports {
22
+ controls: FlexControls;
23
+ }
24
+ const Flex: FC<FlexProps, FlexExports>;
25
+ interface GenericBoxProps extends FCProps {
26
+ color: string;
27
+ width?: number;
28
+ height?: number;
29
+ x?: number;
30
+ y?: number;
31
+ }
32
+ const GenericBox: FC<GenericBoxProps>;
14
33
  }
15
34
 
16
- export { FC, FCProps, UI };
35
+ export { FC, FCExports, FCProps, UI };
package/dist/kayla.d.ts CHANGED
@@ -1,16 +1,35 @@
1
- import { F as FCProps, a as FC } from './kayla-internals-BsxRqVsK.js';
2
- export { E as ExportsOfFC, b as FCExports, J as JSX, K as Kayla, c as KaylaCustomHookConfig, d as KaylaElement, e as KaylaElementRef, f as KaylaExportables, g as KaylaExports, h as KaylaFiberControl, i as KaylaFragment, j as KaylaGame, k as KaylaInternals, l as KaylaRect, m as KaylaRef, n as KaylaRenderer, o as KaylaScene, p as KaylaState, P as PropOfFC, R as Reassignable, U as UnsafeKaylaFiber, q as createElement, r as createGame, s as createReassignableObject, t as createRenderer, u as createScene, v as createUseHook, w as self, x as setLogLevel, y as useDisposableRef, z as useEffect, A as useEntity, B as useExports, C as useFiber, D as useFiberControl, G as useInitialization, H as useNextStack, I as usePaint, L as useRect, M as useRef, N as useSelf, O as useShouldRefresh, Q as useState, S as useTick } from './kayla-internals-BsxRqVsK.js';
3
- import './lea-DvxsutSf.js';
1
+ import { F as FCProps, a as FCExports, b as FC } from './kayla-internals-8Xl7b2Jc.js';
2
+ export { E as ExportsOfFC, J as JSX, K as Kayla, c as KaylaClickType, d as KaylaContext, e as KaylaCustomHookConfig, f as KaylaElement, g as KaylaElementRef, h as KaylaExportables, i as KaylaExports, j as KaylaFiberControl, k as KaylaFragment, l as KaylaGame, m as KaylaInternals, n as KaylaRect, o as KaylaRef, p as KaylaRenderer, q as KaylaScene, r as KaylaState, P as PropOfFC, R as Reassignable, U as UnsafeKaylaFiber, s as createContext, t as createElement, u as createGame, v as createReassignableObject, w as createRenderer, x as createScene, y as createUseHook, z as self, A as setLogLevel, B as useClick, C as useContext, D as useCurrentGame, G as useCurrentRenderer, H as useCurrentScene, I as useCurrentTicker, L as useDisposableRef, M as useEffect, N as useEntity, O as useExports, Q as useFiber, S as useFiberControl, T as useGlobalClick, V as useInitialization, W as useNextStack, X as usePaint, Y as useRect, Z as useRef, _ as useSelf, $ as useShouldRefresh, a0 as useState, a1 as useTick } from './kayla-internals-8Xl7b2Jc.js';
3
+ export { L as LEA } from './lea-k7IGP_-W.js';
4
4
 
5
5
  declare namespace UI {
6
- interface UIProps extends FCProps {
7
- x: number;
8
- y: number;
9
- width: number;
10
- height: number;
11
- onClick?: () => void;
6
+ interface FlexProps extends FCProps {
7
+ direction?: "row" | "column";
8
+ align?: "stretch" | "start" | "end" | "center" | "baseline";
9
+ justify?: "start" | "end" | "center" | "space-between" | "space-around" | "space-evenly";
10
+ wrap?: "wrap" | "nowrap" | "wrap-reverse";
11
+ gap?: number;
12
+ getHeight(): number;
13
+ getWidth(): number;
14
+ getCenterX(): number;
15
+ getCenterY(): number;
16
+ color: string;
12
17
  }
13
- const UIComponent: FC<UIProps>;
18
+ interface FlexControls {
19
+ recalc(): void;
20
+ }
21
+ interface FlexExports extends FCExports {
22
+ controls: FlexControls;
23
+ }
24
+ const Flex: FC<FlexProps, FlexExports>;
25
+ interface GenericBoxProps extends FCProps {
26
+ color: string;
27
+ width?: number;
28
+ height?: number;
29
+ x?: number;
30
+ y?: number;
31
+ }
32
+ const GenericBox: FC<GenericBoxProps>;
14
33
  }
15
34
 
16
- export { FC, FCProps, UI };
35
+ export { FC, FCExports, FCProps, UI };
package/dist/kayla.js CHANGED
@@ -1,5 +1,5 @@
1
- var j=Object.defineProperty;var Y=(r,e)=>{for(var t in e)j(r,t,{get:e[t],enumerable:!0})};var X={};Y(X,{KaylaFragment:()=>me,KaylaInternals:()=>R,createElement:()=>ae,createGame:()=>re,createReassignableObject:()=>be,createRenderer:()=>ie,createScene:()=>se,createUseHook:()=>xe,self:()=>A,setLogLevel:()=>ge,useDisposableRef:()=>ye,useEffect:()=>N,useEntity:()=>pe,useExports:()=>ce,useFiber:()=>de,useFiberControl:()=>fe,useInitialization:()=>ue,useNextStack:()=>W,usePaint:()=>O,useRect:()=>le,useRef:()=>M,useSelf:()=>F,useShouldRefresh:()=>oe,useState:()=>H,useTick:()=>he});var T=class{#e=new Map;constructor(){this.#e=new Map}on(e,t){let s=this.#e.get(e)||[];return s.push(t),this.#e.set(e,s),this}once(e,t){let s=(...i)=>{this.off(e,s),t(...i)};return this.on(e,s),this}off(e,t){let s=this.#e.get(e);if(!s)return this;let i=s.indexOf(t);return i>=0&&s.splice(i,1),this}emit(e,...t){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw t[0];return!1}return s.slice().forEach(i=>i(...t)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},_=class extends T{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:t,viewportHeight:s,cameraWidth:i,cameraHeight:u}={}){if(!E)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=t??e.width,this.#t=s??e.height,this.#n=i??e.width,this.#r=u??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,t=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,t),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!E)return;let e=performance.now(),t=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=t,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},$=class extends T{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),t=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,this.#e+=t*1e3,this.emit("tick",t)}createTimeout(e){return new U(e,this)}createTween(e,t=()=>{}){let s=new G(e),i=(u=0)=>{if(s.finished){this.off("tick",i);return}s.update(u)};return s.on("finish",()=>{this.off("tick",i)}),s.on("delta",u=>{t(u)}),this.on("tick",i),s}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=E&&!isFinite(this.tickInterval)?ee(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,t=0){return .5+.5*Math.sin((this.now()%e/e+t)*2*Math.PI)}},Q;(n=>{function r(a){return a===!0?1:0}n.booleanExport=r;function e(a){return a===0?!1:a===1}n.booleanImport=e;function t(a){return`${a.x}|${a.y}`}n.vec2Export=t;function s(a){let[o,l]=a.split("|"),g=parseFloat(o),x=parseFloat(l);if(isNaN(g)||isNaN(x))throw new Error(`Invalid Vector2 string: ${a}`);return new K(g,x)}n.vec2Import=s,n.booleanMap={mapExport:r,mapImport:e};function u(a){return o=>Number(o.toFixed(a))}n.createRounder=u;function f(a=10){return{mapExport(o){return Math.round(o/a)},mapImport(o){return o*a}}}n.createLowPrecision=f;function d(a){return Math.round(a)}n.lightWeightRounder=d;function c(a=100){return{mapExport(o){return Math.round(o*a)},mapImport(o){return o/a}}}n.createPercent=c;function h(a){let o=new Map(Object.entries(a));return{mapExport:l=>o.get(l)??null,mapImport:l=>Array.from(o.entries()).find(([g,x])=>x===l)?.[0]??null}}n.createLookup=h;function p(a){let o=a*(180/Math.PI);return Math.round((o%360+360)%360)}n.radToDeg=p;function y(a){return a*(Math.PI/180)}n.degToRad=y,n.angleRadToDeg={mapExport:p,mapImport:y};function v(a=10){let o=f(a);return{mapExport(l){return o.mapExport(p(l))},mapImport(l){return o.mapImport(y(l))}}}n.createLowPrecisionRadToDeg=v})(Q||={});var I=class r extends T{name="";scaleRotate=0;scale=1;constructor(e,t=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new K(t,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(t){this.emit("error",t)}}handleDraw(e){if(!(z||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(t){this.emit("error",t)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([i,{mapExport:u}])=>{let f=Reflect.get(this,i);return u?u(f):f});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],t=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(i=>!this.nonSerializableProperties.includes(i)&&!e.includes(i.toString())),s=Object.fromEntries(t.map(i=>{let u=Reflect.get(this,i);if(z&&typeof u=="number"){let f=u.toString().split("."),c=(f[1]?f[1].length:0)>2?Number(u.toFixed(2)):u;return[i,c]}return[i,u]}));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,t){if(!e||!Array.isArray(t))return t;let s={};for(let i=0;i<t.length;i++){let u=e[i];if(!u)break;let[f,{mapImport:d}]=u,c=t[i];if(d&&(c=d(c)),typeof f!="string")break;try{Reflect.set(s,f,c)}catch(h){console.error(h)}}return s}},L=class extends T{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let t of this.entities.values())t.handleUpdate(e)}}handleDraw(e){if(!z&&!this.paused){this.emit("draw",e);for(let t of[...this.entities.values()].sort((s,i)=>s.z-i.z))t.handleDraw(e)}}addEntity(e){if(!(e instanceof I))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof I))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},D=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,t,s=16){this.ticker=new $(s),this.scenes=new Map,this.width=e,this.height=t,this.ticker.on("tick",i=>{for(let u of this.scenes.values())u.paused||u.handleUpdate(i)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},w={lerp(r,e,t){return r+(e-r)*t},clamp(r,e,t){return Math.min(t,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=w.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return w.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[w.randomInt(0,r.length-1)]},createBezier(r,e,t,s){function i(d,c,h,p,y){let b=1-d;return b*b*b*c+3*b*b*d*h+3*b*d*d*p+d*d*d*y}function u(d,c,h,p,y){let b=1-d;return 3*b*b*(h-c)+6*b*d*(p-h)+3*d*d*(y-p)}function f(d){let c=d;for(let h=0;h<6;h++){let p=i(c,0,r,t,1),y=u(c,0,r,t,1);if(y===0)break;c-=(p-d)/y}return w.clamp(c,0,1)}return function(c){c=w.clamp(c,0,1);let h=f(c);return i(h,0,e,s,1)}},lengthSquared(...r){return r.reduce((e,t)=>e+t*t,0)},normalizeRad(r){let e=2*Math.PI;return r=r%e,r<0&&(r+=e),r},angleInvertY(r){return w.normalizeRad(-r)},degToRadFlipY(r){return w.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=w.normalizeRad(r),e=w.normalizeRad(e);let t=w.normalizeRad(e-r),s=w.normalizeRad(r-e);return t<=s?1:-1}},G=class extends T{constructor({delta:e,ms:t,easing:s}){super(),this.delta=e,this.duration=t,this.elapsed=0,this.easing=s??(i=>i),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let t=w.clamp(this.elapsed/this.duration,0,1),s=this.easing(t),i=this.delta*s,u=i-this.lastValue;this.lastValue=i,this.emit("delta",u),t>=1&&(this.finished=!0,this.emit("finish",void 0))}},V=class extends I{constructor(e,t=0,s=0,i=50,u=50){super(e,t,s),this.width=i,this.height=u}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},U=class extends T{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,t=null){super(),this.duration=e,this.ticker=t,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(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,t){return this.promise.then(e,t)}after(e,t){return this.promise.then(e,t)}},K=class r{constructor(e=0,t=0){this.x=e,this.y=t}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let t=Math.cos(e),s=Math.sin(e);return new r(this.x*t-this.y*s,this.x*s+this.y*t)}static from(e){return new r(Math.cos(e),Math.sin(e))}get angle(){return Math.atan2(this.y,this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new r(0,0):new r(this.x/e,this.y/e)}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let t=this.dot(e);return this.subtract(e.scale(2*t))}dotNormalized(e){let t=this.normalized(),s=e.normalized();return t.x*s.x+t.y*s.y}lengthSquaredTo(e){let t=this.x-e.x,s=this.y-e.y;return t*t+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 t=this.x-e.x,s=this.y-e.y;return t*t+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 J(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var q=J(),z=q==="node",E=q==="web",P=class r{static unlock(){E&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=E?new AudioContext:null;static masterGain=E?this.audioCtx.createGain():null;static musicGain=E?this.audioCtx.createGain():null;static sfxGain=E?this.audioCtx.createGain():null;static{E&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let t=r.CACHE_NAME,s,i;if(typeof caches<"u"&&(i=await caches.open(t),s=await i.match(e)),!s){if(s=await fetch(e),!s.ok)throw new Error(`Failed to fetch ${e}`);i&&await i.put(e,s.clone())}let u=await s.arrayBuffer(),f=await this.audioCtx.decodeAudioData(u);return this.audioBufferCache.set(e,f),f}static async getOnlyDownloadedCache(e){let t=r.CACHE_NAME;return await(await caches.open(t)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,t=.2,s=1,i=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let u=this.getCached(e);if(!u)return;let f=new k(u);f.buffer=u;let d=1-.12,c=1+.12;f.playbackRate=s??d+Math.random()*(c-d);let h=this.audioCtx.createGain();h.gain.value=t,f.tempGain=h,f.connect(h),h.connect(this.sfxGain),f.onended=()=>{f.disconnect(),h.disconnect()},f.start(),i&&this.sfsx.set(e,{source:f,gain:h})}catch(u){console.error(u)}}static async playLoop(e,t=1,{loopStart:s=0,loopEnd:i=null,exclusive:u=!0,skipMS:f=0}={}){if(u)for(let y of this.loops.keys())this.stopLoop(y);this.audioBufferCache.has(e)||await this.preLoad(e);let d=this.getCached(e);if(!d)return;let c=new k(d);c.buffer=d,c.loop=!0,typeof s=="number"&&(c.loopStart=s),typeof i=="number"&&(c.loopEnd=i);let h=this.audioCtx.createGain();h.gain.value=t,c.tempGain=h,c.playbackRate=1,c.onended=()=>{c.disconnect(),h.disconnect()},c.connect(h),h.connect(this.musicGain),c.start(0,f/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:c,gain:h}),p}static stopLoop(e){let t=this.loops.get(e);t&&(t.source.stop(),t.source.notIndependent||(t.source.disconnect(),t.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:t=1,speed:s=1,loop:i=!1,loopStart:u=0,loopEnd:f=null,isMusic:d=!1,gain:c=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return null;let p=new k(h);p.loop=i,p.loopStart=u,p.loopEnd=typeof f=="number"?f:h.duration,p.playbackRate=s;let y=this.audioCtx.createGain();return y.gain.value=t,p.connect(y),p.tempGain=y,y.connect(c||(d?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),y.disconnect()},p}catch(h){return console.error("Failed to create LiaAudioSrc:",h),null}}};var k=class{numberOfInputs;numberOfOutputs;constructor(e,t=P.audioCtx){this.context=t,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=E?t.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:t=null}={}){let s=t!==null?t:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-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,t=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-t/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,t,s):this.source.start(this.context.currentTime+e,t),this.pauseTime=t,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let t=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;t=this.loopStart+(t-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=t,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let t=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=t,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,t=0,s=0){if("value"in e)this.output.connect(e,t);else return this.output.connect(e,t,s),e}disconnect(e,t,s){e===void 0?this.output.disconnect():this.output.disconnect(e,t,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let t=this.context.currentTime+e;this.source.stop(t),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Z={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},S=class r{constructor(e={}){this.ctx=P.audioCtx,this.cfg=structuredClone(Z),Object.assign(this.cfg,e)}ctx;cfg;play(e=P.sfxGain){let t=this.ctx,s=t.currentTime,i=this.cfg,u=t.createGain();u.gain.setValueAtTime(1e-4,s);let f=i.ampEnv;u.gain.exponentialRampToValueAtTime(f.volume,s+f.attack),u.gain.exponentialRampToValueAtTime(Math.max(1e-4,f.sustain*f.volume),s+f.attack+f.decay),u.gain.exponentialRampToValueAtTime(1e-4,s+i.duration+f.release);let d=u,c;i.filter.enabled&&(c=t.createBiquadFilter(),c.type=i.filter.type,c.frequency.value=i.filter.freq,c.Q.value=i.filter.Q,c.connect(u),d=c);let h;if(i.osc.enabled){if(h=t.createOscillator(),h.type=i.osc.type,h.frequency.value=i.osc.freq,h.detune.value=i.osc.detune,i.pitchEnv.amount!==0){let a=Math.pow(2,i.pitchEnv.amount/12);h.frequency.exponentialRampToValueAtTime(i.osc.freq*a,s+i.pitchEnv.decay)}h.connect(d),h.start(s),h.stop(s+i.duration+f.release)}let p;if(i.noise.enabled){let a=t.sampleRate*i.duration,o=t.createBuffer(1,a,t.sampleRate),l=o.getChannelData(0);for(let g=0;g<a;g++)l[g]=(Math.random()*2-1)*i.noise.level;p=t.createBufferSource(),p.buffer=o,p.connect(d),p.start(s),p.stop(s+i.duration+f.release)}let y,b;i.lfo.enabled&&h&&(y=t.createOscillator(),y.frequency.value=i.lfo.rate,b=t.createGain(),b.gain.value=i.lfo.depth,y.connect(b),i.lfo.target==="freq"?b.connect(h.frequency):i.lfo.target==="gain"?b.connect(u.gain):i.lfo.target==="filter"&&c&&b.connect(c.frequency),y.start(s),y.stop(s+i.duration)),u.connect(e);let v=[h,p,y,b,c,u],n=s+i.duration+f.release;setTimeout(()=>{v.forEach(a=>a?.disconnect())},(n-t.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,t){return Object.assign(this.cfg[e],t),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,t,s,i){return Object.assign(this.cfg.ampEnv,{attack:e,decay:t,sustain:s,release:i}),this}setPitchEnv(e,t){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:t}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,t,s){return Object.assign(this.cfg.filter,{type:e,freq:t,Q:s,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,t,s){return Object.assign(this.cfg.lfo,{target:e,rate:t,depth:s,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},Ee=new S({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Ce=new S({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Te=new S({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),Se=new S({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}),Re=new S({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function B(r=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(4)),s=Array.from(t).map(i=>i.toString(36).padStart(2,"0")).join("");return(e+s).slice(0,r)}function ee(r){let e=!0;function t(){e&&(r(),requestAnimationFrame(t))}return requestAnimationFrame(t),{clear:()=>e=!1}}function te(){return z?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var Ke=te();function re({width:r,height:e,updateHz:t="frames"}){return new R.KaylaGame(r,e,t==="frames"?1/0:t)}function se(r){let e=new L(r);return new R.KaylaScene(e)}function ie(r){return new R.KaylaRenderer(r)}function ae(r,e){return{type:r,props:e}}var R;(b=>{class r extends D{#e;#t;constructor(n,a,o){super(n,a,o),this.#e=new Set,this.#t=!1}get started(){return this.#t}start(){if(!this.#t){for(let n of this.#e)n.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let n of this.#e)n.stop();this.#t=!1,super.stop()}}addRenderer(n){this.#e.has(n)||(this.#e.add(n),this.#t&&n.start(),n.game=this)}deleteRenderer(n){this.#e.has(n)&&(this.#e.delete(n),this.#t&&n.stop(),delete n.game)}}b.KaylaGame=r;class e extends _{game;pointerX;pointerY;#e;constructor(n){super(n),this.useDraw=this.useDraw.bind(this),this.on("draw",a=>{if(this.game)for(let o of this.game.scenes.values())o.handleDraw(a)}),this.pointerX=0,this.pointerY=0,this.#e=this.#t.bind(this)}#t(n){this.pointerX=n.clientX,this.pointerY=n.clientY}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.#e)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.#e)}pointerPosToWorldPos(n,a){let o=this.canvas.getBoundingClientRect(),l=(n-o.left)/o.width,g=(a-o.top)/o.height,x=l*this.viewportWidth*this.cameraWidth/o.width,C=g*this.viewportHeight*this.cameraHeight/o.height;return new K(x,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(n){let a=o=>{n(o,new s)};return this.on("draw",a),()=>{this.off("draw",a)}}attachTo(n){n.addRenderer(this),this.game=n}detach(){this.game&&this.game.deleteRenderer(this)}}b.KaylaRenderer=e;class t{current;saves;constructor(){this.saves=[]}useTick(n){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]=n,this.current.useStepCallIndex++}usePaint(n){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]=n,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return M(A)}useSelf(n){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let a=M(null);return(a.current===null||a.current===void 0)&&(a.current=n()),a.current}useInitialization(n){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let a=this.current;a.onInit=n}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return F(()=>new b.KaylaRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return F(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let n=this.current;return F(()=>({refresh:()=>n.refresh(),get childrenCount(){return n.lastChildren.length},setMaxChildren:a=>{n.setMaxChildren(a)},getMaxChildren:()=>n.getMaxChildren(),get maxSafeChildren(){return n.maxSafeChildren}}))}useState(n,{alwaysRecall:a=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let l=this.current.state[this.current.useStateCallIndex]??new i(this.current,n,{alwaysRecall:a});return this.current.state[this.current.useStateCallIndex]=l,this.current.useStateCallIndex++,l}useShouldRefresh(n){let a=this.current;if(!a)throw new Error("useShouldRefresh must be called inside a component");a.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),a.watchedDeps=n}useRef(n){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let o=this.current.refs[this.current.useRefCallIndex]??f(n??null);return this.current.refs[this.current.useRefCallIndex]=o,this.current.useRefCallIndex++,o}useEffect(n){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]=n,this.current.useEffectCallIndex++}useExports(n,a){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=a}save(){this.saves.push({current:this.current})}restore(){let n=this.saves.pop();if(!n)throw new Error("Cannot restore without saving.");this.current=n.current}logLevel="warn";logger={debug:(...n)=>{this.logLevel==="debug"&&console.debug(...n)},info:(...n)=>{this.logLevel>="info"&&console.info(...n)},warn:(...n)=>{this.logLevel>="warn"&&console.warn(...n)},error:(...n)=>console.error(...n),withFiber:(n,a,o,...l)=>{let g=n?.fc?.name||"anonymous",x=n?.key?` key=${n.key}`:"";this.logger[a](`${o} <${g}${x}>`,...l)}}}b.GlobalKayla=t;class s{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}b.KaylaEvent=s;class i{#e;#t;#n;alwaysRecall;constructor(n,a,{alwaysRecall:o=!1}={}){this.#t=n,this.#e=a??void 0,this.#n=Date.now(),this.alwaysRecall=o}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
1
+ var He=Object.defineProperty;var xe=(r,e)=>{for(var n in e)He(r,n,{get:e[n],enumerable:!0})};var be={};xe(be,{KaylaContext:()=>te,KaylaFragment:()=>ht,KaylaInternals:()=>D,KaylaRect:()=>A,createContext:()=>Ze,createElement:()=>Je,createGame:()=>Ye,createReassignableObject:()=>dt,createRenderer:()=>Qe,createScene:()=>je,createUseHook:()=>pt,self:()=>pe,setLogLevel:()=>ft,useClick:()=>nt,useContext:()=>lt,useCurrentGame:()=>st,useCurrentRenderer:()=>at,useCurrentScene:()=>ot,useCurrentTicker:()=>ut,useDisposableRef:()=>ct,useEffect:()=>me,useEntity:()=>it,useExports:()=>se,useFiber:()=>De,useFiberControl:()=>ye,useGlobalClick:()=>Le,useInitialization:()=>ne,useNextStack:()=>ge,usePaint:()=>ie,useRect:()=>re,useRef:()=>fe,useSelf:()=>L,useShouldRefresh:()=>tt,useState:()=>et,useTick:()=>rt});var de={};xe(de,{DeltaTweenII:()=>Z,ENVIRONMENT:()=>he,GEmitterMemory:()=>le,LeaEntityII:()=>H,LeaEventEmitter:()=>K,LeaGameII:()=>O,LeaRendererII:()=>U,LeaSceneII:()=>N,LeaSerializers:()=>we,LeaTickerII:()=>J,LeaTimeout:()=>ee,LeaUtilsII:()=>k,LiaAudio:()=>z,LiaAudioSrc:()=>V,LiaOscSFX:()=>M,LiaSFXMap:()=>Xe,NOTE_NAMES:()=>Ee,RectLeaEntity:()=>X,Vector2:()=>P,colToRGBA:()=>$e,defaultSFXConfig:()=>Re,editRGBA:()=>Ue,generateUUID:()=>Fe,getAvoidAngle:()=>Ae,getEnvironment:()=>Ce,getNormalizedColor:()=>ze,getRayHit:()=>Me,isInitiallyMobile:()=>We,isMobile:()=>_e,isNode:()=>q,isNote:()=>Oe,isWeb:()=>E,parseFillStyle:()=>ve,raycastAvoid:()=>Be,scaleCoord:()=>Ne,setAnimInterval:()=>Pe,sfxHit:()=>Ie,sfxJump:()=>Ke,sfxLaser:()=>Se,sfxUIClick:()=>ke,sfxUIHover:()=>Te,shortUID:()=>qe,tinyUID:()=>ce});var K=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let i=this.#e.get(e)||[];return i.push(n),this.#e.set(e,i),this}once(e,n){let i=(...s)=>{this.off(e,i),n(...s)};return this.on(e,i),this}off(e,n){let i=this.#e.get(e);if(!i)return this;let s=i.indexOf(n);return s>=0&&i.splice(s,1),this}emit(e,...n){let i=this.#e.get(e);if(!i||i.length===0){if(e==="error")throw n[0];return!1}return i.slice().forEach(s=>s(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},U=class extends K{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:n,viewportHeight:i,cameraWidth:s,cameraHeight:o}={}){if(!E)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=n??e.width,this.#t=i??e.height,this.#n=s??e.width,this.#r=o??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,n=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,n),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!E)return;let e=performance.now(),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.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},J=class extends K{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,!(E&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new ee(e,this)}createTween(e,n=()=>{}){let i=new Z(e),s=(o=0)=>{if(i.finished){this.off("tick",s);return}i.update(o)};return i.on("finish",()=>{this.off("tick",s)}),i.on("delta",o=>{n(o)}),this.on("tick",s),i}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=E&&!isFinite(this.tickInterval)?Pe(()=>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)}},we;(t=>{function r(a){return a===!0?1:0}t.booleanExport=r;function e(a){return a===0?!1:a===1}t.booleanImport=e;function n(a){return`${a.x}|${a.y}`}t.vec2Export=n;function i(a){let[h,c]=a.split("|"),g=parseFloat(h),w=parseFloat(c);if(isNaN(g)||isNaN(w))throw new Error(`Invalid Vector2 string: ${a}`);return new P(g,w)}t.vec2Import=i,t.booleanMap={mapExport:r,mapImport:e};function o(a){return h=>Number(h.toFixed(a))}t.createRounder=o;function d(a=10){return{mapExport(h){return Math.round(h/a)},mapImport(h){return h*a}}}t.createLowPrecision=d;function f(a){return Math.round(a)}t.lightWeightRounder=f;function u(a=100){return{mapExport(h){return Math.round(h*a)},mapImport(h){return h/a}}}t.createPercent=u;function l(a){let h=new Map(Object.entries(a));return{mapExport:c=>h.get(c)??null,mapImport:c=>Array.from(h.entries()).find(([g,w])=>w===c)?.[0]??null}}t.createLookup=l;function p(a){let h=a*(180/Math.PI);return Math.round((h%360+360)%360)}t.radToDeg=p;function y(a){return a*(Math.PI/180)}t.degToRad=y,t.angleRadToDeg={mapExport:p,mapImport:y};function x(a=10){let h=d(a);return{mapExport(c){return h.mapExport(p(c))},mapImport(c){return h.mapImport(y(c))}}}t.createLowPrecisionRadToDeg=x})(we||={});var H=class r extends K{name="";scaleRotate=0;scale=1;constructor(e,n=0,i=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new P(n,i),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(!(q||!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(([s,{mapExport:o}])=>{let d=Reflect.get(this,s);return o?o(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(s=>!this.nonSerializableProperties.includes(s)&&!e.includes(s.toString())),i=Object.fromEntries(n.map(s=>{let o=Reflect.get(this,s);if(q&&typeof o=="number"){let d=o.toString().split("."),u=(d[1]?d[1].length:0)>2?Number(o.toFixed(2)):o;return[s,u]}return[s,o]}));return JSON.parse(JSON.stringify(i))}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 i={};for(let s=0;s<n.length;s++){let o=e[s];if(!o)break;let[d,{mapImport:f}]=o,u=n[s];if(f&&(u=f(u)),typeof d!="string")break;try{Reflect.set(i,d,u)}catch(l){console.error(l)}}return i}},N=class extends K{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(!q&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((i,s)=>i.z-s.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof H))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 H))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},O=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,i=16){this.ticker=new J(i),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",s=>{for(let o of this.scenes.values())o.paused||o.handleUpdate(s)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},k={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=k.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return k.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[k.randomInt(0,r.length-1)]},createBezier(r,e,n,i){function s(f,u,l,p,y){let b=1-f;return b*b*b*u+3*b*b*f*l+3*b*f*f*p+f*f*f*y}function o(f,u,l,p,y){let b=1-f;return 3*b*b*(l-u)+6*b*f*(p-l)+3*f*f*(y-p)}function d(f){let u=f;for(let l=0;l<6;l++){let p=s(u,0,r,n,1),y=o(u,0,r,n,1);if(y===0)break;u-=(p-f)/y}return k.clamp(u,0,1)}return function(u){u=k.clamp(u,0,1);let l=d(u);return s(l,0,e,i,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 k.normalizeRad(-r)},degToRadFlipY(r){return k.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=k.normalizeRad(r),e=k.normalizeRad(e);let n=k.normalizeRad(e-r),i=k.normalizeRad(r-e);return n<=i?1:-1}},Z=class extends K{constructor({delta:e,ms:n,easing:i}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=i??(s=>s),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=k.clamp(this.elapsed/this.duration,0,1),i=this.easing(n),s=this.delta*i,o=s-this.lastValue;this.lastValue=s,this.emit("delta",o),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},X=class extends H{constructor(e,n=0,i=0,s=50,o=50){super(e,n,i),this.width=s,this.height=o}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},ee=class extends K{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(i=>this._resolve=i),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)}},P=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),i=Math.sin(e);return new r(this.x*n-this.y*i,this.x*i+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(),i=e.normalized();return n.x*i.x+n.y*i.y}lengthSquaredTo(e){let n=this.x-e.x,i=this.y-e.y;return n*n+i*i}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,i=this.y-e.y;return n*n+i*i}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 ze(r){let e=/^rgba?\(([^)]+)\)$/,n=r.match(e);if(n){let[i,s,o,d=1]=n[1].split(",").map(f=>parseFloat(f));return{r:Math.max(0,Math.min(255,Math.floor(i))),g:Math.max(0,Math.min(255,Math.floor(s))),b:Math.max(0,Math.min(255,Math.floor(o))),a:Math.max(0,Math.min(1,Math.floor(d*255)/255))}}return ve(r)}function $e(r){return`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a})`}function ve(r){if(r=r.trim().toLowerCase(),r[0]==="#"){let n,i,s;if(r.length===7)n=parseInt(r.slice(1,3),16),i=parseInt(r.slice(3,5),16),s=parseInt(r.slice(5,7),16);else if(r.length===4)n=parseInt(r[1]+r[1],16),i=parseInt(r[2]+r[2],16),s=parseInt(r[3]+r[3],16);else throw new Error("Invalid hex color");return{r:n,g:i,b:s,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 Ue(r,{r:e,g:n,b:i,a:s}={}){let[o,d,f,u,l]=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??d}, ${n??f}, ${i??u}, ${s??(l||1)})`}function Ne(r,e,n){return n+(r-n)*e}function Ce(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var he=Ce(),q=he==="node",E=he==="web",z=class r{static unlock(){E&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=E?new AudioContext:null;static masterGain=E?this.audioCtx.createGain():null;static musicGain=E?this.audioCtx.createGain():null;static sfxGain=E?this.audioCtx.createGain():null;static{E&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,i,s;if(typeof caches<"u"&&(s=await caches.open(n),i=await s.match(e)),!i){if(i=await fetch(e),!i.ok)throw new Error(`Failed to fetch ${e}`);s&&await s.put(e,i.clone())}let o=await i.arrayBuffer(),d=await this.audioCtx.decodeAudioData(o);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,i=1,s=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return;let d=new V(o);d.buffer=o;let f=1-.12,u=1+.12;d.playbackRate=i??f+Math.random()*(u-f);let l=this.audioCtx.createGain();l.gain.value=n,d.tempGain=l,d.connect(l),l.connect(this.sfxGain),d.onended=()=>{d.disconnect(),l.disconnect()},d.start(),s&&this.sfsx.set(e,{source:d,gain:l})}catch(o){console.error(o)}}static async playLoop(e,n=1,{loopStart:i=0,loopEnd:s=null,exclusive:o=!0,skipMS:d=0}={}){if(o)for(let y of this.loops.keys())this.stopLoop(y);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let u=new V(f);u.buffer=f,u.loop=!0,typeof i=="number"&&(u.loopStart=i),typeof s=="number"&&(u.loopEnd=s);let l=this.audioCtx.createGain();l.gain.value=n,u.tempGain=l,u.playbackRate=1,u.onended=()=>{u.disconnect(),l.disconnect()},u.connect(l),l.connect(this.musicGain),u.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:u,gain:l}),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:i=1,loop:s=!1,loopStart:o=0,loopEnd:d=null,isMusic:f=!1,gain:u=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return null;let p=new V(l);p.loop=s,p.loopStart=o,p.loopEnd=typeof d=="number"?d:l.duration,p.playbackRate=i;let y=this.audioCtx.createGain();return y.gain.value=n,p.connect(y),p.tempGain=y,y.connect(u||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),y.disconnect()},p}catch(l){return console.error("Failed to create LiaAudioSrc:",l),null}}},Ee=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Oe(r){return Ee.includes(r)}var V=class{numberOfInputs;numberOfOutputs;constructor(e,n=z.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=E?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 i=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-i/this.playbackRate,this.source.start(0,i),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,i){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,i!==void 0?this.source.start(this.context.currentTime+e,n,i):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 i=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%i}if(this.isPlaying=!1,e>0){let i=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,i),this.output.gain.linearRampToValueAtTime(0,i+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,i=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,i),e}disconnect(e,n,i){e===void 0?this.output.disconnect():this.output.disconnect(e,n,i)}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},Re={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},M=class r{constructor(e={}){this.ctx=z.audioCtx,this.cfg=structuredClone(Re),Object.assign(this.cfg,e)}ctx;cfg;play(e=z.sfxGain){let n=this.ctx,i=n.currentTime,s=this.cfg,o=n.createGain();o.gain.setValueAtTime(1e-4,i);let d=s.ampEnv;o.gain.exponentialRampToValueAtTime(d.volume,i+d.attack),o.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),i+d.attack+d.decay),o.gain.exponentialRampToValueAtTime(1e-4,i+s.duration+d.release);let f=o,u;s.filter.enabled&&(u=n.createBiquadFilter(),u.type=s.filter.type,u.frequency.value=s.filter.freq,u.Q.value=s.filter.Q,u.connect(o),f=u);let l;if(s.osc.enabled){if(l=n.createOscillator(),l.type=s.osc.type,l.frequency.value=s.osc.freq,l.detune.value=s.osc.detune,s.pitchEnv.amount!==0){let a=Math.pow(2,s.pitchEnv.amount/12);l.frequency.exponentialRampToValueAtTime(s.osc.freq*a,i+s.pitchEnv.decay)}l.connect(f),l.start(i),l.stop(i+s.duration+d.release)}let p;if(s.noise.enabled){let a=n.sampleRate*s.duration,h=n.createBuffer(1,a,n.sampleRate),c=h.getChannelData(0);for(let g=0;g<a;g++)c[g]=(Math.random()*2-1)*s.noise.level;p=n.createBufferSource(),p.buffer=h,p.connect(f),p.start(i),p.stop(i+s.duration+d.release)}let y,b;s.lfo.enabled&&l&&(y=n.createOscillator(),y.frequency.value=s.lfo.rate,b=n.createGain(),b.gain.value=s.lfo.depth,y.connect(b),s.lfo.target==="freq"?b.connect(l.frequency):s.lfo.target==="gain"?b.connect(o.gain):s.lfo.target==="filter"&&u&&b.connect(u.frequency),y.start(i),y.stop(i+s.duration)),o.connect(e);let x=[l,p,y,b,u,o],t=i+s.duration+d.release;setTimeout(()=>{x.forEach(a=>a?.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,i,s){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:i,release:s}),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,i){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:i,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,i){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:i,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},ke=new M({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Te=new M({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Ke=new M({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),Se=new M({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),Ie=new M({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}),Xe=new Map([["ui_click",ke],["ui_hover",Te],["jump",Ke],["laser",Se],["hit",Ie]]);function qe(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(r)),i=Array.from(n).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+i).slice(0,r)}function ce(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),i=Array.from(n).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+i).slice(0,r)}var le=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${Fe()}_${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(i=>i!==n))}_emit(e,n){this.events[e]?.forEach(i=>i(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 Fe(){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 Pe(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function Me(r,e,n,i,s){let o=Math.cos(s),d=Math.sin(s),f=[];if(o!==0){let u=(0-r)/o,l=e+u*d;u>0&&l>=0&&l<=i&&f.push({side:"left",t:u})}if(o!==0){let u=(n-r)/o,l=e+u*d;u>0&&l>=0&&l<=i&&f.push({side:"right",t:u})}if(d!==0){let u=(0-e)/d,l=r+u*o;u>0&&l>=0&&l<=n&&f.push({side:"top",t:u})}if(d!==0){let u=(i-e)/d,l=r+u*o;u>0&&l>=0&&l<=n&&f.push({side:"bottom",t:u})}return f.length===0?null:(f.sort((u,l)=>u.t-l.t),f[0])}function Ae(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 Be(r,e,n,i,s){let o=Me(r,e,n,i,s);return o?{...o,avoidAngle:Ae(s,o.side)}:null}function _e(){return q?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var We=_e();function Ye({width:r,height:e,updateHz:n="frames"}){return new D.KaylaGame(r,e,n==="frames"?1/0:n)}function je(r){let e=new N(r);return new D.KaylaScene(e)}function Qe(r){return new D.KaylaRenderer(r)}function Je(r,e){return{type:r,props:e}}var A;(i=>{function r(s,o){return!(s.right<o.left||s.left>o.right||s.bottom<o.top||s.top>o.bottom)}i.rawCollision=r;function e(s,o,d){let f=o*Math.PI/180,u=Math.cos(f),l=Math.sin(f),p=1/0;return u>0&&(p=Math.min(p,(d.right-s.x)/u)),u<0&&(p=Math.min(p,(d.left-s.x)/u)),l>0&&(p=Math.min(p,(d.bottom-s.y)/l)),l<0&&(p=Math.min(p,(d.top-s.y)/l)),P.from(o).scale(p)}i.getCurrToBound=e;function n(s){let{left:o,right:d,top:f,bottom:u,width:l,height:p,x:y=0,y:b=0}=s;if(l===null||p===null)throw new Error("width and height are required");let x,t;if(o!=null&&d!=null){if(Math.abs(d-o-l)>1e-6)throw new Error("left, right, and width mismatch");x=o}else y!=null?x=y-l/2:o!=null?x=o:d!=null?x=d-l:x=0;if(f!=null&&u!=null){if(Math.abs(u-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else b!=null?t=b-p/2:f!=null?t=f:u!=null?t=u-p:t=0;return{left:x,right:x+l,top:t,bottom:t+p,width:l,height:p,x:x+l/2,y:t+p/2}}i.createRawRect=n})(A||={});var D;(b=>{class r extends O{#e;#t;constructor(t,a,h){super(t,a,h),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)}}b.KaylaGame=r;class e extends U{game;pointerX;pointerY;pointerEvents;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",a=>{if(this.game)for(let h of this.game.scenes.values())h.handleDraw(a)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new K,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=this.onPointerDown.bind(this)}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerDown(t){this.pointerPosUpdater(t);let a=e.getClickType(t);if(a!=="invalid"){t.preventDefault();let h=this.getMousePos();this.pointerEvents.emit("down",h,a)}}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)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown)}pointerPosToWorldPos(t,a){let h=this.canvas.getBoundingClientRect(),c=(t-h.left)/h.width,g=(a-h.top)/h.height,w=c*this.viewportWidth*this.cameraWidth/h.width,C=g*this.viewportHeight*this.cameraHeight/h.height;return new P(w,C)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let a=h=>{t(h,new i)};return this.on("draw",a),()=>{this.off("draw",a)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}b.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 fe(pe)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let a=fe(null);return(a.current===null||a.current===void 0)&&(a.current=t()),a.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let a=this.current;a.onInit=t}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return L(()=>new b.KaylaInternalRect(this.current))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return L(()=>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 L(()=>({refresh:()=>t.refresh(),get childrenCount(){return t.lastChildren.length},setMaxChildren:a=>{t.setMaxChildren(a)},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:a=!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 s(this.current,t,{alwaysRecall:a});return this.current.state[this.current.useStateCallIndex]=c,this.current.useStateCallIndex++,c}useShouldRefresh(t){let a=this.current;if(!a)throw new Error("useShouldRefresh must be called inside a component");a.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),a.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let h=this.current.refs[this.current.useRefCallIndex]??d(t??null);return this.current.refs[this.current.useRefCallIndex]=h,this.current.useRefCallIndex++,h}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++}useExports(t,a){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=a}useGlobalClick(t){if(!this.current)throw new Error("Hook 'useGlobalClick' must be executed in the top level scope of a component.");this.current.onGlobalClick[this.current.useGlobalClickCallIndex]=t,this.current.useGlobalClickCallIndex++}useClick(t){if(!this.current)throw new Error("Hook 'useClick' must be executed in the top level scope of a component.");let a=this.current;Le((h,c)=>{let g=a.entity;if(!g)return;let w=g.getRawRect(),C=A.createRawRect({x:h.x,y:h.y,width:3,height:3});A.rawCollision(w,C)&&t(h,c)})}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,a,h,...c)=>{let g=t?.fc?.name||"anonymous",w=t?.key?` key=${t.key}`:"";this.logger[a](`${h} <${g}${w}>`,...c)}}}b.GlobalKayla=n;class i{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}b.KaylaEvent=i;class s{#e;#t;#n;alwaysRecall;constructor(t,a,{alwaysRecall:h=!1}={}){this.#t=t,this.#e=a??void 0,this.#n=Date.now(),this.alwaysRecall=h}get(){return this.#e}*[Symbol.iterator](){throw new Error(`Hey! KaylaState is NOT an array / iterable like useState in React.
2
2
  You probably wrote: const [value, setValue] = useState(...)
3
3
 
4
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(n,{recall:a}={}){this.set(this.get()+n,{recall:a})}multiply(n,{recall:a}={}){this.set(this.get()*n,{recall:a})}set(n,{recall:a=!1}={}){let o=this.#e;if(n===o)return;this.#e=n;let g=Date.now()-this.#n;a&&g<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${g}ms`),(a||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}b.KaylaInternalState=i;class u{#e;constructor(n){this.#e=n??void 0}#t;setSetter(n){this.#t=n}get current(){return this.#e}set current(n){this.#e=n,this.#t&&this.#t(this.#e)}}b.KaylaInternalRef=u;function f(v){return new u(v)}b.createReassignableRef=f;class d{state;refs;global;callProps;scene;exports;get childrenCount(){return this.lastChildren.length}maxSafeChildren;constructor(n,a,o){if(!o)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=a,this.state=[],this.refs=[],this.fc=o.type,this.callProps=o.props??{},this.global=n,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[]}get key(){return this.callProps.key}set key(n){this.callProps.key=n}get children(){return this.callProps.children}set children(n){this.callProps.children=n}entity;onExport=()=>({});onEffect;onInit;onUnInit;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];setMaxChildren(n){if(this.maxSafeChildren=Math.max(0,n),this.global.logger.debug(`Max children limit updated to ${n} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let a=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${a} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let o=this.lastChildren.slice(0,this.maxSafeChildren),l=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=o;for(let g of l)g.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}shouldFullRefresh(){if(this.isFirstUse||!this.watchedDeps||this.watchedDeps.length===0)return!0;for(let n=0;n<this.watchedDeps.length;n++){let a=this.watchedDeps[n],o=this.lastDepStamps[n]??0;if(a.lastChanged>o)return!0}return!1}captureDepStamps(){this.watchedDeps&&(this.lastDepStamps=this.watchedDeps.map(n=>n.lastChanged))}refresh(){if(!this.shouldFullRefresh())return;let n=this.fc?.name||"anonymous";if(!this.shouldFullRefresh()){this.global.logger.debug(`Refresh skipped <${n} key=${this.key}>`);return}this.global.logger.debug(`Refresh executed <${n} key=${this.key}> reason=${this.isFirstUse?"first":"deps-changed"}`),this.lastChildren.length>this.maxSafeChildren&&this.global.logger.warn(`High child count <${n} key=${this.key}> children=${this.lastChildren.length}`);let a;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0;let o=[];try{let l=this.fc(this.callProps)??[];if(l&&!Array.isArray(l)&&(l=[l]),!Array.isArray(l))throw new Error("Non array or non undefined children received.");o=l}catch(l){a=l}this.useStateCallIndex=0,this.useRefCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.global.restore();try{let l=0,g=[];for(let x of o){let C=this.lastChildren.at(l)??new d(this.global,this.scene,x);this.lastChildren[l]=C,g.push(C),l++}for(let x of this.lastChildren.filter(C=>!g.includes(C))){let C=this.lastChildren.indexOf(x);C!==1&&this.lastChildren.splice(C,1),x.unuse()}for(let x of this.lastChildren)try{x.refresh()}catch(C){console.error(C)}this.captureDepStamps(),W(()=>{this.use()})}catch(l){console.error(l)}if(a)throw a}lastChildren;isFirstUse=!0;use(){try{let n=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(n=this.onEffectDeps.some((a,o)=>{let l=this.lastStateDeps.at(o);if(l){let g=a.lastChanged,x=l.stamp;return g>x}})),n||this.isFirstUse){this.global.logger.debug(`Effects re-registered <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let a=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(l=>({stamp:l.lastChanged,stateRef:l}))),this.key??=this.fc.name+"_"+B(),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new c(this,this.key);for(let l of this.refs)l.current===A&&(l.current=this.entity);if(this.callProps.ref instanceof u&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof u&&(this.callProps.exportsRef.current=this.exports),this.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),a&&this.onInit)try{let l=this.onInit();typeof l=="function"&&(this.onUnInit=l)}catch(l){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",l),l}try{for(let l of this.onUnEffect??[])l()}catch(l){console.error(l)}let o=this.onEffect.map(l=>l()).filter(l=>l!==void 0);this.onUnEffect=o}}catch(n){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,n),n}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.watchedDeps=void 0,this.lastDepStamps=[];try{this.onUnInit&&this.onUnInit();for(let n of this.onUnEffect)n()}catch(n){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,n)}this.scene.getScene().removeEntity(this.entity);for(let n of this.lastChildren)n.unuse();this.lastChildren.length=0}}b.KaylaFiber=d;class c extends V{#e;constructor(n,a){super(a,0,0,0,0),this.#e=n}update(n){let a=new s;if(this.#e.onTick)for(let o of this.#e.onTick)o(n,a);a.isPrevented()}draw(n){let a=new s;if(this.#e.onPaint)for(let o of this.#e.onPaint)o(n,a);a.isPrevented()||super.draw(n)}}b.KaylaRectEntity=c;class h{#e;constructor(n){this.#e=n}get entity(){return this.#e.entity??null}isCollidingWith(n){return this.entity.isCollidingWith(n.entity)}get pos(){return this.entity.pos}get x(){return this.pos.x}set x(n){this.pos.x=n}get y(){return this.pos.y}set y(n){this.pos.y=n}get width(){return this.entity.width}set width(n){this.entity.width=n}get height(){return this.entity.height}set height(n){this.entity.height=n}get z(){return this.entity.z}set z(n){this.entity.z=n}}b.KaylaRect=h;class p{constructor(n){this.#t=n,this.#e=null,n.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getScene(){return this.#t}drawHandler(n){return this.#t.handleDraw(n)}attachTo(n){n.addScene(this.#t),this.#e=n}spawn(n){new d(b.singleGlobalInstance,this,n).refresh()}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}b.KaylaScene=p,b.singleGlobalInstance=new b.GlobalKayla})(R||={});var m=R.singleGlobalInstance,H=m.useState.bind(m),M=m.useRef.bind(m),oe=m.useShouldRefresh.bind(m),N=m.useEffect.bind(m),ue=m.useInitialization.bind(m),le=m.useRect.bind(m),he=m.useTick.bind(m),O=m.usePaint.bind(m),ce=m.useExports.bind(m),F=m.useSelf.bind(m),fe=m.useFiberControl.bind(m),de=m.useFiber.bind(m),pe=m.useEntity.bind(m),A=Symbol("self_ref");var W=r=>{Promise.resolve(1).then(()=>r())},me=({children:r})=>Array.isArray(r)?[...r]:r;function ye(r){return R.createReassignableRef(r)}function be(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(s,i,u){return i==="reassignSelf"?f=>{e.current=f}:Reflect.get(e.current,i,u)},set(s,i,u,f){return Reflect.set(e.current,i,u,f)},has(s,i){return Reflect.has(e.current,i)},ownKeys(s){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(s,i){return Reflect.getOwnPropertyDescriptor(e.current,i)},deleteProperty(s,i){return Reflect.deleteProperty(e.current,i)}})}function ge(r){m.logLevel=r}function xe(r){let e=r.name||"anonymous-custom-hook";return function(s){let i=m.current;if(!i)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let u=s??{};return r.memoize!==!1?F(()=>(i.global.logLevel==="debug"&&i.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${i.fc?.name||"anonymous"} key=${i.key||"no-key"}>`),r.onUse(i,m,u))):(i.global.logLevel==="debug"&&i.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${i.fc?.name||"anonymous"} key=${i.key||"no-key"}>`),r.onUse(i,m,u))}}Reflect.set(globalThis,"Kayla",X);var ve;(e=>e.UIComponent=({x:t,y:s,width:i,height:u,children:f})=>{let d=M(A),c=H(!1);return N(()=>{if(c.get()===!0)return;c.set(!0);let h=d.current;h.width=i,h.height=u,h.x=t,h.y=s}),O(h=>{h.fillStyle="rgba(0, 0, 0, 0.5)",h.fillRect(t,s,i,u)}),f??[]})(ve||={});export{X as Kayla,me as KaylaFragment,R as KaylaInternals,ve as UI,ae as createElement,re as createGame,be as createReassignableObject,ie as createRenderer,se as createScene,xe as createUseHook,A as self,ge as setLogLevel,ye as useDisposableRef,N as useEffect,pe as useEntity,ce as useExports,de as useFiber,fe as useFiberControl,ue as useInitialization,W as useNextStack,O as usePaint,le as useRect,M as useRef,F as useSelf,oe as useShouldRefresh,H as useState,he as useTick};
5
+ \u2192 Then: value.get() / value.set(v) / value.add(n)`)}refreshBased(){return[this.set.bind(this),this.get()]}add(t,{recall:a}={}){this.set(this.get()+t,{recall:a})}multiply(t,{recall:a}={}){this.set(this.get()*t,{recall:a})}set(t,{recall:a=!1}={}){let h=this.#e;if(t===h)return;this.#e=t;let g=Date.now()-this.#n;a&&g<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${g}ms`),(a||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}b.KaylaInternalState=s;class o{#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)}}b.KaylaInternalRef=o;function d(x){return new o(x)}b.createReassignableRef=d;class f{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;get childrenCount(){return this.lastChildren.length}maxSafeChildren;constructor(t,a,h){if(!h)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=a,this.state=[],this.refs=[],this.fc=h.type,this.callProps=h.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalClick=[],this.pointerHook=this.pointerHook.bind(this),this.contextInfo=null,this.detectedParent=null}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,a){try{for(let h of this.onGlobalClick)h(t,a)}catch(h){this.global.logger.error(h)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&t.pointerEvents.on("down",this.pointerHook)}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&t.pointerEvents.off("down",this.pointerHook)}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;onGlobalClick;onInit;onUnInit;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=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 a=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${a} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let h=this.lastChildren.slice(0,this.maxSafeChildren),c=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=h;for(let g of c)g.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],a=this.detectedParent;for(;a;)t.push(a),a=a?.detectedParent;return t}getContextChain(){return this.getFiberChain().map(t=>t.contextInfo).filter(Boolean)}findContextValueFromInst(t){return this.getContextChain().find(a=>a.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 a=this.watchedDeps[t],h=this.lastDepStamps[t]??0;if(a.lastChanged>h)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 a;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0;let h=[];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 g of c)if(g.type===this.fc)throw new Error("Circular Component.");h=c}catch(c){a=c}this.useStateCallIndex=0,this.useRefCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0,this.global.restore();try{let c=0,g=[];for(let w of h){let C=this.lastChildren.at(c)??new f(this.global,this.scene,w);this.lastChildren[c]=C,C.detectedParent=this,g.push(C),c++}this.captureDepStamps(),this.use();for(let w of this.lastChildren.filter(C=>!g.includes(C))){let C=this.lastChildren.indexOf(w);C!==1&&this.lastChildren.splice(C,1),w.unuse()}for(let w of this.lastChildren)try{w.refresh()}catch(C){console.error(C)}}catch(c){console.error(c)}if(a)throw a}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=this.onEffectDeps.some((a,h)=>{let c=this.lastStateDeps.at(h);if(c){let g=a.lastChanged,w=c.stamp;return g>w}})),t||this.isFirstUse){this.key??=this.fc.name+"_"+ce(),this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let a=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 u(this,this.key);for(let c of this.refs)c.current===pe&&(c.current=this.entity);if(this.callProps.ref instanceof o&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof o&&(this.callProps.exportsRef.current=this.exports),this.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),a&&this.onInit){this.bindEvents();try{let c=this.onInit();typeof c=="function"&&(this.onUnInit=c)}catch(c){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",c),c}}try{for(let c of this.onUnEffect??[])c()}catch(c){console.error(c)}let h=this.onEffect.map(c=>c()).filter(c=>c!==void 0);this.onUnEffect=h}}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.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{this.onUnInit&&this.onUnInit();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}}b.KaylaFiber=f;class u extends X{#e;flags;getRawRect(){return A.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,a){super(a,0,0,0,0),this.#e=t,this.flags=new Map}setFlag(t,a){return this.flags.set(t,a)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){let a=new i;if(this.#e&&this.#e.onTick)for(let h of this.#e.onTick)h(t,a);a.isPrevented()}draw(t){let a=new i;if(this.#e&&this.#e.onPaint)for(let h of this.#e.onPaint)h(t,a);a.isPrevented()||super.draw(t)}getRect(){return new l(this.getFiber())}}b.KaylaRectEntity=u;class l{#e;constructor(t){this.#e=t}getRaw(){return A.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(),a=this.#e.getAttachedRenderer().getMousePos(),h=A.createRawRect({x:a.x,y:a.y,width:3,height:3});return A.rawCollision(t,h)}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)}}b.KaylaInternalRect=l;class p{constructor(t){this.#t=t,this.#e=null,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#t}getGame(){return this.#e}drawHandler(t){return this.#t.handleDraw(t)}attachTo(t){t.addScene(this.#t),this.#e=t}async spawn(t){let a=this.createFiber(t);await this.#e.delay(0),a.refresh()}createFiber(t){return new f(b.singleGlobalInstance,this,t)}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}b.KaylaScene=p,b.singleGlobalInstance=new b.GlobalKayla})(D||={});var te=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 i=De();return ne(()=>{i.contextInfo={instance:this,value:e}}),se(this.Provider,()=>({value:e})),n}Provider;Consumer};function Ze(r){return new te(r)}var m=D.singleGlobalInstance,et=m.useState.bind(m),fe=m.useRef.bind(m),tt=m.useShouldRefresh.bind(m),me=m.useEffect.bind(m),Le=m.useGlobalClick.bind(m),nt=m.useClick.bind(m),ne=m.useInitialization.bind(m),re=m.useRect.bind(m),rt=m.useTick.bind(m),ie=m.usePaint.bind(m),se=m.useExports.bind(m),L=m.useSelf.bind(m),ye=m.useFiberControl.bind(m),De=m.useFiber.bind(m),it=m.useEntity.bind(m),st=m.useCurrentGame.bind(m),at=m.useCurrentRenderer.bind(m),ot=m.useCurrentScene.bind(m),ut=m.useCurrentTicker.bind(m),lt=m.useContext.bind(m),pe=Symbol("self_ref");var ge=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},ht=({children:r})=>Array.isArray(r)?[...r]:r;function ct(r){return D.createReassignableRef(r)}function dt(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(i,s,o){return s==="reassignSelf"?d=>{e.current=d}:Reflect.get(e.current,s,o)},set(i,s,o,d){return Reflect.set(e.current,s,o,d)},has(i,s){return Reflect.has(e.current,s)},ownKeys(i){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(i,s){return Reflect.getOwnPropertyDescriptor(e.current,s)},deleteProperty(i,s){return Reflect.deleteProperty(e.current,s)}})}function ft(r){m.logLevel=r}function pt(r){let e=r.name||"anonymous-custom-hook";return function(i){let s=m.current;if(!s)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let o=i??{};return r.memoize!==!1?L(()=>(s.global.logLevel==="debug"&&s.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${s.fc?.name||"anonymous"} key=${s.key||"no-key"}>`),r.onUse(s,m,o))):(s.global.logLevel==="debug"&&s.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${s.fc?.name||"anonymous"} key=${s.key||"no-key"}>`),r.onUse(s,m,o))}}Reflect.set(globalThis,"Kayla",be);var mt;(n=>(n.Flex=({align:i="stretch",children:s,direction:o="row",gap:d=0,justify:f="start",wrap:u="nowrap",getHeight:l,getWidth:p,getCenterX:y,getCenterY:b,color:x})=>{let t=ye(),a=re(),h=L(()=>({recalc(){let c=Number(d)||0,g=y(),w=b(),C=p(),Ge=l();a.x=g,a.y=w,a.width=C,a.height=Ge;let Ve=t.getChildrenEntities().filter(Boolean).map(v=>v.getRect()).filter(v=>v.getFlag("flex-ignored")!==!0),S=o==="row",F=S?a.width:a.height,gt=S?a.height:a.width,ae=0,$=0,oe=[],B=[];Ve.forEach(v=>{let W=S?v.width:v.height;ae+W>F&&u==="wrap"?(oe.push({height:$,items:B}),B=[v],ae=W,$=S?v.height:v.width):(B.push(v),ae+=W+c,$=Math.max($,S?v.height:v.width))}),oe.push({height:$,items:B});let ue=0;oe.forEach((v,W)=>{let I=v.items,_=I.reduce((R,Y)=>R+(S?Y.width:Y.height),0)+c*(I.length-1),T=0;f==="center"&&(T=(F-_)/2),f==="end"&&(T=F-_),f==="space-between"&&(T=0),f==="space-around"&&(T=(F-_)/(I.length*2)),f==="space-evenly"&&(T=(F-_)/(I.length+1)),I.forEach((R,Y)=>{R.z=a.z+1;let G=S?R.width:R.height,j=S?R.height:R.width,Q=0;i==="center"&&(Q=(v.height-j)/2),i==="end"&&(Q=v.height-j),i==="stretch"&&(S?R.height=v.height:R.width=v.height),S?(R.x=T+G/2,R.y=ue+Q+j/2):(R.x=ue+Q+j/2,R.y=T+G/2),f==="space-between"&&Y<I.length-1?T+=G+c+(F-_)/(I.length-1):f==="space-around"?T+=G+c+(F-_)/I.length:f==="space-evenly"?T+=G+c+(F-_)/(I.length+1):T+=G+c}),ue+=v.height+c})}}));return ie((c,g)=>{g.preventDefault(),c.fillStyle=x,c.fillRect(a.left,a.top,a.width,a.height)}),me(()=>{ge(()=>{h.recalc()})}),se(n.Flex,()=>({controls:h})),s},n.GenericBox=({color:i,width:s=20,height:o=20,x:d=0,y:f=0})=>{let u=re();ne(()=>{u.width=s,u.height=o,u.x=d,u.y=f}),ie((l,p)=>{p.preventDefault(),l.fillStyle=i,l.fillRect(u.left,u.top,u.width,u.height)})}))(mt||={});export{be as Kayla,te as KaylaContext,ht as KaylaFragment,D as KaylaInternals,A as KaylaRect,de as LEA,mt as UI,Ze as createContext,Je as createElement,Ye as createGame,dt as createReassignableObject,Qe as createRenderer,je as createScene,pt as createUseHook,pe as self,ft as setLogLevel,nt as useClick,lt as useContext,st as useCurrentGame,at as useCurrentRenderer,ot as useCurrentScene,ut as useCurrentTicker,ct as useDisposableRef,me as useEffect,it as useEntity,se as useExports,De as useFiber,ye as useFiberControl,Le as useGlobalClick,ne as useInitialization,ge as useNextStack,ie as usePaint,re as useRect,fe as useRef,L as useSelf,tt as useShouldRefresh,et as useState,rt as useTick};