@kayelaa/canvas 0.2.2 → 0.2.4
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 +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/jsx-dev-runtime.cjs +2 -2
- package/dist/jsx-dev-runtime.d.cts +1 -1
- package/dist/jsx-dev-runtime.d.ts +1 -1
- package/dist/jsx-dev-runtime.js +2 -2
- package/dist/jsx-runtime.cjs +2 -2
- package/dist/jsx-runtime.d.cts +1 -1
- package/dist/jsx-runtime.d.ts +1 -1
- package/dist/jsx-runtime.js +2 -2
- package/dist/{kayla-internals-vuPhjkRg.d.cts → kayla-internals-BnnDnUVI.d.cts} +37 -16
- package/dist/{kayla-internals-C8v5s-0r.d.ts → kayla-internals-uYrgURKn.d.ts} +37 -16
- package/dist/kayla.cjs +2 -2
- package/dist/kayla.d.cts +2 -2
- package/dist/kayla.d.ts +2 -2
- package/dist/kayla.js +2 -2
- package/package.json +1 -1
package/dist/jsx-dev-runtime.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var le=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var Fe=Object.prototype.hasOwnProperty;var ve=(r,e)=>{for(var n in e)le(r,n,{get:e[n],enumerable:!0})},Pe=(r,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ie(e))!Fe.call(r,s)&&s!==n&&le(r,s,{get:()=>e[s],enumerable:!(a=Se(e,s))||a.enumerable});return r};var Me=r=>Pe(le({},"__esModule",{value:!0}),r);var ot={};ve(ot,{Fragment:()=>at,jsx:()=>it,jsxDEV:()=>st,jsxs:()=>Ke});module.exports=Me(ot);var xe={};ve(xe,{KaylaContext:()=>Z,KaylaFragment:()=>be,KaylaInternals:()=>D,KaylaRect:()=>M,createContext:()=>Ue,createElement:()=>ee,createGame:()=>Ge,createReassignableObject:()=>et,createRenderer:()=>ze,createScene:()=>He,createUseHook:()=>nt,self:()=>pe,setLogLevel:()=>tt,useClick:()=>Xe,useContext:()=>Je,useCurrentGame:()=>We,useCurrentRenderer:()=>je,useCurrentScene:()=>Ye,useCurrentTicker:()=>Qe,useDisposableRef:()=>Ze,useEffect:()=>me,useEntity:()=>Be,useExports:()=>ie,useFiber:()=>ke,useFiberControl:()=>ye,useGlobalClick:()=>Re,useInitialization:()=>te,useNextStack:()=>ge,usePaint:()=>re,useRect:()=>ne,useRef:()=>fe,useSelf:()=>V,useShouldRefresh:()=>Ne,useState:()=>$e,useTick:()=>qe,useViewportEffect:()=>Oe});var S=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let a=this.#e.get(e)||[];return a.push(n),this.#e.set(e,a),this}once(e,n){let a=(...s)=>{this.off(e,a),n(...s)};return this.on(e,a),this}off(e,n){let a=this.#e.get(e);if(!a)return this;let s=a.indexOf(n);return s>=0&&a.splice(s,1),this}emit(e,...n){let a=this.#e.get(e);if(!a||a.length===0){if(e==="error")throw n[0];return!1}return a.slice().forEach(s=>s(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},W=class extends S{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:n,viewportHeight:a,cameraWidth:s,cameraHeight:l}={}){if(!E)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=n??e.width,this.#t=a??e.height,this.#n=s??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(),this.emitViewportUpdate()}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(),this.emitViewportUpdate()}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}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!E)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},ue=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,!(E&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new ce(e,this)}createTween(e,n=()=>{}){let a=new he(e),s=(l=0)=>{if(a.finished){this.off("tick",s);return}a.update(l)};return a.on("finish",()=>{this.off("tick",s)}),a.on("delta",l=>{n(l)}),this.on("tick",s),a}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=E&&!isFinite(this.tickInterval)?Ve(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},Ae;(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 a(i){let[o,h]=i.split("|"),y=parseFloat(o),w=parseFloat(h);if(isNaN(y)||isNaN(w))throw new Error(`Invalid Vector2 string: ${i}`);return new _(y,w)}t.vec2Import=a,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 u(i=100){return{mapExport(o){return Math.round(o*i)},mapImport(o){return o/i}}}t.createPercent=u;function c(i){let o=new Map(Object.entries(i));return{mapExport:h=>o.get(h)??null,mapImport:h=>Array.from(o.entries()).find(([y,w])=>w===h)?.[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 g(i){return i*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:p,mapImport:g};function x(i=10){let o=d(i);return{mapExport(h){return o.mapExport(p(h))},mapImport(h){return o.mapImport(g(h))}}}t.createLowPrecisionRadToDeg=x})(Ae||={});var U=class r extends S{name="";scaleRotate=0;scale=1;constructor(e,n=0,a=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new _(n,a),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(!(J||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([s,{mapExport:l}])=>{let d=Reflect.get(this,s);return l?l(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(s=>!this.nonSerializableProperties.includes(s)&&!e.includes(s.toString())),a=Object.fromEntries(n.map(s=>{let l=Reflect.get(this,s);if(J&&typeof l=="number"){let d=l.toString().split("."),u=(d[1]?d[1].length:0)>2?Number(l.toFixed(2)):l;return[s,u]}return[s,l]}));return JSON.parse(JSON.stringify(a))}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 a={};for(let s=0;s<n.length;s++){let l=e[s];if(!l)break;let[d,{mapImport:f}]=l,u=n[s];if(f&&(u=f(u)),typeof d!="string")break;try{Reflect.set(a,d,u)}catch(c){console.error(c)}}return a}},j=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(!J&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((a,s)=>a.z-s.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof U))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof U))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},Y=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,n,a=16){this.ticker=new ue(a),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",s=>{for(let l of this.scenes.values())l.paused||l.handleUpdate(s)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},R={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=R.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return R.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[R.randomInt(0,r.length-1)]},createBezier(r,e,n,a){function s(f,u,c,p,g){let b=1-f;return b*b*b*u+3*b*b*f*c+3*b*f*f*p+f*f*f*g}function l(f,u,c,p,g){let b=1-f;return 3*b*b*(c-u)+6*b*f*(p-c)+3*f*f*(g-p)}function d(f){let u=f;for(let c=0;c<6;c++){let p=s(u,0,r,n,1),g=l(u,0,r,n,1);if(g===0)break;u-=(p-f)/g}return R.clamp(u,0,1)}return function(u){u=R.clamp(u,0,1);let c=d(u);return s(c,0,e,a,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 R.normalizeRad(-r)},degToRadFlipY(r){return R.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=R.normalizeRad(r),e=R.normalizeRad(e);let n=R.normalizeRad(e-r),a=R.normalizeRad(r-e);return n<=a?1:-1}},he=class extends S{constructor({delta:e,ms:n,easing:a}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=a??(s=>s),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=R.clamp(this.elapsed/this.duration,0,1),a=this.easing(n),s=this.delta*a,l=s-this.lastValue;this.lastValue=s,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},Q=class extends U{constructor(e,n=0,a=0,s=50,l=50){super(e,n,a),this.width=s,this.height=l}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},ce=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(a=>this._resolve=a),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)}},_=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),a=Math.sin(e);return new r(this.x*n-this.y*a,this.x*a+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(),a=e.normalized();return n.x*a.x+n.y*a.y}lengthSquaredTo(e){let n=this.x-e.x,a=this.y-e.y;return n*n+a*a}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,a=this.y-e.y;return n*n+a*a}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 _e(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var Ce=_e(),J=Ce==="node",E=Ce==="web",$=class r{static unlock(){E&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=E?new AudioContext:null;static masterGain=E?this.audioCtx.createGain():null;static musicGain=E?this.audioCtx.createGain():null;static sfxGain=E?this.audioCtx.createGain():null;static{E&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,a,s;if(typeof caches<"u"&&(s=await caches.open(n),a=await s.match(e)),!a){if(a=await fetch(e),!a.ok)throw new Error(`Failed to fetch ${e}`);s&&await s.put(e,a.clone())}let l=await a.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,a=1,s=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return;let d=new z(l);d.buffer=l;let f=1-.12,u=1+.12;d.playbackRate=a??f+Math.random()*(u-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(),s&&this.sfsx.set(e,{source:d,gain:c})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:a=0,loopEnd:s=null,exclusive:l=!0,skipMS:d=0}={}){if(l)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let u=new z(f);u.buffer=f,u.loop=!0,typeof a=="number"&&(u.loopStart=a),typeof s=="number"&&(u.loopEnd=s);let c=this.audioCtx.createGain();c.gain.value=n,u.tempGain=c,u.playbackRate=1,u.onended=()=>{u.disconnect(),c.disconnect()},u.connect(c),c.connect(this.musicGain),u.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:u,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:a=1,loop:s=!1,loopStart:l=0,loopEnd:d=null,isMusic:f=!1,gain:u=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return null;let p=new z(c);p.loop=s,p.loopStart=l,p.loopEnd=typeof d=="number"?d:c.duration,p.playbackRate=a;let g=this.audioCtx.createGain();return g.gain.value=n,p.connect(g),p.tempGain=g,g.connect(u||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),g.disconnect()},p}catch(c){return console.error("Failed to create LiaAudioSrc:",c),null}}};var z=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=E?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let a=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-a/this.playbackRate,this.source.start(0,a),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,a){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,a!==void 0?this.source.start(this.context.currentTime+e,n,a):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 a=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%a}if(this.isPlaying=!1,e>0){let a=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,a),this.output.gain.linearRampToValueAtTime(0,a+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,a=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,a),e}disconnect(e,n,a){e===void 0?this.output.disconnect():this.output.disconnect(e,n,a)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Le={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},L=class r{constructor(e={}){this.ctx=$.audioCtx,this.cfg=structuredClone(Le),Object.assign(this.cfg,e)}ctx;cfg;play(e=$.sfxGain){let n=this.ctx,a=n.currentTime,s=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,a);let d=s.ampEnv;l.gain.exponentialRampToValueAtTime(d.volume,a+d.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),a+d.attack+d.decay),l.gain.exponentialRampToValueAtTime(1e-4,a+s.duration+d.release);let f=l,u;s.filter.enabled&&(u=n.createBiquadFilter(),u.type=s.filter.type,u.frequency.value=s.filter.freq,u.Q.value=s.filter.Q,u.connect(l),f=u);let c;if(s.osc.enabled){if(c=n.createOscillator(),c.type=s.osc.type,c.frequency.value=s.osc.freq,c.detune.value=s.osc.detune,s.pitchEnv.amount!==0){let i=Math.pow(2,s.pitchEnv.amount/12);c.frequency.exponentialRampToValueAtTime(s.osc.freq*i,a+s.pitchEnv.decay)}c.connect(f),c.start(a),c.stop(a+s.duration+d.release)}let p;if(s.noise.enabled){let i=n.sampleRate*s.duration,o=n.createBuffer(1,i,n.sampleRate),h=o.getChannelData(0);for(let y=0;y<i;y++)h[y]=(Math.random()*2-1)*s.noise.level;p=n.createBufferSource(),p.buffer=o,p.connect(f),p.start(a),p.stop(a+s.duration+d.release)}let g,b;s.lfo.enabled&&c&&(g=n.createOscillator(),g.frequency.value=s.lfo.rate,b=n.createGain(),b.gain.value=s.lfo.depth,g.connect(b),s.lfo.target==="freq"?b.connect(c.frequency):s.lfo.target==="gain"?b.connect(l.gain):s.lfo.target==="filter"&&u&&b.connect(u.frequency),g.start(a),g.stop(a+s.duration)),l.connect(e);let x=[c,p,g,b,u,l],t=a+s.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,a,s){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:a,release:s}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,n,a){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:a,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,a){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:a,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},ht=new L({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),ct=new L({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),dt=new L({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),ft=new L({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),pt=new L({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function de(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),a=Array.from(n).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+a).slice(0,r)}function Ve(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function De(){return J?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var mt=De();function Ge({width:r,height:e,updateHz:n="frames"}){return new D.KaylaGame(r,e,n==="frames"?1/0:n)}function He(r){let e=new j(r);return new D.KaylaScene(e)}function ze(r){return new D.KaylaRenderer(r)}function ee(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+de(),{type:r,props:n}}var M;(a=>{function r(s,l){return!(s.right<l.left||s.left>l.right||s.bottom<l.top||s.top>l.bottom)}a.rawCollision=r;function e(s,l,d){let f=l*Math.PI/180,u=Math.cos(f),c=Math.sin(f),p=1/0;return u>0&&(p=Math.min(p,(d.right-s.x)/u)),u<0&&(p=Math.min(p,(d.left-s.x)/u)),c>0&&(p=Math.min(p,(d.bottom-s.y)/c)),c<0&&(p=Math.min(p,(d.top-s.y)/c)),_.from(l).scale(p)}a.getCurrToBound=e;function n(s){let{left:l,right:d,top:f,bottom:u,width:c,height:p,x:g=0,y:b=0}=s;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 g!=null?x=g-c/2:l!=null?x=l:d!=null?x=d-c:x=0;if(f!=null&&u!=null){if(Math.abs(u-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else b!=null?t=b-p/2:f!=null?t=f:u!=null?t=u-p:t=0;return{left:x,right:x+c,top:t,bottom:t+p,width:c,height:p,x:x+c/2,y:t+p/2}}a.createRawRect=n})(M||={});var D;(b=>{class r extends Y{#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 W{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(),h=(t-o.left)/o.width,y=(i-o.top)/o.height,w=h*this.viewportWidth*this.cameraWidth/o.width,k=y*this.viewportHeight*this.cameraHeight/o.height;return new _(w,k)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let i=o=>{t(o,new a)};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 fe(pe)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let i=fe(null);return(i.current===null||i.current===void 0)&&(i.current=t()),i.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let i=this.current;i.onInits[this.current.useInitCallIndex]=t,i.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return V(()=>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 V(()=>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 V(()=>({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 h=this.current.state[this.current.useStateCallIndex]??new s(this.current,t,{alwaysRecall:i});return this.current.state[this.current.useStateCallIndex]=h,this.current.useStateCallIndex++,h}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++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,i){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=i}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;Re((o,h)=>{let y=i.entity;if(!y)return;let w=y.getRawRect(),k=M.createRawRect({x:o.x,y:o.y,width:3,height:3});M.rawCollision(w,k)&&t(o,h)})}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,...h)=>{let y=t?.fc?.name||"anonymous",w=t?.key?` key=${t.key}`:"";this.logger[i](`${o} <${y}${w}>`,...h)}}}b.GlobalKayla=n;class a{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}b.KaylaEvent=a;class s{#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.
|
|
1
|
+
"use strict";var ue=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Fe=Object.prototype.hasOwnProperty;var we=(r,e)=>{for(var n in e)ue(r,n,{get:e[n],enumerable:!0})},Me=(r,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pe(e))!Fe.call(r,s)&&s!==n&&ue(r,s,{get:()=>e[s],enumerable:!(a=Ie(e,s))||a.enumerable});return r};var Ae=r=>Me(ue({},"__esModule",{value:!0}),r);var lt={};we(lt,{Fragment:()=>ot,jsx:()=>st,jsxDEV:()=>at,jsxs:()=>Te});module.exports=Ae(lt);var ve={};we(ve,{JSX:()=>Re,KaylaContext:()=>ee,KaylaFragment:()=>xe,KaylaInternals:()=>D,KaylaRect:()=>M,createContext:()=>$e,createElement:()=>te,createGame:()=>He,createReassignableObject:()=>tt,createRenderer:()=>Ue,createScene:()=>ze,createUseHook:()=>rt,self:()=>me,setLogLevel:()=>nt,useClick:()=>qe,useContext:()=>Ze,useCurrentGame:()=>je,useCurrentRenderer:()=>Ye,useCurrentScene:()=>Qe,useCurrentTicker:()=>Je,useDisposableRef:()=>et,useEffect:()=>ye,useEntity:()=>We,useExports:()=>se,useFiber:()=>Ke,useFiberControl:()=>ge,useGlobalClick:()=>ke,useInitialization:()=>ne,useNextStack:()=>be,usePaint:()=>ie,useRect:()=>re,useRef:()=>fe,useSelf:()=>V,useShouldRefresh:()=>Oe,useState:()=>Ne,useTick:()=>Be,useViewportEffect:()=>Xe});var I=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let a=this.#e.get(e)||[];return a.push(n),this.#e.set(e,a),this}once(e,n){let a=(...s)=>{this.off(e,a),n(...s)};return this.on(e,a),this}off(e,n){let a=this.#e.get(e);if(!a)return this;let s=a.indexOf(n);return s>=0&&a.splice(s,1),this}emit(e,...n){let a=this.#e.get(e);if(!a||a.length===0){if(e==="error")throw n[0];return!1}return a.slice().forEach(s=>s(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},j=class extends I{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:n,viewportHeight:a,cameraWidth:s,cameraHeight:l}={}){if(!E)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=n??e.width,this.#t=a??e.height,this.#n=s??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(),this.emitViewportUpdate()}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(),this.emitViewportUpdate()}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}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!E)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},he=class extends I{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(E&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new de(e,this)}createTween(e,n=()=>{}){let a=new ce(e),s=(l=0)=>{if(a.finished){this.off("tick",s);return}a.update(l)};return a.on("finish",()=>{this.off("tick",s)}),a.on("delta",l=>{n(l)}),this.on("tick",s),a}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=E&&!isFinite(this.tickInterval)?De(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,n=0){return .5+.5*Math.sin((this.now()%e/e+n)*2*Math.PI)}},_e;(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 a(i){let[o,u]=i.split("|"),y=parseFloat(o),v=parseFloat(u);if(isNaN(y)||isNaN(v))throw new Error(`Invalid Vector2 string: ${i}`);return new _(y,v)}t.vec2Import=a,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 p(i){return Math.round(i)}t.lightWeightRounder=p;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(([y,v])=>v===u)?.[0]??null}}t.createLookup=c;function f(i){let o=i*(180/Math.PI);return Math.round((o%360+360)%360)}t.radToDeg=f;function g(i){return i*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:f,mapImport:g};function x(i=10){let o=d(i);return{mapExport(u){return o.mapExport(f(u))},mapImport(u){return o.mapImport(g(u))}}}t.createLowPrecisionRadToDeg=x})(_e||={});var U=class r extends I{name="";scaleRotate=0;scale=1;constructor(e,n=0,a=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new _(n,a),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(!(Z||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(n){this.emit("error",n)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([s,{mapExport:l}])=>{let d=Reflect.get(this,s);return l?l(d):d});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],n=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(s=>!this.nonSerializableProperties.includes(s)&&!e.includes(s.toString())),a=Object.fromEntries(n.map(s=>{let l=Reflect.get(this,s);if(Z&&typeof l=="number"){let d=l.toString().split("."),h=(d[1]?d[1].length:0)>2?Number(l.toFixed(2)):l;return[s,h]}return[s,l]}));return JSON.parse(JSON.stringify(a))}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 a={};for(let s=0;s<n.length;s++){let l=e[s];if(!l)break;let[d,{mapImport:p}]=l,h=n[s];if(p&&(h=p(h)),typeof d!="string")break;try{Reflect.set(a,d,h)}catch(c){console.error(c)}}return a}},Y=class extends I{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!Z&&!this.paused){this.emit("draw",e);for(let n of[...this.entities.values()].sort((a,s)=>a.z-s.z))n.handleDraw(e)}}addEntity(e){if(!(e instanceof U))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof U))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},Q=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,a=16){this.ticker=new he(a),this.scenes=new Map,this.width=e,this.height=n,this.ticker.on("tick",s=>{for(let l of this.scenes.values())l.paused||l.handleUpdate(s)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},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,a){function s(p,h,c,f,g){let b=1-p;return b*b*b*h+3*b*b*p*c+3*b*p*p*f+p*p*p*g}function l(p,h,c,f,g){let b=1-p;return 3*b*b*(c-h)+6*b*p*(f-c)+3*p*p*(g-f)}function d(p){let h=p;for(let c=0;c<6;c++){let f=s(h,0,r,n,1),g=l(h,0,r,n,1);if(g===0)break;h-=(f-p)/g}return K.clamp(h,0,1)}return function(h){h=K.clamp(h,0,1);let c=d(h);return s(c,0,e,a,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),a=K.normalizeRad(r-e);return n<=a?1:-1}},ce=class extends I{constructor({delta:e,ms:n,easing:a}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=a??(s=>s),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=K.clamp(this.elapsed/this.duration,0,1),a=this.easing(n),s=this.delta*a,l=s-this.lastValue;this.lastValue=s,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},J=class extends U{constructor(e,n=0,a=0,s=50,l=50){super(e,n,a),this.width=s,this.height=l}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},de=class extends I{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(a=>this._resolve=a),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)}},_=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),a=Math.sin(e);return new r(this.x*n-this.y*a,this.x*a+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(),a=e.normalized();return n.x*a.x+n.y*a.y}lengthSquaredTo(e){let n=this.x-e.x,a=this.y-e.y;return n*n+a*a}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,a=this.y-e.y;return n*n+a*a}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 Le(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var Ce=Le(),Z=Ce==="node",E=Ce==="web",$=class r{static unlock(){E&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=E?new AudioContext:null;static masterGain=E?this.audioCtx.createGain():null;static musicGain=E?this.audioCtx.createGain():null;static sfxGain=E?this.audioCtx.createGain():null;static{E&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,a,s;if(typeof caches<"u"&&(s=await caches.open(n),a=await s.match(e)),!a){if(a=await fetch(e),!a.ok)throw new Error(`Failed to fetch ${e}`);s&&await s.put(e,a.clone())}let l=await a.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,a=1,s=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let l=this.getCached(e);if(!l)return;let d=new z(l);d.buffer=l;let p=1-.12,h=1+.12;d.playbackRate=a??p+Math.random()*(h-p);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(),s&&this.sfsx.set(e,{source:d,gain:c})}catch(l){console.error(l)}}static async playLoop(e,n=1,{loopStart:a=0,loopEnd:s=null,exclusive:l=!0,skipMS:d=0}={}){if(l)for(let g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let p=this.getCached(e);if(!p)return;let h=new z(p);h.buffer=p,h.loop=!0,typeof a=="number"&&(h.loopStart=a),typeof s=="number"&&(h.loopEnd=s);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 f=++this.loopIdCounter;return this.loops.set(f,{source:h,gain:c}),f}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:a=1,loop:s=!1,loopStart:l=0,loopEnd:d=null,isMusic:p=!1,gain:h=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return null;let f=new z(c);f.loop=s,f.loopStart=l,f.loopEnd=typeof d=="number"?d:c.duration,f.playbackRate=a;let g=this.audioCtx.createGain();return g.gain.value=n,f.connect(g),f.tempGain=g,g.connect(h||(p?this.musicGain:this.sfxGain)),f.onended=()=>{f.disconnect(),g.disconnect()},f}catch(c){return console.error("Failed to create LiaAudioSrc:",c),null}}};var z=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=E?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let a=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-a/this.playbackRate,this.source.start(0,a),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,a){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,a!==void 0?this.source.start(this.context.currentTime+e,n,a):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 a=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%a}if(this.isPlaying=!1,e>0){let a=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,a),this.output.gain.linearRampToValueAtTime(0,a+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,a=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,a),e}disconnect(e,n,a){e===void 0?this.output.disconnect():this.output.disconnect(e,n,a)}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},Ve={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},L=class r{constructor(e={}){this.ctx=$.audioCtx,this.cfg=structuredClone(Ve),Object.assign(this.cfg,e)}ctx;cfg;play(e=$.sfxGain){let n=this.ctx,a=n.currentTime,s=this.cfg,l=n.createGain();l.gain.setValueAtTime(1e-4,a);let d=s.ampEnv;l.gain.exponentialRampToValueAtTime(d.volume,a+d.attack),l.gain.exponentialRampToValueAtTime(Math.max(1e-4,d.sustain*d.volume),a+d.attack+d.decay),l.gain.exponentialRampToValueAtTime(1e-4,a+s.duration+d.release);let p=l,h;s.filter.enabled&&(h=n.createBiquadFilter(),h.type=s.filter.type,h.frequency.value=s.filter.freq,h.Q.value=s.filter.Q,h.connect(l),p=h);let c;if(s.osc.enabled){if(c=n.createOscillator(),c.type=s.osc.type,c.frequency.value=s.osc.freq,c.detune.value=s.osc.detune,s.pitchEnv.amount!==0){let i=Math.pow(2,s.pitchEnv.amount/12);c.frequency.exponentialRampToValueAtTime(s.osc.freq*i,a+s.pitchEnv.decay)}c.connect(p),c.start(a),c.stop(a+s.duration+d.release)}let f;if(s.noise.enabled){let i=n.sampleRate*s.duration,o=n.createBuffer(1,i,n.sampleRate),u=o.getChannelData(0);for(let y=0;y<i;y++)u[y]=(Math.random()*2-1)*s.noise.level;f=n.createBufferSource(),f.buffer=o,f.connect(p),f.start(a),f.stop(a+s.duration+d.release)}let g,b;s.lfo.enabled&&c&&(g=n.createOscillator(),g.frequency.value=s.lfo.rate,b=n.createGain(),b.gain.value=s.lfo.depth,g.connect(b),s.lfo.target==="freq"?b.connect(c.frequency):s.lfo.target==="gain"?b.connect(l.gain):s.lfo.target==="filter"&&h&&b.connect(h.frequency),g.start(a),g.stop(a+s.duration)),l.connect(e);let x=[c,f,g,b,h,l],t=a+s.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,a,s){return Object.assign(this.cfg.ampEnv,{attack:e,decay:n,sustain:a,release:s}),this}setPitchEnv(e,n){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:n}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,n,a){return Object.assign(this.cfg.filter,{type:e,freq:n,Q:a,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,n,a){return Object.assign(this.cfg.lfo,{target:e,rate:n,depth:a,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new r(structuredClone(this.cfg))}},ct=new L({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),dt=new L({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),pt=new L({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),ft=new L({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),mt=new L({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function pe(r=12){let e=Date.now().toString(36),n=crypto.getRandomValues(new Uint8Array(4)),a=Array.from(n).map(s=>s.toString(36).padStart(2,"0")).join("");return(e+a).slice(0,r)}function De(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function Ge(){return Z?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var yt=Ge();function He({width:r,height:e,updateHz:n="frames"}){return new D.KaylaGame(r,e,n==="frames"?1/0:n)}function ze(r){let e=new Y(r);return new D.KaylaScene(e)}function Ue(r){return new D.KaylaRenderer(r)}function te(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+pe(),{type:r,props:n}}var M;(a=>{function r(s,l){return!(s.right<l.left||s.left>l.right||s.bottom<l.top||s.top>l.bottom)}a.rawCollision=r;function e(s,l,d){let p=l*Math.PI/180,h=Math.cos(p),c=Math.sin(p),f=1/0;return h>0&&(f=Math.min(f,(d.right-s.x)/h)),h<0&&(f=Math.min(f,(d.left-s.x)/h)),c>0&&(f=Math.min(f,(d.bottom-s.y)/c)),c<0&&(f=Math.min(f,(d.top-s.y)/c)),_.from(l).scale(f)}a.getCurrToBound=e;function n(s){let{left:l,right:d,top:p,bottom:h,width:c,height:f,x:g=0,y:b=0}=s;if(c===null||f===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 g!=null?x=g-c/2:l!=null?x=l:d!=null?x=d-c:x=0;if(p!=null&&h!=null){if(Math.abs(h-p-f)>1e-6)throw new Error("top, bottom, and height mismatch");t=p}else b!=null?t=b-f/2:p!=null?t=p:h!=null?t=h-f:t=0;return{left:x,right:x+c,top:t,bottom:t+f,width:c,height:f,x:x+c/2,y:t+f/2}}a.createRawRect=n})(M||={});var D;(b=>{class r extends Q{#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 j{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",i=>{if(this.game)for(let o of this.game.scenes.values())o.handleDraw(i)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new I,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=i=>this.onPointerAll(i,"down"),this.onPointerUp=i=>this.onPointerAll(i,"up"),this.onPointerCancel=i=>this.onPointerAll(i,"cancel"),this.onPointerMove=i=>this.onPointerAll(i,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,i){this.pointerPosUpdater(t);let o=e.getClickType(t);if(o!=="invalid"){t.preventDefault();let u=this.getMousePos();this.pointerEvents.emit("action",u,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),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,i){let o=this.canvas.getBoundingClientRect(),u=(t-o.left)/o.width,y=(i-o.top)/o.height,v=u*this.viewportWidth*this.cameraWidth/o.width,k=y*this.viewportHeight*this.cameraHeight/o.height;return new _(v,k)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(t){let i=o=>{t(o,new a)};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 fe(me)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let i=fe(null);return(i.current===null||i.current===void 0)&&(i.current=t()),i.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let i=this.current;i.onInits[this.current.useInitCallIndex]=t,i.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return V(()=>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 V(()=>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 V(()=>({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 s(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++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,i){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=i}useGlobalClick(t,i){if(!this.current)throw new Error("Hook 'useGlobalClick' must be executed in the top level scope of a component.");i??={},this.current.onGlobalClick[this.current.useGlobalClickCallIndex]={handler:t,config:i},this.current.useGlobalClickCallIndex++}useClick(t,i){if(!this.current)throw new Error("Hook 'useClick' must be executed in the top level scope of a component.");i??={};let o=this.current;ke((u,y,v)=>{let k=o.entity;if(!k)return;let T=k.getRawRect(),N=M.createRawRect({x:u.x,y:u.y,width:3,height:3});M.rawCollision(T,N)&&t(u,y,v)},i)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,i,o,...u)=>{let y=t?.fc?.name||"anonymous",v=t?.key?` key=${t.key}`:"";this.logger[i](`${o} <${y}${v}>`,...u)}}}b.GlobalKayla=n;class a{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}b.KaylaEvent=a;class s{#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(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 y=Date.now()-this.#n;i&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(i||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}b.KaylaInternalState=s;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;dynamicChildren;constructor(t,i,o){if(!o)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=i,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=o.type,this.callProps=o.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalClick=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+de(),this.onViewportEffect=[]}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)}}resizeHook({width:t,height:i}){try{for(let o of this.onViewportEffect)o(this.getAttachedRenderer(),t,i)}catch(o){this.global.logger.error(o)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("down",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("down",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){return this.callProps.children}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalClick;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let i=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${i} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let o=this.lastChildren.slice(0,this.maxSafeChildren),h=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=o;for(let y of h)y.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,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let o=[];try{let h=this.fc(this.callProps)??[];if(h&&!Array.isArray(h)&&(h=[h]),!Array.isArray(h))throw new Error("Non array or non undefined children received.");for(let y of h)if(y.type===this.fc)throw new Error("Circular Component.");o=h}catch(h){i=h}if(this.global.restore(),this.updateChildren(o,!0),i)throw i}updateChildren(t,i){try{let o=[...t,...this.dynamicChildren],h=[],y=[];for(let w of o){let k=w.props?.key,F;k!=null&&(F=this.lastChildren.find(we=>we.key===k)),F||(F=new f(this.global,this.scene,w)),F.detectedParent=this,y.push(F),h.push(F)}for(let w of this.lastChildren)h.includes(w)||w.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let w of this.lastChildren)try{w.refresh()}catch(k){console.error(k)}}catch(o){console.error(o)}}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=this.onEffectDeps.some((i,o)=>{let h=this.lastStateDeps.at(o);if(h){let y=i.lastChanged,w=h.stamp;return y>w}})),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let i=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(h=>({stamp:h.lastChanged,stateRef:h}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new u(this,this.key);for(let h of this.refs)h.current===pe&&(h.current=this.entity);if(this.callProps.ref instanceof l&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof l&&(this.callProps.exportsRef.current=this.exports),this.entity&&this.entity!==this.entity&&this.global.logger.warn(`Entity name mismatch during refresh <${this.fc?.name} key=${this.key}>`),this.scene.getScene().addEntity(this.entity),i){this.onUnInits=[];for(let h of this.onInits){this.bindEvents();try{let y=h();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let h of this.onUnEffect??[])h()}catch(h){console.error(h)}let o=this.onEffect.map(h=>h()).filter(h=>h!==void 0);this.onUnEffect=o}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}}b.KaylaFiber=f;class u extends Q{#e;flags;getRawRect(){return M.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,i){super(i,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,i){return this.flags.set(t,i)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){let i=new a;if(this.#e&&this.#e.onTick)for(let o of this.#e.onTick)o(t,i);i.isPrevented()}draw(t){let i=new a;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=u;class c{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return M.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=M.createRawRect({x:i.x,y:i.y,width:3,height:3});return M.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 Z=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 a=ke();return te(()=>{a.contextInfo={instance:this,value:e}}),ie(this.Provider,()=>({value:e})),n}Provider;Consumer};function Ue(r){return new Z(r)}var m=D.singleGlobalInstance,$e=m.useState.bind(m),fe=m.useRef.bind(m),Ne=m.useShouldRefresh.bind(m),me=m.useEffect.bind(m),Oe=m.useViewportEffect.bind(m),Re=m.useGlobalClick.bind(m),Xe=m.useClick.bind(m),te=m.useInitialization.bind(m),ne=m.useRect.bind(m),qe=m.useTick.bind(m),re=m.usePaint.bind(m),ie=m.useExports.bind(m),V=m.useSelf.bind(m),ye=m.useFiberControl.bind(m),ke=m.useFiber.bind(m),Be=m.useEntity.bind(m),We=m.useCurrentGame.bind(m),je=m.useCurrentRenderer.bind(m),Ye=m.useCurrentScene.bind(m),Qe=m.useCurrentTicker.bind(m),Je=m.useContext.bind(m),pe=Symbol("self_ref");var ge=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},be=({children:r})=>Array.isArray(r)?[...r]:r;function Ze(r){return D.createReassignableRef(r)}function et(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(a,s,l){return s==="reassignSelf"?d=>{e.current=d}:Reflect.get(e.current,s,l)},set(a,s,l,d){return Reflect.set(e.current,s,l,d)},has(a,s){return Reflect.has(e.current,s)},ownKeys(a){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(a,s){return Reflect.getOwnPropertyDescriptor(e.current,s)},deleteProperty(a,s){return Reflect.deleteProperty(e.current,s)}})}function tt(r){m.logLevel=r}function nt(r){let e=r.name||"anonymous-custom-hook";return function(a){let s=m.current;if(!s)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let l=a??{};return r.memoize!==!1?V(()=>(s.global.logLevel==="debug"&&s.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${s.fc?.name||"anonymous"} key=${s.key||"no-key"}>`),r.onUse(s,m,l))):(s.global.logLevel==="debug"&&s.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${s.fc?.name||"anonymous"} key=${s.key||"no-key"}>`),r.onUse(s,m,l))}}Reflect.set(globalThis,"Kayla",xe);var rt;(n=>(n.Flex=({align:a="stretch",children:s,direction:l="row",gap:d=0,justify:f="start",wrap:u="nowrap",getHeight:c,getWidth:p,getCenterX:g,getCenterY:b,color:x})=>{let t=ye(),i=ne(),o=V(()=>({recalc(){let h=Number(d)||0,y=g(),w=b(),k=p(),F=c();i.x=y,i.y=w,i.width=k,i.height=F;let Te=t.getChildrenEntities().filter(Boolean).map(v=>v.getRect()).filter(v=>v.getFlag("flex-ignored")!==!0),T=l==="row",P=T?i.width:i.height,lt=T?i.height:i.width,se=0,H=0,ae=[],N=[];Te.forEach(v=>{let O=T?v.width:v.height;se+O>P&&u==="wrap"?(ae.push({height:H,items:N}),N=[v],se=O,H=T?v.height:v.width):(N.push(v),se+=O+h,H=Math.max(H,T?v.height:v.width))}),ae.push({height:H,items:N});let oe=0;ae.forEach((v,O)=>{let I=v.items,A=I.reduce((C,X)=>C+(T?X.width:X.height),0)+h*(I.length-1),K=0;f==="center"&&(K=(P-A)/2),f==="end"&&(K=P-A),f==="space-between"&&(K=0),f==="space-around"&&(K=(P-A)/(I.length*2)),f==="space-evenly"&&(K=(P-A)/(I.length+1)),I.forEach((C,X)=>{C.z=i.z+1;let G=T?C.width:C.height,q=T?C.height:C.width,B=0;a==="center"&&(B=(v.height-q)/2),a==="end"&&(B=v.height-q),a==="stretch"&&(T?C.height=v.height:C.width=v.height),T?(C.x=K+G/2,C.y=oe+B+q/2):(C.x=oe+B+q/2,C.y=K+G/2),f==="space-between"&&X<I.length-1?K+=G+h+(P-A)/(I.length-1):f==="space-around"?K+=G+h+(P-A)/I.length:f==="space-evenly"?K+=G+h+(P-A)/(I.length+1):K+=G+h}),oe+=v.height+h})}}));return re((h,y)=>{y.preventDefault(),h.fillStyle=x,h.fillRect(i.left,i.top,i.width,i.height)}),me(()=>{ge(()=>{o.recalc()})}),ie(n.Flex,()=>({controls:o})),s},n.GenericBox=({color:a,width:s=20,height:l=20,x:d=0,y:f=0})=>{let u=ne();te(()=>{u.width=s,u.height=l,u.x=d,u.y=f}),re((c,p)=>{p.preventDefault(),c.fillStyle=a,c.fillRect(u.left,u.top,u.width,u.height)})}))(rt||={});function it(r,e,...n){if(typeof r=="string")throw new Error("Cannot use intrinsic elements.");return ee(r,{...e,children:e.children??n})}function Ke(r,e,...n){if(typeof r=="string")throw new Error("Cannot use intrinsic elements.");return ee(r,{...e,children:e.children??n})}function st(r,e){return Ke(r,e)}var at=be;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: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 y=Date.now()-this.#n;i&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(i||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}b.KaylaInternalState=s;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 p{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,i,o){if(!o)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=i,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=o.type,this.callProps=o.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalClick=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+pe(),this.onViewportEffect=[]}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,i,o){try{for(let{handler:u,config:y}of this.onGlobalClick)y.type??="any",y.action??="down",!(y.action!=="any"&&y.action!==o||y.type!=="any"&&y.type!==i)&&u(t,i,o)}catch(u){this.global.logger.error(u)}}resizeHook({width:t,height:i}){try{for(let o of this.onViewportEffect)o(this.getAttachedRenderer(),t,i)}catch(o){this.global.logger.error(o)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){return this.callProps.children}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalClick;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let i=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${i} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let o=this.lastChildren.slice(0,this.maxSafeChildren),u=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=o;for(let y of u)y.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,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let o=[];try{let 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 y of u)if(y.type===this.fc)throw new Error("Circular Component.");o=u}catch(u){i=u}if(this.global.restore(),this.updateChildren(o,!0),i)throw i}updateChildren(t,i){try{let o=[...t,...this.dynamicChildren],u=[],y=[];for(let v of o){let k=v.props?.key,T;k!=null&&(T=this.lastChildren.find(N=>N.key===k)),T||(T=new p(this.global,this.scene,v)),T.detectedParent=this,y.push(T),u.push(T)}for(let v of this.lastChildren)u.includes(v)||v.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let v of this.lastChildren)try{v.refresh()}catch(k){console.error(k)}}catch(o){console.error(o)}}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 y=i.lastChanged,v=u.stamp;return y>v}})),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let i=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(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===me&&(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.onUnInits=[];for(let u of this.onInits){this.bindEvents();try{let y=u();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let 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.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}}b.KaylaFiber=p;class h extends J{#e;flags;getRawRect(){return M.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,i){super(i,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,i){return this.flags.set(t,i)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){let i=new a;if(this.#e&&this.#e.onTick)for(let o of this.#e.onTick)o(t,i);i.isPrevented()}draw(t){let i=new a;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}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return M.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=M.createRawRect({x:i.x,y:i.y,width:3,height:3});return M.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 f{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 p(b.singleGlobalInstance,this,t)}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}b.KaylaScene=f,b.singleGlobalInstance=new b.GlobalKayla})(D||={});var ee=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 a=Ke();return ne(()=>{a.contextInfo={instance:this,value:e}}),se(this.Provider,()=>({value:e})),n}Provider;Consumer};function $e(r){return new ee(r)}var m=D.singleGlobalInstance,Ne=m.useState.bind(m),fe=m.useRef.bind(m),Oe=m.useShouldRefresh.bind(m),ye=m.useEffect.bind(m),Xe=m.useViewportEffect.bind(m),ke=m.useGlobalClick.bind(m),qe=m.useClick.bind(m),ne=m.useInitialization.bind(m),re=m.useRect.bind(m),Be=m.useTick.bind(m),ie=m.usePaint.bind(m),se=m.useExports.bind(m),V=m.useSelf.bind(m),ge=m.useFiberControl.bind(m),Ke=m.useFiber.bind(m),We=m.useEntity.bind(m),je=m.useCurrentGame.bind(m),Ye=m.useCurrentRenderer.bind(m),Qe=m.useCurrentScene.bind(m),Je=m.useCurrentTicker.bind(m),Ze=m.useContext.bind(m),me=Symbol("self_ref");var be=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},xe=({children:r})=>Array.isArray(r)?[...r]:r;function et(r){return D.createReassignableRef(r)}function tt(r){if(typeof r!="object"||typeof r=="function"||r===null)return r;let e={current:r};return new Proxy({},{get(a,s,l){return s==="reassignSelf"?d=>{e.current=d}:Reflect.get(e.current,s,l)},set(a,s,l,d){return Reflect.set(e.current,s,l,d)},has(a,s){return Reflect.has(e.current,s)},ownKeys(a){return Reflect.ownKeys(e.current)},getOwnPropertyDescriptor(a,s){return Reflect.getOwnPropertyDescriptor(e.current,s)},deleteProperty(a,s){return Reflect.deleteProperty(e.current,s)}})}function nt(r){m.logLevel=r}function rt(r){let e=r.name||"anonymous-custom-hook";return function(a){let s=m.current;if(!s)throw new Error(`Custom hook '${e}' must be called inside a Kayla component`);let l=a??{};return r.memoize!==!1?V(()=>(s.global.logLevel==="debug"&&s.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${s.fc?.name||"anonymous"} key=${s.key||"no-key"}>`),r.onUse(s,m,l))):(s.global.logLevel==="debug"&&s.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${s.fc?.name||"anonymous"} key=${s.key||"no-key"}>`),r.onUse(s,m,l))}}var Re;(e=>e.id="kayla")(Re||={});Reflect.set(globalThis,"Kayla",ve);var it;(n=>(n.Flex=({align:a="stretch",children:s,direction:l="row",gap:d=0,justify:p="start",wrap:h="nowrap",getHeight:c,getWidth:f,getCenterX:g,getCenterY:b,color:x})=>{let t=ge(),i=re(),o=V(()=>({recalc(){let u=Number(d)||0,y=g(),v=b(),k=f(),T=c();i.x=y,i.y=v,i.width=k,i.height=T;let Se=t.getChildrenEntities().filter(Boolean).map(w=>w.getRect()).filter(w=>w.getFlag("flex-ignored")!==!0),S=l==="row",F=S?i.width:i.height,ut=S?i.height:i.width,ae=0,H=0,oe=[],O=[];Se.forEach(w=>{let X=S?w.width:w.height;ae+X>F&&h==="wrap"?(oe.push({height:H,items:O}),O=[w],ae=X,H=S?w.height:w.width):(O.push(w),ae+=X+u,H=Math.max(H,S?w.height:w.width))}),oe.push({height:H,items:O});let le=0;oe.forEach((w,X)=>{let P=w.items,A=P.reduce((C,q)=>C+(S?q.width:q.height),0)+u*(P.length-1),R=0;p==="center"&&(R=(F-A)/2),p==="end"&&(R=F-A),p==="space-between"&&(R=0),p==="space-around"&&(R=(F-A)/(P.length*2)),p==="space-evenly"&&(R=(F-A)/(P.length+1)),P.forEach((C,q)=>{C.z=i.z+1;let G=S?C.width:C.height,B=S?C.height:C.width,W=0;a==="center"&&(W=(w.height-B)/2),a==="end"&&(W=w.height-B),a==="stretch"&&(S?C.height=w.height:C.width=w.height),S?(C.x=R+G/2,C.y=le+W+B/2):(C.x=le+W+B/2,C.y=R+G/2),p==="space-between"&&q<P.length-1?R+=G+u+(F-A)/(P.length-1):p==="space-around"?R+=G+u+(F-A)/P.length:p==="space-evenly"?R+=G+u+(F-A)/(P.length+1):R+=G+u}),le+=w.height+u})}}));return ie((u,y)=>{y.preventDefault(),u.fillStyle=x,u.fillRect(i.left,i.top,i.width,i.height)}),ye(()=>{be(()=>{o.recalc()})}),se(n.Flex,()=>({controls:o})),s},n.GenericBox=({color:a,width:s=20,height:l=20,x:d=0,y:p=0})=>{let h=re();ne(()=>{h.width=s,h.height=l,h.x=d,h.y=p}),ie((c,f)=>{f.preventDefault(),c.fillStyle=a,c.fillRect(h.left,h.top,h.width,h.height)})}))(it||={});function st(r,e,...n){if(typeof r=="string")throw new Error("Cannot use intrinsic elements.");return te(r,{...e,children:e.children??n})}function Te(r,e,...n){if(typeof r=="string")throw new Error("Cannot use intrinsic elements.");return te(r,{...e,children:e.children??n})}function at(r,e){return Te(r,e)}var ot=xe;0&&(module.exports={Fragment,jsx,jsxDEV,jsxs});
|
package/dist/jsx-dev-runtime.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var ke=Object.defineProperty;var Ke=(r,e)=>{for(var n in e)ke(r,n,{get:e[n],enumerable:!0})};var be={};Ke(be,{KaylaContext:()=>Z,KaylaFragment:()=>ge,KaylaInternals:()=>D,KaylaRect:()=>M,createContext:()=>Le,createElement:()=>ee,createGame:()=>Me,createReassignableObject:()=>We,createRenderer:()=>_e,createScene:()=>Ae,createUseHook:()=>Ye,self:()=>fe,setLogLevel:()=>je,useClick:()=>He,useContext:()=>qe,useCurrentGame:()=>$e,useCurrentRenderer:()=>Ne,useCurrentScene:()=>Oe,useCurrentTicker:()=>Xe,useDisposableRef:()=>Be,useEffect:()=>pe,useEntity:()=>Ue,useExports:()=>ie,useFiber:()=>Ee,useFiberControl:()=>me,useGlobalClick:()=>Ce,useInitialization:()=>te,useNextStack:()=>ye,usePaint:()=>re,useRect:()=>ne,useRef:()=>de,useSelf:()=>V,useShouldRefresh:()=>De,useState:()=>Ve,useTick:()=>ze,useViewportEffect:()=>Ge});var S=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let s=this.#e.get(e)||[];return s.push(n),this.#e.set(e,s),this}once(e,n){let s=(...a)=>{this.off(e,s),n(...a)};return this.on(e,s),this}off(e,n){let s=this.#e.get(e);if(!s)return this;let a=s.indexOf(n);return a>=0&&s.splice(a,1),this}emit(e,...n){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw n[0];return!1}return s.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},W=class extends S{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:n,viewportHeight:s,cameraWidth:a,cameraHeight:l}={}){if(!E)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=n??e.width,this.#t=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(),this.emitViewportUpdate()}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(),this.emitViewportUpdate()}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}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!E)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},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,!(E&&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),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=E&&!isFinite(this.tickInterval)?Fe(()=>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)}},Te;(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,h]=i.split("|"),y=parseFloat(o),w=parseFloat(h);if(isNaN(y)||isNaN(w))throw new Error(`Invalid Vector2 string: ${i}`);return new _(y,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 u(i=100){return{mapExport(o){return Math.round(o*i)},mapImport(o){return o/i}}}t.createPercent=u;function c(i){let o=new Map(Object.entries(i));return{mapExport:h=>o.get(h)??null,mapImport:h=>Array.from(o.entries()).find(([y,w])=>w===h)?.[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 g(i){return i*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:p,mapImport:g};function x(i=10){let o=d(i);return{mapExport(h){return o.mapExport(p(h))},mapImport(h){return o.mapImport(g(h))}}}t.createLowPrecisionRadToDeg=x})(Te||={});var U=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 _(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(!(J||!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(J&&typeof l=="number"){let d=l.toString().split("."),u=(d[1]?d[1].length:0)>2?Number(l.toFixed(2)):l;return[a,u]}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,u=n[a];if(f&&(u=f(u)),typeof d!="string")break;try{Reflect.set(s,d,u)}catch(c){console.error(c)}}return s}},j=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(!J&&!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 U))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof U))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},Y=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,n,s=16){this.ticker=new le(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()}},R={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=R.clamp(r,0,1),r*r*(3-2*r)},randomLerp(r,e){return R.lerp(r,e,Math.random())},randomInt(r,e){return Math.floor(Math.random()*(e-r+1))+r},randomArrayValue(r){return r[R.randomInt(0,r.length-1)]},createBezier(r,e,n,s){function a(f,u,c,p,g){let b=1-f;return b*b*b*u+3*b*b*f*c+3*b*f*f*p+f*f*f*g}function l(f,u,c,p,g){let b=1-f;return 3*b*b*(c-u)+6*b*f*(p-c)+3*f*f*(g-p)}function d(f){let u=f;for(let c=0;c<6;c++){let p=a(u,0,r,n,1),g=l(u,0,r,n,1);if(g===0)break;u-=(p-f)/g}return R.clamp(u,0,1)}return function(u){u=R.clamp(u,0,1);let c=d(u);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 R.normalizeRad(-r)},degToRadFlipY(r){return R.angleInvertY(r*Math.PI/180)},minimalAngularDirection(r,e){r=R.normalizeRad(r),e=R.normalizeRad(e);let n=R.normalizeRad(e-r),s=R.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??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=R.clamp(this.elapsed/this.duration,0,1),s=this.easing(n),a=this.delta*s,l=a-this.lastValue;this.lastValue=a,this.emit("delta",l),n>=1&&(this.finished=!0,this.emit("finish",void 0))}},Q=class extends U{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)}},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)}},_=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 Se(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var we=Se(),J=we==="node",E=we==="web",$=class r{static unlock(){E&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=E?new AudioContext:null;static masterGain=E?this.audioCtx.createGain():null;static musicGain=E?this.audioCtx.createGain():null;static sfxGain=E?this.audioCtx.createGain():null;static{E&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,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 z(l);d.buffer=l;let f=1-.12,u=1+.12;d.playbackRate=s??f+Math.random()*(u-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 g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let f=this.getCached(e);if(!f)return;let u=new z(f);u.buffer=f,u.loop=!0,typeof s=="number"&&(u.loopStart=s),typeof a=="number"&&(u.loopEnd=a);let c=this.audioCtx.createGain();c.gain.value=n,u.tempGain=c,u.playbackRate=1,u.onended=()=>{u.disconnect(),c.disconnect()},u.connect(c),c.connect(this.musicGain),u.start(0,d/1e3);let p=++this.loopIdCounter;return this.loops.set(p,{source:u,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:u=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return null;let p=new z(c);p.loop=a,p.loopStart=l,p.loopEnd=typeof d=="number"?d:c.duration,p.playbackRate=s;let g=this.audioCtx.createGain();return g.gain.value=n,p.connect(g),p.tempGain=g,g.connect(u||(f?this.musicGain:this.sfxGain)),p.onended=()=>{p.disconnect(),g.disconnect()},p}catch(c){return console.error("Failed to create LiaAudioSrc:",c),null}}};var z=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=E?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let s=n!==null?n:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-s/this.playbackRate,this.source.start(0,s),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,n=0,s){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-n/this.playbackRate,s!==void 0?this.source.start(this.context.currentTime+e,n,s):this.source.start(this.context.currentTime+e,n),this.pauseTime=n,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let n=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let s=this.loopEnd-this.loopStart;n=this.loopStart+(n-this.loopStart)%s}if(this.isPlaying=!1,e>0){let s=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,s),this.output.gain.linearRampToValueAtTime(0,s+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=n}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let n=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=n,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,n=0,s=0){if("value"in e)this.output.connect(e,n);else return this.output.connect(e,n,s),e}disconnect(e,n,s){e===void 0?this.output.disconnect():this.output.disconnect(e,n,s)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let n=this.context.currentTime+e;this.source.stop(n),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Ie={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},L=class r{constructor(e={}){this.ctx=$.audioCtx,this.cfg=structuredClone(Ie),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,u;a.filter.enabled&&(u=n.createBiquadFilter(),u.type=a.filter.type,u.frequency.value=a.filter.freq,u.Q.value=a.filter.Q,u.connect(l),f=u);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),h=o.getChannelData(0);for(let y=0;y<i;y++)h[y]=(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 g,b;a.lfo.enabled&&c&&(g=n.createOscillator(),g.frequency.value=a.lfo.rate,b=n.createGain(),b.gain.value=a.lfo.depth,g.connect(b),a.lfo.target==="freq"?b.connect(c.frequency):a.lfo.target==="gain"?b.connect(l.gain):a.lfo.target==="filter"&&u&&b.connect(u.frequency),g.start(s),g.stop(s+a.duration)),l.connect(e);let x=[c,p,g,b,u,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))}},tt=new L({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),nt=new L({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),rt=new L({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),it=new L({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),st=new L({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function ce(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 Fe(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function Pe(){return J?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var at=Pe();function Me({width:r,height:e,updateHz:n="frames"}){return new D.KaylaGame(r,e,n==="frames"?1/0:n)}function Ae(r){let e=new j(r);return new D.KaylaScene(e)}function _e(r){return new D.KaylaRenderer(r)}function ee(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+ce(),{type:r,props:n}}var M;(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,u=Math.cos(f),c=Math.sin(f),p=1/0;return u>0&&(p=Math.min(p,(d.right-a.x)/u)),u<0&&(p=Math.min(p,(d.left-a.x)/u)),c>0&&(p=Math.min(p,(d.bottom-a.y)/c)),c<0&&(p=Math.min(p,(d.top-a.y)/c)),_.from(l).scale(p)}s.getCurrToBound=e;function n(a){let{left:l,right:d,top:f,bottom:u,width:c,height:p,x:g=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 g!=null?x=g-c/2:l!=null?x=l:d!=null?x=d-c:x=0;if(f!=null&&u!=null){if(Math.abs(u-f-p)>1e-6)throw new Error("top, bottom, and height mismatch");t=f}else b!=null?t=b-p/2:f!=null?t=f:u!=null?t=u-p:t=0;return{left:x,right:x+c,top:t,bottom:t+p,width:c,height:p,x:x+c/2,y:t+p/2}}s.createRawRect=n})(M||={});var D;(b=>{class r extends Y{#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 W{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(),h=(t-o.left)/o.width,y=(i-o.top)/o.height,w=h*this.viewportWidth*this.cameraWidth/o.width,k=y*this.viewportHeight*this.cameraHeight/o.height;return new _(w,k)}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 de(fe)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let i=de(null);return(i.current===null||i.current===void 0)&&(i.current=t()),i.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let i=this.current;i.onInits[this.current.useInitCallIndex]=t,i.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return V(()=>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 V(()=>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 V(()=>({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 h=this.current.state[this.current.useStateCallIndex]??new a(this.current,t,{alwaysRecall:i});return this.current.state[this.current.useStateCallIndex]=h,this.current.useStateCallIndex++,h}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++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,i){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=i}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;Ce((o,h)=>{let y=i.entity;if(!y)return;let w=y.getRawRect(),k=M.createRawRect({x:o.x,y:o.y,width:3,height:3});M.rawCollision(w,k)&&t(o,h)})}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,...h)=>{let y=t?.fc?.name||"anonymous",w=t?.key?` key=${t.key}`:"";this.logger[i](`${o} <${y}${w}>`,...h)}}}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.
|
|
1
|
+
var Re=Object.defineProperty;var Te=(r,e)=>{for(var n in e)Re(r,n,{get:e[n],enumerable:!0})};var xe={};Te(xe,{JSX:()=>ke,KaylaContext:()=>ee,KaylaFragment:()=>be,KaylaInternals:()=>D,KaylaRect:()=>M,createContext:()=>Ve,createElement:()=>te,createGame:()=>Ae,createReassignableObject:()=>je,createRenderer:()=>Le,createScene:()=>_e,createUseHook:()=>Qe,self:()=>fe,setLogLevel:()=>Ye,useClick:()=>ze,useContext:()=>Be,useCurrentGame:()=>Ne,useCurrentRenderer:()=>Oe,useCurrentScene:()=>Xe,useCurrentTicker:()=>qe,useDisposableRef:()=>We,useEffect:()=>me,useEntity:()=>$e,useExports:()=>se,useFiber:()=>Ee,useFiberControl:()=>ye,useGlobalClick:()=>Ce,useInitialization:()=>ne,useNextStack:()=>ge,usePaint:()=>ie,useRect:()=>re,useRef:()=>pe,useSelf:()=>V,useShouldRefresh:()=>Ge,useState:()=>De,useTick:()=>Ue,useViewportEffect:()=>He});var I=class{#e=new Map;constructor(){this.#e=new Map}on(e,n){let s=this.#e.get(e)||[];return s.push(n),this.#e.set(e,s),this}once(e,n){let s=(...a)=>{this.off(e,s),n(...a)};return this.on(e,s),this}off(e,n){let s=this.#e.get(e);if(!s)return this;let a=s.indexOf(n);return a>=0&&s.splice(a,1),this}emit(e,...n){let s=this.#e.get(e);if(!s||s.length===0){if(e==="error")throw n[0];return!1}return s.slice().forEach(a=>a(...n)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},j=class extends I{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:n,viewportHeight:s,cameraWidth:a,cameraHeight:l}={}){if(!E)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=n??e.width,this.#t=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(),this.emitViewportUpdate()}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(),this.emitViewportUpdate()}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}emitViewportUpdate(){this.emit("viewport_update",{width:this.viewportWidth,height:this.viewportHeight})}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!E)return;let e=performance.now(),n=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=n,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!E||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},ue=class extends I{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),n=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,!(E&&typeof this.__intervalId=="function"&&document.hidden)&&(this.#e+=n*1e3,this.emit("tick",n))}createTimeout(e){return new ce(e,this)}createTween(e,n=()=>{}){let s=new he(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=E&&!isFinite(this.tickInterval)?Fe(()=>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)}},Se;(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("|"),y=parseFloat(o),v=parseFloat(u);if(isNaN(y)||isNaN(v))throw new Error(`Invalid Vector2 string: ${i}`);return new _(y,v)}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 p(i){return Math.round(i)}t.lightWeightRounder=p;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(([y,v])=>v===u)?.[0]??null}}t.createLookup=c;function f(i){let o=i*(180/Math.PI);return Math.round((o%360+360)%360)}t.radToDeg=f;function g(i){return i*(Math.PI/180)}t.degToRad=g,t.angleRadToDeg={mapExport:f,mapImport:g};function x(i=10){let o=d(i);return{mapExport(u){return o.mapExport(f(u))},mapImport(u){return o.mapImport(g(u))}}}t.createLowPrecisionRadToDeg=x})(Se||={});var U=class r extends I{name="";scaleRotate=0;scale=1;constructor(e,n=0,s=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new _(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(!(Z||!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(Z&&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:p}]=l,h=n[a];if(p&&(h=p(h)),typeof d!="string")break;try{Reflect.set(s,d,h)}catch(c){console.error(c)}}return s}},Y=class extends I{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let n of this.entities.values())n.handleUpdate(e)}}handleDraw(e){if(!Z&&!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 U))throw new Error("invalid entity");if(!e.name)throw new Error("Entity must have a name.");this.entities.set(e.name,e)}removeEntity(e){if(!(e instanceof U))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},Q=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 ue(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(p,h,c,f,g){let b=1-p;return b*b*b*h+3*b*b*p*c+3*b*p*p*f+p*p*p*g}function l(p,h,c,f,g){let b=1-p;return 3*b*b*(c-h)+6*b*p*(f-c)+3*p*p*(g-f)}function d(p){let h=p;for(let c=0;c<6;c++){let f=a(h,0,r,n,1),g=l(h,0,r,n,1);if(g===0)break;h-=(f-p)/g}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}},he=class extends I{constructor({delta:e,ms:n,easing:s}){super(),this.delta=e,this.duration=n,this.elapsed=0,this.easing=s??(a=>a),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let n=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))}},J=class extends U{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)}},ce=class extends I{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,n=null){super(),this.duration=e,this.ticker=n,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(s=>this._resolve=s),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,n){return this.promise.then(e,n)}after(e,n){return this.promise.then(e,n)}},_=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 Ie(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var ve=Ie(),Z=ve==="node",E=ve==="web",$=class r{static unlock(){E&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=E?new AudioContext:null;static masterGain=E?this.audioCtx.createGain():null;static musicGain=E?this.audioCtx.createGain():null;static sfxGain=E?this.audioCtx.createGain():null;static{E&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let n=r.CACHE_NAME,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 z(l);d.buffer=l;let p=1-.12,h=1+.12;d.playbackRate=s??p+Math.random()*(h-p);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 g of this.loops.keys())this.stopLoop(g);this.audioBufferCache.has(e)||await this.preLoad(e);let p=this.getCached(e);if(!p)return;let h=new z(p);h.buffer=p,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 f=++this.loopIdCounter;return this.loops.set(f,{source:h,gain:c}),f}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:p=!1,gain:h=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return null;let f=new z(c);f.loop=a,f.loopStart=l,f.loopEnd=typeof d=="number"?d:c.duration,f.playbackRate=s;let g=this.audioCtx.createGain();return g.gain.value=n,f.connect(g),f.tempGain=g,g.connect(h||(p?this.musicGain:this.sfxGain)),f.onended=()=>{f.disconnect(),g.disconnect()},f}catch(c){return console.error("Failed to create LiaAudioSrc:",c),null}}};var z=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=E?n.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:n=null}={}){let 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},Pe={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},L=class r{constructor(e={}){this.ctx=$.audioCtx,this.cfg=structuredClone(Pe),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 p=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),p=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(p),c.start(s),c.stop(s+a.duration+d.release)}let f;if(a.noise.enabled){let i=n.sampleRate*a.duration,o=n.createBuffer(1,i,n.sampleRate),u=o.getChannelData(0);for(let y=0;y<i;y++)u[y]=(Math.random()*2-1)*a.noise.level;f=n.createBufferSource(),f.buffer=o,f.connect(p),f.start(s),f.stop(s+a.duration+d.release)}let g,b;a.lfo.enabled&&c&&(g=n.createOscillator(),g.frequency.value=a.lfo.rate,b=n.createGain(),b.gain.value=a.lfo.depth,g.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),g.start(s),g.stop(s+a.duration)),l.connect(e);let x=[c,f,g,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))}},nt=new L({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),rt=new L({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),it=new L({osc:{enabled:!0,type:"triangle",freq:500,detune:0},pitchEnv:{amount:12,decay:.15},ampEnv:{attack:.01,decay:.12,sustain:0,release:.05,volume:.25},duration:.18}),st=new L({osc:{enabled:!0,type:"sawtooth",freq:1200,detune:0},pitchEnv:{amount:-24,decay:.3},ampEnv:{attack:.005,decay:.25,sustain:0,release:.05,volume:.3},duration:.35}),at=new L({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function de(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 Fe(r){let e=!0;function n(){e&&(r(),requestAnimationFrame(n))}return requestAnimationFrame(n),{clear:()=>e=!1}}function Me(){return Z?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var ot=Me();function Ae({width:r,height:e,updateHz:n="frames"}){return new D.KaylaGame(r,e,n==="frames"?1/0:n)}function _e(r){let e=new Y(r);return new D.KaylaScene(e)}function Le(r){return new D.KaylaRenderer(r)}function te(r,e){if(typeof r!="function")throw new Error("Invalid Element Type.");let n=e??{};return n.key??=r.name+"_"+de(),{type:r,props:n}}var M;(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 p=l*Math.PI/180,h=Math.cos(p),c=Math.sin(p),f=1/0;return h>0&&(f=Math.min(f,(d.right-a.x)/h)),h<0&&(f=Math.min(f,(d.left-a.x)/h)),c>0&&(f=Math.min(f,(d.bottom-a.y)/c)),c<0&&(f=Math.min(f,(d.top-a.y)/c)),_.from(l).scale(f)}s.getCurrToBound=e;function n(a){let{left:l,right:d,top:p,bottom:h,width:c,height:f,x:g=0,y:b=0}=a;if(c===null||f===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 g!=null?x=g-c/2:l!=null?x=l:d!=null?x=d-c:x=0;if(p!=null&&h!=null){if(Math.abs(h-p-f)>1e-6)throw new Error("top, bottom, and height mismatch");t=p}else b!=null?t=b-f/2:p!=null?t=p:h!=null?t=h-f:t=0;return{left:x,right:x+c,top:t,bottom:t+f,width:c,height:f,x:x+c/2,y:t+f/2}}s.createRawRect=n})(M||={});var D;(b=>{class r extends Q{#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 j{game;pointerX;pointerY;pointerEvents;onPointerDown;onPointerUp;onPointerCancel;onPointerMove;constructor(t){super(t),this.useDraw=this.useDraw.bind(this),this.on("draw",i=>{if(this.game)for(let o of this.game.scenes.values())o.handleDraw(i)}),this.pointerX=0,this.pointerY=0,this.pointerEvents=new I,this.pointerPosUpdater=this.pointerPosUpdater.bind(this),this.onPointerDown=i=>this.onPointerAll(i,"down"),this.onPointerUp=i=>this.onPointerAll(i,"up"),this.onPointerCancel=i=>this.onPointerAll(i,"cancel"),this.onPointerMove=i=>this.onPointerAll(i,"move")}pointerPosUpdater(t){this.pointerX=t.clientX,this.pointerY=t.clientY}onPointerAll(t,i){this.pointerPosUpdater(t);let o=e.getClickType(t);if(o!=="invalid"){t.preventDefault();let u=this.getMousePos();this.pointerEvents.emit("action",u,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),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointermove",this.onPointerMove)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.pointerPosUpdater),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointermove",this.onPointerMove)}pointerPosToWorldPos(t,i){let o=this.canvas.getBoundingClientRect(),u=(t-o.left)/o.width,y=(i-o.top)/o.height,v=u*this.viewportWidth*this.cameraWidth/o.width,k=y*this.viewportHeight*this.cameraHeight/o.height;return new _(v,k)}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 pe(fe)}useSelf(t){if(!this.current)throw new Error("Hook 'useSelf' must be executed in the top level scope of a component.");let i=pe(null);return(i.current===null||i.current===void 0)&&(i.current=t()),i.current}useInitialization(t){if(!this.current)throw new Error("Hook 'useInitialization' must be executed in the top level scope of a component.");let i=this.current;i.onInits[this.current.useInitCallIndex]=t,i.useInitCallIndex++}useRect(){if(!this.current)throw new Error("Hook 'useRect' must be executed in the top level scope of a component.");return V(()=>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 V(()=>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 V(()=>({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++}useViewportEffect(t){if(!this.current)throw new Error("Hook 'useViewport' must be executed in the top level scope of a component.");this.current.onViewportEffect[this.current.useViewCallIndex]=t,this.current.useViewCallIndex++}useExports(t,i){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=i}useGlobalClick(t,i){if(!this.current)throw new Error("Hook 'useGlobalClick' must be executed in the top level scope of a component.");i??={},this.current.onGlobalClick[this.current.useGlobalClickCallIndex]={handler:t,config:i},this.current.useGlobalClickCallIndex++}useClick(t,i){if(!this.current)throw new Error("Hook 'useClick' must be executed in the top level scope of a component.");i??={};let o=this.current;Ce((u,y,v)=>{let k=o.entity;if(!k)return;let T=k.getRawRect(),N=M.createRawRect({x:u.x,y:u.y,width:3,height:3});M.rawCollision(T,N)&&t(u,y,v)},i)}useContext(t){if(!this.current)throw new Error("Hook 'useContext' must be executed in the top level scope of a component.");return this.current.findContextValueFromInst(t)}save(){this.saves.push({current:this.current})}restore(){let t=this.saves.pop();if(!t)throw new Error("Cannot restore without saving.");this.current=t.current}logLevel="warn";logger={debug:(...t)=>{this.logLevel==="debug"&&console.debug(...t)},info:(...t)=>{["info","warn","debug"].includes(this.logLevel)&&console.info(...t)},warn:(...t)=>{["warn","debug"].includes(this.logLevel)&&console.warn(...t)},error:(...t)=>console.error(...t),withFiber:(t,i,o,...u)=>{let y=t?.fc?.name||"anonymous",v=t?.key?` key=${t.key}`:"";this.logger[i](`${o} <${y}${v}>`,...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(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 y=Date.now()-this.#n;i&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(i||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}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;dynamicChildren;constructor(t,i,o){if(!o)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=i,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=o.type,this.callProps=o.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalClick=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+ce(),this.onViewportEffect=[]}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)}}resizeHook({width:t,height:i}){try{for(let o of this.onViewportEffect)o(this.getAttachedRenderer(),t,i)}catch(o){this.global.logger.error(o)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("down",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("down",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){return this.callProps.children}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalClick;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let i=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${i} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let o=this.lastChildren.slice(0,this.maxSafeChildren),h=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=o;for(let y of h)y.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,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let o=[];try{let h=this.fc(this.callProps)??[];if(h&&!Array.isArray(h)&&(h=[h]),!Array.isArray(h))throw new Error("Non array or non undefined children received.");for(let y of h)if(y.type===this.fc)throw new Error("Circular Component.");o=h}catch(h){i=h}if(this.global.restore(),this.updateChildren(o,!0),i)throw i}updateChildren(t,i){try{let o=[...t,...this.dynamicChildren],h=[],y=[];for(let w of o){let k=w.props?.key,F;k!=null&&(F=this.lastChildren.find(xe=>xe.key===k)),F||(F=new f(this.global,this.scene,w)),F.detectedParent=this,y.push(F),h.push(F)}for(let w of this.lastChildren)h.includes(w)||w.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let w of this.lastChildren)try{w.refresh()}catch(k){console.error(k)}}catch(o){console.error(o)}}lastChildren;isFirstUse=!0;use(){try{let t=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(t=this.onEffectDeps.some((i,o)=>{let h=this.lastStateDeps.at(o);if(h){let y=i.lastChanged,w=h.stamp;return y>w}})),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let i=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(h=>({stamp:h.lastChanged,stateRef:h}))),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new u(this,this.key);for(let h of this.refs)h.current===fe&&(h.current=this.entity);if(this.callProps.ref instanceof l&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof l&&(this.callProps.exportsRef.current=this.exports),this.entity&&this.entity!==this.entity&&this.global.logger.warn(`Entity name mismatch during refresh <${this.fc?.name} key=${this.key}>`),this.scene.getScene().addEntity(this.entity),i){this.onUnInits=[];for(let h of this.onInits){this.bindEvents();try{let y=h();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let h of this.onUnEffect??[])h()}catch(h){console.error(h)}let o=this.onEffect.map(h=>h()).filter(h=>h!==void 0);this.onUnEffect=o}}catch(t){throw this.global.logger.error(`use() failed <${this.fc?.name||"anonymous"} key=${this.key}>`,t),t}}unuse(){this.global.logger.debug(`unuse called <${this.fc?.name||"anonymous"} key=${this.key}> children=${this.lastChildren.length}`),this.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}}b.KaylaFiber=f;class u extends Q{#e;flags;getRawRect(){return M.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,i){super(i,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,i){return this.flags.set(t,i)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){let i=new s;if(this.#e&&this.#e.onTick)for(let 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=u;class c{#e;constructor(t){this.#e=t}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return M.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=M.createRawRect({x:i.x,y:i.y,width:3,height:3});return M.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 Z=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 te(()=>{s.contextInfo={instance:this,value:e}}),ie(this.Provider,()=>({value:e})),n}Provider;Consumer};function Le(r){return new Z(r)}var m=D.singleGlobalInstance,Ve=m.useState.bind(m),de=m.useRef.bind(m),De=m.useShouldRefresh.bind(m),pe=m.useEffect.bind(m),Ge=m.useViewportEffect.bind(m),Ce=m.useGlobalClick.bind(m),He=m.useClick.bind(m),te=m.useInitialization.bind(m),ne=m.useRect.bind(m),ze=m.useTick.bind(m),re=m.usePaint.bind(m),ie=m.useExports.bind(m),V=m.useSelf.bind(m),me=m.useFiberControl.bind(m),Ee=m.useFiber.bind(m),Ue=m.useEntity.bind(m),$e=m.useCurrentGame.bind(m),Ne=m.useCurrentRenderer.bind(m),Oe=m.useCurrentScene.bind(m),Xe=m.useCurrentTicker.bind(m),qe=m.useContext.bind(m),fe=Symbol("self_ref");var ye=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},ge=({children:r})=>Array.isArray(r)?[...r]:r;function Be(r){return D.createReassignableRef(r)}function We(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 je(r){m.logLevel=r}function Ye(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?V(()=>(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",be);var Qe;(n=>(n.Flex=({align:s="stretch",children:a,direction:l="row",gap:d=0,justify:f="start",wrap:u="nowrap",getHeight:c,getWidth:p,getCenterX:g,getCenterY:b,color:x})=>{let t=me(),i=ne(),o=V(()=>({recalc(){let h=Number(d)||0,y=g(),w=b(),k=p(),F=c();i.x=y,i.y=w,i.width=k,i.height=F;let Re=t.getChildrenEntities().filter(Boolean).map(v=>v.getRect()).filter(v=>v.getFlag("flex-ignored")!==!0),T=l==="row",P=T?i.width:i.height,Ze=T?i.height:i.width,se=0,H=0,ae=[],N=[];Re.forEach(v=>{let O=T?v.width:v.height;se+O>P&&u==="wrap"?(ae.push({height:H,items:N}),N=[v],se=O,H=T?v.height:v.width):(N.push(v),se+=O+h,H=Math.max(H,T?v.height:v.width))}),ae.push({height:H,items:N});let oe=0;ae.forEach((v,O)=>{let I=v.items,A=I.reduce((C,X)=>C+(T?X.width:X.height),0)+h*(I.length-1),K=0;f==="center"&&(K=(P-A)/2),f==="end"&&(K=P-A),f==="space-between"&&(K=0),f==="space-around"&&(K=(P-A)/(I.length*2)),f==="space-evenly"&&(K=(P-A)/(I.length+1)),I.forEach((C,X)=>{C.z=i.z+1;let G=T?C.width:C.height,q=T?C.height:C.width,B=0;s==="center"&&(B=(v.height-q)/2),s==="end"&&(B=v.height-q),s==="stretch"&&(T?C.height=v.height:C.width=v.height),T?(C.x=K+G/2,C.y=oe+B+q/2):(C.x=oe+B+q/2,C.y=K+G/2),f==="space-between"&&X<I.length-1?K+=G+h+(P-A)/(I.length-1):f==="space-around"?K+=G+h+(P-A)/I.length:f==="space-evenly"?K+=G+h+(P-A)/(I.length+1):K+=G+h}),oe+=v.height+h})}}));return re((h,y)=>{y.preventDefault(),h.fillStyle=x,h.fillRect(i.left,i.top,i.width,i.height)}),pe(()=>{ye(()=>{o.recalc()})}),ie(n.Flex,()=>({controls:o})),a},n.GenericBox=({color:s,width:a=20,height:l=20,x:d=0,y:f=0})=>{let u=ne();te(()=>{u.width=a,u.height=l,u.x=d,u.y=f}),re((c,p)=>{p.preventDefault(),c.fillStyle=s,c.fillRect(u.left,u.top,u.width,u.height)})}))(Qe||={});function ft(r,e,...n){if(typeof r=="string")throw new Error("Cannot use intrinsic elements.");return ee(r,{...e,children:e.children??n})}function Je(r,e,...n){if(typeof r=="string")throw new Error("Cannot use intrinsic elements.");return ee(r,{...e,children:e.children??n})}function pt(r,e){return Je(r,e)}var mt=ge;export{mt as Fragment,ft as jsx,pt as jsxDEV,Je 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 y=Date.now()-this.#n;i&&y<67&&this.#t.global.logger.warn(`Hot structural state change <${this.#t.fc?.name||"anonymous"}> delta=${y}ms`),(i||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now()}get value(){return this.#e}get lastChanged(){return this.#n}}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 p{state;refs;global;callProps;scene;exports;detectedParent;contextInfo;get childrenCount(){return this.lastChildren.length}maxSafeChildren;dynamicChildren;constructor(t,i,o){if(!o)throw new Error("Empty element");this.maxSafeChildren=40,this.scene=i,this.state=[],this.refs=[],this.onInits=[],this.onUnInits=[],this.fc=o.type,this.callProps=o.props??{},this.global=t,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[],this.onGlobalClick=[],this.pointerHook=this.pointerHook.bind(this),this.resizeHook=this.resizeHook.bind(this),this.contextInfo=null,this.detectedParent=null,this.dynamicChildren=[],this.key??=this.fc.name+"_"+de(),this.onViewportEffect=[]}getChildrenEntities(){return this.lastChildren.map(t=>t.entity)}pointerHook(t,i,o){try{for(let{handler:u,config:y}of this.onGlobalClick)y.type??="any",y.action??="down",!(y.action!=="any"&&y.action!==o||y.type!=="any"&&y.type!==i)&&u(t,i,o)}catch(u){this.global.logger.error(u)}}resizeHook({width:t,height:i}){try{for(let o of this.onViewportEffect)o(this.getAttachedRenderer(),t,i)}catch(o){this.global.logger.error(o)}}bindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.on("action",this.pointerHook),t.on("viewport_update",this.resizeHook))}unbindEvents(){for(let t of[this.getAttachedRenderer()])t&&(t.pointerEvents.off("action",this.pointerHook),t.off("viewport_update",this.resizeHook))}get key(){return this.callProps.key}set key(t){this.callProps.key=t}get children(){return this.callProps.children}set children(t){this.callProps.children=t}entity;onExport=()=>({});onEffect;onViewportEffect;onGlobalClick;onInits;onUnInits;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useGlobalClickCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;useInitCallIndex=0;useViewCallIndex=0;lastStateDeps;watchedDeps;lastDepStamps=[];getAttachedRenderer(){return this.getAttachedGame().mainRenderer}getAttachedGame(){return this.scene.getGame()}setMaxChildren(t){if(this.maxSafeChildren=Math.max(0,t),this.global.logger.debug(`Max children limit updated to ${t} for <${this.fc?.name||"anonymous"} key=${this.key}>`),this.lastChildren.length>this.maxSafeChildren){let i=this.lastChildren.length-this.maxSafeChildren;this.global.logger.warn(`Child limit exceeded (${this.lastChildren.length} > ${this.maxSafeChildren}) \u2014 removing ${i} oldest children <${this.fc?.name||"anonymous"} key=${this.key}>`);let o=this.lastChildren.slice(0,this.maxSafeChildren),u=this.lastChildren.slice(this.maxSafeChildren);this.lastChildren=o;for(let y of u)y.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,this.useInitCallIndex=0,this.useViewCallIndex=0,this.useStateCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.useGlobalClickCallIndex=0;let o=[];try{let 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 y of u)if(y.type===this.fc)throw new Error("Circular Component.");o=u}catch(u){i=u}if(this.global.restore(),this.updateChildren(o,!0),i)throw i}updateChildren(t,i){try{let o=[...t,...this.dynamicChildren],u=[],y=[];for(let v of o){let k=v.props?.key,T;k!=null&&(T=this.lastChildren.find(N=>N.key===k)),T||(T=new p(this.global,this.scene,v)),T.detectedParent=this,y.push(T),u.push(T)}for(let v of this.lastChildren)u.includes(v)||v.unuse();this.lastChildren=y,this.captureDepStamps(),this.use();for(let v of this.lastChildren)try{v.refresh()}catch(k){console.error(k)}}catch(o){console.error(o)}}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 y=i.lastChanged,v=u.stamp;return y>v}})),t||this.isFirstUse){this.global.logger.debug(`Using <${this.fc?.name||"anonymous"} key=${this.key}> count=${this.onEffect.length}`);let i=this.isFirstUse;this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(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===fe&&(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.onUnInits=[];for(let u of this.onInits){this.bindEvents();try{let y=u();typeof y=="function"&&this.onUnInits.push(y)}catch(y){throw this.global.logger.error("Initialization failed",this.fc?.name||"anonymous",y),y}}}try{for(let 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.detectedParent=null,this.watchedDeps=void 0,this.lastDepStamps=[],this.unbindEvents();try{for(let t of this.onUnInits)t();for(let t of this.onUnEffect)t()}catch(t){this.global.logger.error(`Cleanup failed in unuse <${this.fc?.name||"anonymous"} key=${this.key}>`,t)}this.scene.getScene().removeEntity(this.entity);for(let t of this.lastChildren)t.unuse();this.lastChildren.length=0}}b.KaylaFiber=p;class h extends J{#e;flags;getRawRect(){return M.createRawRect({x:this.x,y:this.y,width:this.width,height:this.height})}getFiber(){return this.#e}constructor(t,i){super(i,0,0,0,0),this.#e=t,this.flags=new Map,this.color="transparent"}setFlag(t,i){return this.flags.set(t,i)}getFlag(t){return this.flags.get(t)}removeFlag(t){return this.flags.delete(t)}update(t){let i=new s;if(this.#e&&this.#e.onTick)for(let 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}get color(){return this.#t(),this.entity.color}set color(t){this.#t(),this.entity.color=t}getRaw(){return M.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=M.createRawRect({x:i.x,y:i.y,width:3,height:3});return M.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 f{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 p(b.singleGlobalInstance,this,t)}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}b.KaylaScene=f,b.singleGlobalInstance=new b.GlobalKayla})(D||={});var ee=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 ne(()=>{s.contextInfo={instance:this,value:e}}),se(this.Provider,()=>({value:e})),n}Provider;Consumer};function Ve(r){return new ee(r)}var m=D.singleGlobalInstance,De=m.useState.bind(m),pe=m.useRef.bind(m),Ge=m.useShouldRefresh.bind(m),me=m.useEffect.bind(m),He=m.useViewportEffect.bind(m),Ce=m.useGlobalClick.bind(m),ze=m.useClick.bind(m),ne=m.useInitialization.bind(m),re=m.useRect.bind(m),Ue=m.useTick.bind(m),ie=m.usePaint.bind(m),se=m.useExports.bind(m),V=m.useSelf.bind(m),ye=m.useFiberControl.bind(m),Ee=m.useFiber.bind(m),$e=m.useEntity.bind(m),Ne=m.useCurrentGame.bind(m),Oe=m.useCurrentRenderer.bind(m),Xe=m.useCurrentScene.bind(m),qe=m.useCurrentTicker.bind(m),Be=m.useContext.bind(m),fe=Symbol("self_ref");var ge=r=>{Promise.resolve(1).then(()=>{try{r()}catch(e){console.error(e)}})},be=({children:r})=>Array.isArray(r)?[...r]:r;function We(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,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 Ye(r){m.logLevel=r}function Qe(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?V(()=>(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' initialized (memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,l))):(a.global.logLevel==="debug"&&a.global.logger.debug(`Custom hook '${e}' running (non-memoized) <${a.fc?.name||"anonymous"} key=${a.key||"no-key"}>`),r.onUse(a,m,l))}}var ke;(e=>e.id="kayla")(ke||={});Reflect.set(globalThis,"Kayla",xe);var Je;(n=>(n.Flex=({align:s="stretch",children:a,direction:l="row",gap:d=0,justify:p="start",wrap:h="nowrap",getHeight:c,getWidth:f,getCenterX:g,getCenterY:b,color:x})=>{let t=ye(),i=re(),o=V(()=>({recalc(){let u=Number(d)||0,y=g(),v=b(),k=f(),T=c();i.x=y,i.y=v,i.width=k,i.height=T;let Ke=t.getChildrenEntities().filter(Boolean).map(w=>w.getRect()).filter(w=>w.getFlag("flex-ignored")!==!0),S=l==="row",F=S?i.width:i.height,et=S?i.height:i.width,ae=0,H=0,oe=[],O=[];Ke.forEach(w=>{let X=S?w.width:w.height;ae+X>F&&h==="wrap"?(oe.push({height:H,items:O}),O=[w],ae=X,H=S?w.height:w.width):(O.push(w),ae+=X+u,H=Math.max(H,S?w.height:w.width))}),oe.push({height:H,items:O});let le=0;oe.forEach((w,X)=>{let P=w.items,A=P.reduce((C,q)=>C+(S?q.width:q.height),0)+u*(P.length-1),R=0;p==="center"&&(R=(F-A)/2),p==="end"&&(R=F-A),p==="space-between"&&(R=0),p==="space-around"&&(R=(F-A)/(P.length*2)),p==="space-evenly"&&(R=(F-A)/(P.length+1)),P.forEach((C,q)=>{C.z=i.z+1;let G=S?C.width:C.height,B=S?C.height:C.width,W=0;s==="center"&&(W=(w.height-B)/2),s==="end"&&(W=w.height-B),s==="stretch"&&(S?C.height=w.height:C.width=w.height),S?(C.x=R+G/2,C.y=le+W+B/2):(C.x=le+W+B/2,C.y=R+G/2),p==="space-between"&&q<P.length-1?R+=G+u+(F-A)/(P.length-1):p==="space-around"?R+=G+u+(F-A)/P.length:p==="space-evenly"?R+=G+u+(F-A)/(P.length+1):R+=G+u}),le+=w.height+u})}}));return ie((u,y)=>{y.preventDefault(),u.fillStyle=x,u.fillRect(i.left,i.top,i.width,i.height)}),me(()=>{ge(()=>{o.recalc()})}),se(n.Flex,()=>({controls:o})),a},n.GenericBox=({color:s,width:a=20,height:l=20,x:d=0,y:p=0})=>{let h=re();ne(()=>{h.width=a,h.height=l,h.x=d,h.y=p}),ie((c,f)=>{f.preventDefault(),c.fillStyle=s,c.fillRect(h.left,h.top,h.width,h.height)})}))(Je||={});function ft(r,e,...n){if(typeof r=="string")throw new Error("Cannot use intrinsic elements.");return te(r,{...e,children:e.children??n})}function Ze(r,e,...n){if(typeof r=="string")throw new Error("Cannot use intrinsic elements.");return te(r,{...e,children:e.children??n})}function mt(r,e){return Ze(r,e)}var yt=be;export{yt as Fragment,ft as jsx,mt as jsxDEV,Ze as jsxs};
|