@kayelaa/canvas 0.2.10 → 0.2.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var xe=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Ye=Object.prototype.hasOwnProperty;var ve=(r,e)=>{for(var n in e)xe(r,n,{get:e[n],enumerable:!0})},Qe=(r,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of je(e))!Ye.call(r,a)&&a!==n&&xe(r,a,{get:()=>e[a],enumerable:!(i=We(e,a))||i.enumerable});return r};var Je=r=>Qe(xe({},"__esModule",{value:!0}),r);var Lt={};ve(Lt,{Kayla:()=>W,LEA:()=>X,default:()=>Mt});module.exports=Je(Lt);var X={};ve(X,{DeltaTweenII:()=>he,ENVIRONMENT:()=>Ce,GEmitterMemory:()=>we,LeaEntityII:()=>U,LeaEventEmitter:()=>F,LeaGameII:()=>J,LeaRendererII:()=>Y,LeaSceneII:()=>Q,LeaSerializers:()=>Pe,LeaTickerII:()=>ue,LeaTimeout:()=>ce,LeaUtilsII:()=>P,LiaAudio:()=>O,LiaAudioSrc:()=>H,LiaOscSFX:()=>_,LiaSFXMap:()=>it,NOTE_NAMES:()=>Fe,RectLeaEntity:()=>Z,Vector2:()=>A,colToRGBA:()=>et,defaultSFXConfig:()=>Ae,editRGBA:()=>tt,generateUUID:()=>Ge,getAvoidAngle:()=>He,getEnvironment:()=>Ie,getNormalizedColor:()=>Ze,getRayHit:()=>$e,isInitiallyMobile:()=>ot,isMobile:()=>Ue,isNode:()=>G,isNote:()=>rt,isWeb:()=>T,parseFillStyle:()=>Se,raycastAvoid:()=>at,scaleCoord:()=>nt,setAnimInterval:()=>ze,sfxHit:()=>De,sfxJump:()=>_e,sfxLaser:()=>Ve,sfxUIClick:()=>Me,sfxUIHover:()=>Le,shortUID:()=>st,tinyUID:()=>N});var F=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=(...a)=>{this.off(e,i),n(...a)};return this.on(e,i),this}off(e,n){let i=this.#e.get(e);if(!i)return this;let a=i.indexOf(n);return a>=0&&i.splice(a,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(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},Y=class extends F{#e;#t;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;get canvas(){return this.#e}get ctx(){return this.#t}set canvas(e){this.#e=e,this.#t=e.getContext("2d"),this.updateCanvasResolution()}constructor(e,{viewportWidth:n,viewportHeight:i,cameraWidth:a,cameraHeight:o}={}){if(!T)throw new Error("Web-Only");super(),this.canvas=e,this.automatic=!0,this.#n=n??e.width,this.#r=i??e.height,this.#i=a??e.width,this.#s=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.#i/this.#n,n=this.#s/this.#r;this.ctx.translate(this.#i/2,this.#s/2),this.ctx.scale(e,n),this.ctx.translate(-this.#n/2,-this.#r/2)}#n=0;#r=0;#i=0;#s=0;get viewportWidth(){return this.#n}set viewportWidth(e){this.#n=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#n}get height(){return this.#r}get centerX(){return this.#n/2}get centerY(){return this.#r/2}get left(){return 0}get top(){return 0}get right(){return this.#n}get bottom(){return this.#r}get viewportHeight(){return this.#r}set viewportHeight(e){this.#r=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#i}set cameraWidth(e){this.#i=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#s}set cameraHeight(e){this.#s=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#i,this.canvas.height=this.#s}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!T)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#i,this.#s),this.emit("draw",this.ctx)}start(){if(!this.running){if(!T||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!T||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},ue=class extends F{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,!(T&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new ce(e,this)}createTween(e,n=()=>{}){let i=new he(e),a=(o=0)=>{if(i.finished){this.off("tick",a);return}i.update(o)};return i.on("finish",()=>{this.off("tick",a)}),i.on("delta",o=>{n(o)}),this.on("tick",a),i}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=T&&!isFinite(this.tickInterval)?ze(()=>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)}getLoopMod(e,n=0){return(this.now()+n*e)%e/e}},Pe;(t=>{function r(s){return s===!0?1:0}t.booleanExport=r;function e(s){return s===0?!1:s===1}t.booleanImport=e;function n(s){return`${s.x}|${s.y}`}t.vec2Export=n;function i(s){let[u,d]=s.split("|"),y=parseFloat(u),g=parseFloat(d);if(isNaN(y)||isNaN(g))throw new Error(`Invalid Vector2 string: ${s}`);return new A(y,g)}t.vec2Import=i,t.booleanMap={mapExport:r,mapImport:e};function o(s){return u=>Number(u.toFixed(s))}t.createRounder=o;function h(s=10){return{mapExport(u){return Math.round(u/s)},mapImport(u){return u*s}}}t.createLowPrecision=h;function f(s){return Math.round(s)}t.lightWeightRounder=f;function l(s=100){return{mapExport(u){return Math.round(u*s)},mapImport(u){return u/s}}}t.createPercent=l;function c(s){let u=new Map(Object.entries(s));return{mapExport:d=>u.get(d)??null,mapImport:d=>Array.from(u.entries()).find(([y,g])=>g===d)?.[0]??null}}t.createLookup=c;function p(s){let u=s*(180/Math.PI);return Math.round((u%360+360)%360)}t.radToDeg=p;function b(s){return s*(Math.PI/180)}t.degToRad=b,t.angleRadToDeg={mapExport:p,mapImport:b};function v(s=10){let u=h(s);return{mapExport(d){return u.mapExport(p(d))},mapImport(d){return u.mapImport(b(d))}}}t.createLowPrecisionRadToDeg=v})(Pe||={});var U=class r extends F{name="";scaleRotate=0;scale=1;constructor(e,n=0,i=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new A(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(!(G||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([a,{mapExport:o}])=>{let h=Reflect.get(this,a);return o?o(h):h});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(a=>!this.nonSerializableProperties.includes(a)&&!e.includes(a.toString())),i=Object.fromEntries(n.map(a=>{let o=Reflect.get(this,a);if(G&&typeof o=="number"){let h=o.toString().split("."),l=(h[1]?h[1].length:0)>2?Number(o.toFixed(2)):o;return[a,l]}return[a,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 a=0;a<n.length;a++){let o=e[a];if(!o)break;let[h,{mapImport:f}]=o,l=n[a];if(f&&(l=f(l)),typeof h!="string")break;try{Reflect.set(i,h,l)}catch(c){console.error(c)}}return i}},Q=class extends F{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(!G&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((i,a)=>i.z-a.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof U))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 U))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},J=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,n,i=16){this.ticker=new ue(i),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",a=>{for(let o of this.scenes.values())o.paused||o.handleUpdate(a)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},P={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=P.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return P.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[P.randomInt(0,r.length-1)]},createBezier(r,e,n,i){function a(f,l,c,p,b){let x=1-f;return x*x*x*l+3*x*x*f*c+3*x*f*f*p+f*f*f*b}function o(f,l,c,p,b){let x=1-f;return 3*x*x*(c-l)+6*x*f*(p-c)+3*f*f*(b-p)}function h(f){let l=f;for(let c=0;c<6;c++){let p=a(l,0,r,n,1),b=o(l,0,r,n,1);if(b===0)break;l-=(p-f)/b}return P.clamp(l,0,1)}return function(l){l=P.clamp(l,0,1);let c=h(l);return a(c,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 P.normalizeRad(-r)},degToRadFlipY(r){return P.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=P.normalizeRad(r),e=P.normalizeRad(e);let n=P.normalizeRad(e-r),i=P.normalizeRad(r-e);return n<=i?1:-1}},he=class extends F{constructor({delta:e,ms:n,easing:i}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=i??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=P.clamp(this.elapsed/this.duration,0,1),i=this.easing(n),a=this.delta*i,o=a-this.lastValue;this.lastValue=a,this.emit("delta",o),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},Z=class extends U{constructor(e,n=0,i=0,a=50,o=50){super(e,n,i),this.width=a,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)}},ce=class extends F{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)}},A=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,a,o,h=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(a))),b:Math.max(0,Math.min(255,Math.floor(o))),a:Math.max(0,Math.min(1,Math.floor(h*255)/255))}}return Se(r)}function et(r){return`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a})`}function Se(r){if(r=r.trim().toLowerCase(),r[0]==="#"){let n,i,a;if(r.length===7)n=parseInt(r.slice(1,3),16),i=parseInt(r.slice(3,5),16),a=parseInt(r.slice(5,7),16);else if(r.length===4)n=parseInt(r[1]+r[1],16),i=parseInt(r[2]+r[2],16),a=parseInt(r[3]+r[3],16);else throw new Error("Invalid hex color");return{r:n,g:i,b:a,a:1}}let e=r.match(/^rgba?\s*\(\s*(\d+)[, ]\s*(\d+)[, ]\s*(\d+)(?:[, ]\s*([\d.]+))?\s*\)$/);if(e)return{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3]),a:e[4]!==void 0?parseFloat(e[4]):1};throw new Error("Unsupported fillStyle format")}function tt(r,{r:e,g:n,b:i,a}={}){let[o,h,f,l,c]=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??h}, ${n??f}, ${i??l}, ${a??(c||1)})`}function nt(r,e,n){return n+(r-n)*e}function Ie(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var Ce=Ie(),G=Ce==="node",T=Ce==="web",O=class r{static unlock(){T&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=T?new AudioContext:null;static masterGain=T?this.audioCtx.createGain():null;static musicGain=T?this.audioCtx.createGain():null;static sfxGain=T?this.audioCtx.createGain():null;static{T&&(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,a;if(typeof caches<"u"&&(a=await caches.open(n),i=await a.match(e)),!i){if(i=await fetch(e),!i.ok)throw new Error(`Failed to fetch ${e}`);a&&await a.put(e,i.clone())}let o=await i.arrayBuffer(),h=await this.audioCtx.decodeAudioData(o);return this.audioBufferCache.set(e,h),h}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,a=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return;let h=new H(o);h.buffer=o;let f=1-.12,l=1+.12;h.playbackRate=i??f+Math.random()*(l-f);let c=this.audioCtx.createGain();c.gain.value=n,h.tempGain=c,h.connect(c),c.connect(this.sfxGain),h.onended=()=>{h.disconnect(),c.disconnect()},h.start(),a&&this.sfsx.set(e,{source:h,gain:c})}catch(o){console.error(o)}}static async playLoop(e,n=1,{loopStart:i=0,loopEnd:a=null,exclusive:o=!0,skipMS:h=0}={}){if(o)for(let b of this.loops.keys())this.stopLoop(b);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let l=new H(f);l.buffer=f,l.loop=!0,typeof i=="number"&&(l.loopStart=i),typeof a=="number"&&(l.loopEnd=a);let c=this.audioCtx.createGain();c.gain.value=n,l.tempGain=c,l.playbackRate=1,l.onended=()=>{l.disconnect(),c.disconnect()},l.connect(c),c.connect(this.musicGain),l.start(0,h/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:l,gain:c}),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:a=!1,loopStart:o=0,loopEnd:h=null,isMusic:f=!1,gain:l=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return null;let p=new H(c);p.loop=a,p.loopStart=o,p.loopEnd=typeof h=="number"?h:c.duration,p.playbackRate=i;let b=this.audioCtx.createGain();return b.gain.value=n,p.connect(b),p.tempGain=b,b.connect(l||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),b.disconnect()},p}catch(c){return console.error("Failed to create LiaAudioSrc:",c),null}}},Fe=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function rt(r){return Fe.includes(r)}var H=class{numberOfInputs;numberOfOutputs;constructor(e,n=O.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=T?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},Ae={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},_=class r{constructor(e={}){this.ctx=O.audioCtx,this.cfg=structuredClone(Ae),Object.assign(this.cfg,e)}ctx;cfg;play(e=O.sfxGain){let n=this.ctx,i=n.currentTime,a=this.cfg,o=n.createGain();o.gain.setValueAtTime(1e-4,i);let h=a.ampEnv;o.gain.exponentialRampToValueAtTime(h.volume,i+h.attack),o.gain.exponentialRampToValueAtTime(Math.max(1e-4,h.sustain*h.volume),i+h.attack+h.decay),o.gain.exponentialRampToValueAtTime(1e-4,i+a.duration+h.release);let f=o,l;a.filter.enabled&&(l=n.createBiquadFilter(),l.type=a.filter.type,l.frequency.value=a.filter.freq,l.Q.value=a.filter.Q,l.connect(o),f=l);let c;if(a.osc.enabled){if(c=n.createOscillator(),c.type=a.osc.type,c.frequency.value=a.osc.freq,c.detune.value=a.osc.detune,a.pitchEnv.amount!==0){let s=Math.pow(2,a.pitchEnv.amount/12);c.frequency.exponentialRampToValueAtTime(a.osc.freq*s,i+a.pitchEnv.decay)}c.connect(f),c.start(i),c.stop(i+a.duration+h.release)}let p;if(a.noise.enabled){let s=n.sampleRate*a.duration,u=n.createBuffer(1,s,n.sampleRate),d=u.getChannelData(0);for(let y=0;y<s;y++)d[y]=(Math.random()*2-1)*a.noise.level;p=n.createBufferSource(),p.buffer=u,p.connect(f),p.start(i),p.stop(i+a.duration+h.release)}let b,x;a.lfo.enabled&&c&&(b=n.createOscillator(),b.frequency.value=a.lfo.rate,x=n.createGain(),x.gain.value=a.lfo.depth,b.connect(x),a.lfo.target==="freq"?x.connect(c.frequency):a.lfo.target==="gain"?x.connect(o.gain):a.lfo.target==="filter"&&l&&x.connect(l.frequency),b.start(i),b.stop(i+a.duration)),o.connect(e);let v=[c,p,b,x,l,o],t=i+a.duration+h.release;setTimeout(()=>{v.forEach(s=>s?.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,a){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:i,release:a}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,n,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))}},Me=new _({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),Le=new _({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),_e=new _({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}),Ve=new _({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}),De=new _({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}),it=new Map([["ui_click",Me],["ui_hover",Le],["jump",_e],["laser",Ve],["hit",De]]);function st(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(r)),i=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+i).slice(0,r)}function N(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),i=Array.from(n).map(a=>a.toString(36).padStart(2,"0")).join("");return(e+i).slice(0,r)}var we=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${Ge()}_${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 Ge(){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 ze(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function $e(r,e,n,i,a){let o=Math.cos(a),h=Math.sin(a),f=[];if(o!==0){let l=(0-r)/o,c=e+l*h;l>0&&c>=0&&c<=i&&f.push({side:"left",t:l})}if(o!==0){let l=(n-r)/o,c=e+l*h;l>0&&c>=0&&c<=i&&f.push({side:"right",t:l})}if(h!==0){let l=(0-e)/h,c=r+l*o;l>0&&c>=0&&c<=n&&f.push({side:"top",t:l})}if(h!==0){let l=(i-e)/h,c=r+l*o;l>0&&c>=0&&c<=n&&f.push({side:"bottom",t:l})}return f.length===0?null:(f.sort((l,c)=>l.t-c.t),f[0])}function He(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 at(r,e,n,i,a){let o=$e(r,e,n,i,a);return o?{...o,avoidAngle:He(a,o.side)}:null}function Ue(){return G?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var ot=Ue();var W={};ve(W,{JSX:()=>qe,KMatrix2D:()=>Ke,KaylaContext:()=>de,KaylaElement:()=>ee,KaylaFragment:()=>Rt,KaylaInternals:()=>z,KaylaRect:()=>V,Layer:()=>St,Rect:()=>Ft,Text:()=>Be,createContext:()=>ct,createElement:()=>Oe,createGame:()=>lt,createReassignableObject:()=>Tt,createRenderer:()=>ht,createScene:()=>ut,createUseHook:()=>Pt,safeValueRepresentation:()=>te,self:()=>Re,setLogLevel:()=>kt,tinyUID:()=>It,useClick:()=>yt,useContext:()=>Et,useCurrentGame:()=>vt,useCurrentRenderer:()=>wt,useCurrentScene:()=>Xe,useCurrentTicker:()=>Ct,useDisposableRef:()=>Kt,useEffect:()=>ne,useEntity:()=>xt,useExports:()=>pe,useFiber:()=>ke,useFiberControl:()=>Te,useGlobalClick:()=>Ne,useGlobalPointer:()=>mt,useInitialization:()=>fe,useNextStack:()=>me,usePaint:()=>re,usePointer:()=>gt,useRect:()=>B,useRef:()=>Ee,useSelf:()=>q,useShouldRefresh:()=>ft,useState:()=>dt,useTick:()=>bt,useViewportEffect:()=>pt});function lt({width:r,height:e,updateHz:n="frames"}){return new z.KaylaGame(r,e,n==="frames"?1/0:n)}function ut(r){let e=new Q(r);return new z.KaylaScene(e)}function ht(r){return new z.KaylaRenderer(r)}function Oe(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};n.key??=r.name+"_"+N();let i=Array.isArray(e.children)?[...e.children]:e.children?[e.children]:[];for(let o=0;o<i.length;o++){let h=i[o];if(typeof h!="object"||!(h instanceof ee))if(typeof h=="string")i[o]=Oe(Be,{color:"white",label:h,parentRect:null,x:0,y:0,size:20,align:"center"});else throw new Error("Invalid JSX Child Parameter.")}n.children=i;let a=new ee;return a.type=r,a.props=n,a}var ee=class{type;props},V;(i=>{function r(a,o){return!(a.right<o.left||a.left>o.right||a.bottom<o.top||a.top>o.bottom)}i.rawCollision=r;function e(a,o,h){let f=o*Math.PI/180,l=Math.cos(f),c=Math.sin(f),p=1/0;return l>0&&(p=Math.min(p,(h.right-a.x)/l)),l<0&&(p=Math.min(p,(h.left-a.x)/l)),c>0&&(p=Math.min(p,(h.bottom-a.y)/c)),c<0&&(p=Math.min(p,(h.top-a.y)/c)),A.from(o).scale(p)}i.getCurrToBound=e;function n(a){let{left:o,right:h,top:f,bottom:l,width:c,height:p,x:b=0,y:x=0}=a;if(c===null||p===null)throw new Error("width and height are required");let v,t;if(o!=null&&h!=null){if(Math.abs(h-o-c)>1e-6)throw new Error("left, right, and width mismatch");v=o}else b!=null?v=b-c/2:o!=null?v=o:h!=null?v=h-c:v=0;if(f!=null&&l!=null){if(Math.abs(l-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else x!=null?t=x-p/2:f!=null?t=f:l!=null?t=l-p:t=0;return{left:v,right:v+c,top:t,bottom:t+p,width:c,height:p,x:v+c/2,y:t+p/2}}i.createRawRect=n})(V||={});var z;(x=>{class r extends J{#e;#t;constructor(t,s,u){super(t,s,u),this.#e=new Set,this.#t=!1}delay(t){return this.ticker.createTimeout(t)}get started(){return this.#t}start(){if(!this.#t){for(let t of this.#e)t.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let t of this.#e)t.stop();this.#t=!1,super.stop()}}addRenderer(t){this.#e.has(t)||(this.#e.add(t),this.#t&&t.start(),t.game=this)}get mainRenderer(){return[...this.#e].at(0)}getRenderers(){return[...this.#e]}deleteRenderer(t){this.#e.has(t)&&(this.#e.delete(t),this.#t&&t.stop(),delete t.game)}}x.KaylaGame=r;class e extends Y{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",s=>{if(this.game)for(let u of this.game.scenes.values())u.handleDraw(s)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new F,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=s=>this.onPointerAll(s,"down"),this.onPointerUp=s=>this.onPointerAll(s,"up"),this.onPointerCancel=s=>this.onPointerAll(s,"cancel"),this.onPointerMove=s=>this.onPointerAll(s,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,s){this.pointerPosUpdater(t);let u=e.getClickType(t);if(u!=="invalid"||s==="move"||s==="cancel"){t.preventDefault();let d=this.getMousePos();this.pointerEvents.emit("action",d,u,s)}}static getClickType(t){switch(t.button){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"invalid"}}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.pointerPosUpdater),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,s){let u=this.canvas.getBoundingClientRect(),d=(t-u.left)/u.width,y=(s-u.top)/u.height,g=d*this.viewportWidth*this.cameraWidth/u.width,w=y*this.viewportHeight*this.cameraHeight/u.height;return new A(g,w)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let s=u=>{t(u,new i)};return this.on("draw",s),()=>{this.off("draw",s)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}x.KaylaRenderer=e;class n{current;saves;constructor(){this.saves=[]}useTick(t){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");this.current.onTick[this.current.useStepCallIndex]=t,this.current.useStepCallIndex++}usePaint(t){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return Ee(Re)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let s=Ee(null);return(s.current===null||s.current===void 0)&&(s.current=t()),s.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let s=this.current;s.onInits[this.current.useInitCallIndex]=t,s.useInitCallIndex++}useRect(t="self"){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");if(t==="disposableSelf")return new x.KaylaInternalRect(this.current);let s=null;if(t==="self"&&(s=this.current),t==="parent"&&(s=this.current.detectedParent),!s)throw new Error("Missing valid target fiber.");return q(()=>new x.KaylaInternalRect(s))}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return q(()=>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 q(()=>({refresh:()=>t.refresh(),toString(){return t.toString()},get childrenCount(){return t.lastChildren.length},setMaxChildren:s=>{t.setMaxChildren(s)},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:s=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let d=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:s});return this.current.state[this.current.useStateCallIndex]=d,this.current.useStateCallIndex++,d}useShouldRefresh(t){let s=this.current;if(!s)throw new Error("useShouldRefresh must be called inside a component");s.watchedDeps&&console.warn("useShouldRefresh called multiple times \u2014 using the last call"),s.watchedDeps=t}useRef(t){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let u=this.current.refs[this.current.useRefCallIndex]??h(t??null);return this.current.refs[this.current.useRefCallIndex]=u,this.current.useRefCallIndex++,u}useEffect(t){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,s){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=s}useGlobalPointer(t,s){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");s??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:s},this.current.useGlobalClickCallIndex++}usePointer(t,s){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");s??={};let u=this.current;Ne((d,y,g)=>{let w=u.entity;if(!w)return;let C=w.getRawRect(),S=V.createRawRect({x:d.x,y:d.y,width:3,height:3});V.rawCollision(C,S)&&t(d,y,g)},s)}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,s,u,...d)=>{let y=t?.fc?.name||"anonymous",g=t?.key?` key=${t.key}`:"";this.logger[s](`${u} <${y}${g}>`,...d)}}}x.GlobalKayla=n;class i{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}x.KaylaEvent=i;class a{#e;#t;#n;alwaysRecall;constructor(t,s,{alwaysRecall:u=!1}={}){this.#t=t,this.#e=s??void 0,this.#n=Date.now(),this.alwaysRecall=u}get(){return this.#e}get 0(){return this.get()}1(t){this.set(t,{recall:!0})}legacy(){return[this[0],this[1].bind(this)]}add(t,{recall:s}={}){this.set(this.get()+t,{recall:s})}multiply(t,{recall:s}={}){this.set(this.get()*t,{recall:s})}set(t,{recall:s=!1}={}){let u=this.#e;if(t===u)return;this.#e=t;let y=Date.now()-this.#n;s&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(s||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}x.KaylaInternalState=a;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)}}x.KaylaInternalRef=o;function h(v){return new o(v)}x.createReassignableRef=h;class f{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;lastLayer;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,s,u){if(!u)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=s,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=u.type,this.callProps=u.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalPointer=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+N(),this.onViewportEffect=[],this.lastLayer=null}getCorrectMousePos(t){return t??=this.getAttachedRenderer().getMousePos(),this.lastLayer?.transform?this.lastLayer.transform.inverseV(t):t}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,s,u){t=this.getCorrectMousePos(t);try{for(let{handler:d,config:y}of this.onGlobalPointer)y.type??="any",y.action??="down",!(y.action!=="any"&&y.action!==u||y.type!=="any"&&y.type!==s)&&d(t,s,u)}catch(d){this.global.logger.error(d)}}resizeHook({width:t,height:s}){try{for(let u of this.onViewportEffect)u(this.getAttachedRenderer(),t,s)}catch(u){this.global.logger.error(u)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){let t=this.callProps.children;return Array.isArray(t)?t:[t]}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalPointer;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let s=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${s} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let u=this.lastChildren.slice(0,this.maxSafeChildren),d=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=u;for(let y of d)y.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],s=this.detectedParent;for(;s;)t.push(s),s=s?.detectedParent;return t}getAllChildrenNestedFlattened(){let t=[],s=(u=[])=>{for(let d of u)t.push(d),d.lastChildren?.length&&s(d.lastChildren)};return s(this.lastChildren),t}getContextChain(){return this.getFiberChain().map(t=>t.contextInfo).filter(Boolean)}findContextValueFromInst(t){return this.getContextChain().find(s=>s.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 s=this.watchedDeps[t],u=this.lastDepStamps[t]??0;if(s.lastChanged>u)return!0}return!1}captureDepStamps(){this.watchedDeps&&(this.lastDepStamps=this.watchedDeps.map(t=>t.lastChanged))}refresh(){if(!this.shouldFullRefresh())return;let t=this.fc?.name||"anonymous";if(!this.shouldFullRefresh()){this.global.logger.debug(`Refresh skipped <${t} key=${this.key}>`);return}this.global.logger.debug(`Refresh executed <${t} key=${this.key}> reason=${this.isFirstUse?"first":"deps-changed"}`),this.lastChildren.length>this.maxSafeChildren&&this.global.logger.warn(`High child count <${t} key=${this.key}> children=${this.lastChildren.length}`);let s;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let u=[];try{let d=this.fc(this.callProps)??[];if(d&&!Array.isArray(d)&&(d=[d]),!Array.isArray(d))throw new Error("Non array or non undefined children received.");for(let y of d);u=d}catch(d){s=d}if(this.global.restore(),this.updateChildren(u,!0),s)throw s}updateChildren(t,s){try{let u=[...t,...this.dynamicChildren],d=[],y=[];for(let g of u){let w=g.props?.key,C;w!=null&&(C=this.lastChildren.find(S=>S.key===w)),C||(C=new f(this.global,this.scene,g)),C.callProps=g.props,C.key=w??`${g.type?.name??""}_${N()}`,C.detectedParent=this,y.push(C),d.push(C)}for(let g of this.lastChildren)d.includes(g)||g.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let g of this.lastChildren)try{g.refresh()}catch(w){console.error(w)}}catch(u){console.error(u)}}toString(){return this.getStringRepresentation(0," ")}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=!0),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let s=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(d=>({stamp:d.lastChanged,stateRef:d}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new l(this,this.key);for(let d of this.refs)d.current===Re&&(d.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),s){this.onUnInits=[];for(let d of this.onInits){this.bindEvents();try{let y=d();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let d of this.onUnEffect??[])d()}catch(d){console.error(d)}let u=this.onEffect.map(d=>d()).filter(d=>d!==void 0);this.onUnEffect=u}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}getStringRepresentation(t=0,s=" "){let u=s.repeat(t),d=this,y="",g=Object.entries(this.callProps);for(let S=0;S<g.length;S++){let[R,K]=g[S];if(["children"].includes(R))continue;y+=` ${R}=${typeof K=="string"?`${te(K)}`:`{${te(K,0)}}`}`}let w=Array.from(d.lastChildren).map(S=>S.getStringRepresentation(t+1,s)).join(""),C=d.fc.displayName??d.fc.name.replaceAll(" ","-");return w&&w.length>0?`${u}<${C}${y}>
2
- ${w}${u}</${C}>
3
- `:`${u}<${C}${y}/>
4
- `}}x.KaylaFiber=f;class l extends Z{#e;flags;getRawRect(){return V.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,s){super(s,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,s){return this.flags.set(t,s)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){me(()=>{let s=new i;if(this.#e&&this.#e.onTick)for(let u of this.#e.onTick)u(t,s);s.isPrevented()})}draw(t){let s=new i;if(this.#e&&this.#e.onPaint)for(let u of this.#e.onPaint)u(t,s);s.isPrevented()||super.draw(t)}getRect(){return new c(this.getFiber())}}x.KaylaRectEntity=l;class c{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return V.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(),s=this.#e.getCorrectMousePos(),u=V.createRawRect({x:s.x,y:s.y,width:3,height:3});return V.rawCollision(t,u)}get pos(){return this.#t(),this.entity.pos}get x(){return this.#t(),this.pos.x}set x(t){this.#t(),this.pos.x=t}get y(){return this.#t(),this.pos.y}set y(t){this.#t(),this.pos.y=t}get width(){return this.#t(),this.entity.width}set width(t){this.#t(),this.entity.width=t}get height(){return this.#t(),this.entity.height}set height(t){this.#t(),this.entity.height=t}get z(){return this.#t(),this.entity.z}set z(t){this.#t(),this.entity.z=t}get left(){return this.#t(),this.entity.left}set left(t){this.#t(),this.entity.left=t}get right(){return this.#t(),this.entity.right}set right(t){this.#t(),this.entity.right=t}get top(){return this.#t(),this.entity.top}set top(t){this.#t(),this.entity.top=t}get bottom(){return this.#t(),this.entity.bottom}set bottom(t){this.#t(),this.entity.bottom=t}get toLocal(){return this.entity.toLocal.bind(this.entity)}get toWorld(){return this.entity.toWorld.bind(this.entity)}}x.KaylaInternalRect=c;class p{#e;#t;constructor(t){this.#r=t,this.#n=null,this.#e=new Map,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this),t.handleDraw=this.drawHandler,this.#t=null}getLayers(){return this.#e}#n;#r;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#r}getGame(){return this.#n}getOrCreateLayer(t,s=0){return this.#e.has(t)||this.#e.set(t,{name:t,z:s,visible:!0,rootFiber:null}),this.#e.get(t)}getSortedLayers(){return Array.from(this.#e.values()).filter(t=>t.visible).sort((t,s)=>t.z-s.z)}setLayerVisible(t,s){let u=this.#e.get(t);u&&(u.visible=s)}handleDraw(t){if(G)return;let s=this.getScene();if(s.paused)return;s.emit("draw",t);let u=this.getSortedLayers(),d=[];for(let g of u){if(!g.visible)continue;let w=g.rootFiber;if(!w)continue;let C=w.getAllChildrenNestedFlattened().flat().map(R=>R.entity).filter(Boolean);if(d.push(...C),t.save(),g.transform){let R=g.transform;t.setTransform(R.a,R.b,R.c,R.d,R.e,R.f)}g.blendMode&&(t.globalCompositeOperation=g.blendMode??"source-over");let S=Array.from(C).sort((R,K)=>R.z-K.z);for(let R of S)R.getFiber().lastLayer=g,R.handleDraw(t);t.restore()}let y=[...s.entities.values()].filter(g=>!d.includes(g));for(let g of y.sort((w,C)=>w.z-C.z))g.getFiber().lastLayer=null,g.handleDraw(t)}drawHandler(t){return this.handleDraw(t)}attachTo(t){t.addScene(this.#r),this.#n=t}async spawn(t){this.#t&&(this.#t.unuse(),this.#t=null);let s=this.createFiber(t);this.#t=s,await this.#n.delay(0),s.refresh()}getRoot(){return this.#t??null}createFiber(t){return new f(x.singleGlobalInstance,this,t)}detach(){this.#n&&this.#n.removeScene(this.#r)}tickHandler(){}}x.KaylaScene=p,x.singleGlobalInstance=new x.GlobalKayla})(z||={});var de=class{#e;constructor(e){this.Provider=this.#t.bind(this),this.#e=e,this.Provider.displayName="[[ KaylaContext ]].Provider"}get defaultValue(){return this.#e}#t({value:e=this.defaultValue,children:n}){let i=ke();return ne(()=>{i.contextInfo={instance:this,value:e}}),pe(this.Provider,()=>({value:e})),n}Provider;Consumer};function ct(r){return new de(r)}var m=z.singleGlobalInstance,dt=m.useState.bind(m),Ee=m.useRef.bind(m),ft=m.useShouldRefresh.bind(m),ne=m.useEffect.bind(m),pt=m.useViewportEffect.bind(m),Ne=m.useGlobalPointer.bind(m),mt=m.useGlobalPointer.bind(m),yt=m.usePointer.bind(m),gt=m.usePointer.bind(m),fe=m.useInitialization.bind(m),B=m.useRect.bind(m),bt=m.useTick.bind(m),re=m.usePaint.bind(m),pe=m.useExports.bind(m),q=m.useSelf.bind(m),Te=m.useFiberControl.bind(m),ke=m.useFiber.bind(m),xt=m.useEntity.bind(m),vt=m.useCurrentGame.bind(m),wt=m.useCurrentRenderer.bind(m),Xe=m.useCurrentScene.bind(m),Ct=m.useCurrentTicker.bind(m),Et=m.useContext.bind(m),Re=Symbol("self_ref");var me=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},Rt=({children:r})=>Array.isArray(r)?[...r]:r;function Kt(r){return z.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,a,o){return a==="reassignSelf"?h=>{e.current=h}:Reflect.get(e.current,a,o)},set(i,a,o,h){return Reflect.set(e.current,a,o,h)},has(i,a){return Reflect.has(e.current,a)},ownKeys(i){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(i,a){return Reflect.getOwnPropertyDescriptor(e.current,a)},deleteProperty(i,a){return Reflect.deleteProperty(e.current,a)}})}function kt(r){m.logLevel=r}function Pt(r){let e=r.name||"anonymous-custom-hook";function n(...i){let a=m.current;if(!a)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let o=i??[];return a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,...o)}return n.name=r.name,n}var St=({name:r,z:e=0,blend:n,visible:i=!0,children:a,transform:o})=>{let h=Xe(),f=ke();return fe(()=>{let l=h.getOrCreateLayer(r,e);return l.blendMode=n,l.visible=i,l.rootFiber=f,l.transform=o??null,()=>{h.getLayers().delete(r)}}),a},Ke=class extends DOMMatrix{#e;constructor(){super(),this.#e=new DOMPoint}transformV(e){this.#e.x=e.x,this.#e.y=e.y;let n=this.#e.matrixTransform(this);return new A(n.x,n.y)}inverseV(e){let n=this.inverse();this.#e.x=e.x,this.#e.y=e.y;let i=this.#e.matrixTransform(n);return new A(i.x,i.y)}},te=(r,e=0)=>{try{if(Array.isArray(r))return`[ ${r.map(n=>te(n,e)).join(", ")} ]`;if(typeof r=="object"&&r!==null){let n=r.constructor?.name;return n!=="Object"&&n?`[[ ${n} ]]`:`{ ${Object.entries(r).map(([i,a])=>`${i}: ${te(a,e)}`).join(", ")} }`}return JSON.stringify(r,null,e)}catch{return"[[ Non-serializable ]]"}},qe;(e=>e.id="kayla")(qe||={});var It=N,Ft=({color:r,cx:e,cy:n,height:i,width:a,children:o})=>{let h=B();return ne(()=>{h.color=r??"red",h.x=e??0,h.y=n??0,h.width=a??1,h.height=i??1}),o},Be=({label:r,size:e,align:n="center",parentRect:i,color:a,x:o,y:h,ox:f=0,oy:l=0})=>{i??=B("parent"),re(c=>{c.fillStyle=a,c.font=`${e}px sans-serif`,c.textBaseline="middle",c.textAlign=n,c.fillText(r.toString(),(i?.x??o)+f,(i?.y??h)+l)})};Reflect.set(globalThis,"Kayla",W);var At;(n=>(n.Flex=({align:i="stretch",children:a,direction:o="row",gap:h=0,justify:f="start",wrap:l="nowrap",getHeight:c,getWidth:p,getCenterX:b,getCenterY:x,color:v})=>{let t=Te(),s=B(),u=q(()=>({recalc(){let d=Number(h)||0,y=b(),g=x(),w=p(),C=c();s.x=y,s.y=g,s.width=w,s.height=C;let R=t.getChildrenEntities().filter(Boolean).map(E=>E.getRect()).filter(E=>E.getFlag("flex-ignored")!==!0),K=o==="row",M=K?s.width:s.height,_t=K?s.height:s.width,ye=0,j=0,ge=[],ie=[];R.forEach(E=>{let se=K?E.width:E.height;ye+se>M&&l==="wrap"?(ge.push({height:j,items:ie}),ie=[E],ye=se,j=K?E.height:E.width):(ie.push(E),ye+=se+d,j=Math.max(j,K?E.height:E.width))}),ge.push({height:j,items:ie});let be=0;ge.forEach((E,se)=>{let L=E.items,D=L.reduce((k,ae)=>k+(K?ae.width:ae.height),0)+d*(L.length-1),I=0;f==="center"&&(I=(M-D)/2),f==="end"&&(I=M-D),f==="space-between"&&(I=0),f==="space-around"&&(I=(M-D)/(L.length*2)),f==="space-evenly"&&(I=(M-D)/(L.length+1)),L.forEach((k,ae)=>{k.z=s.z+1;let $=K?k.width:k.height,oe=K?k.height:k.width,le=0;i==="center"&&(le=(E.height-oe)/2),i==="end"&&(le=E.height-oe),i==="stretch"&&(K?k.height=E.height:k.width=E.height),K?(k.x=I+$/2,k.y=be+le+oe/2):(k.x=be+le+oe/2,k.y=I+$/2),f==="space-between"&&ae<L.length-1?I+=$+d+(M-D)/(L.length-1):f==="space-around"?I+=$+d+(M-D)/L.length:f==="space-evenly"?I+=$+d+(M-D)/(L.length+1):I+=$+d}),be+=E.height+d})}}));return re((d,y)=>{y.preventDefault(),d.fillStyle=v,d.fillRect(s.left,s.top,s.width,s.height)}),ne(()=>{me(()=>{u.recalc()})}),pe(n.Flex,()=>({controls:u})),a},n.GenericBox=({color:i,width:a=20,height:o=20,x:h=0,y:f=0})=>{let l=B();fe(()=>{l.width=a,l.height=o,l.x=h,l.y=f}),re((c,p)=>{p.preventDefault(),c.fillStyle=i,c.fillRect(l.left,l.top,l.width,l.height)})}))(At||={});var Mt={LEA:X,Kayla:W};0&&(module.exports={Kayla,LEA});
1
+ "use strict";var Se=Object.defineProperty;var At=Object.getOwnPropertyDescriptor;var Mt=Object.getOwnPropertyNames;var Lt=Object.prototype.hasOwnProperty;var Pe=(r,e)=>{for(var n in e)Se(r,n,{get:e[n],enumerable:!0})},_t=(r,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Mt(e))!Lt.call(r,s)&&s!==n&&Se(r,s,{get:()=>e[s],enumerable:!(i=At(e,s))||i.enumerable});return r};var Dt=r=>_t(Se({},"__esModule",{value:!0}),r);var Gt={};Pe(Gt,{DeltaTweenII:()=>oe,ENVIRONMENT:()=>ve,GEmitterMemory:()=>xe,JSX:()=>We,KMatrix2D:()=>Ee,Kayla:()=>ie,KaylaContext:()=>ue,KaylaElement:()=>ee,KaylaFragment:()=>Et,KaylaInternals:()=>z,KaylaRect:()=>V,LEA:()=>Z,Layer:()=>St,LeaEntityII:()=>U,LeaEventEmitter:()=>A,LeaGameII:()=>Y,LeaRendererII:()=>W,LeaSceneII:()=>j,LeaSerializers:()=>Ie,LeaTickerII:()=>ae,LeaTimeout:()=>le,LeaUtilsII:()=>P,LiaAudio:()=>O,LiaAudioSrc:()=>$,LiaOscSFX:()=>D,LiaSFXMap:()=>nt,NOTE_NAMES:()=>Me,Rect:()=>Pt,RectLeaEntity:()=>Q,Substepper:()=>N,Text:()=>Ye,UI:()=>Ft,Vector2:()=>F,colToRGBA:()=>Je,createContext:()=>ut,createElement:()=>Xe,createGame:()=>at,createReassignableObject:()=>Rt,createRenderer:()=>lt,createScene:()=>ot,createUseHook:()=>Tt,default:()=>Vt,defaultSFXConfig:()=>Le,editRGBA:()=>Ze,generateUUID:()=>He,getAvoidAngle:()=>Oe,getEnvironment:()=>Ae,getNormalizedColor:()=>Qe,getRayHit:()=>Ue,isInitiallyMobile:()=>st,isMobile:()=>Ne,isNode:()=>L,isNote:()=>tt,isWeb:()=>S,parseFillStyle:()=>Fe,raycastAvoid:()=>it,safeValueRepresentation:()=>te,scaleCoord:()=>et,self:()=>Ce,setAnimInterval:()=>$e,setLogLevel:()=>kt,sfxHit:()=>ze,sfxJump:()=>Ve,sfxLaser:()=>Ge,sfxUIClick:()=>_e,sfxUIHover:()=>De,shortUID:()=>rt,tinyUID:()=>je,useClick:()=>ft,useContext:()=>wt,useCurrentGame:()=>gt,useCurrentRenderer:()=>xt,useCurrentScene:()=>Be,useCurrentTicker:()=>vt,useDisposableRef:()=>Kt,useEffect:()=>ne,useEntity:()=>bt,useExports:()=>ce,useFiber:()=>Re,useFiberControl:()=>Ke,useGlobalClick:()=>qe,useGlobalPointer:()=>pt,useInitialization:()=>he,useNextStack:()=>de,usePaint:()=>re,usePointer:()=>mt,useRect:()=>X,useRef:()=>we,useSelf:()=>G,useShouldRefresh:()=>ct,useState:()=>ht,useSubstep:()=>Ct,useTick:()=>yt,useUsing:()=>It,useViewportEffect:()=>dt});module.exports=Dt(Gt);var Z={};Pe(Z,{DeltaTweenII:()=>oe,ENVIRONMENT:()=>ve,GEmitterMemory:()=>xe,LeaEntityII:()=>U,LeaEventEmitter:()=>A,LeaGameII:()=>Y,LeaRendererII:()=>W,LeaSceneII:()=>j,LeaSerializers:()=>Ie,LeaTickerII:()=>ae,LeaTimeout:()=>le,LeaUtilsII:()=>P,LiaAudio:()=>O,LiaAudioSrc:()=>$,LiaOscSFX:()=>D,LiaSFXMap:()=>nt,NOTE_NAMES:()=>Me,RectLeaEntity:()=>Q,Substepper:()=>N,Vector2:()=>F,colToRGBA:()=>Je,defaultSFXConfig:()=>Le,editRGBA:()=>Ze,generateUUID:()=>He,getAvoidAngle:()=>Oe,getEnvironment:()=>Ae,getNormalizedColor:()=>Qe,getRayHit:()=>Ue,isInitiallyMobile:()=>st,isMobile:()=>Ne,isNode:()=>L,isNote:()=>tt,isWeb:()=>S,parseFillStyle:()=>Fe,raycastAvoid:()=>it,scaleCoord:()=>et,setAnimInterval:()=>$e,sfxHit:()=>ze,sfxJump:()=>Ve,sfxLaser:()=>Ge,sfxUIClick:()=>_e,sfxUIHover:()=>De,shortUID:()=>rt,tinyUID:()=>J});var A=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}},W=class extends A{#e;#t;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;get canvas(){return this.#e}get ctx(){return this.#t}set canvas(e){this.#e=e,this.#t=e.getContext("2d"),this.updateCanvasResolution()}constructor(e,{viewportWidth:n,viewportHeight:i,cameraWidth:s,cameraHeight:l}={}){if(!S)throw new Error("Web-Only");super(),this.canvas=e,this.automatic=!0,this.#n=n??e.width,this.#r=i??e.height,this.#i=s??e.width,this.#s=l??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#i/this.#n,n=this.#s/this.#r;this.ctx.translate(this.#i/2,this.#s/2),this.ctx.scale(e,n),this.ctx.translate(-this.#n/2,-this.#r/2)}#n=0;#r=0;#i=0;#s=0;get viewportWidth(){return this.#n}set viewportWidth(e){this.#n=e,this.retransform(),this.emitViewportUpdate()}get width(){return this.#n}get height(){return this.#r}get centerX(){return this.#n/2}get centerY(){return this.#r/2}get left(){return 0}get top(){return 0}get right(){return this.#n}get bottom(){return this.#r}get viewportHeight(){return this.#r}set viewportHeight(e){this.#r=e,this.retransform(),this.emitViewportUpdate()}get cameraWidth(){return this.#i}set cameraWidth(e){this.#i=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#s}set cameraHeight(e){this.#s=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#i,this.canvas.height=this.#s}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!S)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#i,this.#s),this.emit("draw",this.ctx)}start(){if(!this.running){if(!S||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!S||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},ae=class extends A{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,!(S&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new le(e,this)}createTween(e,n=()=>{}){let i=new oe(e),s=(l=0)=>{if(i.finished){this.off("tick",s);return}i.update(l)};return i.on("finish",()=>{this.off("tick",s)}),i.on("delta",l=>{n(l)}),this.on("tick",s),i}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=S&&!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)}getLoopMod(e,n=0){return(this.now()+n*e)%e/e}},Ie;(R=>{function r(f){return f===!0?1:0}R.booleanExport=r;function e(f){return f===0?!1:f===1}R.booleanImport=e;function n(f){return`${f.x}|${f.y}`}R.vec2Export=n;function i(f){let[t,a]=f.split("|"),o=parseFloat(t),d=parseFloat(a);if(isNaN(o)||isNaN(d))throw new Error(`Invalid Vector2 string: ${f}`);return new F(o,d)}R.vec2Import=i,R.booleanMap={mapExport:r,mapImport:e};function l(f){return t=>Number(t.toFixed(f))}R.createRounder=l;function c(f=10){return{mapExport(t){return Math.round(t/f)},mapImport(t){return t*f}}}R.createLowPrecision=c;function p(f){return Math.round(f)}R.lightWeightRounder=p;function u(f=100){return{mapExport(t){return Math.round(t*f)},mapImport(t){return t/f}}}R.createPercent=u;function h(f){let t=new Map(Object.entries(f));return{mapExport:a=>t.get(a)??null,mapImport:a=>Array.from(t.entries()).find(([o,d])=>d===a)?.[0]??null}}R.createLookup=h;function m(f){let t=f*(180/Math.PI);return Math.round((t%360+360)%360)}R.radToDeg=m;function x(f){return f*(Math.PI/180)}R.degToRad=x,R.angleRadToDeg={mapExport:m,mapImport:x};function T(f=10){let t=c(f);return{mapExport(a){return t.mapExport(m(a))},mapImport(a){return t.mapImport(x(a))}}}R.createLowPrecisionRadToDeg=T})(Ie||={});var U=class r extends A{name="";scaleRotate=0;scale=1;constructor(e,n=0,i=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new F(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(!(L||!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:l}])=>{let c=Reflect.get(this,s);return l?l(c):c});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 l=Reflect.get(this,s);if(L&&typeof l=="number"){let c=l.toString().split("."),u=(c[1]?c[1].length:0)>2?Number(l.toFixed(2)):l;return[s,u]}return[s,l]}));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 l=e[s];if(!l)break;let[c,{mapImport:p}]=l,u=n[s];if(p&&(u=p(u)),typeof c!="string")break;try{Reflect.set(i,c,u)}catch(h){console.error(h)}}return i}},j=class extends A{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(!L&&!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 U))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 U))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},Y=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 ae(i),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",s=>{for(let l of this.scenes.values())l.paused||l.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()}},P={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=P.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return P.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[P.randomInt(0,r.length-1)]},createBezier(r,e,n,i){function s(p,u,h,m,x){let w=1-p;return w*w*w*u+3*w*w*p*h+3*w*p*p*m+p*p*p*x}function l(p,u,h,m,x){let w=1-p;return 3*w*w*(h-u)+6*w*p*(m-h)+3*p*p*(x-m)}function c(p){let u=p;for(let h=0;h<6;h++){let m=s(u,0,r,n,1),x=l(u,0,r,n,1);if(x===0)break;u-=(m-p)/x}return P.clamp(u,0,1)}return function(u){u=P.clamp(u,0,1);let h=c(u);return s(h,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 P.normalizeRad(-r)},degToRadFlipY(r){return P.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=P.normalizeRad(r),e=P.normalizeRad(e);let n=P.normalizeRad(e-r),i=P.normalizeRad(r-e);return n<=i?1:-1}},oe=class extends A{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=P.clamp(this.elapsed/this.duration,0,1),i=this.easing(n),s=this.delta*i,l=s-this.lastValue;this.lastValue=s,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},Q=class extends U{constructor(e,n=0,i=0,s=50,l=50){super(e,n,i),this.width=s,this.height=l}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},le=class extends A{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)}},F=class r{constructor(e=0,n=0){this.x=e,this.y=n}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let n=Math.cos(e),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 Qe(r){let e=/^rgba?\(([^)]+)\)$/,n=r.match(e);if(n){let[i,s,l,c=1]=n[1].split(",").map(p=>parseFloat(p));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(l))),a:Math.max(0,Math.min(1,Math.floor(c*255)/255))}}return Fe(r)}function Je(r){return`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a})`}function Fe(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 Ze(r,{r:e,g:n,b:i,a:s}={}){let[l,c,p,u,h]=r.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??c}, ${n??p}, ${i??u}, ${s??(h||1)})`}function et(r,e,n){return n+(r-n)*e}function Ae(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var ve=Ae(),L=ve==="node",S=ve==="web",O=class r{static unlock(){S&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=S?new AudioContext:null;static masterGain=S?this.audioCtx.createGain():null;static musicGain=S?this.audioCtx.createGain():null;static sfxGain=S?this.audioCtx.createGain():null;static{S&&(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 l=await i.arrayBuffer(),c=await this.audioCtx.decodeAudioData(l);return this.audioBufferCache.set(e,c),c}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 l=this.getCached(e);if(!l)return;let c=new $(l);c.buffer=l;let p=1-.12,u=1+.12;c.playbackRate=i??p+Math.random()*(u-p);let h=this.audioCtx.createGain();h.gain.value=n,c.tempGain=h,c.connect(h),h.connect(this.sfxGain),c.onended=()=>{c.disconnect(),h.disconnect()},c.start(),s&&this.sfsx.set(e,{source:c,gain:h})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:i=0,loopEnd:s=null,exclusive:l=!0,skipMS:c=0}={}){if(l)for(let x of this.loops.keys())this.stopLoop(x);this.audioBufferCache.has(e)||await this.preLoad(e);let p=this.getCached(e);if(!p)return;let u=new $(p);u.buffer=p,u.loop=!0,typeof i=="number"&&(u.loopStart=i),typeof s=="number"&&(u.loopEnd=s);let h=this.audioCtx.createGain();h.gain.value=n,u.tempGain=h,u.playbackRate=1,u.onended=()=>{u.disconnect(),h.disconnect()},u.connect(h),h.connect(this.musicGain),u.start(0,c/1e3);let m=++this.loopIdCounter;return this.loops.set(m,{source:u,gain:h}),m}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:l=0,loopEnd:c=null,isMusic:p=!1,gain:u=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return null;let m=new $(h);m.loop=s,m.loopStart=l,m.loopEnd=typeof c=="number"?c:h.duration,m.playbackRate=i;let x=this.audioCtx.createGain();return x.gain.value=n,m.connect(x),m.tempGain=x,x.connect(u||(p?this.musicGain:this.sfxGain)),m.onended=()=>{m.disconnect(),x.disconnect()},m}catch(h){return console.error("Failed to create LiaAudioSrc:",h),null}}},Me=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function tt(r){return Me.includes(r)}var $=class{numberOfInputs;numberOfOutputs;constructor(e,n=O.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=S?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},Le={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},D=class r{constructor(e={}){if(L)return this;this.ctx=O.audioCtx,this.cfg=structuredClone(Le),Object.assign(this.cfg,e)}ctx;cfg;play(e=O.sfxGain){if(L)throw new Error("Cannot use Web APIs on node.");let n=this.ctx,i=n.currentTime,s=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,i);let c=s.ampEnv;l.gain.exponentialRampToValueAtTime(c.volume,i+c.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,c.sustain*c.volume),i+c.attack+c.decay),l.gain.exponentialRampToValueAtTime(1e-4,i+s.duration+c.release);let p=l,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(l),p=u);let h;if(s.osc.enabled){if(h=n.createOscillator(),h.type=s.osc.type,h.frequency.value=s.osc.freq,h.detune.value=s.osc.detune,s.pitchEnv.amount!==0){let f=Math.pow(2,s.pitchEnv.amount/12);h.frequency.exponentialRampToValueAtTime(s.osc.freq*f,i+s.pitchEnv.decay)}h.connect(p),h.start(i),h.stop(i+s.duration+c.release)}let m;if(s.noise.enabled){let f=n.sampleRate*s.duration,t=n.createBuffer(1,f,n.sampleRate),a=t.getChannelData(0);for(let o=0;o<f;o++)a[o]=(Math.random()*2-1)*s.noise.level;m=n.createBufferSource(),m.buffer=t,m.connect(p),m.start(i),m.stop(i+s.duration+c.release)}let x,w;s.lfo.enabled&&h&&(x=n.createOscillator(),x.frequency.value=s.lfo.rate,w=n.createGain(),w.gain.value=s.lfo.depth,x.connect(w),s.lfo.target==="freq"?w.connect(h.frequency):s.lfo.target==="gain"?w.connect(l.gain):s.lfo.target==="filter"&&u&&w.connect(u.frequency),x.start(i),x.stop(i+s.duration)),l.connect(e);let T=[h,m,x,w,u,l],R=i+s.duration+c.release;setTimeout(()=>{T.forEach(f=>f?.disconnect())},(R-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))}},_e=new D({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),De=new D({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),Ve=new D({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}),Ge=new D({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}),ze=new D({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}),nt=new Map([["ui_click",_e],["ui_hover",De],["jump",Ve],["laser",Ge],["hit",ze]]);function rt(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 J(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 xe=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${He()}_${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 He(){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 Ue(r,e,n,i,s){let l=Math.cos(s),c=Math.sin(s),p=[];if(l!==0){let u=(0-r)/l,h=e+u*c;u>0&&h>=0&&h<=i&&p.push({side:"left",t:u})}if(l!==0){let u=(n-r)/l,h=e+u*c;u>0&&h>=0&&h<=i&&p.push({side:"right",t:u})}if(c!==0){let u=(0-e)/c,h=r+u*l;u>0&&h>=0&&h<=n&&p.push({side:"top",t:u})}if(c!==0){let u=(i-e)/c,h=r+u*l;u>0&&h>=0&&h<=n&&p.push({side:"bottom",t:u})}return p.length===0?null:(p.sort((u,h)=>u.t-h.t),p[0])}function Oe(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 it(r,e,n,i,s){let l=Ue(r,e,n,i,s);return l?{...l,avoidAngle:Oe(s,l.side)}:null}function Ne(){return L?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var st=Ne(),N=class r{static defaultInterval=1e3/60;handler;interval;accumulated;constructor(e=r.defaultInterval,n){this.handler=n??null,this.interval=e,this.accumulated=0}update(e){if(!this.handler)throw new Error("Missing handler.");if(this.interval<=.001){this.handler(this,0);return}this.accumulated+=e*1e3;let n=0;for(;this.accumulated>=this.interval;)this.accumulated-=this.interval,this.handler(this,n),n++}};var ie={};Pe(ie,{JSX:()=>We,KMatrix2D:()=>Ee,KaylaContext:()=>ue,KaylaElement:()=>ee,KaylaFragment:()=>Et,KaylaInternals:()=>z,KaylaRect:()=>V,Layer:()=>St,Rect:()=>Pt,Text:()=>Ye,createContext:()=>ut,createElement:()=>Xe,createGame:()=>at,createReassignableObject:()=>Rt,createRenderer:()=>lt,createScene:()=>ot,createUseHook:()=>Tt,safeValueRepresentation:()=>te,self:()=>Ce,setLogLevel:()=>kt,tinyUID:()=>je,useClick:()=>ft,useContext:()=>wt,useCurrentGame:()=>gt,useCurrentRenderer:()=>xt,useCurrentScene:()=>Be,useCurrentTicker:()=>vt,useDisposableRef:()=>Kt,useEffect:()=>ne,useEntity:()=>bt,useExports:()=>ce,useFiber:()=>Re,useFiberControl:()=>Ke,useGlobalClick:()=>qe,useGlobalPointer:()=>pt,useInitialization:()=>he,useNextStack:()=>de,usePaint:()=>re,usePointer:()=>mt,useRect:()=>X,useRef:()=>we,useSelf:()=>G,useShouldRefresh:()=>ct,useState:()=>ht,useSubstep:()=>Ct,useTick:()=>yt,useUsing:()=>It,useViewportEffect:()=>dt});function at({width:r,height:e,updateHz:n="frames"}){return new z.KaylaGame(r,e,n==="frames"?1/0:n)}function ot(r){let e=new j(r);return new z.KaylaScene(e)}function lt(r,e){return new z.KaylaRenderer(r,e)}function Xe(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};n.key??=r.name+"_"+J();let i=Array.isArray(e.children)?[...e.children]:e.children?[e.children]:[];for(let l=0;l<i.length;l++){let c=i[l];if(typeof c!="object"||!(c instanceof ee))if(typeof c=="string")i[l]=Xe(Ye,{color:"white",label:c,parentRect:null,x:0,y:0,size:20,align:"center"});else throw new Error("Invalid JSX Child Parameter.")}n.children=i;let s=new ee;return s.type=r,s.props=n,s}var ee=class{type;props},V;(i=>{function r(s,l){return!(s.right<l.left||s.left>l.right||s.bottom<l.top||s.top>l.bottom)}i.rawCollision=r;function e(s,l,c){let p=l*Math.PI/180,u=Math.cos(p),h=Math.sin(p),m=1/0;return u>0&&(m=Math.min(m,(c.right-s.x)/u)),u<0&&(m=Math.min(m,(c.left-s.x)/u)),h>0&&(m=Math.min(m,(c.bottom-s.y)/h)),h<0&&(m=Math.min(m,(c.top-s.y)/h)),F.from(l).scale(m)}i.getCurrToBound=e;function n(s){let{left:l,right:c,top:p,bottom:u,width:h,height:m,x=0,y:w=0}=s;if(h===null||m===null)throw new Error("width and height are required");let T,R;if(l!=null&&c!=null){if(Math.abs(c-l-h)>1e-6)throw new Error("left, right, and width mismatch");T=l}else x!=null?T=x-h/2:l!=null?T=l:c!=null?T=c-h:T=0;if(p!=null&&u!=null){if(Math.abs(u-p-m)>1e-6)throw new Error("top, bottom, and height mismatch");R=p}else w!=null?R=w-m/2:p!=null?R=p:u!=null?R=u-m:R=0;return{left:T,right:T+h,top:R,bottom:R+m,width:h,height:m,x:T+h/2,y:R+m/2}}i.createRawRect=n})(V||={});var z;(R=>{class r extends Y{#e;#t;constructor(t,a,o){super(t,a,o),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)}}R.KaylaGame=r;class e extends W{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;isKaylaDisabled;constructor(t,a={}){super(t),this.isKaylaDisabled=a.disableKaylaBehavior,this.useDraw=this.useDraw.bind(this),this.on("draw",o=>{if(!a.noAutoDraw&&this.game)for(let d of this.game.scenes.values())d.handleDraw(o)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new A,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=o=>this.onPointerAll(o,"down"),this.onPointerUp=o=>this.onPointerAll(o,"up"),this.onPointerCancel=o=>this.onPointerAll(o,"cancel"),this.onPointerMove=o=>this.onPointerAll(o,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,a){this.pointerPosUpdater(t);let o=e.getClickType(t);if(o!=="invalid"||a==="move"||a==="cancel"){t.preventDefault();let d=this.getMousePos();this.pointerEvents.emit("action",d,o,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),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,a){let o=this.canvas.getBoundingClientRect(),d=(t-o.left)/o.width,b=(a-o.top)/o.height,g=this.cameraWidth/o.width,v=this.cameraHeight/o.height,K=d*this.viewportWidth*this.cameraWidth/o.width/g,E=b*this.viewportHeight*this.cameraHeight/o.height/v;return new F(K,E)}camToViewportPos(t,a){let o=t/this.cameraWidth*this.viewportWidth,d=a/this.cameraHeight*this.viewportHeight;return new F(o,d)}pointerPosToWorldPosOLD(t,a){let o=this.canvas.getBoundingClientRect(),d=(t-o.left)/o.width,b=(a-o.top)/o.height,g=d*this.viewportWidth*this.cameraWidth/o.width,v=b*this.viewportHeight*this.cameraHeight/o.height;return new F(g,v)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let a=o=>{t(o,new l)};return this.on("draw",a),()=>{this.off("draw",a)}}attachTo(t){t.addRenderer(this),this.game=t}detach(){this.game&&this.game.deleteRenderer(this)}}R.KaylaRenderer=e;let n=Symbol("unlock_substepper");class i{#e;constructor(t){this.#e=t}[n](){return this.#e}get interval(){return this.#e.interval}}class s{current;saves;constructor(){this.saves=[]}useTick(t,a=null){if(!this.current)throw new Error("Hook 'useTick' must be executed in the top level scope of a component.");let o=t;this.current.onTick[this.current.useStepCallIndex]=o,this.current.onTickSubsteps[this.current.useStepCallIndex]=a,this.current.useStepCallIndex++}usePaint(t){if(!this.current)throw new Error("Hook 'usePaint' must be executed in the top level scope of a component.");this.current.onPaint[this.current.useDrawCallIndex]=t,this.current.useDrawCallIndex++}useEntity(){if(!this.current)throw new Error("Hook 'useEntity' must be executed in the top level scope of a component.");return we(Ce)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let a=we(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.onInits[this.current.useInitCallIndex]=t,a.useInitCallIndex++}useRect(t="self"){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");if(t==="disposableSelf")return new R.KaylaInternalRect(this.current);let a=null;if(t==="self"&&(a=this.current),t==="parent"&&(a=this.current.detectedParent),!a)throw new Error("Missing valid target fiber.");return G(()=>new R.KaylaInternalRect(a))}useSubstep(t){t==="default"&&(t=N.defaultInterval);let a=G(()=>{let d=new N(0);return new i(d)}),o=a[n]();return o.interval=t,a}useFiber(){if(!this.current)throw new Error("Hook 'useFiber' must be executed in the top level scope of a component.");return G(()=>this.current)}useFiberControl(){if(!this.current)throw new Error("Hook 'useFiberControl' must be executed in the top level scope of a component.");let t=this.current;return G(()=>({refresh:()=>t.refresh(),toString(){return t.toString()},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 d=this.current.state[this.current.useStateCallIndex]??new c(this.current,t,{alwaysRecall:a});return this.current.state[this.current.useStateCallIndex]=d,this.current.useStateCallIndex++,d}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 o=this.current.refs[this.current.useRefCallIndex]??u(t??null);return this.current.refs[this.current.useRefCallIndex]=o,this.current.useRefCallIndex++,o}useEffect(t){if(!this.current)throw new Error("Hook 'useEffect' must be executed in the top level scope of a component.");this.current.onEffect[this.current.useEffectCallIndex]=t,this.current.useEffectCallIndex++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,a){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=a}useGlobalPointer(t,a){if(!this.current)throw new Error("Hook 'useGlobalPointer/useGlobalClick' must be executed in the top level scope of a component.");a??={},this.current.onGlobalPointer[this.current.useGlobalClickCallIndex]={handler:t,config:a},this.current.useGlobalClickCallIndex++}usePointer(t,a){if(!this.current)throw new Error("Hook 'usePointer/useClick' must be executed in the top level scope of a component.");a??={};let o=this.current;qe((d,b,g)=>{let v=o.entity;if(!v)return;let K=v.getRawRect(),E=V.createRawRect({x:d.x,y:d.y,width:3,height:3});V.rawCollision(K,E)&&t(d,b,g)},a)}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,o,...d)=>{let b=t?.fc?.name||"anonymous",g=t?.key?` key=${t.key}`:"";this.logger[a](`${o} <${b}${g}>`,...d)}}}R.GlobalKayla=s;class l{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}R.KaylaEvent=l;class c{#e;#t;#n;alwaysRecall;constructor(t,a,{alwaysRecall:o=!1}={}){this.#t=t,this.#e=a??void 0,this.#n=Date.now(),this.alwaysRecall=o}get(){return this.#e}get 0(){return this.get()}1(t){this.set(t,{recall:!0})}legacy(){return[this[0],this[1].bind(this)]}add(t,{recall: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 o=this.#e;if(t===o)return;this.#e=t;let b=Date.now()-this.#n;a&&b<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${b}ms`),(a||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}R.KaylaInternalState=c;class p{#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)}}R.KaylaInternalRef=p;function u(f){return new p(f)}R.createReassignableRef=u;class h{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;lastLayer;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,a,o){if(!o)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=a,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=o.type,this.callProps=o.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onTickSubsteps=[],this.onGlobalPointer=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+J(),this.onViewportEffect=[],this.lastLayer=null}getCorrectMousePos(t){return t??=this.getAttachedRenderer().getMousePos(),this.lastLayer?.transform?this.lastLayer.transform.inverseV(t):t}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,a,o){t=this.getCorrectMousePos(t);try{for(let{handler:d,config:b}of this.onGlobalPointer)b.type??="any",b.action??="down",!(b.action!=="any"&&b.action!==o||b.type!=="any"&&b.type!==a)&&d(t,a,o)}catch(d){this.global.logger.error(d)}}resizeHook({width:t,height:a}){try{for(let o of this.onViewportEffect)o(this.getAttachedRenderer(),t,a)}catch(o){this.global.logger.error(o)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){let t=this.callProps.children;return Array.isArray(t)?t:[t]}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalPointer;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;onTickSubsteps;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let 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),d=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=o;for(let b of d)b.unuse()}}getMaxChildren(){return this.maxSafeChildren??1/0}getFiberChain(){let t=[],a=this.detectedParent;for(;a;)t.push(a),a=a?.detectedParent;return t}getAllChildrenNestedFlattened(){let t=[],a=(o=[])=>{for(let d of o)t.push(d),d.lastChildren?.length&&a(d.lastChildren)};return a(this.lastChildren),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],o=this.lastDepStamps[t]??0;if(a.lastChanged>o)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,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let o=[];try{let d=this.fc(this.callProps)??[];if(d&&!Array.isArray(d)&&(d=[d]),!Array.isArray(d))throw new Error("Non array or non undefined children received.");for(let b of d);o=d}catch(d){a=d}if(this.global.restore(),this.updateChildren(o,!0),a)throw a}updateChildren(t,a){try{let o=[...t,...this.dynamicChildren],d=[],b=[];for(let g of o){let v=g.props?.key,K;v!=null&&(K=this.lastChildren.find(E=>E.key===v)),K||(K=new h(this.global,this.scene,g)),K.callProps=g.props,K.key=v??`${g.type?.name??""}_${J()}`,K.detectedParent=this,b.push(K),d.push(K)}for(let g of this.lastChildren)d.includes(g)||g.unuse();this.lastChildren=b,this.captureDepStamps(),this.use();for(let g of this.lastChildren)try{g.refresh()}catch(v){console.error(v)}}catch(o){console.error(o)}}toString(){return this.getStringRepresentation(0," ")}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=!0),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let a=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(d=>({stamp:d.lastChanged,stateRef:d}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new m(this,this.key);for(let d of this.refs)d.current===Ce&&(d.current=this.entity);if(this.callProps.ref instanceof p&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof p&&(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.onUnInits=[];for(let d of this.onInits){this.bindEvents();try{let b=d();typeof b=="function"&&this.onUnInits.push(b)}catch(b){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",b),b}}}try{for(let d of this.onUnEffect??[])d()}catch(d){console.error(d)}let o=this.onEffect.map(d=>d()).filter(d=>d!==void 0);this.onUnEffect=o}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}getStringRepresentation(t=0,a=" "){let o=a.repeat(t),d=this,b="",g=Object.entries(this.callProps);for(let E=0;E<g.length;E++){let[C,q]=g[E];if(["children"].includes(C))continue;b+=` ${C}=${typeof q=="string"?`${te(q)}`:`{${te(q,0)}}`}`}let v=Array.from(d.lastChildren).map(E=>E.getStringRepresentation(t+1,a)).join(""),K=d.fc.displayName??d.fc.name.replaceAll(" ","-");return v&&v.length>0?`${o}<${K}${b}>
2
+ ${v}${o}</${K}>
3
+ `:`${o}<${K}${b}/>
4
+ `}}R.KaylaFiber=h;class m extends Q{#e;flags;getRawRect(){return V.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,this.color="transparent"}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){de(()=>{let a=new l;if(this.#e&&this.#e.onTick){let o=0;for(let d of this.#e.onTick){let b=this.#e.onTickSubsteps.at(o)??null;if(b){let g=b[n]();g.handler=()=>{d(g.interval/1e3,a)},g.update(t)}else d(t,a);o++}}a.isPrevented()})}draw(t){let a=new l;if(this.#e&&this.#e.onPaint)for(let o of this.#e.onPaint)o(t,a);a.isPrevented()||super.draw(t)}getRect(){return new x(this.getFiber())}}R.KaylaRectEntity=m;class x{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return V.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.getCorrectMousePos(),o=V.createRawRect({x:a.x,y:a.y,width:3,height:3});return V.rawCollision(t,o)}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)}}R.KaylaInternalRect=x;class w{#e;#t;constructor(t){this.#r=t,this.#n=null,this.#e=new Map,t.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this),t.handleDraw=this.drawHandler,this.#t=null}getLayers(){return this.#e}#n;#r;getFibers(){return this.getEntities().map(t=>t.getFiber())}getEntities(){return Array.from(this.getScene().entities.values())}getScene(){return this.#r}getGame(){return this.#n}getOrCreateLayer(t,a=0){return this.#e.has(t)||this.#e.set(t,{name:t,z:a,visible:!0,rootFiber:null}),this.#e.get(t)}getSortedLayers(){return Array.from(this.#e.values()).filter(t=>t.visible).sort((t,a)=>t.z-a.z)}setLayerVisible(t,a){let o=this.#e.get(t);o&&(o.visible=a)}handleDraw(t){if(L)return;let a=this.getScene();if(a.paused)return;a.emit("draw",t);let o=this.getSortedLayers(),d=[];for(let g of o){if(!g.visible)continue;let v=g.rootFiber;if(!v)continue;let K=v.getAllChildrenNestedFlattened().flat().map(C=>C.entity).filter(Boolean);if(d.push(...K),t.save(),g.transform){let C=g.transform;t.setTransform(C.a,C.b,C.c,C.d,C.e,C.f)}g.blendMode&&(t.globalCompositeOperation=g.blendMode??"source-over");let E=Array.from(K).sort((C,q)=>C.z-q.z);for(let C of E)C.getFiber().lastLayer=g,C.handleDraw(t);t.restore()}let b=[...a.entities.values()].filter(g=>!d.includes(g));for(let g of b.sort((v,K)=>v.z-K.z)){let v=g instanceof m?g.getFiber():null;v&&(v.lastLayer=null),g.handleDraw(t)}}drawHandler(t){return this.handleDraw(t)}attachTo(t){t.addScene(this.#r),this.#n=t}async spawn(t){this.#t&&(this.#t.unuse(),this.#t=null);let a=this.createFiber(t);this.#t=a,await this.#n.delay(0),a.refresh()}getRoot(){return this.#t??null}createFiber(t){return new h(R.singleGlobalInstance,this,t)}detach(){this.#n&&this.#n.removeScene(this.#r)}tickHandler(){}}R.KaylaScene=w,R.singleGlobalInstance=new R.GlobalKayla})(z||={});var ue=class{#e;constructor(e){this.Provider=this.#t.bind(this),this.#e=e,this.Provider.displayName="[[ KaylaContext ]].Provider"}get defaultValue(){return this.#e}#t({value:e=this.defaultValue,children:n}){let i=Re();return ne(()=>{i.contextInfo={instance:this,value:e}}),ce(this.Provider,()=>({value:e})),n}Provider;Consumer};function ut(r){return new ue(r)}var y=z.singleGlobalInstance,ht=y.useState.bind(y),we=y.useRef.bind(y),ct=y.useShouldRefresh.bind(y),ne=y.useEffect.bind(y),dt=y.useViewportEffect.bind(y),qe=y.useGlobalPointer.bind(y),pt=y.useGlobalPointer.bind(y),ft=y.usePointer.bind(y),mt=y.usePointer.bind(y),he=y.useInitialization.bind(y),X=y.useRect.bind(y),yt=y.useTick.bind(y),re=y.usePaint.bind(y),ce=y.useExports.bind(y),G=y.useSelf.bind(y),Ke=y.useFiberControl.bind(y),Re=y.useFiber.bind(y),bt=y.useEntity.bind(y),gt=y.useCurrentGame.bind(y),xt=y.useCurrentRenderer.bind(y),Be=y.useCurrentScene.bind(y),vt=y.useCurrentTicker.bind(y),wt=y.useContext.bind(y),Ct=y.useSubstep.bind(y),Ce=Symbol("self_ref");var de=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},Et=({children:r})=>Array.isArray(r)?[...r]:r;function Kt(r){return z.createReassignableRef(r)}function Rt(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(i,s,l){return s==="reassignSelf"?c=>{e.current=c}:Reflect.get(e.current,s,l)},set(i,s,l,c){return Reflect.set(e.current,s,l,c)},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 kt(r){y.logLevel=r}function Tt(r){let e=r.name||"anonymous-custom-hook";function n(...i){let s=y.current;if(!s)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let l=i??[];return 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,y,...l)}return n.name=r.name,n}var St=({name:r,z:e=0,blend:n,visible:i=!0,children:s,transform:l})=>{let c=Be(),p=Re();return he(()=>{let u=c.getOrCreateLayer(r,e);return u.blendMode=n,u.visible=i,u.rootFiber=p,u.transform=l??null,()=>{c.getLayers().delete(r)}}),s},Ee=class extends DOMMatrix{#e;constructor(){super(),this.#e=new DOMPoint}transformV(e){this.#e.x=e.x,this.#e.y=e.y;let n=this.#e.matrixTransform(this);return new F(n.x,n.y)}inverseV(e){let n=this.inverse();this.#e.x=e.x,this.#e.y=e.y;let i=this.#e.matrixTransform(n);return new F(i.x,i.y)}},te=(r,e=0)=>{try{if(Array.isArray(r))return`[ ${r.map(n=>te(n,e)).join(", ")} ]`;if(typeof r=="object"&&r!==null){let n=r.constructor?.name;return n!=="Object"&&n?`[[ ${n} ]]`:`{ ${Object.entries(r).map(([i,s])=>`${i}: ${te(s,e)}`).join(", ")} }`}return JSON.stringify(r,null,e)}catch{return"[[ Non-serializable ]]"}},We;(e=>e.id="kayla")(We||={});var je=J,Pt=({color:r,cx:e,cy:n,height:i,width:s,children:l})=>{let c=X();return ne(()=>{c.color=r??"red",c.x=e??0,c.y=n??0,c.width=s??1,c.height=i??1}),l},Ye=({label:r,size:e,align:n="center",parentRect:i,color:s,x:l,y:c,ox:p=0,oy:u=0})=>{i??=X("parent"),re(h=>{h.fillStyle=s,h.font=`${e}px sans-serif`,h.textBaseline="middle",h.textAlign=n,h.fillText(r.toString(),(i?.x??l)+p,(i?.y??c)+u)})};function It(r){switch(r){case"use":{y.current.use();break}case"unuse":{y.current.unuse();break}}}Reflect.set(globalThis,"Kayla",ie);var Ft;(n=>(n.Flex=({align:i="stretch",children:s,direction:l="row",gap:c=0,justify:p="start",wrap:u="nowrap",getHeight:h,getWidth:m,getCenterX:x,getCenterY:w,color:T})=>{let R=Ke(),f=X(),t=G(()=>({recalc(){let a=Number(c)||0,o=x(),d=w(),b=m(),g=h();f.x=o,f.y=d,f.width=b,f.height=g;let K=R.getChildrenEntities().filter(Boolean).map(k=>k.getRect()).filter(k=>k.getFlag("flex-ignored")!==!0),E=l==="row",C=E?f.width:f.height,q=E?f.height:f.width,pe=0,se=0,ke=[],fe=[];K.forEach(k=>{let me=E?k.width:k.height;pe+me>C&&u==="wrap"?(ke.push({height:se,items:fe}),fe=[k],pe=me,se=E?k.height:k.width):(fe.push(k),pe+=me+a,se=Math.max(se,E?k.height:k.width))}),ke.push({height:se,items:fe});let Te=0;ke.forEach((k,me)=>{let _=k.items,H=_.reduce((I,ye)=>I+(E?ye.width:ye.height),0)+a*(_.length-1),M=0;p==="center"&&(M=(C-H)/2),p==="end"&&(M=C-H),p==="space-between"&&(M=0),p==="space-around"&&(M=(C-H)/(_.length*2)),p==="space-evenly"&&(M=(C-H)/(_.length+1)),_.forEach((I,ye)=>{I.z=f.z+1;let B=E?I.width:I.height,be=E?I.height:I.width,ge=0;i==="center"&&(ge=(k.height-be)/2),i==="end"&&(ge=k.height-be),i==="stretch"&&(E?I.height=k.height:I.width=k.height),E?(I.x=M+B/2,I.y=Te+ge+be/2):(I.x=Te+ge+be/2,I.y=M+B/2),p==="space-between"&&ye<_.length-1?M+=B+a+(C-H)/(_.length-1):p==="space-around"?M+=B+a+(C-H)/_.length:p==="space-evenly"?M+=B+a+(C-H)/(_.length+1):M+=B+a}),Te+=k.height+a})}}));return re((a,o)=>{o.preventDefault(),a.fillStyle=T,a.fillRect(f.left,f.top,f.width,f.height)}),ne(()=>{de(()=>{t.recalc()})}),ce(n.Flex,()=>({controls:t})),s},n.GenericBox=({color:i,width:s=20,height:l=20,x:c=0,y:p=0})=>{let u=X();he(()=>{u.width=s,u.height=l,u.x=c,u.y=p}),re((h,m)=>{m.preventDefault(),h.fillStyle=i,h.fillRect(u.left,u.top,u.width,u.height)})}))(Ft||={});var Vt={LEA:Z,Kayla:ie};0&&(module.exports={DeltaTweenII,ENVIRONMENT,GEmitterMemory,JSX,KMatrix2D,Kayla,KaylaContext,KaylaElement,KaylaFragment,KaylaInternals,KaylaRect,LEA,Layer,LeaEntityII,LeaEventEmitter,LeaGameII,LeaRendererII,LeaSceneII,LeaSerializers,LeaTickerII,LeaTimeout,LeaUtilsII,LiaAudio,LiaAudioSrc,LiaOscSFX,LiaSFXMap,NOTE_NAMES,Rect,RectLeaEntity,Substepper,Text,UI,Vector2,colToRGBA,createContext,createElement,createGame,createReassignableObject,createRenderer,createScene,createUseHook,defaultSFXConfig,editRGBA,generateUUID,getAvoidAngle,getEnvironment,getNormalizedColor,getRayHit,isInitiallyMobile,isMobile,isNode,isNote,isWeb,parseFillStyle,raycastAvoid,safeValueRepresentation,scaleCoord,self,setAnimInterval,setLogLevel,sfxHit,sfxJump,sfxLaser,sfxUIClick,sfxUIHover,shortUID,tinyUID,useClick,useContext,useCurrentGame,useCurrentRenderer,useCurrentScene,useCurrentTicker,useDisposableRef,useEffect,useEntity,useExports,useFiber,useFiberControl,useGlobalClick,useGlobalPointer,useInitialization,useNextStack,usePaint,usePointer,useRect,useRef,useSelf,useShouldRefresh,useState,useSubstep,useTick,useUsing,useViewportEffect});
package/dist/index.d.cts CHANGED
@@ -1,5 +1,8 @@
1
- import { L as LEA } from './lea-RdPmM_ci.cjs';
2
- import { K as Kayla } from './kayla-internals-B5pOzHo9.cjs';
1
+ import { L as LEA } from './lea-C5CjP5X2.cjs';
2
+ export { D as DefaultWSE, a as DeltaTweenII, E as ENVIRONMENT, G as GEmitterMemory, b as LeaEntityII, c as LeaEntitySerializer, d as LeaEntitySerializerArray, e as LeaEntitySerializerEach, f as LeaEventEmitter, g as LeaGameII, h as LeaRendererII, i as LeaSceneII, j as LeaSerializers, k as LeaTickerII, l as LeaTimeout, m as LeaUtilsII, n as LiaAudio, o as LiaAudioSrc, p as LiaOscSFX, q as LiaSFXMap, r as Listener, N as NOTE_NAME, s as NOTE_NAMES, O as OrderedLeaEntitySerializer, R as RayHit, t as RaycastResult, u as RectLeaEntity, S as SFXConfig, v as Side, w as Substepper, V as Vector2, x as colToRGBA, y as defaultSFXConfig, z as editRGBA, A as generateUUID, B as getAvoidAngle, C as getEnvironment, F as getNormalizedColor, H as getRayHit, I as isInitiallyMobile, J as isMobile, K as isNode, M as isNote, P as isWeb, Q as parseFillStyle, T as raycastAvoid, U as scaleCoord, W as setAnimInterval, X as sfxHit, Y as sfxJump, Z as sfxLaser, _ as sfxUIClick, $ as sfxUIHover, a0 as shortUID } from './lea-C5CjP5X2.cjs';
3
+ export { UI } from './kayla.cjs';
4
+ import { K as Kayla } from './kayla-internals-D359_d9x.cjs';
5
+ export { E as ExportsOfFC, F as FC, a as FCExports, b as FCProps, J as JSX, c as KMatrix2D, d as KaylaClickConfig, e as KaylaClickType, f as KaylaContext, g as KaylaCustomHookConfig, h as KaylaElement, i as KaylaElementRef, j as KaylaExportables, k as KaylaExports, l as KaylaFiberControl, m as KaylaFragment, n as KaylaGame, o as KaylaInternals, p as KaylaLayerInfo, q as KaylaLayerProps, r as KaylaPointerAction, s as KaylaRect, t as KaylaRef, u as KaylaRenderer, v as KaylaScene, w as KaylaState, x as KaylaSubstepper, L as Layer, P as PropOfFC, R as Reassignable, y as Rect, T as Text, U as UnsafeKaylaFiber, z as createContext, A as createElement, B as createGame, C as createReassignableObject, D as createRenderer, G as createScene, H as createUseHook, I as safeValueRepresentation, M as self, N as setLogLevel, O as tinyUID, Q as useClick, S as useContext, V as useCurrentGame, W as useCurrentRenderer, X as useCurrentScene, Y as useCurrentTicker, Z as useDisposableRef, _ as useEffect, $ as useEntity, a0 as useExports, a1 as useFiber, a2 as useFiberControl, a3 as useGlobalClick, a4 as useGlobalPointer, a5 as useInitialization, a6 as useNextStack, a7 as usePaint, a8 as usePointer, a9 as useRect, aa as useRef, ab as useSelf, ac as useShouldRefresh, ad as useState, ae as useSubstep, af as useTick, ag as useUsing, ah as useViewportEffect } from './kayla-internals-D359_d9x.cjs';
3
6
 
4
7
  declare const _default: {
5
8
  LEA: typeof LEA;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,8 @@
1
- import { L as LEA } from './lea-RdPmM_ci.js';
2
- import { K as Kayla } from './kayla-internals-QgpIxNOw.js';
1
+ import { L as LEA } from './lea-C5CjP5X2.js';
2
+ export { D as DefaultWSE, a as DeltaTweenII, E as ENVIRONMENT, G as GEmitterMemory, b as LeaEntityII, c as LeaEntitySerializer, d as LeaEntitySerializerArray, e as LeaEntitySerializerEach, f as LeaEventEmitter, g as LeaGameII, h as LeaRendererII, i as LeaSceneII, j as LeaSerializers, k as LeaTickerII, l as LeaTimeout, m as LeaUtilsII, n as LiaAudio, o as LiaAudioSrc, p as LiaOscSFX, q as LiaSFXMap, r as Listener, N as NOTE_NAME, s as NOTE_NAMES, O as OrderedLeaEntitySerializer, R as RayHit, t as RaycastResult, u as RectLeaEntity, S as SFXConfig, v as Side, w as Substepper, V as Vector2, x as colToRGBA, y as defaultSFXConfig, z as editRGBA, A as generateUUID, B as getAvoidAngle, C as getEnvironment, F as getNormalizedColor, H as getRayHit, I as isInitiallyMobile, J as isMobile, K as isNode, M as isNote, P as isWeb, Q as parseFillStyle, T as raycastAvoid, U as scaleCoord, W as setAnimInterval, X as sfxHit, Y as sfxJump, Z as sfxLaser, _ as sfxUIClick, $ as sfxUIHover, a0 as shortUID } from './lea-C5CjP5X2.js';
3
+ export { UI } from './kayla.js';
4
+ import { K as Kayla } from './kayla-internals-BRuWD6zz.js';
5
+ export { E as ExportsOfFC, F as FC, a as FCExports, b as FCProps, J as JSX, c as KMatrix2D, d as KaylaClickConfig, e as KaylaClickType, f as KaylaContext, g as KaylaCustomHookConfig, h as KaylaElement, i as KaylaElementRef, j as KaylaExportables, k as KaylaExports, l as KaylaFiberControl, m as KaylaFragment, n as KaylaGame, o as KaylaInternals, p as KaylaLayerInfo, q as KaylaLayerProps, r as KaylaPointerAction, s as KaylaRect, t as KaylaRef, u as KaylaRenderer, v as KaylaScene, w as KaylaState, x as KaylaSubstepper, L as Layer, P as PropOfFC, R as Reassignable, y as Rect, T as Text, U as UnsafeKaylaFiber, z as createContext, A as createElement, B as createGame, C as createReassignableObject, D as createRenderer, G as createScene, H as createUseHook, I as safeValueRepresentation, M as self, N as setLogLevel, O as tinyUID, Q as useClick, S as useContext, V as useCurrentGame, W as useCurrentRenderer, X as useCurrentScene, Y as useCurrentTicker, Z as useDisposableRef, _ as useEffect, $ as useEntity, a0 as useExports, a1 as useFiber, a2 as useFiberControl, a3 as useGlobalClick, a4 as useGlobalPointer, a5 as useInitialization, a6 as useNextStack, a7 as usePaint, a8 as usePointer, a9 as useRect, aa as useRef, ab as useSelf, ac as useShouldRefresh, ad as useState, ae as useSubstep, af as useTick, ag as useUsing, ah as useViewportEffect } from './kayla-internals-BRuWD6zz.js';
3
6
 
4
7
  declare const _default: {
5
8
  LEA: typeof LEA;