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