@kayelaa/canvas 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +397 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +2267 -0
- package/dist/index.d.ts +2267 -0
- package/dist/index.js +1 -0
- package/dist/kayla.cjs +1 -0
- package/dist/kayla.js +1 -0
- package/dist/lea.cjs +1 -0
- package/dist/lea.js +1 -0
- package/package.json +37 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var Ce=Object.defineProperty;var U=(n,e)=>{for(var t in e)Ce(n,t,{get:e[t],enumerable:!0})};var W={};U(W,{DeltaTweenII:()=>G,ENVIRONMENT:()=>B,GEmitterMemory:()=>q,LeaEntityII:()=>K,LeaEventEmitter:()=>w,LeaGameII:()=>A,LeaRendererII:()=>M,LeaSceneII:()=>_,LeaSerializers:()=>Q,LeaTickerII:()=>L,LeaTimeout:()=>N,LeaUtilsII:()=>g,LiaAudio:()=>R,LiaAudioSrc:()=>I,LiaOscSFX:()=>C,LiaSFXMap:()=>ke,NOTE_NAMES:()=>ee,RectLeaEntity:()=>F,Vector2:()=>S,colToRGBA:()=>Se,defaultSFXConfig:()=>te,editRGBA:()=>Ie,generateUUID:()=>oe,getAvoidAngle:()=>ce,getEnvironment:()=>Z,getNormalizedColor:()=>Te,getRayHit:()=>le,isInitiallyMobile:()=>_e,isMobile:()=>he,isNode:()=>V,isNote:()=>Re,isWeb:()=>v,parseFillStyle:()=>J,raycastAvoid:()=>Me,scaleCoord:()=>Ke,setAnimInterval:()=>ue,sfxHit:()=>ae,sfxJump:()=>se,sfxLaser:()=>ie,sfxUIClick:()=>ne,sfxUIHover:()=>re,shortUID:()=>Pe,tinyUID:()=>$});var w=class{#e=new Map;constructor(){this.#e=new Map}on(e,t){let r=this.#e.get(e)||[];return r.push(t),this.#e.set(e,r),this}once(e,t){let r=(...i)=>{this.off(e,r),t(...i)};return this.on(e,r),this}off(e,t){let r=this.#e.get(e);if(!r)return this;let i=r.indexOf(t);return i>=0&&r.splice(i,1),this}emit(e,...t){let r=this.#e.get(e);if(!r||r.length===0){if(e==="error")throw t[0];return!1}return r.slice().forEach(i=>i(...t)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},M=class extends w{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:t,viewportHeight:r,cameraWidth:i,cameraHeight:u}={}){if(!v)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=t??e.width,this.#t=r??e.height,this.#n=i??e.width,this.#r=u??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,t=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,t),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!v)return;let e=performance.now(),t=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=t,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!v||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!v||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},L=class extends w{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),t=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,this.#e+=t*1e3,this.emit("tick",t)}createTimeout(e){return new N(e,this)}createTween(e,t=()=>{}){let r=new G(e),i=(u=0)=>{if(r.finished){this.off("tick",i);return}r.update(u)};return r.on("finish",()=>{this.off("tick",i)}),r.on("delta",u=>{t(u)}),this.on("tick",i),r}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=v&&!isFinite(this.tickInterval)?ue(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,t=0){return .5+.5*Math.sin((this.now()%e/e+t)*2*Math.PI)}},Q;(l=>{function n(f){return f===!0?1:0}l.booleanExport=n;function e(f){return f===0?!1:f===1}l.booleanImport=e;function t(f){return`${f.x}|${f.y}`}l.vec2Export=t;function r(f){let[m,b]=f.split("|"),E=parseFloat(m),D=parseFloat(b);if(isNaN(E)||isNaN(D))throw new Error(`Invalid Vector2 string: ${f}`);return new S(E,D)}l.vec2Import=r,l.booleanMap={mapExport:n,mapImport:e};function u(f){return m=>Number(m.toFixed(f))}l.createRounder=u;function c(f=10){return{mapExport(m){return Math.round(m/f)},mapImport(m){return m*f}}}l.createLowPrecision=c;function h(f){return Math.round(f)}l.lightWeightRounder=h;function a(f=100){return{mapExport(m){return Math.round(m*f)},mapImport(m){return m/f}}}l.createPercent=a;function o(f){let m=new Map(Object.entries(f));return{mapExport:b=>m.get(b)??null,mapImport:b=>Array.from(m.entries()).find(([E,D])=>D===b)?.[0]??null}}l.createLookup=o;function d(f){let m=f*(180/Math.PI);return Math.round((m%360+360)%360)}l.radToDeg=d;function y(f){return f*(Math.PI/180)}l.degToRad=y,l.angleRadToDeg={mapExport:d,mapImport:y};function p(f=10){let m=c(f);return{mapExport(b){return m.mapExport(d(b))},mapImport(b){return m.mapImport(y(b))}}}l.createLowPrecisionRadToDeg=p})(Q||={});var K=class n extends w{name="";scaleRotate=0;scale=1;constructor(e,t=0,r=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new S(t,r),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(t){this.emit("error",t)}}handleDraw(e){if(!(V||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(t){this.emit("error",t)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([i,{mapExport:u}])=>{let c=Reflect.get(this,i);return u?u(c):c});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],t=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(i=>!this.nonSerializableProperties.includes(i)&&!e.includes(i.toString())),r=Object.fromEntries(t.map(i=>{let u=Reflect.get(this,i);if(V&&typeof u=="number"){let c=u.toString().split("."),a=(c[1]?c[1].length:0)>2?Number(u.toFixed(2)):u;return[i,a]}return[i,u]}));return JSON.parse(JSON.stringify(r))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return n.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,t){if(!e||!Array.isArray(t))return t;let r={};for(let i=0;i<t.length;i++){let u=e[i];if(!u)break;let[c,{mapImport:h}]=u,a=t[i];if(h&&(a=h(a)),typeof c!="string")break;try{Reflect.set(r,c,a)}catch(o){console.error(o)}}return r}},_=class extends w{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let t of this.entities.values())t.handleUpdate(e)}}handleDraw(e){if(!V&&!this.paused){this.emit("draw",e);for(let t of[...this.entities.values()].sort((r,i)=>r.z-i.z))t.handleDraw(e)}}addEntity(e){if(!(e instanceof K))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 K))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},A=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,t,r=16){this.ticker=new L(r),this.scenes=new Map,this.width=e,this.height=t,this.ticker.on("tick",i=>{for(let u of this.scenes.values())u.paused||u.handleUpdate(i)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},g={lerp(n,e,t){return n+(e-n)*t},clamp(n,e,t){return Math.min(t,Math.max(e,n))},clamp01(n){return Math.min(1,Math.max(0,n))},easeLinear(n){return n},easeInQuad(n){return n*n},easeOutQuad(n){return 1-(1-n)*(1-n)},easeInOutQuad(n){return n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2},easeInSine(n){return 1-Math.cos(n*Math.PI/2)},easeOutSine(n){return Math.sin(n*Math.PI/2)},easeInOutSine(n){return-(Math.cos(Math.PI*n)-1)/2},easeInExpo(n){return n===0?0:Math.pow(2,10*n-10)},easeOutExpo(n){return n===1?1:1-Math.pow(2,-10*n)},easeInOutExpo(n){return n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2},smoothstep(n){return n=g.clamp(n,0,1),n*n*(3-2*n)},randomLerp(n,e){return g.lerp(n,e,Math.random())},randomInt(n,e){return Math.floor(Math.random()*(e-n+1))+n},randomArrayValue(n){return n[g.randomInt(0,n.length-1)]},createBezier(n,e,t,r){function i(h,a,o,d,y){let s=1-h;return s*s*s*a+3*s*s*h*o+3*s*h*h*d+h*h*h*y}function u(h,a,o,d,y){let s=1-h;return 3*s*s*(o-a)+6*s*h*(d-o)+3*h*h*(y-d)}function c(h){let a=h;for(let o=0;o<6;o++){let d=i(a,0,n,t,1),y=u(a,0,n,t,1);if(y===0)break;a-=(d-h)/y}return g.clamp(a,0,1)}return function(a){a=g.clamp(a,0,1);let o=c(a);return i(o,0,e,r,1)}},lengthSquared(...n){return n.reduce((e,t)=>e+t*t,0)},normalizeRad(n){let e=2*Math.PI;return n=n%e,n<0&&(n+=e),n},angleInvertY(n){return g.normalizeRad(-n)},degToRadFlipY(n){return g.angleInvertY(n*Math.PI/180)},minimalAngularDirection(n,e){n=g.normalizeRad(n),e=g.normalizeRad(e);let t=g.normalizeRad(e-n),r=g.normalizeRad(n-e);return t<=r?1:-1}},G=class extends w{constructor({delta:e,ms:t,easing:r}){super(),this.delta=e,this.duration=t,this.elapsed=0,this.easing=r??(i=>i),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let t=g.clamp(this.elapsed/this.duration,0,1),r=this.easing(t),i=this.delta*r,u=i-this.lastValue;this.lastValue=i,this.emit("delta",u),t>=1&&(this.finished=!0,this.emit("finish",void 0))}},F=class extends K{constructor(e,t=0,r=0,i=50,u=50){super(e,t,r),this.width=i,this.height=u}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},N=class extends w{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,t=null){super(),this.duration=e,this.ticker=t,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(r=>this._resolve=r),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,t){return this.promise.then(e,t)}after(e,t){return this.promise.then(e,t)}},S=class n{constructor(e=0,t=0){this.x=e,this.y=t}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let t=Math.cos(e),r=Math.sin(e);return new n(this.x*t-this.y*r,this.x*r+this.y*t)}static from(e){return new n(Math.cos(e),Math.sin(e))}get angle(){return Math.atan2(this.y,this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new n(0,0):new n(this.x/e,this.y/e)}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let t=this.dot(e);return this.subtract(e.scale(2*t))}dotNormalized(e){let t=this.normalized(),r=e.normalized();return t.x*r.x+t.y*r.y}lengthSquaredTo(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}directionTo(e){return new n(e.x-this.x,e.y-this.y).normalized()}add(e){return new n(this.x+e.x,this.y+e.y)}addRaw(e){return new n(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new n(this.x-e.x,this.y-e.y)}scale(e){return new n(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new n(this.x,this.y)}};function Te(n){let e=/^rgba?\(([^)]+)\)$/,t=n.match(e);if(t){let[r,i,u,c=1]=t[1].split(",").map(h=>parseFloat(h));return{r:Math.max(0,Math.min(255,Math.floor(r))),g:Math.max(0,Math.min(255,Math.floor(i))),b:Math.max(0,Math.min(255,Math.floor(u))),a:Math.max(0,Math.min(1,Math.floor(c*255)/255))}}return J(n)}function Se(n){return`rgba(${n.r}, ${n.g}, ${n.b}, ${n.a})`}function J(n){if(n=n.trim().toLowerCase(),n[0]==="#"){let t,r,i;if(n.length===7)t=parseInt(n.slice(1,3),16),r=parseInt(n.slice(3,5),16),i=parseInt(n.slice(5,7),16);else if(n.length===4)t=parseInt(n[1]+n[1],16),r=parseInt(n[2]+n[2],16),i=parseInt(n[3]+n[3],16);else throw new Error("Invalid hex color");return{r:t,g:r,b:i,a:1}}let e=n.match(/^rgba?\s*\(\s*(\d+)[, ]\s*(\d+)[, ]\s*(\d+)(?:[, ]\s*([\d.]+))?\s*\)$/);if(e)return{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3]),a:e[4]!==void 0?parseFloat(e[4]):1};throw new Error("Unsupported fillStyle format")}function Ie(n,{r:e,g:t,b:r,a:i}={}){let[u,c,h,a,o]=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??c}, ${t??h}, ${r??a}, ${i??(o||1)})`}function Ke(n,e,t){return t+(n-t)*e}function Z(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var B=Z(),V=B==="node",v=B==="web",R=class n{static unlock(){v&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=v?new AudioContext:null;static masterGain=v?this.audioCtx.createGain():null;static musicGain=v?this.audioCtx.createGain():null;static sfxGain=v?this.audioCtx.createGain():null;static{v&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let t=n.CACHE_NAME,r,i;if(typeof caches<"u"&&(i=await caches.open(t),r=await i.match(e)),!r){if(r=await fetch(e),!r.ok)throw new Error(`Failed to fetch ${e}`);i&&await i.put(e,r.clone())}let u=await r.arrayBuffer(),c=await this.audioCtx.decodeAudioData(u);return this.audioBufferCache.set(e,c),c}static async getOnlyDownloadedCache(e){let t=n.CACHE_NAME;return await(await caches.open(t)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,t=.2,r=1,i=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let u=this.getCached(e);if(!u)return;let c=new I(u);c.buffer=u;let h=1-.12,a=1+.12;c.playbackRate=r??h+Math.random()*(a-h);let o=this.audioCtx.createGain();o.gain.value=t,c.tempGain=o,c.connect(o),o.connect(this.sfxGain),c.onended=()=>{c.disconnect(),o.disconnect()},c.start(),i&&this.sfsx.set(e,{source:c,gain:o})}catch(u){console.error(u)}}static async playLoop(e,t=1,{loopStart:r=0,loopEnd:i=null,exclusive:u=!0,skipMS:c=0}={}){if(u)for(let y of this.loops.keys())this.stopLoop(y);this.audioBufferCache.has(e)||await this.preLoad(e);let h=this.getCached(e);if(!h)return;let a=new I(h);a.buffer=h,a.loop=!0,typeof r=="number"&&(a.loopStart=r),typeof i=="number"&&(a.loopEnd=i);let o=this.audioCtx.createGain();o.gain.value=t,a.tempGain=o,a.playbackRate=1,a.onended=()=>{a.disconnect(),o.disconnect()},a.connect(o),o.connect(this.musicGain),a.start(0,c/1e3);let d=++this.loopIdCounter;return this.loops.set(d,{source:a,gain:o}),d}static stopLoop(e){let t=this.loops.get(e);t&&(t.source.stop(),t.source.notIndependent||(t.source.disconnect(),t.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:t=1,speed:r=1,loop:i=!1,loopStart:u=0,loopEnd:c=null,isMusic:h=!1,gain:a=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return null;let d=new I(o);d.loop=i,d.loopStart=u,d.loopEnd=typeof c=="number"?c:o.duration,d.playbackRate=r;let y=this.audioCtx.createGain();return y.gain.value=t,d.connect(y),d.tempGain=y,y.connect(a||(h?this.musicGain:this.sfxGain)),d.onended=()=>{d.disconnect(),y.disconnect()},d}catch(o){return console.error("Failed to create LiaAudioSrc:",o),null}}},ee=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function Re(n){return ee.includes(n)}var I=class{numberOfInputs;numberOfOutputs;constructor(e,t=R.audioCtx){this.context=t,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=v?t.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:t=null}={}){let r=t!==null?t:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-r/this.playbackRate,this.source.start(0,r),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,t=0,r){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-t/this.playbackRate,r!==void 0?this.source.start(this.context.currentTime+e,t,r):this.source.start(this.context.currentTime+e,t),this.pauseTime=t,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let t=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let r=this.loopEnd-this.loopStart;t=this.loopStart+(t-this.loopStart)%r}if(this.isPlaying=!1,e>0){let r=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,r),this.output.gain.linearRampToValueAtTime(0,r+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let t=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=t,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,t=0,r=0){if("value"in e)this.output.connect(e,t);else return this.output.connect(e,t,r),e}disconnect(e,t,r){e===void 0?this.output.disconnect():this.output.disconnect(e,t,r)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let t=this.context.currentTime+e;this.source.stop(t),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},te={osc:{enabled:!0,type:"sine",freq:440,detune:0},noise:{enabled:!1,level:.5},ampEnv:{attack:.005,decay:.1,sustain:0,release:.1,volume:.3},pitchEnv:{amount:0,decay:.2},filter:{enabled:!1,type:"lowpass",freq:1200,Q:1,envAmount:0,decay:.2},lfo:{enabled:!1,target:"freq",rate:8,depth:20},duration:.4},C=class n{constructor(e={}){this.ctx=R.audioCtx,this.cfg=structuredClone(te),Object.assign(this.cfg,e)}ctx;cfg;play(e=R.sfxGain){let t=this.ctx,r=t.currentTime,i=this.cfg,u=t.createGain();u.gain.setValueAtTime(1e-4,r);let c=i.ampEnv;u.gain.exponentialRampToValueAtTime(c.volume,r+c.attack),u.gain.exponentialRampToValueAtTime(Math.max(1e-4,c.sustain*c.volume),r+c.attack+c.decay),u.gain.exponentialRampToValueAtTime(1e-4,r+i.duration+c.release);let h=u,a;i.filter.enabled&&(a=t.createBiquadFilter(),a.type=i.filter.type,a.frequency.value=i.filter.freq,a.Q.value=i.filter.Q,a.connect(u),h=a);let o;if(i.osc.enabled){if(o=t.createOscillator(),o.type=i.osc.type,o.frequency.value=i.osc.freq,o.detune.value=i.osc.detune,i.pitchEnv.amount!==0){let f=Math.pow(2,i.pitchEnv.amount/12);o.frequency.exponentialRampToValueAtTime(i.osc.freq*f,r+i.pitchEnv.decay)}o.connect(h),o.start(r),o.stop(r+i.duration+c.release)}let d;if(i.noise.enabled){let f=t.sampleRate*i.duration,m=t.createBuffer(1,f,t.sampleRate),b=m.getChannelData(0);for(let E=0;E<f;E++)b[E]=(Math.random()*2-1)*i.noise.level;d=t.createBufferSource(),d.buffer=m,d.connect(h),d.start(r),d.stop(r+i.duration+c.release)}let y,s;i.lfo.enabled&&o&&(y=t.createOscillator(),y.frequency.value=i.lfo.rate,s=t.createGain(),s.gain.value=i.lfo.depth,y.connect(s),i.lfo.target==="freq"?s.connect(o.frequency):i.lfo.target==="gain"?s.connect(u.gain):i.lfo.target==="filter"&&a&&s.connect(a.frequency),y.start(r),y.stop(r+i.duration)),u.connect(e);let p=[o,d,y,s,a,u],l=r+i.duration+c.release;setTimeout(()=>{p.forEach(f=>f?.disconnect())},(l-t.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,t){return Object.assign(this.cfg[e],t),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,t,r,i){return Object.assign(this.cfg.ampEnv,{attack:e,decay:t,sustain:r,release:i}),this}setPitchEnv(e,t){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:t}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,t,r){return Object.assign(this.cfg.filter,{type:e,freq:t,Q:r,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,t,r){return Object.assign(this.cfg.lfo,{target:e,rate:t,depth:r,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new n(structuredClone(this.cfg))}},ne=new C({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),re=new C({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),se=new C({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}),ie=new C({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}),ae=new C({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}),ke=new Map([["ui_click",ne],["ui_hover",re],["jump",se],["laser",ie],["hit",ae]]);function Pe(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(n)),r=Array.from(t).map(i=>i.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}function $(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(4)),r=Array.from(t).map(i=>i.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}var q=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${oe()}_${Date.now()}`}connect(e){e&&(this.peer=e,e.peer=this,this.connected=!0,e.connected=!0),this._emit("open")}isConnected(){return this.connected&&!!this.peer}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(r=>r!==t))}_emit(e,t){this.events[e]?.forEach(r=>r(t))}send(e,t){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,t)}_receive(e,t){e?this._emit(e,t):this._emit("message",t)}close(){if(this.connected=!1,this.peer){let e=this.peer;this.peer=null,e.peer=null,e.connected=!1,e._emit("close")}this._emit("close")}getKey(){return this.key}};function oe(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let n=new Uint8Array(16);return crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,[...n].map(e=>e.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5")}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function ue(n){let e=!0;function t(){e&&(n(),requestAnimationFrame(t))}return requestAnimationFrame(t),{clear:()=>e=!1}}function le(n,e,t,r,i){let u=Math.cos(i),c=Math.sin(i),h=[];if(u!==0){let a=(0-n)/u,o=e+a*c;a>0&&o>=0&&o<=r&&h.push({side:"left",t:a})}if(u!==0){let a=(t-n)/u,o=e+a*c;a>0&&o>=0&&o<=r&&h.push({side:"right",t:a})}if(c!==0){let a=(0-e)/c,o=n+a*u;a>0&&o>=0&&o<=t&&h.push({side:"top",t:a})}if(c!==0){let a=(r-e)/c,o=n+a*u;a>0&&o>=0&&o<=t&&h.push({side:"bottom",t:a})}return h.length===0?null:(h.sort((a,o)=>a.t-o.t),h[0])}function ce(n,e){let t;switch(e){case"left":case"right":t=Math.PI-n;break;case"top":case"bottom":t=2*Math.PI-n;break}return(t%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function Me(n,e,t,r,i){let u=le(n,e,t,r,i);return u?{...u,avoidAngle:ce(i,u.side)}:null}function he(){return V?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var _e=he();var Y={};U(Y,{Kayla:()=>X,KaylaFragment:()=>ve,KaylaInternals:()=>T,UI:()=>we,createElement:()=>me,createGame:()=>pe,createRenderer:()=>de,createScene:()=>fe,self:()=>P,useDisposableRef:()=>Ee,useEffect:()=>O,useEntity:()=>ge,useExports:()=>be,useNextStack:()=>j,usePaint:()=>H,useRef:()=>k,useSelf:()=>xe,useState:()=>z,useTick:()=>ye});var X={};U(X,{KaylaFragment:()=>ve,KaylaInternals:()=>T,createElement:()=>me,createGame:()=>pe,createRenderer:()=>de,createScene:()=>fe,self:()=>P,useDisposableRef:()=>Ee,useEffect:()=>O,useEntity:()=>ge,useExports:()=>be,useNextStack:()=>j,usePaint:()=>H,useRef:()=>k,useSelf:()=>xe,useState:()=>z,useTick:()=>ye});function pe({width:n,height:e,updateHz:t="frames"}){return new T.KaylaGame(n,e,t==="frames"?1/0:t)}function fe(n){let e=new _(n);return new T.KaylaScene(e)}function de(n){return new T.KaylaRenderer(n)}function me(n,e){return{type:n,props:e}}var T;(d=>{class n extends A{#e;#t;constructor(s,p,l){super(s,p,l),this.#e=new Set,this.#t=!1}get started(){return this.#t}start(){if(!this.#t){for(let s of this.#e)s.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let s of this.#e)s.stop();this.#t=!1,super.stop()}}addRenderer(s){this.#e.has(s)||(this.#e.add(s),this.#t&&s.start(),s.game=this)}deleteRenderer(s){this.#e.has(s)&&(this.#e.delete(s),this.#t&&s.stop(),delete s.game)}}d.KaylaGame=n;class e extends M{game;pointerX;pointerY;#e;constructor(s){super(s),this.useDraw=this.useDraw.bind(this),this.on("draw",p=>{if(this.game)for(let l of this.game.scenes.values())l.handleDraw(p)}),this.pointerX=0,this.pointerY=0,this.#e=this.#t.bind(this)}#t(s){this.pointerX=s.clientX,this.pointerY=s.clientY}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.#e)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.#e)}pointerPosToWorldPos(s,p){let l=this.canvas.getBoundingClientRect(),f=(s-l.left)/l.width,m=(p-l.top)/l.height,b=f*this.viewportWidth*this.cameraWidth/l.width,E=m*this.viewportHeight*this.cameraHeight/l.height;return new S(b,E)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(s){let p=l=>{s(l,new r)};return this.on("draw",p),()=>{this.off("draw",p)}}attachTo(s){s.addRenderer(this),this.game=s}detach(){this.game&&this.game.deleteRenderer(this)}}d.KaylaRenderer=e;class t{current;saves;constructor(){this.saves=[]}useTick(s){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]=s,this.current.useStepCallIndex++}usePaint(s){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]=s,this.current.useDrawCallIndex++}useEntity(){return k(P)}useSelf(s){let p=k(null);return(p.current===null||p.current===void 0)&&(p.current=s()),p.current}useState(s,{alwaysRecall:p=!1}={}){if(!this.current)throw new Error("Hook 'useState' must be executed in the top level scope of a component.");let f=this.current.state[this.current.useStateCallIndex]??new i(this.current,s,{alwaysRecall:p});return this.current.state[this.current.useStateCallIndex]=f,this.current.useStateCallIndex++,f}useRef(s){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let l=this.current.refs[this.current.useRefCallIndex]??new u(this.current,s??null);return this.current.refs[this.current.useRefCallIndex]=l,this.current.useRefCallIndex++,l}useEffect(s){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]=s,this.current.useEffectCallIndex++}useExports(s,p){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=p}save(){this.saves.push({current:this.current})}restore(){let s=this.saves.pop();if(!s)throw new Error("Cannot restore without saving.");this.current=s.current}}d.GlobalKayla=t;class r{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}d.KaylaEvent=r;class i{#e;#t;#n;alwaysRecall;constructor(s,p,{alwaysRecall:l=!1}={}){this.#t=s,this.#e=p??void 0,this.#n=Date.now(),this.alwaysRecall=l}get(){return this.#e}add(s,{recall:p}={}){this.set(this.get()+s,{recall:p})}multiply(s,{recall:p}={}){this.set(this.get()*s,{recall:p})}set(s,{recall:p=!1}={}){let l=this.#e;s!==l&&(this.#e=s,(p||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now())}get value(){return this.#e}get lastChanged(){return this.#n}}d.KaylaState=i;class u{#e;#t;constructor(s,p){this.#t=s,this.#e=p??void 0}get current(){return this.#e}set current(s){this.#e=s}}d.KaylaRef=u;class c{state;refs;global;callProps;scene;exports;constructor(s,p,l){if(!l)throw new Error("Empty element");this.scene=p,this.state=[],this.refs=[],this.fc=l.type,this.callProps=l.props??{},this.global=s,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[]}get key(){return this.callProps.key}set key(s){this.callProps.key=s}get children(){return this.callProps.children}set children(s){this.callProps.children=s}entity;onExport=()=>({});onEffect;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;lastStateDeps;refresh(){let s;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0;let p=[];try{let l=this.fc(this.callProps)??[];if(l&&!Array.isArray(l)&&(l=[l]),!Array.isArray(l))throw new Error("Non array or non undefined children received.");p=l}catch(l){s=l}this.useStateCallIndex=0,this.useRefCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.global.restore();try{let l=0,f=[];for(let m of p){let b=this.lastChildren.at(l)??new c(this.global,this.scene,m);this.lastChildren[l]=b,f.push(b),l++}for(let m of this.lastChildren.filter(b=>!f.includes(b))){let b=this.lastChildren.indexOf(m);b!==1&&this.lastChildren.splice(b,1),m.unuse()}for(let m of this.lastChildren)try{m.refresh()}catch(b){console.error(b)}j(()=>{this.use()})}catch(l){console.error(l)}if(s)throw s}lastChildren;isFirstUse=!0;use(){try{let s=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(s=this.onEffectDeps.some((p,l)=>{let f=this.lastStateDeps.at(l);if(f){let m=p.lastChanged,b=f.stamp;return m>b}})),s||this.isFirstUse){this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(l=>({stamp:l.lastChanged,stateRef:l}))),this.key??=this.fc.name+"_"+$(),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 l of this.refs)l.current===P&&(l.current=this.entity);this.callProps.ref instanceof u&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof u&&(this.callProps.exportsRef.current=this.exports),this.scene.getScene().addEntity(this.entity);let p=this.onEffect.map(l=>l()).filter(l=>l!==void 0);this.onUnEffect=p}}catch(s){throw s}}unuse(){try{for(let s of this.onUnEffect)s()}catch(s){console.error(s)}this.scene.getScene().removeEntity(this.entity)}}d.KaylaInternalComponent=c;class h extends F{#e;constructor(s,p){super(p,0,0,0,0),this.#e=s}update(s){let p=new r;if(this.#e.onTick)for(let l of this.#e.onTick)l(s,p);p.isPrevented()}draw(s){let p=new r;if(this.#e.onPaint)for(let l of this.#e.onPaint)l(s,p);p.isPrevented()||super.draw(s)}}d.KaylaRectEntity=h;class a{constructor(s){this.#t=s,this.#e=null,s.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getScene(){return this.#t}drawHandler(s){return this.#t.handleDraw(s)}attachTo(s){s.addScene(this.#t),this.#e=s}spawn(s){new c(d.singleGlobalInstance,this,s).refresh()}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}d.KaylaScene=a,d.singleGlobalInstance=new d.GlobalKayla})(T||={});var x=T.singleGlobalInstance,z=x.useState.bind(x),k=x.useRef.bind(x),O=x.useEffect.bind(x),ye=x.useTick.bind(x),H=x.usePaint.bind(x),be=x.useExports.bind(x),xe=x.useSelf.bind(x),ge=x.useEntity.bind(x),P=Symbol("self_ref");var j=n=>{Promise.resolve(1).then(()=>n())},ve=({children:n})=>Array.isArray(n)?[...n]:n;function Ee(n){return new T.KaylaRef(null,n)}Reflect.set(globalThis,"Kayla",X);var we;(e=>e.UIComponent=({x:t,y:r,width:i,height:u,children:c})=>{let h=k(P),a=z(!1);return O(()=>{if(a.get()===!0)return;a.set(!0);let o=h.current;o.width=i,o.height=u,o.x=t,o.y=r}),H(o=>{o.fillStyle="rgba(0, 0, 0, 0.5)",o.fillRect(t,r,i,u)}),c??[]})(we||={});var De={LEA:W,Kayla:Y};export{Y as Kayla,W as LEA,De as default};
|
package/dist/kayla.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var O=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var ue=Object.prototype.hasOwnProperty;var B=(n,e)=>{for(var t in e)O(n,t,{get:e[t],enumerable:!0})},le=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of oe(e))!ue.call(n,i)&&i!==t&&O(n,i,{get:()=>e[i],enumerable:!(r=ae(e,i))||r.enumerable});return n};var ce=n=>le(O({},"__esModule",{value:!0}),n);var ye={};B(ye,{Kayla:()=>z,KaylaFragment:()=>re,KaylaInternals:()=>C,UI:()=>ie,createElement:()=>J,createGame:()=>j,createRenderer:()=>Q,createScene:()=>Y,self:()=>K,useDisposableRef:()=>se,useEffect:()=>G,useEntity:()=>ne,useExports:()=>ee,useNextStack:()=>q,usePaint:()=>N,useRef:()=>I,useSelf:()=>te,useState:()=>L,useTick:()=>Z});module.exports=ce(ye);var z={};B(z,{KaylaFragment:()=>re,KaylaInternals:()=>C,createElement:()=>J,createGame:()=>j,createRenderer:()=>Q,createScene:()=>Y,self:()=>K,useDisposableRef:()=>se,useEffect:()=>G,useEntity:()=>ne,useExports:()=>ee,useNextStack:()=>q,usePaint:()=>N,useRef:()=>I,useSelf:()=>te,useState:()=>L,useTick:()=>Z});var w=class{#e=new Map;constructor(){this.#e=new Map}on(e,t){let r=this.#e.get(e)||[];return r.push(t),this.#e.set(e,r),this}once(e,t){let r=(...i)=>{this.off(e,r),t(...i)};return this.on(e,r),this}off(e,t){let r=this.#e.get(e);if(!r)return this;let i=r.indexOf(t);return i>=0&&r.splice(i,1),this}emit(e,...t){let r=this.#e.get(e);if(!r||r.length===0){if(e==="error")throw t[0];return!1}return r.slice().forEach(i=>i(...t)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},_=class extends w{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:t,viewportHeight:r,cameraWidth:i,cameraHeight:o}={}){if(!v)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=t??e.width,this.#t=r??e.height,this.#n=i??e.width,this.#r=o??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,t=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,t),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!v)return;let e=performance.now(),t=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=t,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!v||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!v||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},H=class extends w{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),t=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,this.#e+=t*1e3,this.emit("tick",t)}createTimeout(e){return new U(e,this)}createTween(e,t=()=>{}){let r=new X(e),i=(o=0)=>{if(r.finished){this.off("tick",i);return}r.update(o)};return r.on("finish",()=>{this.off("tick",i)}),r.on("delta",o=>{t(o)}),this.on("tick",i),r}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=v&&!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,t=0){return .5+.5*Math.sin((this.now()%e/e+t)*2*Math.PI)}},he;(a=>{function n(h){return h===!0?1:0}a.booleanExport=n;function e(h){return h===0?!1:h===1}a.booleanImport=e;function t(h){return`${h.x}|${h.y}`}a.vec2Export=t;function r(h){let[m,b]=h.split("|"),E=parseFloat(m),M=parseFloat(b);if(isNaN(E)||isNaN(M))throw new Error(`Invalid Vector2 string: ${h}`);return new S(E,M)}a.vec2Import=r,a.booleanMap={mapExport:n,mapImport:e};function o(h){return m=>Number(m.toFixed(h))}a.createRounder=o;function p(h=10){return{mapExport(m){return Math.round(m/h)},mapImport(m){return m*h}}}a.createLowPrecision=p;function d(h){return Math.round(h)}a.lightWeightRounder=d;function l(h=100){return{mapExport(m){return Math.round(m*h)},mapImport(m){return m/h}}}a.createPercent=l;function u(h){let m=new Map(Object.entries(h));return{mapExport:b=>m.get(b)??null,mapImport:b=>Array.from(m.entries()).find(([E,M])=>M===b)?.[0]??null}}a.createLookup=u;function f(h){let m=h*(180/Math.PI);return Math.round((m%360+360)%360)}a.radToDeg=f;function y(h){return h*(Math.PI/180)}a.degToRad=y,a.angleRadToDeg={mapExport:f,mapImport:y};function c(h=10){let m=p(h);return{mapExport(b){return m.mapExport(f(b))},mapImport(b){return m.mapImport(y(b))}}}a.createLowPrecisionRadToDeg=c})(he||={});var k=class n extends w{name="";scaleRotate=0;scale=1;constructor(e,t=0,r=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new S(t,r),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(t){this.emit("error",t)}}handleDraw(e){if(!(D||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(t){this.emit("error",t)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([i,{mapExport:o}])=>{let p=Reflect.get(this,i);return o?o(p):p});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],t=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(i=>!this.nonSerializableProperties.includes(i)&&!e.includes(i.toString())),r=Object.fromEntries(t.map(i=>{let o=Reflect.get(this,i);if(D&&typeof o=="number"){let p=o.toString().split("."),l=(p[1]?p[1].length:0)>2?Number(o.toFixed(2)):o;return[i,l]}return[i,o]}));return JSON.parse(JSON.stringify(r))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return n.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,t){if(!e||!Array.isArray(t))return t;let r={};for(let i=0;i<t.length;i++){let o=e[i];if(!o)break;let[p,{mapImport:d}]=o,l=t[i];if(d&&(l=d(l)),typeof p!="string")break;try{Reflect.set(r,p,l)}catch(u){console.error(u)}}return r}},A=class extends w{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let t of this.entities.values())t.handleUpdate(e)}}handleDraw(e){if(!D&&!this.paused){this.emit("draw",e);for(let t of[...this.entities.values()].sort((r,i)=>r.z-i.z))t.handleDraw(e)}}addEntity(e){if(!(e instanceof k))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 k))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},F=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,t,r=16){this.ticker=new H(r),this.scenes=new Map,this.width=e,this.height=t,this.ticker.on("tick",i=>{for(let o of this.scenes.values())o.paused||o.handleUpdate(i)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},g={lerp(n,e,t){return n+(e-n)*t},clamp(n,e,t){return Math.min(t,Math.max(e,n))},clamp01(n){return Math.min(1,Math.max(0,n))},easeLinear(n){return n},easeInQuad(n){return n*n},easeOutQuad(n){return 1-(1-n)*(1-n)},easeInOutQuad(n){return n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2},easeInSine(n){return 1-Math.cos(n*Math.PI/2)},easeOutSine(n){return Math.sin(n*Math.PI/2)},easeInOutSine(n){return-(Math.cos(Math.PI*n)-1)/2},easeInExpo(n){return n===0?0:Math.pow(2,10*n-10)},easeOutExpo(n){return n===1?1:1-Math.pow(2,-10*n)},easeInOutExpo(n){return n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2},smoothstep(n){return n=g.clamp(n,0,1),n*n*(3-2*n)},randomLerp(n,e){return g.lerp(n,e,Math.random())},randomInt(n,e){return Math.floor(Math.random()*(e-n+1))+n},randomArrayValue(n){return n[g.randomInt(0,n.length-1)]},createBezier(n,e,t,r){function i(d,l,u,f,y){let s=1-d;return s*s*s*l+3*s*s*d*u+3*s*d*d*f+d*d*d*y}function o(d,l,u,f,y){let s=1-d;return 3*s*s*(u-l)+6*s*d*(f-u)+3*d*d*(y-f)}function p(d){let l=d;for(let u=0;u<6;u++){let f=i(l,0,n,t,1),y=o(l,0,n,t,1);if(y===0)break;l-=(f-d)/y}return g.clamp(l,0,1)}return function(l){l=g.clamp(l,0,1);let u=p(l);return i(u,0,e,r,1)}},lengthSquared(...n){return n.reduce((e,t)=>e+t*t,0)},normalizeRad(n){let e=2*Math.PI;return n=n%e,n<0&&(n+=e),n},angleInvertY(n){return g.normalizeRad(-n)},degToRadFlipY(n){return g.angleInvertY(n*Math.PI/180)},minimalAngularDirection(n,e){n=g.normalizeRad(n),e=g.normalizeRad(e);let t=g.normalizeRad(e-n),r=g.normalizeRad(n-e);return t<=r?1:-1}},X=class extends w{constructor({delta:e,ms:t,easing:r}){super(),this.delta=e,this.duration=t,this.elapsed=0,this.easing=r??(i=>i),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let t=g.clamp(this.elapsed/this.duration,0,1),r=this.easing(t),i=this.delta*r,o=i-this.lastValue;this.lastValue=i,this.emit("delta",o),t>=1&&(this.finished=!0,this.emit("finish",void 0))}},V=class extends k{constructor(e,t=0,r=0,i=50,o=50){super(e,t,r),this.width=i,this.height=o}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},U=class extends w{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,t=null){super(),this.duration=e,this.ticker=t,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(r=>this._resolve=r),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,t){return this.promise.then(e,t)}after(e,t){return this.promise.then(e,t)}},S=class n{constructor(e=0,t=0){this.x=e,this.y=t}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let t=Math.cos(e),r=Math.sin(e);return new n(this.x*t-this.y*r,this.x*r+this.y*t)}static from(e){return new n(Math.cos(e),Math.sin(e))}get angle(){return Math.atan2(this.y,this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new n(0,0):new n(this.x/e,this.y/e)}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let t=this.dot(e);return this.subtract(e.scale(2*t))}dotNormalized(e){let t=this.normalized(),r=e.normalized();return t.x*r.x+t.y*r.y}lengthSquaredTo(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}directionTo(e){return new n(e.x-this.x,e.y-this.y).normalized()}add(e){return new n(this.x+e.x,this.y+e.y)}addRaw(e){return new n(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new n(this.x-e.x,this.y-e.y)}scale(e){return new n(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new n(this.x,this.y)}};function pe(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var $=pe(),D=$==="node",v=$==="web",P=class n{static unlock(){v&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=v?new AudioContext:null;static masterGain=v?this.audioCtx.createGain():null;static musicGain=v?this.audioCtx.createGain():null;static sfxGain=v?this.audioCtx.createGain():null;static{v&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let t=n.CACHE_NAME,r,i;if(typeof caches<"u"&&(i=await caches.open(t),r=await i.match(e)),!r){if(r=await fetch(e),!r.ok)throw new Error(`Failed to fetch ${e}`);i&&await i.put(e,r.clone())}let o=await r.arrayBuffer(),p=await this.audioCtx.decodeAudioData(o);return this.audioBufferCache.set(e,p),p}static async getOnlyDownloadedCache(e){let t=n.CACHE_NAME;return await(await caches.open(t)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,t=.2,r=1,i=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return;let p=new R(o);p.buffer=o;let d=1-.12,l=1+.12;p.playbackRate=r??d+Math.random()*(l-d);let u=this.audioCtx.createGain();u.gain.value=t,p.tempGain=u,p.connect(u),u.connect(this.sfxGain),p.onended=()=>{p.disconnect(),u.disconnect()},p.start(),i&&this.sfsx.set(e,{source:p,gain:u})}catch(o){console.error(o)}}static async playLoop(e,t=1,{loopStart:r=0,loopEnd:i=null,exclusive:o=!0,skipMS:p=0}={}){if(o)for(let y of this.loops.keys())this.stopLoop(y);this.audioBufferCache.has(e)||await this.preLoad(e);let d=this.getCached(e);if(!d)return;let l=new R(d);l.buffer=d,l.loop=!0,typeof r=="number"&&(l.loopStart=r),typeof i=="number"&&(l.loopEnd=i);let u=this.audioCtx.createGain();u.gain.value=t,l.tempGain=u,l.playbackRate=1,l.onended=()=>{l.disconnect(),u.disconnect()},l.connect(u),u.connect(this.musicGain),l.start(0,p/1e3);let f=++this.loopIdCounter;return this.loops.set(f,{source:l,gain:u}),f}static stopLoop(e){let t=this.loops.get(e);t&&(t.source.stop(),t.source.notIndependent||(t.source.disconnect(),t.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:t=1,speed:r=1,loop:i=!1,loopStart:o=0,loopEnd:p=null,isMusic:d=!1,gain:l=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let u=this.getCached(e);if(!u)return null;let f=new R(u);f.loop=i,f.loopStart=o,f.loopEnd=typeof p=="number"?p:u.duration,f.playbackRate=r;let y=this.audioCtx.createGain();return y.gain.value=t,f.connect(y),f.tempGain=y,y.connect(l||(d?this.musicGain:this.sfxGain)),f.onended=()=>{f.disconnect(),y.disconnect()},f}catch(u){return console.error("Failed to create LiaAudioSrc:",u),null}}};var R=class{numberOfInputs;numberOfOutputs;constructor(e,t=P.audioCtx){this.context=t,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=v?t.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:t=null}={}){let r=t!==null?t:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-r/this.playbackRate,this.source.start(0,r),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,t=0,r){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-t/this.playbackRate,r!==void 0?this.source.start(this.context.currentTime+e,t,r):this.source.start(this.context.currentTime+e,t),this.pauseTime=t,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let t=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let r=this.loopEnd-this.loopStart;t=this.loopStart+(t-this.loopStart)%r}if(this.isPlaying=!1,e>0){let r=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,r),this.output.gain.linearRampToValueAtTime(0,r+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let t=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=t,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,t=0,r=0){if("value"in e)this.output.connect(e,t);else return this.output.connect(e,t,r),e}disconnect(e,t,r){e===void 0?this.output.disconnect():this.output.disconnect(e,t,r)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let t=this.context.currentTime+e;this.source.stop(t),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},de={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},T=class n{constructor(e={}){this.ctx=P.audioCtx,this.cfg=structuredClone(de),Object.assign(this.cfg,e)}ctx;cfg;play(e=P.sfxGain){let t=this.ctx,r=t.currentTime,i=this.cfg,o=t.createGain();o.gain.setValueAtTime(1e-4,r);let p=i.ampEnv;o.gain.exponentialRampToValueAtTime(p.volume,r+p.attack),o.gain.exponentialRampToValueAtTime(Math.max(1e-4,p.sustain*p.volume),r+p.attack+p.decay),o.gain.exponentialRampToValueAtTime(1e-4,r+i.duration+p.release);let d=o,l;i.filter.enabled&&(l=t.createBiquadFilter(),l.type=i.filter.type,l.frequency.value=i.filter.freq,l.Q.value=i.filter.Q,l.connect(o),d=l);let u;if(i.osc.enabled){if(u=t.createOscillator(),u.type=i.osc.type,u.frequency.value=i.osc.freq,u.detune.value=i.osc.detune,i.pitchEnv.amount!==0){let h=Math.pow(2,i.pitchEnv.amount/12);u.frequency.exponentialRampToValueAtTime(i.osc.freq*h,r+i.pitchEnv.decay)}u.connect(d),u.start(r),u.stop(r+i.duration+p.release)}let f;if(i.noise.enabled){let h=t.sampleRate*i.duration,m=t.createBuffer(1,h,t.sampleRate),b=m.getChannelData(0);for(let E=0;E<h;E++)b[E]=(Math.random()*2-1)*i.noise.level;f=t.createBufferSource(),f.buffer=m,f.connect(d),f.start(r),f.stop(r+i.duration+p.release)}let y,s;i.lfo.enabled&&u&&(y=t.createOscillator(),y.frequency.value=i.lfo.rate,s=t.createGain(),s.gain.value=i.lfo.depth,y.connect(s),i.lfo.target==="freq"?s.connect(u.frequency):i.lfo.target==="gain"?s.connect(o.gain):i.lfo.target==="filter"&&l&&s.connect(l.frequency),y.start(r),y.stop(r+i.duration)),o.connect(e);let c=[u,f,y,s,l,o],a=r+i.duration+p.release;setTimeout(()=>{c.forEach(h=>h?.disconnect())},(a-t.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,t){return Object.assign(this.cfg[e],t),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,t,r,i){return Object.assign(this.cfg.ampEnv,{attack:e,decay:t,sustain:r,release:i}),this}setPitchEnv(e,t){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:t}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,t,r){return Object.assign(this.cfg.filter,{type:e,freq:t,Q:r,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,t,r){return Object.assign(this.cfg.lfo,{target:e,rate:t,depth:r,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new n(structuredClone(this.cfg))}},xe=new T({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),ge=new T({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),ve=new T({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}),Ee=new T({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}),we=new T({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 W(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(4)),r=Array.from(t).map(i=>i.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}function fe(n){let e=!0;function t(){e&&(n(),requestAnimationFrame(t))}return requestAnimationFrame(t),{clear:()=>e=!1}}function me(){return D?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var Ce=me();function j({width:n,height:e,updateHz:t="frames"}){return new C.KaylaGame(n,e,t==="frames"?1/0:t)}function Y(n){let e=new A(n);return new C.KaylaScene(e)}function Q(n){return new C.KaylaRenderer(n)}function J(n,e){return{type:n,props:e}}var C;(f=>{class n extends F{#e;#t;constructor(s,c,a){super(s,c,a),this.#e=new Set,this.#t=!1}get started(){return this.#t}start(){if(!this.#t){for(let s of this.#e)s.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let s of this.#e)s.stop();this.#t=!1,super.stop()}}addRenderer(s){this.#e.has(s)||(this.#e.add(s),this.#t&&s.start(),s.game=this)}deleteRenderer(s){this.#e.has(s)&&(this.#e.delete(s),this.#t&&s.stop(),delete s.game)}}f.KaylaGame=n;class e extends _{game;pointerX;pointerY;#e;constructor(s){super(s),this.useDraw=this.useDraw.bind(this),this.on("draw",c=>{if(this.game)for(let a of this.game.scenes.values())a.handleDraw(c)}),this.pointerX=0,this.pointerY=0,this.#e=this.#t.bind(this)}#t(s){this.pointerX=s.clientX,this.pointerY=s.clientY}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.#e)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.#e)}pointerPosToWorldPos(s,c){let a=this.canvas.getBoundingClientRect(),h=(s-a.left)/a.width,m=(c-a.top)/a.height,b=h*this.viewportWidth*this.cameraWidth/a.width,E=m*this.viewportHeight*this.cameraHeight/a.height;return new S(b,E)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(s){let c=a=>{s(a,new r)};return this.on("draw",c),()=>{this.off("draw",c)}}attachTo(s){s.addRenderer(this),this.game=s}detach(){this.game&&this.game.deleteRenderer(this)}}f.KaylaRenderer=e;class t{current;saves;constructor(){this.saves=[]}useTick(s){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]=s,this.current.useStepCallIndex++}usePaint(s){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]=s,this.current.useDrawCallIndex++}useEntity(){return I(K)}useSelf(s){let c=I(null);return(c.current===null||c.current===void 0)&&(c.current=s()),c.current}useState(s,{alwaysRecall:c=!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 i(this.current,s,{alwaysRecall:c});return this.current.state[this.current.useStateCallIndex]=h,this.current.useStateCallIndex++,h}useRef(s){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let a=this.current.refs[this.current.useRefCallIndex]??new o(this.current,s??null);return this.current.refs[this.current.useRefCallIndex]=a,this.current.useRefCallIndex++,a}useEffect(s){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]=s,this.current.useEffectCallIndex++}useExports(s,c){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=c}save(){this.saves.push({current:this.current})}restore(){let s=this.saves.pop();if(!s)throw new Error("Cannot restore without saving.");this.current=s.current}}f.GlobalKayla=t;class r{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}f.KaylaEvent=r;class i{#e;#t;#n;alwaysRecall;constructor(s,c,{alwaysRecall:a=!1}={}){this.#t=s,this.#e=c??void 0,this.#n=Date.now(),this.alwaysRecall=a}get(){return this.#e}add(s,{recall:c}={}){this.set(this.get()+s,{recall:c})}multiply(s,{recall:c}={}){this.set(this.get()*s,{recall:c})}set(s,{recall:c=!1}={}){let a=this.#e;s!==a&&(this.#e=s,(c||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now())}get value(){return this.#e}get lastChanged(){return this.#n}}f.KaylaState=i;class o{#e;#t;constructor(s,c){this.#t=s,this.#e=c??void 0}get current(){return this.#e}set current(s){this.#e=s}}f.KaylaRef=o;class p{state;refs;global;callProps;scene;exports;constructor(s,c,a){if(!a)throw new Error("Empty element");this.scene=c,this.state=[],this.refs=[],this.fc=a.type,this.callProps=a.props??{},this.global=s,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[]}get key(){return this.callProps.key}set key(s){this.callProps.key=s}get children(){return this.callProps.children}set children(s){this.callProps.children=s}entity;onExport=()=>({});onEffect;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;lastStateDeps;refresh(){let s;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0;let c=[];try{let a=this.fc(this.callProps)??[];if(a&&!Array.isArray(a)&&(a=[a]),!Array.isArray(a))throw new Error("Non array or non undefined children received.");c=a}catch(a){s=a}this.useStateCallIndex=0,this.useRefCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.global.restore();try{let a=0,h=[];for(let m of c){let b=this.lastChildren.at(a)??new p(this.global,this.scene,m);this.lastChildren[a]=b,h.push(b),a++}for(let m of this.lastChildren.filter(b=>!h.includes(b))){let b=this.lastChildren.indexOf(m);b!==1&&this.lastChildren.splice(b,1),m.unuse()}for(let m of this.lastChildren)try{m.refresh()}catch(b){console.error(b)}q(()=>{this.use()})}catch(a){console.error(a)}if(s)throw s}lastChildren;isFirstUse=!0;use(){try{let s=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(s=this.onEffectDeps.some((c,a)=>{let h=this.lastStateDeps.at(a);if(h){let m=c.lastChanged,b=h.stamp;return m>b}})),s||this.isFirstUse){this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(a=>({stamp:a.lastChanged,stateRef:a}))),this.key??=this.fc.name+"_"+W(),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new d(this,this.key);for(let a of this.refs)a.current===K&&(a.current=this.entity);this.callProps.ref instanceof o&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof o&&(this.callProps.exportsRef.current=this.exports),this.scene.getScene().addEntity(this.entity);let c=this.onEffect.map(a=>a()).filter(a=>a!==void 0);this.onUnEffect=c}}catch(s){throw s}}unuse(){try{for(let s of this.onUnEffect)s()}catch(s){console.error(s)}this.scene.getScene().removeEntity(this.entity)}}f.KaylaInternalComponent=p;class d extends V{#e;constructor(s,c){super(c,0,0,0,0),this.#e=s}update(s){let c=new r;if(this.#e.onTick)for(let a of this.#e.onTick)a(s,c);c.isPrevented()}draw(s){let c=new r;if(this.#e.onPaint)for(let a of this.#e.onPaint)a(s,c);c.isPrevented()||super.draw(s)}}f.KaylaRectEntity=d;class l{constructor(s){this.#t=s,this.#e=null,s.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getScene(){return this.#t}drawHandler(s){return this.#t.handleDraw(s)}attachTo(s){s.addScene(this.#t),this.#e=s}spawn(s){new p(f.singleGlobalInstance,this,s).refresh()}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}f.KaylaScene=l,f.singleGlobalInstance=new f.GlobalKayla})(C||={});var x=C.singleGlobalInstance,L=x.useState.bind(x),I=x.useRef.bind(x),G=x.useEffect.bind(x),Z=x.useTick.bind(x),N=x.usePaint.bind(x),ee=x.useExports.bind(x),te=x.useSelf.bind(x),ne=x.useEntity.bind(x),K=Symbol("self_ref");var q=n=>{Promise.resolve(1).then(()=>n())},re=({children:n})=>Array.isArray(n)?[...n]:n;function se(n){return new C.KaylaRef(null,n)}Reflect.set(globalThis,"Kayla",z);var ie;(e=>e.UIComponent=({x:t,y:r,width:i,height:o,children:p})=>{let d=I(K),l=L(!1);return G(()=>{if(l.get()===!0)return;l.set(!0);let u=d.current;u.width=i,u.height=o,u.x=t,u.y=r}),N(u=>{u.fillStyle="rgba(0, 0, 0, 0.5)",u.fillRect(t,r,i,o)}),p??[]})(ie||={});0&&(module.exports={Kayla,KaylaFragment,KaylaInternals,UI,createElement,createGame,createRenderer,createScene,self,useDisposableRef,useEffect,useEntity,useExports,useNextStack,usePaint,useRef,useSelf,useState,useTick});
|
package/dist/kayla.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var $=Object.defineProperty;var W=(n,e)=>{for(var t in e)$(n,t,{get:e[t],enumerable:!0})};var X={};W(X,{KaylaFragment:()=>ue,KaylaInternals:()=>T,createElement:()=>re,createGame:()=>ee,createRenderer:()=>ne,createScene:()=>te,self:()=>P,useDisposableRef:()=>le,useEffect:()=>O,useEntity:()=>oe,useExports:()=>ie,useNextStack:()=>B,usePaint:()=>H,useRef:()=>k,useSelf:()=>ae,useState:()=>z,useTick:()=>se});var w=class{#e=new Map;constructor(){this.#e=new Map}on(e,t){let r=this.#e.get(e)||[];return r.push(t),this.#e.set(e,r),this}once(e,t){let r=(...i)=>{this.off(e,r),t(...i)};return this.on(e,r),this}off(e,t){let r=this.#e.get(e);if(!r)return this;let i=r.indexOf(t);return i>=0&&r.splice(i,1),this}emit(e,...t){let r=this.#e.get(e);if(!r||r.length===0){if(e==="error")throw t[0];return!1}return r.slice().forEach(i=>i(...t)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},_=class extends w{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:t,viewportHeight:r,cameraWidth:i,cameraHeight:o}={}){if(!v)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=t??e.width,this.#t=r??e.height,this.#n=i??e.width,this.#r=o??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,t=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,t),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!v)return;let e=performance.now(),t=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=t,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!v||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!v||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},L=class extends w{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),t=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,this.#e+=t*1e3,this.emit("tick",t)}createTimeout(e){return new N(e,this)}createTween(e,t=()=>{}){let r=new G(e),i=(o=0)=>{if(r.finished){this.off("tick",i);return}r.update(o)};return r.on("finish",()=>{this.off("tick",i)}),r.on("delta",o=>{t(o)}),this.on("tick",i),r}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=v&&!isFinite(this.tickInterval)?J(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,t=0){return .5+.5*Math.sin((this.now()%e/e+t)*2*Math.PI)}},j;(a=>{function n(h){return h===!0?1:0}a.booleanExport=n;function e(h){return h===0?!1:h===1}a.booleanImport=e;function t(h){return`${h.x}|${h.y}`}a.vec2Export=t;function r(h){let[m,b]=h.split("|"),E=parseFloat(m),M=parseFloat(b);if(isNaN(E)||isNaN(M))throw new Error(`Invalid Vector2 string: ${h}`);return new S(E,M)}a.vec2Import=r,a.booleanMap={mapExport:n,mapImport:e};function o(h){return m=>Number(m.toFixed(h))}a.createRounder=o;function p(h=10){return{mapExport(m){return Math.round(m/h)},mapImport(m){return m*h}}}a.createLowPrecision=p;function d(h){return Math.round(h)}a.lightWeightRounder=d;function l(h=100){return{mapExport(m){return Math.round(m*h)},mapImport(m){return m/h}}}a.createPercent=l;function u(h){let m=new Map(Object.entries(h));return{mapExport:b=>m.get(b)??null,mapImport:b=>Array.from(m.entries()).find(([E,M])=>M===b)?.[0]??null}}a.createLookup=u;function f(h){let m=h*(180/Math.PI);return Math.round((m%360+360)%360)}a.radToDeg=f;function y(h){return h*(Math.PI/180)}a.degToRad=y,a.angleRadToDeg={mapExport:f,mapImport:y};function c(h=10){let m=p(h);return{mapExport(b){return m.mapExport(f(b))},mapImport(b){return m.mapImport(y(b))}}}a.createLowPrecisionRadToDeg=c})(j||={});var K=class n extends w{name="";scaleRotate=0;scale=1;constructor(e,t=0,r=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new S(t,r),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(t){this.emit("error",t)}}handleDraw(e){if(!(D||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(t){this.emit("error",t)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([i,{mapExport:o}])=>{let p=Reflect.get(this,i);return o?o(p):p});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],t=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(i=>!this.nonSerializableProperties.includes(i)&&!e.includes(i.toString())),r=Object.fromEntries(t.map(i=>{let o=Reflect.get(this,i);if(D&&typeof o=="number"){let p=o.toString().split("."),l=(p[1]?p[1].length:0)>2?Number(o.toFixed(2)):o;return[i,l]}return[i,o]}));return JSON.parse(JSON.stringify(r))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return n.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,t){if(!e||!Array.isArray(t))return t;let r={};for(let i=0;i<t.length;i++){let o=e[i];if(!o)break;let[p,{mapImport:d}]=o,l=t[i];if(d&&(l=d(l)),typeof p!="string")break;try{Reflect.set(r,p,l)}catch(u){console.error(u)}}return r}},A=class extends w{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let t of this.entities.values())t.handleUpdate(e)}}handleDraw(e){if(!D&&!this.paused){this.emit("draw",e);for(let t of[...this.entities.values()].sort((r,i)=>r.z-i.z))t.handleDraw(e)}}addEntity(e){if(!(e instanceof K))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 K))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},F=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,t,r=16){this.ticker=new L(r),this.scenes=new Map,this.width=e,this.height=t,this.ticker.on("tick",i=>{for(let o of this.scenes.values())o.paused||o.handleUpdate(i)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},g={lerp(n,e,t){return n+(e-n)*t},clamp(n,e,t){return Math.min(t,Math.max(e,n))},clamp01(n){return Math.min(1,Math.max(0,n))},easeLinear(n){return n},easeInQuad(n){return n*n},easeOutQuad(n){return 1-(1-n)*(1-n)},easeInOutQuad(n){return n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2},easeInSine(n){return 1-Math.cos(n*Math.PI/2)},easeOutSine(n){return Math.sin(n*Math.PI/2)},easeInOutSine(n){return-(Math.cos(Math.PI*n)-1)/2},easeInExpo(n){return n===0?0:Math.pow(2,10*n-10)},easeOutExpo(n){return n===1?1:1-Math.pow(2,-10*n)},easeInOutExpo(n){return n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2},smoothstep(n){return n=g.clamp(n,0,1),n*n*(3-2*n)},randomLerp(n,e){return g.lerp(n,e,Math.random())},randomInt(n,e){return Math.floor(Math.random()*(e-n+1))+n},randomArrayValue(n){return n[g.randomInt(0,n.length-1)]},createBezier(n,e,t,r){function i(d,l,u,f,y){let s=1-d;return s*s*s*l+3*s*s*d*u+3*s*d*d*f+d*d*d*y}function o(d,l,u,f,y){let s=1-d;return 3*s*s*(u-l)+6*s*d*(f-u)+3*d*d*(y-f)}function p(d){let l=d;for(let u=0;u<6;u++){let f=i(l,0,n,t,1),y=o(l,0,n,t,1);if(y===0)break;l-=(f-d)/y}return g.clamp(l,0,1)}return function(l){l=g.clamp(l,0,1);let u=p(l);return i(u,0,e,r,1)}},lengthSquared(...n){return n.reduce((e,t)=>e+t*t,0)},normalizeRad(n){let e=2*Math.PI;return n=n%e,n<0&&(n+=e),n},angleInvertY(n){return g.normalizeRad(-n)},degToRadFlipY(n){return g.angleInvertY(n*Math.PI/180)},minimalAngularDirection(n,e){n=g.normalizeRad(n),e=g.normalizeRad(e);let t=g.normalizeRad(e-n),r=g.normalizeRad(n-e);return t<=r?1:-1}},G=class extends w{constructor({delta:e,ms:t,easing:r}){super(),this.delta=e,this.duration=t,this.elapsed=0,this.easing=r??(i=>i),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let t=g.clamp(this.elapsed/this.duration,0,1),r=this.easing(t),i=this.delta*r,o=i-this.lastValue;this.lastValue=i,this.emit("delta",o),t>=1&&(this.finished=!0,this.emit("finish",void 0))}},V=class extends K{constructor(e,t=0,r=0,i=50,o=50){super(e,t,r),this.width=i,this.height=o}width;height;get left(){return this.x-this.width/2}set left(e){this.x=e+this.width/2}get right(){return this.x+this.width/2}set right(e){this.x=e-this.width/2}get top(){return this.y-this.height/2}set top(e){this.y=e+this.height/2}get bottom(){return this.y+this.height/2}set bottom(e){this.y=e-this.height/2}get lx(){return 0}get ly(){return 0}get lleft(){return-this.width/2}get lright(){return this.width/2}get ltop(){return-this.height/2}get lbottom(){return this.height/2}isCollidingWith(e){return!(this.right<e.left||this.left>e.right||this.bottom<e.top||this.top>e.bottom)}color="rgba(0, 0, 255, 0.3)";draw(e){e.translate(this.x,this.y),e.rotate(this.scaleRotate),e.fillStyle=this.color,e.fillRect(-this.width/2,-this.height/2,this.width,this.height)}},N=class extends w{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,t=null){super(),this.duration=e,this.ticker=t,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(r=>this._resolve=r),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,t){return this.promise.then(e,t)}after(e,t){return this.promise.then(e,t)}},S=class n{constructor(e=0,t=0){this.x=e,this.y=t}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let t=Math.cos(e),r=Math.sin(e);return new n(this.x*t-this.y*r,this.x*r+this.y*t)}static from(e){return new n(Math.cos(e),Math.sin(e))}get angle(){return Math.atan2(this.y,this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new n(0,0):new n(this.x/e,this.y/e)}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let t=this.dot(e);return this.subtract(e.scale(2*t))}dotNormalized(e){let t=this.normalized(),r=e.normalized();return t.x*r.x+t.y*r.y}lengthSquaredTo(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}directionTo(e){return new n(e.x-this.x,e.y-this.y).normalized()}add(e){return new n(this.x+e.x,this.y+e.y)}addRaw(e){return new n(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new n(this.x-e.x,this.y-e.y)}scale(e){return new n(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new n(this.x,this.y)}};function Y(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var U=Y(),D=U==="node",v=U==="web",R=class n{static unlock(){v&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=v?new AudioContext:null;static masterGain=v?this.audioCtx.createGain():null;static musicGain=v?this.audioCtx.createGain():null;static sfxGain=v?this.audioCtx.createGain():null;static{v&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let t=n.CACHE_NAME,r,i;if(typeof caches<"u"&&(i=await caches.open(t),r=await i.match(e)),!r){if(r=await fetch(e),!r.ok)throw new Error(`Failed to fetch ${e}`);i&&await i.put(e,r.clone())}let o=await r.arrayBuffer(),p=await this.audioCtx.decodeAudioData(o);return this.audioBufferCache.set(e,p),p}static async getOnlyDownloadedCache(e){let t=n.CACHE_NAME;return await(await caches.open(t)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,t=.2,r=1,i=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return;let p=new I(o);p.buffer=o;let d=1-.12,l=1+.12;p.playbackRate=r??d+Math.random()*(l-d);let u=this.audioCtx.createGain();u.gain.value=t,p.tempGain=u,p.connect(u),u.connect(this.sfxGain),p.onended=()=>{p.disconnect(),u.disconnect()},p.start(),i&&this.sfsx.set(e,{source:p,gain:u})}catch(o){console.error(o)}}static async playLoop(e,t=1,{loopStart:r=0,loopEnd:i=null,exclusive:o=!0,skipMS:p=0}={}){if(o)for(let y of this.loops.keys())this.stopLoop(y);this.audioBufferCache.has(e)||await this.preLoad(e);let d=this.getCached(e);if(!d)return;let l=new I(d);l.buffer=d,l.loop=!0,typeof r=="number"&&(l.loopStart=r),typeof i=="number"&&(l.loopEnd=i);let u=this.audioCtx.createGain();u.gain.value=t,l.tempGain=u,l.playbackRate=1,l.onended=()=>{l.disconnect(),u.disconnect()},l.connect(u),u.connect(this.musicGain),l.start(0,p/1e3);let f=++this.loopIdCounter;return this.loops.set(f,{source:l,gain:u}),f}static stopLoop(e){let t=this.loops.get(e);t&&(t.source.stop(),t.source.notIndependent||(t.source.disconnect(),t.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:t=1,speed:r=1,loop:i=!1,loopStart:o=0,loopEnd:p=null,isMusic:d=!1,gain:l=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let u=this.getCached(e);if(!u)return null;let f=new I(u);f.loop=i,f.loopStart=o,f.loopEnd=typeof p=="number"?p:u.duration,f.playbackRate=r;let y=this.audioCtx.createGain();return y.gain.value=t,f.connect(y),f.tempGain=y,y.connect(l||(d?this.musicGain:this.sfxGain)),f.onended=()=>{f.disconnect(),y.disconnect()},f}catch(u){return console.error("Failed to create LiaAudioSrc:",u),null}}};var I=class{numberOfInputs;numberOfOutputs;constructor(e,t=R.audioCtx){this.context=t,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=v?t.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:t=null}={}){let r=t!==null?t:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-r/this.playbackRate,this.source.start(0,r),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,t=0,r){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-t/this.playbackRate,r!==void 0?this.source.start(this.context.currentTime+e,t,r):this.source.start(this.context.currentTime+e,t),this.pauseTime=t,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let t=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let r=this.loopEnd-this.loopStart;t=this.loopStart+(t-this.loopStart)%r}if(this.isPlaying=!1,e>0){let r=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,r),this.output.gain.linearRampToValueAtTime(0,r+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let t=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=t,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,t=0,r=0){if("value"in e)this.output.connect(e,t);else return this.output.connect(e,t,r),e}disconnect(e,t,r){e===void 0?this.output.disconnect():this.output.disconnect(e,t,r)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let t=this.context.currentTime+e;this.source.stop(t),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},Q={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},C=class n{constructor(e={}){this.ctx=R.audioCtx,this.cfg=structuredClone(Q),Object.assign(this.cfg,e)}ctx;cfg;play(e=R.sfxGain){let t=this.ctx,r=t.currentTime,i=this.cfg,o=t.createGain();o.gain.setValueAtTime(1e-4,r);let p=i.ampEnv;o.gain.exponentialRampToValueAtTime(p.volume,r+p.attack),o.gain.exponentialRampToValueAtTime(Math.max(1e-4,p.sustain*p.volume),r+p.attack+p.decay),o.gain.exponentialRampToValueAtTime(1e-4,r+i.duration+p.release);let d=o,l;i.filter.enabled&&(l=t.createBiquadFilter(),l.type=i.filter.type,l.frequency.value=i.filter.freq,l.Q.value=i.filter.Q,l.connect(o),d=l);let u;if(i.osc.enabled){if(u=t.createOscillator(),u.type=i.osc.type,u.frequency.value=i.osc.freq,u.detune.value=i.osc.detune,i.pitchEnv.amount!==0){let h=Math.pow(2,i.pitchEnv.amount/12);u.frequency.exponentialRampToValueAtTime(i.osc.freq*h,r+i.pitchEnv.decay)}u.connect(d),u.start(r),u.stop(r+i.duration+p.release)}let f;if(i.noise.enabled){let h=t.sampleRate*i.duration,m=t.createBuffer(1,h,t.sampleRate),b=m.getChannelData(0);for(let E=0;E<h;E++)b[E]=(Math.random()*2-1)*i.noise.level;f=t.createBufferSource(),f.buffer=m,f.connect(d),f.start(r),f.stop(r+i.duration+p.release)}let y,s;i.lfo.enabled&&u&&(y=t.createOscillator(),y.frequency.value=i.lfo.rate,s=t.createGain(),s.gain.value=i.lfo.depth,y.connect(s),i.lfo.target==="freq"?s.connect(u.frequency):i.lfo.target==="gain"?s.connect(o.gain):i.lfo.target==="filter"&&l&&s.connect(l.frequency),y.start(r),y.stop(r+i.duration)),o.connect(e);let c=[u,f,y,s,l,o],a=r+i.duration+p.release;setTimeout(()=>{c.forEach(h=>h?.disconnect())},(a-t.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,t){return Object.assign(this.cfg[e],t),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,t,r,i){return Object.assign(this.cfg.ampEnv,{attack:e,decay:t,sustain:r,release:i}),this}setPitchEnv(e,t){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:t}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,t,r){return Object.assign(this.cfg.filter,{type:e,freq:t,Q:r,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,t,r){return Object.assign(this.cfg.lfo,{target:e,rate:t,depth:r,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new n(structuredClone(this.cfg))}},pe=new C({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),de=new C({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),fe=new C({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}),me=new C({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}),ye=new C({osc:{enabled:!0,type:"square",freq:180,detune:0},noise:{enabled:!0,level:.4},ampEnv:{attack:.002,decay:.15,sustain:0,release:.05,volume:.35},duration:.2});function q(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(4)),r=Array.from(t).map(i=>i.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}function J(n){let e=!0;function t(){e&&(n(),requestAnimationFrame(t))}return requestAnimationFrame(t),{clear:()=>e=!1}}function Z(){return D?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var be=Z();function ee({width:n,height:e,updateHz:t="frames"}){return new T.KaylaGame(n,e,t==="frames"?1/0:t)}function te(n){let e=new A(n);return new T.KaylaScene(e)}function ne(n){return new T.KaylaRenderer(n)}function re(n,e){return{type:n,props:e}}var T;(f=>{class n extends F{#e;#t;constructor(s,c,a){super(s,c,a),this.#e=new Set,this.#t=!1}get started(){return this.#t}start(){if(!this.#t){for(let s of this.#e)s.start();this.#t=!0,super.start()}}stop(){if(this.#t){for(let s of this.#e)s.stop();this.#t=!1,super.stop()}}addRenderer(s){this.#e.has(s)||(this.#e.add(s),this.#t&&s.start(),s.game=this)}deleteRenderer(s){this.#e.has(s)&&(this.#e.delete(s),this.#t&&s.stop(),delete s.game)}}f.KaylaGame=n;class e extends _{game;pointerX;pointerY;#e;constructor(s){super(s),this.useDraw=this.useDraw.bind(this),this.on("draw",c=>{if(this.game)for(let a of this.game.scenes.values())a.handleDraw(c)}),this.pointerX=0,this.pointerY=0,this.#e=this.#t.bind(this)}#t(s){this.pointerX=s.clientX,this.pointerY=s.clientY}listenPointerUpdates(){this.canvas.addEventListener("pointermove",this.#e)}unlistenPointerUpdates(){this.canvas.removeEventListener("pointermove",this.#e)}pointerPosToWorldPos(s,c){let a=this.canvas.getBoundingClientRect(),h=(s-a.left)/a.width,m=(c-a.top)/a.height,b=h*this.viewportWidth*this.cameraWidth/a.width,E=m*this.viewportHeight*this.cameraHeight/a.height;return new S(b,E)}getMousePos(){return this.pointerPosToWorldPos(this.pointerX,this.pointerY)}useDraw(s){let c=a=>{s(a,new r)};return this.on("draw",c),()=>{this.off("draw",c)}}attachTo(s){s.addRenderer(this),this.game=s}detach(){this.game&&this.game.deleteRenderer(this)}}f.KaylaRenderer=e;class t{current;saves;constructor(){this.saves=[]}useTick(s){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]=s,this.current.useStepCallIndex++}usePaint(s){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]=s,this.current.useDrawCallIndex++}useEntity(){return k(P)}useSelf(s){let c=k(null);return(c.current===null||c.current===void 0)&&(c.current=s()),c.current}useState(s,{alwaysRecall:c=!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 i(this.current,s,{alwaysRecall:c});return this.current.state[this.current.useStateCallIndex]=h,this.current.useStateCallIndex++,h}useRef(s){if(!this.current)throw new Error("Hook 'useRef' must be executed in the top level scope of a component.");let a=this.current.refs[this.current.useRefCallIndex]??new o(this.current,s??null);return this.current.refs[this.current.useRefCallIndex]=a,this.current.useRefCallIndex++,a}useEffect(s){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]=s,this.current.useEffectCallIndex++}useExports(s,c){if(!this.current)throw new Error("Hook 'useExports' must be executed in the top level scope of a component.");this.current.onExport=c}save(){this.saves.push({current:this.current})}restore(){let s=this.saves.pop();if(!s)throw new Error("Cannot restore without saving.");this.current=s.current}}f.GlobalKayla=t;class r{preventDefault(){this.#e=!0}#e=!1;isPrevented(){return this.#e}}f.KaylaEvent=r;class i{#e;#t;#n;alwaysRecall;constructor(s,c,{alwaysRecall:a=!1}={}){this.#t=s,this.#e=c??void 0,this.#n=Date.now(),this.alwaysRecall=a}get(){return this.#e}add(s,{recall:c}={}){this.set(this.get()+s,{recall:c})}multiply(s,{recall:c}={}){this.set(this.get()*s,{recall:c})}set(s,{recall:c=!1}={}){let a=this.#e;s!==a&&(this.#e=s,(c||this.alwaysRecall)&&this.#t.refresh(),this.#n=Date.now())}get value(){return this.#e}get lastChanged(){return this.#n}}f.KaylaState=i;class o{#e;#t;constructor(s,c){this.#t=s,this.#e=c??void 0}get current(){return this.#e}set current(s){this.#e=s}}f.KaylaRef=o;class p{state;refs;global;callProps;scene;exports;constructor(s,c,a){if(!a)throw new Error("Empty element");this.scene=c,this.state=[],this.refs=[],this.fc=a.type,this.callProps=a.props??{},this.global=s,this.lastStateDeps=[],this.entity=null,this.lastChildren=[],this.onEffect=[],this.onUnEffect=[],this.onPaint=[],this.onTick=[]}get key(){return this.callProps.key}set key(s){this.callProps.key=s}get children(){return this.callProps.children}set children(s){this.callProps.children=s}entity;onExport=()=>({});onEffect;onUnEffect;onEffectDeps;onPaint;onTick;fc;useStateCallIndex=0;useEffectCallIndex=0;useDrawCallIndex=0;useStepCallIndex=0;useRefCallIndex=0;lastStateDeps;refresh(){let s;this.global.save(),this.global.current=this,this.useStateCallIndex=0,this.useRefCallIndex=0;let c=[];try{let a=this.fc(this.callProps)??[];if(a&&!Array.isArray(a)&&(a=[a]),!Array.isArray(a))throw new Error("Non array or non undefined children received.");c=a}catch(a){s=a}this.useStateCallIndex=0,this.useRefCallIndex=0,this.useDrawCallIndex=0,this.useStepCallIndex=0,this.useEffectCallIndex=0,this.global.restore();try{let a=0,h=[];for(let m of c){let b=this.lastChildren.at(a)??new p(this.global,this.scene,m);this.lastChildren[a]=b,h.push(b),a++}for(let m of this.lastChildren.filter(b=>!h.includes(b))){let b=this.lastChildren.indexOf(m);b!==1&&this.lastChildren.splice(b,1),m.unuse()}for(let m of this.lastChildren)try{m.refresh()}catch(b){console.error(b)}B(()=>{this.use()})}catch(a){console.error(a)}if(s)throw s}lastChildren;isFirstUse=!0;use(){try{let s=!0;if(this.lastStateDeps??=[],Array.isArray(this.onEffectDeps)&&(s=this.onEffectDeps.some((c,a)=>{let h=this.lastStateDeps.at(a);if(h){let m=c.lastChanged,b=h.stamp;return m>b}})),s||this.isFirstUse){this.isFirstUse=!1,Array.isArray(this.onEffectDeps)&&(this.lastStateDeps=this.onEffectDeps.map(a=>({stamp:a.lastChanged,stateRef:a}))),this.key??=this.fc.name+"_"+q(),this.entity&&this.scene.getScene().removeEntity(this.entity),this.entity&&this.entity.name!==this.key&&(this.entity=null),this.entity=this.entity??new d(this,this.key);for(let a of this.refs)a.current===P&&(a.current=this.entity);this.callProps.ref instanceof o&&(this.callProps.ref.current=this.entity),this.exports=this.onExport(),this.callProps.exportsRef instanceof o&&(this.callProps.exportsRef.current=this.exports),this.scene.getScene().addEntity(this.entity);let c=this.onEffect.map(a=>a()).filter(a=>a!==void 0);this.onUnEffect=c}}catch(s){throw s}}unuse(){try{for(let s of this.onUnEffect)s()}catch(s){console.error(s)}this.scene.getScene().removeEntity(this.entity)}}f.KaylaInternalComponent=p;class d extends V{#e;constructor(s,c){super(c,0,0,0,0),this.#e=s}update(s){let c=new r;if(this.#e.onTick)for(let a of this.#e.onTick)a(s,c);c.isPrevented()}draw(s){let c=new r;if(this.#e.onPaint)for(let a of this.#e.onPaint)a(s,c);c.isPrevented()||super.draw(s)}}f.KaylaRectEntity=d;class l{constructor(s){this.#t=s,this.#e=null,s.on("update",this.tickHandler.bind(this)),this.drawHandler=this.drawHandler.bind(this)}#e;#t;getScene(){return this.#t}drawHandler(s){return this.#t.handleDraw(s)}attachTo(s){s.addScene(this.#t),this.#e=s}spawn(s){new p(f.singleGlobalInstance,this,s).refresh()}detach(){this.#e&&this.#e.removeScene(this.#t)}tickHandler(){}}f.KaylaScene=l,f.singleGlobalInstance=new f.GlobalKayla})(T||={});var x=T.singleGlobalInstance,z=x.useState.bind(x),k=x.useRef.bind(x),O=x.useEffect.bind(x),se=x.useTick.bind(x),H=x.usePaint.bind(x),ie=x.useExports.bind(x),ae=x.useSelf.bind(x),oe=x.useEntity.bind(x),P=Symbol("self_ref");var B=n=>{Promise.resolve(1).then(()=>n())},ue=({children:n})=>Array.isArray(n)?[...n]:n;function le(n){return new T.KaylaRef(null,n)}Reflect.set(globalThis,"Kayla",X);var ce;(e=>e.UIComponent=({x:t,y:r,width:i,height:o,children:p})=>{let d=k(P),l=z(!1);return O(()=>{if(l.get()===!0)return;l.set(!0);let u=d.current;u.width=i,u.height=o,u.x=t,u.y=r}),H(u=>{u.fillStyle="rgba(0, 0, 0, 0.5)",u.fillRect(t,r,i,o)}),p??[]})(ce||={});export{X as Kayla,ue as KaylaFragment,T as KaylaInternals,ce as UI,re as createElement,ee as createGame,ne as createRenderer,te as createScene,P as self,le as useDisposableRef,O as useEffect,oe as useEntity,ie as useExports,B as useNextStack,H as usePaint,k as useRef,ae as useSelf,z as useState,se as useTick};
|
package/dist/lea.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var R=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var ne=Object.prototype.hasOwnProperty;var re=(n,e)=>{for(var t in e)R(n,t,{get:e[t],enumerable:!0})},ie=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of te(e))!ne.call(n,i)&&i!==t&&R(n,i,{get:()=>e[i],enumerable:!(r=ee(e,i))||r.enumerable});return n};var se=n=>ie(R({},"__esModule",{value:!0}),n);var be={};re(be,{DeltaTweenII:()=>_,ENVIRONMENT:()=>N,GEmitterMemory:()=>L,LeaEntityII:()=>E,LeaEventEmitter:()=>y,LeaGameII:()=>V,LeaRendererII:()=>F,LeaSceneII:()=>P,LeaSerializers:()=>G,LeaTickerII:()=>I,LeaTimeout:()=>A,LeaUtilsII:()=>f,LiaAudio:()=>T,LiaAudioSrc:()=>w,LiaOscSFX:()=>x,LiaSFXMap:()=>le,NOTE_NAMES:()=>D,RectLeaEntity:()=>K,Vector2:()=>C,colToRGBA:()=>oe,defaultSFXConfig:()=>X,editRGBA:()=>ue,generateUUID:()=>j,getAvoidAngle:()=>Y,getEnvironment:()=>q,getNormalizedColor:()=>ae,getRayHit:()=>J,isInitiallyMobile:()=>fe,isMobile:()=>Z,isNode:()=>k,isNote:()=>he,isWeb:()=>b,parseFillStyle:()=>O,raycastAvoid:()=>pe,scaleCoord:()=>ce,setAnimInterval:()=>Q,sfxHit:()=>W,sfxJump:()=>H,sfxLaser:()=>$,sfxUIClick:()=>B,sfxUIHover:()=>U,shortUID:()=>me,tinyUID:()=>de});module.exports=se(be);var y=class{#e=new Map;constructor(){this.#e=new Map}on(e,t){let r=this.#e.get(e)||[];return r.push(t),this.#e.set(e,r),this}once(e,t){let r=(...i)=>{this.off(e,r),t(...i)};return this.on(e,r),this}off(e,t){let r=this.#e.get(e);if(!r)return this;let i=r.indexOf(t);return i>=0&&r.splice(i,1),this}emit(e,...t){let r=this.#e.get(e);if(!r||r.length===0){if(e==="error")throw t[0];return!1}return r.slice().forEach(i=>i(...t)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},F=class extends y{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:t,viewportHeight:r,cameraWidth:i,cameraHeight:a}={}){if(!b)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=t??e.width,this.#t=r??e.height,this.#n=i??e.width,this.#r=a??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,t=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,t),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!b)return;let e=performance.now(),t=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=t,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!b||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!b||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},I=class extends y{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),t=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,this.#e+=t*1e3,this.emit("tick",t)}createTimeout(e){return new A(e,this)}createTween(e,t=()=>{}){let r=new _(e),i=(a=0)=>{if(r.finished){this.off("tick",i);return}r.update(a)};return r.on("finish",()=>{this.off("tick",i)}),r.on("delta",a=>{t(a)}),this.on("tick",i),r}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=b&&!isFinite(this.tickInterval)?Q(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,t=0){return .5+.5*Math.sin((this.now()%e/e+t)*2*Math.PI)}},G;(M=>{function n(h){return h===!0?1:0}M.booleanExport=n;function e(h){return h===0?!1:h===1}M.booleanImport=e;function t(h){return`${h.x}|${h.y}`}M.vec2Export=t;function r(h){let[d,g]=h.split("|"),v=parseFloat(d),S=parseFloat(g);if(isNaN(v)||isNaN(S))throw new Error(`Invalid Vector2 string: ${h}`);return new C(v,S)}M.vec2Import=r,M.booleanMap={mapExport:n,mapImport:e};function a(h){return d=>Number(d.toFixed(h))}M.createRounder=a;function u(h=10){return{mapExport(d){return Math.round(d/h)},mapImport(d){return d*h}}}M.createLowPrecision=u;function c(h){return Math.round(h)}M.lightWeightRounder=c;function s(h=100){return{mapExport(d){return Math.round(d*h)},mapImport(d){return d/h}}}M.createPercent=s;function o(h){let d=new Map(Object.entries(h));return{mapExport:g=>d.get(g)??null,mapImport:g=>Array.from(d.entries()).find(([v,S])=>S===g)?.[0]??null}}M.createLookup=o;function l(h){let d=h*(180/Math.PI);return Math.round((d%360+360)%360)}M.radToDeg=l;function m(h){return h*(Math.PI/180)}M.degToRad=m,M.angleRadToDeg={mapExport:l,mapImport:m};function z(h=10){let d=u(h);return{mapExport(g){return d.mapExport(l(g))},mapImport(g){return d.mapImport(m(g))}}}M.createLowPrecisionRadToDeg=z})(G||={});var E=class n extends y{name="";scaleRotate=0;scale=1;constructor(e,t=0,r=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new C(t,r),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(t){this.emit("error",t)}}handleDraw(e){if(!(k||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(t){this.emit("error",t)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([i,{mapExport:a}])=>{let u=Reflect.get(this,i);return a?a(u):u});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],t=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(i=>!this.nonSerializableProperties.includes(i)&&!e.includes(i.toString())),r=Object.fromEntries(t.map(i=>{let a=Reflect.get(this,i);if(k&&typeof a=="number"){let u=a.toString().split("."),s=(u[1]?u[1].length:0)>2?Number(a.toFixed(2)):a;return[i,s]}return[i,a]}));return JSON.parse(JSON.stringify(r))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return n.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,t){if(!e||!Array.isArray(t))return t;let r={};for(let i=0;i<t.length;i++){let a=e[i];if(!a)break;let[u,{mapImport:c}]=a,s=t[i];if(c&&(s=c(s)),typeof u!="string")break;try{Reflect.set(r,u,s)}catch(o){console.error(o)}}return r}},P=class extends y{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let t of this.entities.values())t.handleUpdate(e)}}handleDraw(e){if(!k&&!this.paused){this.emit("draw",e);for(let t of[...this.entities.values()].sort((r,i)=>r.z-i.z))t.handleDraw(e)}}addEntity(e){if(!(e instanceof E))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 E))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},V=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,t,r=16){this.ticker=new I(r),this.scenes=new Map,this.width=e,this.height=t,this.ticker.on("tick",i=>{for(let a of this.scenes.values())a.paused||a.handleUpdate(i)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},f={lerp(n,e,t){return n+(e-n)*t},clamp(n,e,t){return Math.min(t,Math.max(e,n))},clamp01(n){return Math.min(1,Math.max(0,n))},easeLinear(n){return n},easeInQuad(n){return n*n},easeOutQuad(n){return 1-(1-n)*(1-n)},easeInOutQuad(n){return n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2},easeInSine(n){return 1-Math.cos(n*Math.PI/2)},easeOutSine(n){return Math.sin(n*Math.PI/2)},easeInOutSine(n){return-(Math.cos(Math.PI*n)-1)/2},easeInExpo(n){return n===0?0:Math.pow(2,10*n-10)},easeOutExpo(n){return n===1?1:1-Math.pow(2,-10*n)},easeInOutExpo(n){return n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2},smoothstep(n){return n=f.clamp(n,0,1),n*n*(3-2*n)},randomLerp(n,e){return f.lerp(n,e,Math.random())},randomInt(n,e){return Math.floor(Math.random()*(e-n+1))+n},randomArrayValue(n){return n[f.randomInt(0,n.length-1)]},createBezier(n,e,t,r){function i(c,s,o,l,m){let p=1-c;return p*p*p*s+3*p*p*c*o+3*p*c*c*l+c*c*c*m}function a(c,s,o,l,m){let p=1-c;return 3*p*p*(o-s)+6*p*c*(l-o)+3*c*c*(m-l)}function u(c){let s=c;for(let o=0;o<6;o++){let l=i(s,0,n,t,1),m=a(s,0,n,t,1);if(m===0)break;s-=(l-c)/m}return f.clamp(s,0,1)}return function(s){s=f.clamp(s,0,1);let o=u(s);return i(o,0,e,r,1)}},lengthSquared(...n){return n.reduce((e,t)=>e+t*t,0)},normalizeRad(n){let e=2*Math.PI;return n=n%e,n<0&&(n+=e),n},angleInvertY(n){return f.normalizeRad(-n)},degToRadFlipY(n){return f.angleInvertY(n*Math.PI/180)},minimalAngularDirection(n,e){n=f.normalizeRad(n),e=f.normalizeRad(e);let t=f.normalizeRad(e-n),r=f.normalizeRad(n-e);return t<=r?1:-1}},_=class extends y{constructor({delta:e,ms:t,easing:r}){super(),this.delta=e,this.duration=t,this.elapsed=0,this.easing=r??(i=>i),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let t=f.clamp(this.elapsed/this.duration,0,1),r=this.easing(t),i=this.delta*r,a=i-this.lastValue;this.lastValue=i,this.emit("delta",a),t>=1&&(this.finished=!0,this.emit("finish",void 0))}},K=class extends E{constructor(e,t=0,r=0,i=50,a=50){super(e,t,r),this.width=i,this.height=a}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)}},A=class extends y{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,t=null){super(),this.duration=e,this.ticker=t,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(r=>this._resolve=r),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,t){return this.promise.then(e,t)}after(e,t){return this.promise.then(e,t)}},C=class n{constructor(e=0,t=0){this.x=e,this.y=t}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let t=Math.cos(e),r=Math.sin(e);return new n(this.x*t-this.y*r,this.x*r+this.y*t)}static from(e){return new n(Math.cos(e),Math.sin(e))}get angle(){return Math.atan2(this.y,this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new n(0,0):new n(this.x/e,this.y/e)}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let t=this.dot(e);return this.subtract(e.scale(2*t))}dotNormalized(e){let t=this.normalized(),r=e.normalized();return t.x*r.x+t.y*r.y}lengthSquaredTo(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}directionTo(e){return new n(e.x-this.x,e.y-this.y).normalized()}add(e){return new n(this.x+e.x,this.y+e.y)}addRaw(e){return new n(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new n(this.x-e.x,this.y-e.y)}scale(e){return new n(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new n(this.x,this.y)}};function ae(n){let e=/^rgba?\(([^)]+)\)$/,t=n.match(e);if(t){let[r,i,a,u=1]=t[1].split(",").map(c=>parseFloat(c));return{r:Math.max(0,Math.min(255,Math.floor(r))),g:Math.max(0,Math.min(255,Math.floor(i))),b:Math.max(0,Math.min(255,Math.floor(a))),a:Math.max(0,Math.min(1,Math.floor(u*255)/255))}}return O(n)}function oe(n){return`rgba(${n.r}, ${n.g}, ${n.b}, ${n.a})`}function O(n){if(n=n.trim().toLowerCase(),n[0]==="#"){let t,r,i;if(n.length===7)t=parseInt(n.slice(1,3),16),r=parseInt(n.slice(3,5),16),i=parseInt(n.slice(5,7),16);else if(n.length===4)t=parseInt(n[1]+n[1],16),r=parseInt(n[2]+n[2],16),i=parseInt(n[3]+n[3],16);else throw new Error("Invalid hex color");return{r:t,g:r,b:i,a:1}}let e=n.match(/^rgba?\s*\(\s*(\d+)[, ]\s*(\d+)[, ]\s*(\d+)(?:[, ]\s*([\d.]+))?\s*\)$/);if(e)return{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3]),a:e[4]!==void 0?parseFloat(e[4]):1};throw new Error("Unsupported fillStyle format")}function ue(n,{r:e,g:t,b:r,a:i}={}){let[a,u,c,s,o]=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??u}, ${t??c}, ${r??s}, ${i??(o||1)})`}function ce(n,e,t){return t+(n-t)*e}function q(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var N=q(),k=N==="node",b=N==="web",T=class n{static unlock(){b&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=b?new AudioContext:null;static masterGain=b?this.audioCtx.createGain():null;static musicGain=b?this.audioCtx.createGain():null;static sfxGain=b?this.audioCtx.createGain():null;static{b&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let t=n.CACHE_NAME,r,i;if(typeof caches<"u"&&(i=await caches.open(t),r=await i.match(e)),!r){if(r=await fetch(e),!r.ok)throw new Error(`Failed to fetch ${e}`);i&&await i.put(e,r.clone())}let a=await r.arrayBuffer(),u=await this.audioCtx.decodeAudioData(a);return this.audioBufferCache.set(e,u),u}static async getOnlyDownloadedCache(e){let t=n.CACHE_NAME;return await(await caches.open(t)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,t=.2,r=1,i=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let a=this.getCached(e);if(!a)return;let u=new w(a);u.buffer=a;let c=1-.12,s=1+.12;u.playbackRate=r??c+Math.random()*(s-c);let o=this.audioCtx.createGain();o.gain.value=t,u.tempGain=o,u.connect(o),o.connect(this.sfxGain),u.onended=()=>{u.disconnect(),o.disconnect()},u.start(),i&&this.sfsx.set(e,{source:u,gain:o})}catch(a){console.error(a)}}static async playLoop(e,t=1,{loopStart:r=0,loopEnd:i=null,exclusive:a=!0,skipMS:u=0}={}){if(a)for(let m of this.loops.keys())this.stopLoop(m);this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return;let s=new w(c);s.buffer=c,s.loop=!0,typeof r=="number"&&(s.loopStart=r),typeof i=="number"&&(s.loopEnd=i);let o=this.audioCtx.createGain();o.gain.value=t,s.tempGain=o,s.playbackRate=1,s.onended=()=>{s.disconnect(),o.disconnect()},s.connect(o),o.connect(this.musicGain),s.start(0,u/1e3);let l=++this.loopIdCounter;return this.loops.set(l,{source:s,gain:o}),l}static stopLoop(e){let t=this.loops.get(e);t&&(t.source.stop(),t.source.notIndependent||(t.source.disconnect(),t.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:t=1,speed:r=1,loop:i=!1,loopStart:a=0,loopEnd:u=null,isMusic:c=!1,gain:s=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return null;let l=new w(o);l.loop=i,l.loopStart=a,l.loopEnd=typeof u=="number"?u:o.duration,l.playbackRate=r;let m=this.audioCtx.createGain();return m.gain.value=t,l.connect(m),l.tempGain=m,m.connect(s||(c?this.musicGain:this.sfxGain)),l.onended=()=>{l.disconnect(),m.disconnect()},l}catch(o){return console.error("Failed to create LiaAudioSrc:",o),null}}},D=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function he(n){return D.includes(n)}var w=class{numberOfInputs;numberOfOutputs;constructor(e,t=T.audioCtx){this.context=t,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=b?t.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:t=null}={}){let r=t!==null?t:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-r/this.playbackRate,this.source.start(0,r),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,t=0,r){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-t/this.playbackRate,r!==void 0?this.source.start(this.context.currentTime+e,t,r):this.source.start(this.context.currentTime+e,t),this.pauseTime=t,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let t=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let r=this.loopEnd-this.loopStart;t=this.loopStart+(t-this.loopStart)%r}if(this.isPlaying=!1,e>0){let r=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,r),this.output.gain.linearRampToValueAtTime(0,r+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let t=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=t,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,t=0,r=0){if("value"in e)this.output.connect(e,t);else return this.output.connect(e,t,r),e}disconnect(e,t,r){e===void 0?this.output.disconnect():this.output.disconnect(e,t,r)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let t=this.context.currentTime+e;this.source.stop(t),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},X={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},x=class n{constructor(e={}){this.ctx=T.audioCtx,this.cfg=structuredClone(X),Object.assign(this.cfg,e)}ctx;cfg;play(e=T.sfxGain){let t=this.ctx,r=t.currentTime,i=this.cfg,a=t.createGain();a.gain.setValueAtTime(1e-4,r);let u=i.ampEnv;a.gain.exponentialRampToValueAtTime(u.volume,r+u.attack),a.gain.exponentialRampToValueAtTime(Math.max(1e-4,u.sustain*u.volume),r+u.attack+u.decay),a.gain.exponentialRampToValueAtTime(1e-4,r+i.duration+u.release);let c=a,s;i.filter.enabled&&(s=t.createBiquadFilter(),s.type=i.filter.type,s.frequency.value=i.filter.freq,s.Q.value=i.filter.Q,s.connect(a),c=s);let o;if(i.osc.enabled){if(o=t.createOscillator(),o.type=i.osc.type,o.frequency.value=i.osc.freq,o.detune.value=i.osc.detune,i.pitchEnv.amount!==0){let h=Math.pow(2,i.pitchEnv.amount/12);o.frequency.exponentialRampToValueAtTime(i.osc.freq*h,r+i.pitchEnv.decay)}o.connect(c),o.start(r),o.stop(r+i.duration+u.release)}let l;if(i.noise.enabled){let h=t.sampleRate*i.duration,d=t.createBuffer(1,h,t.sampleRate),g=d.getChannelData(0);for(let v=0;v<h;v++)g[v]=(Math.random()*2-1)*i.noise.level;l=t.createBufferSource(),l.buffer=d,l.connect(c),l.start(r),l.stop(r+i.duration+u.release)}let m,p;i.lfo.enabled&&o&&(m=t.createOscillator(),m.frequency.value=i.lfo.rate,p=t.createGain(),p.gain.value=i.lfo.depth,m.connect(p),i.lfo.target==="freq"?p.connect(o.frequency):i.lfo.target==="gain"?p.connect(a.gain):i.lfo.target==="filter"&&s&&p.connect(s.frequency),m.start(r),m.stop(r+i.duration)),a.connect(e);let z=[o,l,m,p,s,a],M=r+i.duration+u.release;setTimeout(()=>{z.forEach(h=>h?.disconnect())},(M-t.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,t){return Object.assign(this.cfg[e],t),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,t,r,i){return Object.assign(this.cfg.ampEnv,{attack:e,decay:t,sustain:r,release:i}),this}setPitchEnv(e,t){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:t}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,t,r){return Object.assign(this.cfg.filter,{type:e,freq:t,Q:r,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,t,r){return Object.assign(this.cfg.lfo,{target:e,rate:t,depth:r,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new n(structuredClone(this.cfg))}},B=new x({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),U=new x({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),H=new x({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}),$=new x({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}),W=new x({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}),le=new Map([["ui_click",B],["ui_hover",U],["jump",H],["laser",$],["hit",W]]);function me(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(n)),r=Array.from(t).map(i=>i.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}function de(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(4)),r=Array.from(t).map(i=>i.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}var L=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${j()}_${Date.now()}`}connect(e){e&&(this.peer=e,e.peer=this,this.connected=!0,e.connected=!0),this._emit("open")}isConnected(){return this.connected&&!!this.peer}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(r=>r!==t))}_emit(e,t){this.events[e]?.forEach(r=>r(t))}send(e,t){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,t)}_receive(e,t){e?this._emit(e,t):this._emit("message",t)}close(){if(this.connected=!1,this.peer){let e=this.peer;this.peer=null,e.peer=null,e.connected=!1,e._emit("close")}this._emit("close")}getKey(){return this.key}};function j(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let n=new Uint8Array(16);return crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,[...n].map(e=>e.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5")}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function Q(n){let e=!0;function t(){e&&(n(),requestAnimationFrame(t))}return requestAnimationFrame(t),{clear:()=>e=!1}}function J(n,e,t,r,i){let a=Math.cos(i),u=Math.sin(i),c=[];if(a!==0){let s=(0-n)/a,o=e+s*u;s>0&&o>=0&&o<=r&&c.push({side:"left",t:s})}if(a!==0){let s=(t-n)/a,o=e+s*u;s>0&&o>=0&&o<=r&&c.push({side:"right",t:s})}if(u!==0){let s=(0-e)/u,o=n+s*a;s>0&&o>=0&&o<=t&&c.push({side:"top",t:s})}if(u!==0){let s=(r-e)/u,o=n+s*a;s>0&&o>=0&&o<=t&&c.push({side:"bottom",t:s})}return c.length===0?null:(c.sort((s,o)=>s.t-o.t),c[0])}function Y(n,e){let t;switch(e){case"left":case"right":t=Math.PI-n;break;case"top":case"bottom":t=2*Math.PI-n;break}return(t%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function pe(n,e,t,r,i){let a=J(n,e,t,r,i);return a?{...a,avoidAngle:Y(i,a.side)}:null}function Z(){return k?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var fe=Z();0&&(module.exports={DeltaTweenII,ENVIRONMENT,GEmitterMemory,LeaEntityII,LeaEventEmitter,LeaGameII,LeaRendererII,LeaSceneII,LeaSerializers,LeaTickerII,LeaTimeout,LeaUtilsII,LiaAudio,LiaAudioSrc,LiaOscSFX,LiaSFXMap,NOTE_NAMES,RectLeaEntity,Vector2,colToRGBA,defaultSFXConfig,editRGBA,generateUUID,getAvoidAngle,getEnvironment,getNormalizedColor,getRayHit,isInitiallyMobile,isMobile,isNode,isNote,isWeb,parseFillStyle,raycastAvoid,scaleCoord,setAnimInterval,sfxHit,sfxJump,sfxLaser,sfxUIClick,sfxUIHover,shortUID,tinyUID});
|
package/dist/lea.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var y=class{#e=new Map;constructor(){this.#e=new Map}on(e,t){let r=this.#e.get(e)||[];return r.push(t),this.#e.set(e,r),this}once(e,t){let r=(...i)=>{this.off(e,r),t(...i)};return this.on(e,r),this}off(e,t){let r=this.#e.get(e);if(!r)return this;let i=r.indexOf(t);return i>=0&&r.splice(i,1),this}emit(e,...t){let r=this.#e.get(e);if(!r||r.length===0){if(e==="error")throw t[0];return!1}return r.slice().forEach(i=>i(...t)),!0}removeAllListeners(e){return e?this.#e.delete(e):this.#e.clear(),this}listenerCount(e){return this.#e.get(e)?.length??0}},F=class extends y{canvas;ctx;running;_rafId;_fps;_frameCount;_fpsTimer;_lastFrameTime;constructor(e,{viewportWidth:t,viewportHeight:r,cameraWidth:i,cameraHeight:a}={}){if(!b)throw new Error("Web-Only");super(),this.canvas=e,this.ctx=e.getContext("2d"),this.automatic=!0,this.#e=t??e.width,this.#t=r??e.height,this.#n=i??e.width,this.#r=a??e.height,this.running=!1,this._rafId=null,this._loop=this._loop.bind(this),this.updateCanvasResolution(),this._fps=60,this._frameCount=0,this._fpsTimer=0}automatic;retransform(){this.ctx.setTransform(1,0,0,1,0,0);let e=this.#n/this.#e,t=this.#r/this.#t;this.ctx.translate(this.#n/2,this.#r/2),this.ctx.scale(e,t),this.ctx.translate(-this.#e/2,-this.#t/2)}#e=0;#t=0;#n=0;#r=0;get viewportWidth(){return this.#e}set viewportWidth(e){this.#e=e,this.retransform()}get width(){return this.#e}get height(){return this.#t}get centerX(){return this.#e/2}get centerY(){return this.#t/2}get left(){return 0}get top(){return 0}get right(){return this.#e}get bottom(){return this.#t}get viewportHeight(){return this.#t}set viewportHeight(e){this.#t=e,this.retransform()}get cameraWidth(){return this.#n}set cameraWidth(e){this.#n=e,this.updateCanvasResolution(),this.retransform()}get cameraHeight(){return this.#r}set cameraHeight(e){this.#r=e,this.updateCanvasResolution(),this.retransform()}updateCanvasResolution(){this.canvas.width=this.#n,this.canvas.height=this.#r}applyTransform(){this.retransform()}get FPS(){return this._fps}_loop(){this.automatic&&this.update(),this._rafId=requestAnimationFrame(this._loop)}update(){if(!this.running||!b)return;let e=performance.now(),t=(e-(this._lastFrameTime??e))/1e3;this._lastFrameTime=e,this._frameCount++,this._fpsTimer+=t,this._fpsTimer>=1&&(this._fps=Math.round(this._frameCount/this._fpsTimer),this._frameCount=0,this._fpsTimer=0),this.ctx.clearRect(0,0,this.#n,this.#r),this.emit("draw",this.ctx)}start(){if(!this.running){if(!b||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!0,this._rafId=requestAnimationFrame(this._loop)}}stop(){if(!b||typeof globalThis.requestAnimationFrame>"u")throw new Error("Raf is not supported");this.running=!1,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}},I=class extends y{setNow(e){this.#e=e}#e=0;__intervalId=null;__lastTime=0;constructor(e=16){super(),this.#t=e,this.speedHackDT=1}speedHackDT;get isRaf(){return this.tickInterval===1/0}#t=15;get tickInterval(){return this.#t}set tickInterval(e){this.#t=e,this.__intervalId&&(this.stop(),this.start())}now(){return this.#e}__tick(){let e=performance.now(),t=(e-this.__lastTime)/1e3*this.speedHackDT;this.__lastTime=e,this.#e+=t*1e3,this.emit("tick",t)}createTimeout(e){return new A(e,this)}createTween(e,t=()=>{}){let r=new _(e),i=(a=0)=>{if(r.finished){this.off("tick",i);return}r.update(a)};return r.on("finish",()=>{this.off("tick",i)}),r.on("delta",a=>{t(a)}),this.on("tick",i),r}start(){this.__intervalId===null&&(this.__lastTime=performance.now(),this.__intervalId=b&&!isFinite(this.tickInterval)?j(()=>this.__tick()).clear:setInterval(()=>this.__tick(),this.tickInterval))}stop(){this.__intervalId!==null&&(typeof this.__intervalId=="function"?this.__intervalId():clearInterval(this.__intervalId)),this.__intervalId=null}getSineMod(e,t=0){return .5+.5*Math.sin((this.now()%e/e+t)*2*Math.PI)}},z;(C=>{function n(h){return h===!0?1:0}C.booleanExport=n;function e(h){return h===0?!1:h===1}C.booleanImport=e;function t(h){return`${h.x}|${h.y}`}C.vec2Export=t;function r(h){let[d,g]=h.split("|"),x=parseFloat(d),k=parseFloat(g);if(isNaN(x)||isNaN(k))throw new Error(`Invalid Vector2 string: ${h}`);return new M(x,k)}C.vec2Import=r,C.booleanMap={mapExport:n,mapImport:e};function a(h){return d=>Number(d.toFixed(h))}C.createRounder=a;function u(h=10){return{mapExport(d){return Math.round(d/h)},mapImport(d){return d*h}}}C.createLowPrecision=u;function c(h){return Math.round(h)}C.lightWeightRounder=c;function s(h=100){return{mapExport(d){return Math.round(d*h)},mapImport(d){return d/h}}}C.createPercent=s;function o(h){let d=new Map(Object.entries(h));return{mapExport:g=>d.get(g)??null,mapImport:g=>Array.from(d.entries()).find(([x,k])=>k===g)?.[0]??null}}C.createLookup=o;function l(h){let d=h*(180/Math.PI);return Math.round((d%360+360)%360)}C.radToDeg=l;function m(h){return h*(Math.PI/180)}C.degToRad=m,C.angleRadToDeg={mapExport:l,mapImport:m};function R(h=10){let d=u(h);return{mapExport(g){return d.mapExport(l(g))},mapImport(g){return d.mapImport(m(g))}}}C.createLowPrecisionRadToDeg=R})(z||={});var E=class n extends y{name="";scaleRotate=0;scale=1;constructor(e,t=0,r=0){super(),this.autoTranslate=!1,this.name=e,this.z=0,this.___pos=new M(t,r),this.nonSerializableProperties=[],this.nonSerializableProperties.push("___pos","autoTranslate","arraySerializeMap"),this.forceSerializableProperties=[],this.forceSerializableProperties.push("x","y")}arraySerializeMap;autoTranslate;z;___pos;nonSerializableProperties;forceSerializableProperties;get pos(){return this.___pos}get x(){return this.pos.x}get y(){return this.pos.y}set x(e){this.pos.x=e}set y(e){this.pos.y=e}handleUpdate(e){if(this.update)try{this.emit("update",e),this.update(e)}catch(t){this.emit("error",t)}}handleDraw(e){if(!(S||!this.draw)){e.save(),this.autoTranslate&&e.translate(this.x,this.y);try{this.emit("draw",e),this.draw(e)}catch(t){this.emit("error",t)}e.restore()}}serialize(){if(Array.isArray(this.arraySerializeMap))return this.arraySerializeMap.map(([i,{mapExport:a}])=>{let u=Reflect.get(this,i);return a?a(u):u});let e=["_events","_eventsCount","_maxListeners","nonSerializableProperties","forceSerializableProperties"],t=[...Reflect.ownKeys(this),...this.forceSerializableProperties].filter(i=>!this.nonSerializableProperties.includes(i)&&!e.includes(i.toString())),r=Object.fromEntries(t.map(i=>{let a=Reflect.get(this,i);if(S&&typeof a=="number"){let u=a.toString().split("."),s=(u[1]?u[1].length:0)>2?Number(a.toFixed(2)):a;return[i,s]}return[i,a]}));return JSON.parse(JSON.stringify(r))}toLocal(e){return e.subtract(this.pos)}toWorld(e){return e.add(this.pos)}deserializeArray(e){return n.deserializeArray(this.arraySerializeMap,e)}static deserializeArray(e,t){if(!e||!Array.isArray(t))return t;let r={};for(let i=0;i<t.length;i++){let a=e[i];if(!a)break;let[u,{mapImport:c}]=a,s=t[i];if(c&&(s=c(s)),typeof u!="string")break;try{Reflect.set(r,u,s)}catch(o){console.error(o)}}return r}},P=class extends y{name="";entities=new Map;paused=!0;constructor(e){super(),this.name=e}handleUpdate(e){if(!this.paused){this.emit("update",e);for(let t of this.entities.values())t.handleUpdate(e)}}handleDraw(e){if(!S&&!this.paused){this.emit("draw",e);for(let t of[...this.entities.values()].sort((r,i)=>r.z-i.z))t.handleDraw(e)}}addEntity(e){if(!(e instanceof E))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 E))throw new Error("invalid entity");this.entities.delete(e.name)}getEntity(e){return this.entities.get(e)}},V=class{scenes;ticker;get centerX(){return this.width/2}get centerY(){return this.height/2}get left(){return 0}get top(){return 0}get right(){return this.width}get bottom(){return this.height}width;height;constructor(e,t,r=16){this.ticker=new I(r),this.scenes=new Map,this.width=e,this.height=t,this.ticker.on("tick",i=>{for(let a of this.scenes.values())a.paused||a.handleUpdate(i)})}addScene(e){if(!e.name)throw new Error("Scene must have a name.");e.paused=!1,this.scenes.set(e.name,e)}removeScene(e){e&&(e.paused=!0),this.scenes.delete(e.name)}now(){return this.ticker.now()}start(){this.ticker.start()}stop(){this.ticker.stop()}},f={lerp(n,e,t){return n+(e-n)*t},clamp(n,e,t){return Math.min(t,Math.max(e,n))},clamp01(n){return Math.min(1,Math.max(0,n))},easeLinear(n){return n},easeInQuad(n){return n*n},easeOutQuad(n){return 1-(1-n)*(1-n)},easeInOutQuad(n){return n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2},easeInSine(n){return 1-Math.cos(n*Math.PI/2)},easeOutSine(n){return Math.sin(n*Math.PI/2)},easeInOutSine(n){return-(Math.cos(Math.PI*n)-1)/2},easeInExpo(n){return n===0?0:Math.pow(2,10*n-10)},easeOutExpo(n){return n===1?1:1-Math.pow(2,-10*n)},easeInOutExpo(n){return n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2},smoothstep(n){return n=f.clamp(n,0,1),n*n*(3-2*n)},randomLerp(n,e){return f.lerp(n,e,Math.random())},randomInt(n,e){return Math.floor(Math.random()*(e-n+1))+n},randomArrayValue(n){return n[f.randomInt(0,n.length-1)]},createBezier(n,e,t,r){function i(c,s,o,l,m){let p=1-c;return p*p*p*s+3*p*p*c*o+3*p*c*c*l+c*c*c*m}function a(c,s,o,l,m){let p=1-c;return 3*p*p*(o-s)+6*p*c*(l-o)+3*c*c*(m-l)}function u(c){let s=c;for(let o=0;o<6;o++){let l=i(s,0,n,t,1),m=a(s,0,n,t,1);if(m===0)break;s-=(l-c)/m}return f.clamp(s,0,1)}return function(s){s=f.clamp(s,0,1);let o=u(s);return i(o,0,e,r,1)}},lengthSquared(...n){return n.reduce((e,t)=>e+t*t,0)},normalizeRad(n){let e=2*Math.PI;return n=n%e,n<0&&(n+=e),n},angleInvertY(n){return f.normalizeRad(-n)},degToRadFlipY(n){return f.angleInvertY(n*Math.PI/180)},minimalAngularDirection(n,e){n=f.normalizeRad(n),e=f.normalizeRad(e);let t=f.normalizeRad(e-n),r=f.normalizeRad(n-e);return t<=r?1:-1}},_=class extends y{constructor({delta:e,ms:t,easing:r}){super(),this.delta=e,this.duration=t,this.elapsed=0,this.easing=r??(i=>i),this.lastValue=0,this.finished=!1}delta;duration;elapsed;lastValue;finished;easing;update(e){this.elapsed+=e*1e3;let t=f.clamp(this.elapsed/this.duration,0,1),r=this.easing(t),i=this.delta*r,a=i-this.lastValue;this.lastValue=i,this.emit("delta",a),t>=1&&(this.finished=!0,this.emit("finish",void 0))}},K=class extends E{constructor(e,t=0,r=0,i=50,a=50){super(e,t,r),this.width=i,this.height=a}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)}},A=class extends y{duration;ticker;elapsed;finished;_resolve;promise;_timeoutId;constructor(e,t=null){super(),this.duration=e,this.ticker=t,this.elapsed=0,this.finished=!1,this._resolve=null,this.promise=new Promise(r=>this._resolve=r),this.update=this.update.bind(this),this.ticker&&this.ticker.on("tick",this.update)}update(e=0){this.finished||(this.elapsed+=e*1e3,this.elapsed>=this.duration&&this.finish())}finish(){this.finished||(this.finished=!0,this.emit("finish",void 0),this._resolve&&this._resolve(),this.ticker&&this.ticker.off("tick",this.update))}start(){return this.ticker||(this._timeoutId=setTimeout(()=>this.finish(),this.duration)),this}cancel(){this.finished||(this.finished=!0,!this.ticker&&this._timeoutId!=null&&clearTimeout(this._timeoutId),this.ticker&&this.ticker.off("tick",this.update))}then(e,t){return this.promise.then(e,t)}after(e,t){return this.promise.then(e,t)}},M=class n{constructor(e=0,t=0){this.x=e,this.y=t}x;y;toJSON(){return{x:this.x,y:this.y,vec2:!0}}static isVec2(e){return e&&typeof e=="object"&&"x"in e&&"y"in e&&e.vec2===!0}static fromSerialized(e){return this.isVec2(e)?new this(e.x,e.y):null}rotate(e){let t=Math.cos(e),r=Math.sin(e);return new n(this.x*t-this.y*r,this.x*r+this.y*t)}static from(e){return new n(Math.cos(e),Math.sin(e))}get angle(){return Math.atan2(this.y,this.x)}get length(){return Math.hypot(this.x,this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}normalized(){let e=this.length;return e===0?new n(0,0):new n(this.x/e,this.y/e)}project(e){return e.scale(this.dotNormalized(e))}reflect(e){let t=this.dot(e);return this.subtract(e.scale(2*t))}dotNormalized(e){let t=this.normalized(),r=e.normalized();return t.x*r.x+t.y*r.y}lengthSquaredTo(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}dot(e){return this.x*e.x+this.y*e.y}distanceTo(e){return Math.hypot(this.x-e.x,this.y-e.y)}distanceToCheap(e){let t=this.x-e.x,r=this.y-e.y;return t*t+r*r}directionTo(e){return new n(e.x-this.x,e.y-this.y).normalized()}add(e){return new n(this.x+e.x,this.y+e.y)}addRaw(e){return new n(this.x+e,this.y+e)}overwite(e){this.x=e.x,this.y=e.y}subtract(e){return new n(this.x-e.x,this.y-e.y)}scale(e){return new n(this.x*e,this.y*e)}toString(){return`Vector2(${this.x}, ${this.y})`}clone(){return new n(this.x,this.y)}};function Z(n){let e=/^rgba?\(([^)]+)\)$/,t=n.match(e);if(t){let[r,i,a,u=1]=t[1].split(",").map(c=>parseFloat(c));return{r:Math.max(0,Math.min(255,Math.floor(r))),g:Math.max(0,Math.min(255,Math.floor(i))),b:Math.max(0,Math.min(255,Math.floor(a))),a:Math.max(0,Math.min(1,Math.floor(u*255)/255))}}return G(n)}function ee(n){return`rgba(${n.r}, ${n.g}, ${n.b}, ${n.a})`}function G(n){if(n=n.trim().toLowerCase(),n[0]==="#"){let t,r,i;if(n.length===7)t=parseInt(n.slice(1,3),16),r=parseInt(n.slice(3,5),16),i=parseInt(n.slice(5,7),16);else if(n.length===4)t=parseInt(n[1]+n[1],16),r=parseInt(n[2]+n[2],16),i=parseInt(n[3]+n[3],16);else throw new Error("Invalid hex color");return{r:t,g:r,b:i,a:1}}let e=n.match(/^rgba?\s*\(\s*(\d+)[, ]\s*(\d+)[, ]\s*(\d+)(?:[, ]\s*([\d.]+))?\s*\)$/);if(e)return{r:parseInt(e[1]),g:parseInt(e[2]),b:parseInt(e[3]),a:e[4]!==void 0?parseFloat(e[4]):1};throw new Error("Unsupported fillStyle format")}function te(n,{r:e,g:t,b:r,a:i}={}){let[a,u,c,s,o]=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*([\d.]*)\)?/)||[];return`rgba(${e??u}, ${t??c}, ${r??s}, ${i??(o||1)})`}function ne(n,e,t){return t+(n-t)*e}function O(){return typeof process<"u"&&process.release?.name==="node"?"node":typeof window<"u"||typeof self<"u"?"web":"unknown"}var N=O(),S=N==="node",b=N==="web",T=class n{static unlock(){b&&this.audioCtx.state!=="running"&&this.audioCtx.resume()}static audioCtx=b?new AudioContext:null;static masterGain=b?this.audioCtx.createGain():null;static musicGain=b?this.audioCtx.createGain():null;static sfxGain=b?this.audioCtx.createGain():null;static{b&&(this.masterGain.gain.value=1,this.musicGain.gain.value=1,this.sfxGain.gain.value=1,this.sfxGain.connect(this.masterGain),this.musicGain.connect(this.masterGain),this.masterGain.connect(this.audioCtx.destination))}static get SFX_VOLUME(){return this.sfxGain.gain.value}static get MUSIC_VOLUME(){return this.musicGain.gain.value}static get VOLUME(){return this.masterGain.gain.value}static set SFX_VOLUME(e){this.sfxGain.gain.value=e}static set MUSIC_VOLUME(e){this.musicGain.gain.value=e}static set VOLUME(e){this.masterGain.gain.value=e}static noteToHz(e){return this.tuningFreq*Math.pow(2,(e-9)/12)}static tuningFreq=440;static audioBufferCache=new Map;static loops=new Map;static sfsx=new Map;static loopIdCounter=0;static CACHE_NAME="lia-audio-cache-v1";static async preLoad(e){if(this.audioBufferCache.has(e))return this.audioBufferCache.get(e);let t=n.CACHE_NAME,r,i;if(typeof caches<"u"&&(i=await caches.open(t),r=await i.match(e)),!r){if(r=await fetch(e),!r.ok)throw new Error(`Failed to fetch ${e}`);i&&await i.put(e,r.clone())}let a=await r.arrayBuffer(),u=await this.audioCtx.decodeAudioData(a);return this.audioBufferCache.set(e,u),u}static async getOnlyDownloadedCache(e){let t=n.CACHE_NAME;return await(await caches.open(t)).match(e)}static getCached(e){return this.audioBufferCache.get(e)||null}static async playSound(e,t=.2,r=1,i=!0){try{this.sfsx.has(e)&&this.sfsx.get(e).source.stop(),this.audioBufferCache.has(e)||await this.preLoad(e);let a=this.getCached(e);if(!a)return;let u=new w(a);u.buffer=a;let c=1-.12,s=1+.12;u.playbackRate=r??c+Math.random()*(s-c);let o=this.audioCtx.createGain();o.gain.value=t,u.tempGain=o,u.connect(o),o.connect(this.sfxGain),u.onended=()=>{u.disconnect(),o.disconnect()},u.start(),i&&this.sfsx.set(e,{source:u,gain:o})}catch(a){console.error(a)}}static async playLoop(e,t=1,{loopStart:r=0,loopEnd:i=null,exclusive:a=!0,skipMS:u=0}={}){if(a)for(let m of this.loops.keys())this.stopLoop(m);this.audioBufferCache.has(e)||await this.preLoad(e);let c=this.getCached(e);if(!c)return;let s=new w(c);s.buffer=c,s.loop=!0,typeof r=="number"&&(s.loopStart=r),typeof i=="number"&&(s.loopEnd=i);let o=this.audioCtx.createGain();o.gain.value=t,s.tempGain=o,s.playbackRate=1,s.onended=()=>{s.disconnect(),o.disconnect()},s.connect(o),o.connect(this.musicGain),s.start(0,u/1e3);let l=++this.loopIdCounter;return this.loops.set(l,{source:s,gain:o}),l}static stopLoop(e){let t=this.loops.get(e);t&&(t.source.stop(),t.source.notIndependent||(t.source.disconnect(),t.gain.disconnect()),this.loops.delete(e))}static async createLiaSource(e,{volume:t=1,speed:r=1,loop:i=!1,loopStart:a=0,loopEnd:u=null,isMusic:c=!1,gain:s=null}={}){try{this.audioBufferCache.has(e)||await this.preLoad(e);let o=this.getCached(e);if(!o)return null;let l=new w(o);l.loop=i,l.loopStart=a,l.loopEnd=typeof u=="number"?u:o.duration,l.playbackRate=r;let m=this.audioCtx.createGain();return m.gain.value=t,l.connect(m),l.tempGain=m,m.connect(s||(c?this.musicGain:this.sfxGain)),l.onended=()=>{l.disconnect(),m.disconnect()},l}catch(o){return console.error("Failed to create LiaAudioSrc:",o),null}}},q=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function re(n){return q.includes(n)}var w=class{numberOfInputs;numberOfOutputs;constructor(e,t=T.audioCtx){this.context=t,this.buffer=e,this.source=null,this.startTime=0,this.pauseTime=0,this.playbackRate=1,this.isPlaying=!1,this.loop=!1,this.output=b?t.createGain():null,this.output.gain.value=1,this.channelCount=2,this.channelCountMode="max",this.channelInterpretation="speakers",this.numberOfInputs=0,this.numberOfOutputs=1,this.onended=null}channelCount;channelCountMode;channelInterpretation;onended;source;buffer;context;_createSource(){this.source&&(this.source.onended=null);let e=this.context.createBufferSource();return e.buffer=this.buffer,e.playbackRate.value=this.playbackRate,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd>0?this.loopEnd:this.buffer.duration,e.connect(this.output),this.source=e,e.onended=()=>{this.source===e&&(this.isPlaying&&!this.loop&&(this.isPlaying=!1,this.pauseTime=0),typeof this.onended=="function"&&this.onended())},e}play({fadeIn:e=0,offset:t=null}={}){let r=t!==null?t:this.pauseTime;if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.source=this._createSource(),this.startTime=this.context.currentTime-r/this.playbackRate,this.source.start(0,r),e>0?(this.output.gain.setValueAtTime(0,this.context.currentTime),this.output.gain.linearRampToValueAtTime(1,this.context.currentTime+e)):this.output.gain.setValueAtTime(1,this.context.currentTime),this.isPlaying=!0}start(e=0,t=0,r){this.isPlaying||(this.source=this._createSource(),this.startTime=this.context.currentTime+e-t/this.playbackRate,r!==void 0?this.source.start(this.context.currentTime+e,t,r):this.source.start(this.context.currentTime+e,t),this.pauseTime=t,this.isPlaying=!0)}pause({fadeOut:e=0}={}){if(!this.isPlaying)return;let t=this.getElapsed()/1e3;if(this.loop&&this.loopEnd>this.loopStart){let r=this.loopEnd-this.loopStart;t=this.loopStart+(t-this.loopStart)%r}if(this.isPlaying=!1,e>0){let r=this.context.currentTime;this.output.gain.setValueAtTime(this.output.gain.value,r),this.output.gain.linearRampToValueAtTime(0,r+e),setTimeout(()=>{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t,this.output.gain.setValueAtTime(1,this.context.currentTime)},e*1e3)}else{if(this.source){this.source.onended=null;try{this.source.stop()}catch{}}this.pauseTime=t}}getElapsed(){return this.isPlaying?(this.context.currentTime-this.startTime)*this.playbackRate*1e3:this.pauseTime*1e3}setSpeed(e){if(e<=0)throw new Error("Playback rate must be positive");let t=this.getElapsed()/1e3;this.playbackRate=e,this.isPlaying&&(this.pause(),this.pauseTime=t,this.play())}setLoop(e=!0){this.loop=e,this.source&&(this.source.loop=e)}loop;playbackRate;startTime;tempGain=null;connect(e,t=0,r=0){if("value"in e)this.output.connect(e,t);else return this.output.connect(e,t,r),e}disconnect(e,t,r){e===void 0?this.output.disconnect():this.output.disconnect(e,t,r)}output;stop(e=0){if(this.notIndependent)return this.pause();if(!this.source)return;let t=this.context.currentTime+e;this.source.stop(t),this.isPlaying=!1,this.notIndependent||(this.pauseTime=0)}pauseTime;isPlaying;notIndependent=!1;loopStart=0;loopEnd=0},D={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},v=class n{constructor(e={}){this.ctx=T.audioCtx,this.cfg=structuredClone(D),Object.assign(this.cfg,e)}ctx;cfg;play(e=T.sfxGain){let t=this.ctx,r=t.currentTime,i=this.cfg,a=t.createGain();a.gain.setValueAtTime(1e-4,r);let u=i.ampEnv;a.gain.exponentialRampToValueAtTime(u.volume,r+u.attack),a.gain.exponentialRampToValueAtTime(Math.max(1e-4,u.sustain*u.volume),r+u.attack+u.decay),a.gain.exponentialRampToValueAtTime(1e-4,r+i.duration+u.release);let c=a,s;i.filter.enabled&&(s=t.createBiquadFilter(),s.type=i.filter.type,s.frequency.value=i.filter.freq,s.Q.value=i.filter.Q,s.connect(a),c=s);let o;if(i.osc.enabled){if(o=t.createOscillator(),o.type=i.osc.type,o.frequency.value=i.osc.freq,o.detune.value=i.osc.detune,i.pitchEnv.amount!==0){let h=Math.pow(2,i.pitchEnv.amount/12);o.frequency.exponentialRampToValueAtTime(i.osc.freq*h,r+i.pitchEnv.decay)}o.connect(c),o.start(r),o.stop(r+i.duration+u.release)}let l;if(i.noise.enabled){let h=t.sampleRate*i.duration,d=t.createBuffer(1,h,t.sampleRate),g=d.getChannelData(0);for(let x=0;x<h;x++)g[x]=(Math.random()*2-1)*i.noise.level;l=t.createBufferSource(),l.buffer=d,l.connect(c),l.start(r),l.stop(r+i.duration+u.release)}let m,p;i.lfo.enabled&&o&&(m=t.createOscillator(),m.frequency.value=i.lfo.rate,p=t.createGain(),p.gain.value=i.lfo.depth,m.connect(p),i.lfo.target==="freq"?p.connect(o.frequency):i.lfo.target==="gain"?p.connect(a.gain):i.lfo.target==="filter"&&s&&p.connect(s.frequency),m.start(r),m.stop(r+i.duration)),a.connect(e);let R=[o,l,m,p,s,a],C=r+i.duration+u.release;setTimeout(()=>{R.forEach(h=>h?.disconnect())},(C-t.currentTime)*1e3)}getConfig(){return structuredClone(this.cfg)}setConfig(e){return Object.assign(this.cfg,e),this}getKey(e){return this.cfg[e]}setKey(e,t){return Object.assign(this.cfg[e],t),this}setFreq(e){return this.cfg.osc.freq=e,this}setWave(e){return this.cfg.osc.type=e,this}setVolume(e){return this.cfg.ampEnv.volume=e,this}setAmpEnv(e,t,r,i){return Object.assign(this.cfg.ampEnv,{attack:e,decay:t,sustain:r,release:i}),this}setPitchEnv(e,t){return Object.assign(this.cfg.pitchEnv,{amount:e,decay:t}),this}setNoiseEnabled(e){return this.cfg.noise.enabled=e,this}setNoiseLevel(e){return this.cfg.noise.level=e,this}setFilterEnabled(e){return this.cfg.filter.enabled=e,this}setFilter(e,t,r){return Object.assign(this.cfg.filter,{type:e,freq:t,Q:r,enabled:!0}),this}setLFOEnabled(e){return this.cfg.lfo.enabled=e,this}setLFO(e,t,r){return Object.assign(this.cfg.lfo,{target:e,rate:t,depth:r,enabled:!0}),this}setDuration(e){return this.cfg.duration=e,this}clone(){return new n(structuredClone(this.cfg))}},X=new v({osc:{enabled:!0,type:"square",freq:900,detune:0},ampEnv:{attack:.002,decay:.04,sustain:0,release:.02,volume:.15},duration:.05}),B=new v({osc:{enabled:!0,type:"sine",freq:600,detune:0},ampEnv:{attack:.01,decay:.08,sustain:0,release:.04,volume:.12},duration:.1}),U=new v({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}),H=new v({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}),$=new v({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}),ie=new Map([["ui_click",X],["ui_hover",B],["jump",U],["laser",H],["hit",$]]);function se(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(n)),r=Array.from(t).map(i=>i.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}function ae(n=12){let e=Date.now().toString(36),t=crypto.getRandomValues(new Uint8Array(4)),r=Array.from(t).map(i=>i.toString(36).padStart(2,"0")).join("");return(e+r).slice(0,n)}var L=class{peer=null;key;events={};mbAcc=0;connected=!1;constructor(){this.key=`${W()}_${Date.now()}`}connect(e){e&&(this.peer=e,e.peer=this,this.connected=!0,e.connected=!0),this._emit("open")}isConnected(){return this.connected&&!!this.peer}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(r=>r!==t))}_emit(e,t){this.events[e]?.forEach(r=>r(t))}send(e,t){if(!this.peer)throw new Error("No peer connected");this.peer._receive(e,t)}_receive(e,t){e?this._emit(e,t):this._emit("message",t)}close(){if(this.connected=!1,this.peer){let e=this.peer;this.peer=null,e.peer=null,e.connected=!1,e._emit("close")}this._emit("close")}getKey(){return this.key}};function W(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let n=new Uint8Array(16);return crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,[...n].map(e=>e.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5")}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function j(n){let e=!0;function t(){e&&(n(),requestAnimationFrame(t))}return requestAnimationFrame(t),{clear:()=>e=!1}}function Q(n,e,t,r,i){let a=Math.cos(i),u=Math.sin(i),c=[];if(a!==0){let s=(0-n)/a,o=e+s*u;s>0&&o>=0&&o<=r&&c.push({side:"left",t:s})}if(a!==0){let s=(t-n)/a,o=e+s*u;s>0&&o>=0&&o<=r&&c.push({side:"right",t:s})}if(u!==0){let s=(0-e)/u,o=n+s*a;s>0&&o>=0&&o<=t&&c.push({side:"top",t:s})}if(u!==0){let s=(r-e)/u,o=n+s*a;s>0&&o>=0&&o<=t&&c.push({side:"bottom",t:s})}return c.length===0?null:(c.sort((s,o)=>s.t-o.t),c[0])}function J(n,e){let t;switch(e){case"left":case"right":t=Math.PI-n;break;case"top":case"bottom":t=2*Math.PI-n;break}return(t%(2*Math.PI)+2*Math.PI)%(2*Math.PI)}function oe(n,e,t,r,i){let a=Q(n,e,t,r,i);return a?{...a,avoidAngle:J(i,a.side)}:null}function Y(){return S?!1:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}var ue=Y();export{_ as DeltaTweenII,N as ENVIRONMENT,L as GEmitterMemory,E as LeaEntityII,y as LeaEventEmitter,V as LeaGameII,F as LeaRendererII,P as LeaSceneII,z as LeaSerializers,I as LeaTickerII,A as LeaTimeout,f as LeaUtilsII,T as LiaAudio,w as LiaAudioSrc,v as LiaOscSFX,ie as LiaSFXMap,q as NOTE_NAMES,K as RectLeaEntity,M as Vector2,ee as colToRGBA,D as defaultSFXConfig,te as editRGBA,W as generateUUID,J as getAvoidAngle,O as getEnvironment,Z as getNormalizedColor,Q as getRayHit,ue as isInitiallyMobile,Y as isMobile,S as isNode,re as isNote,b as isWeb,G as parseFillStyle,oe as raycastAvoid,ne as scaleCoord,j as setAnimInterval,$ as sfxHit,U as sfxJump,H as sfxLaser,X as sfxUIClick,B as sfxUIHover,se as shortUID,ae as tinyUID};
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@kayelaa/canvas",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Declarative entity composition hooks + canvas utilities for LEA-based 2D games",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Kayelaa Cagara",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./dist/index.cjs",
|
|
9
|
+
"module": "./dist/index.js",
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"import": "./dist/index.js",
|
|
14
|
+
"require": "./dist/index.cjs"
|
|
15
|
+
},
|
|
16
|
+
"./kayla": {
|
|
17
|
+
"import": "./dist/kayla.js",
|
|
18
|
+
"require": "./dist/kayla.cjs"
|
|
19
|
+
},
|
|
20
|
+
"./lea": {
|
|
21
|
+
"import": "./dist/lea.js",
|
|
22
|
+
"require": "./dist/lea.cjs"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsup",
|
|
30
|
+
"clean": "rm -rf dist"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@types/web": "^0.0.327",
|
|
34
|
+
"tsup": "^8.5.1",
|
|
35
|
+
"typescript": "^5.9.3"
|
|
36
|
+
}
|
|
37
|
+
}
|