A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
chore: sync SDK build output
esengine0e1fd75a584f
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.jsindex f621e0230..2ed599da4 100644--- a/desktop/public/sdk/esm/esengine.js+++ b/desktop/public/sdk/esm/esengine.js@@ -1,2 +1,2 @@-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return null!==e}function n(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function d(e,s){return t().instantiateWasm(e,s)}function u(e,s){return t().createCanvas(e,s)}function h(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new p(this.context_,e),s=e.parent?this.buses_.get(e.parent):this.master;return s&&s.addChild(t),this.buses_.set(e.name,t),t}}class _{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class g{constructor(e,t,s,n,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=s,this.poolNode_=n,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}class y{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.urlToId_=new Map,this.loadingUrls_=new Map,this.nextBufferId_=0,this.nextHandleId_=0,this.resumeHandler_=null}get mixer(){return this.mixer_}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new m(this.context_,e.mixerConfig),this.pool_=new _(this.context_,e.initialPoolSize),"suspended"===this.context_.state){const e=()=>{this.context_.resume(),document.removeEventListener("touchstart",e),document.removeEventListener("mousedown",e),document.removeEventListener("keydown",e),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}async ensureResumed(){this.context_&&"suspended"===this.context_.state&&await this.context_.resume()}async loadBuffer(e){if(!this.context_)throw new Error("AudioContext not initialized");const t=this.urlToId_.get(e);if(void 0!==t&&this.buffers_.has(t)){return{id:t,duration:this.buffers_.get(t).duration}}const s=this.loadingUrls_.get(e);if(s)return s;const n=this.doLoadBuffer_(e);this.loadingUrls_.set(e,n);try{return await n}finally{this.loadingUrls_.delete(e)}}async doLoadBuffer_(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to load audio: ${e} (${t.status})`);const s=await t.arrayBuffer();let n;try{n=await this.context_.decodeAudioData(s)}catch(t){throw new Error(`Failed to decode audio ${e}: ${t.message}`)}const i=++this.nextBufferId_;return this.buffers_.set(i,n),this.urlToId_.set(e,i),{id:i,duration:n.duration}}unloadBuffer(e){this.buffers_.delete(e.id)}play(e,t){if(!this.context_||!this.pool_||!this.mixer_)throw new Error("Audio system not initialized");const s=this.buffers_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=this.pool_.acquire(),i=this.context_.createBufferSource();i.buffer=s,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(n.gain),n.source=i,n.gain.gain.value=t.volume??1,n.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;n.panner.connect(r.node);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new g(l,i,s,n,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.urlToId_.clear(),this.loadingUrls_.clear(),this.context_?.close(),this.context_=null}}const w=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const s=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),n={};return s.headers.forEach((e,t)=>{n[t]=e}),{ok:s.ok,status:s.status,statusText:s.statusText,headers:n,json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async loadImagePixels(e){const t=this.createImage();await new Promise((s,n)=>{t.crossOrigin="anonymous",t.onload=()=>s(),t.onerror=()=>n(new Error(`Failed to load image: ${e}`)),t.src=e});const s=this.createCanvas(t.width,t.height).getContext("2d");s.drawImage(t,0,0);const n=s.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(n.data.buffer)}}async instantiateWasm(e,t){let s;s="string"==typeof e?await this.readFile(e):e;const n=await WebAssembly.instantiate(s,t);return{instance:n.instance,module:n.module}}createImage(){return new Image}createCanvas(e,t){let s;return s="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),s.width=e,s.height=t,s}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t??document.querySelector("canvas")??document.body,n=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),o=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},r=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},d=()=>{e.onPointerUp(0)},u=t=>{const s=t;let n=s.deltaX,i=s.deltaY;1===s.deltaMode?(n*=16,i*=16):2===s.deltaMode&&(n*=window.innerWidth,i*=window.innerHeight),e.onWheel(n,i)};document.addEventListener("keydown",n),document.addEventListener("keyup",i),s.addEventListener("mousemove",o),s.addEventListener("mousedown",r),document.addEventListener("mouseup",a),s.addEventListener("touchstart",l),s.addEventListener("touchmove",c),s.addEventListener("touchend",d),s.addEventListener("wheel",u),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",i),s.removeEventListener("mousemove",o),s.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),s.removeEventListener("touchstart",l),s.removeEventListener("touchmove",c),s.removeEventListener("touchend",d),s.removeEventListener("wheel",u)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new y}},x=1920,v=1080,b=100,S=512,M={x:100,y:100},P="Arial",T=24,E=1.2,C=.5,R=1/60,A={x:0,y:-9.81},I=1/60,k="default",F={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function B(e){e.Text&&(e.Text._default.fontFamily=F.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=F.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=F.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=F.canvasMatchWidthOrHeight)}const z={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function U(e,t){if(void 0!==t.maxDeltaTime&&(F.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(F.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(F.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(F.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(F.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");F.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(F.canvasScaleMode=z[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(F.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const $=0,D=4294967295,L=4294967295,O=0,W=(e=0,t=0)=>({x:e,y:t}),H=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),X=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),j=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),Y=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function V(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(V);const t={};for(const s in e)t[s]=V(e[s]);return t}let N=0;function G(e,t){const s=++N,n=function(e){for(const t in e){const s=e[t];if(null!==s&&"object"==typeof s)return!0}return!1}(t);return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>n?e?{...V(t),...e}:V(t):e?{...t,...e}:{...t}}}function q(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function K(e,t){const s=ne.get(e)??q().get(e);if(s)return s;const n=G(e,t);return q().set(e,n),ne.set(e,n),te(e,t,!1),n}function J(e){const t=ne.get(e)??q().get(e);if(t)return t;const s=G(e,{});return q().set(e,s),ne.set(e,s),te(e,{},!0),s}function Q(e){return q().get(e)}function Z(){const e=q();for(const t of e.keys())ne.delete(t);e.clear()}function ee(e){q().delete(e),ne.delete(e)}function te(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function se(e){return!0===e._builtin}const ne=new Map;function ie(e,t){ne.set(e,t)}function oe(e){return ne.get(e)??Q(e)}function re(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return ne.set(e,s),s}const ae={Perspective:0,Orthographic:1},le={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ce={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},de=re("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),ue=de,he=de,fe=re("Sprite",{texture:D,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),pe=re("Camera",{projectionType:ae.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:le.ColorAndDepth}),me=re("Canvas",{designResolution:{x:x,y:v},pixelsPerUnit:100,scaleMode:ce.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),_e=re("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),ge=re("Parent",{entity:0}),ye=re("Children",{entities:[]}),we=re("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:L,enabled:!0}),xe=re("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),ve=K("Name",{value:""}),be=K("SceneOwner",{scene:"",persistent:!1});function Se(e){const t=oe(e);return t?V(t._default):null}const Me=re("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Pe=re("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Te=re("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ee=re("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ce={Static:0,Kinematic:1,Dynamic:2};let Re=0;function Ae(e,t){const s=++Re;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Ie(e){return{_type:"res",_resource:e}}function ke(e){return{_type:"res_mut",_resource:e}}class Fe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class Be{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Fe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const ze=Ae({delta:0,elapsed:0,frameCount:0},"Time");function Ue(e,t,s){const n=[];for(const[e,i]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const s=$e(t[e]),o=$e(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function $e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function De(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let Le=null;function Oe(e){Le=e}function We(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Le&&Le(e,t)}function He(e){let t=!1;for(const s of Object.keys(e)){const n=e[s];if(null!=n&&"object"==typeof n&&!Array.isArray(n)){if("r"in n&&"g"in n&&"b"in n&&"a"in n&&!("x"in n)){t=!0;break}}}if(!t)return e;const s={};for(const t of Object.keys(e)){const n=e[t];if(null==n||"object"!=typeof n||Array.isArray(n))s[t]=n;else{const e=n;s[t]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:n}}return s}let Xe=1;const je=new WeakMap;function Ye(e){let t=je.get(e);return void 0===t&&(t=Xe++,je.set(e,t)),t}const Ve=[];function Ne(e,t=[],s=[]){Ve.length=0;for(const t of e)Ve.push(Ye(t));Ve.sort((e,t)=>e-t);let n=Ve.join(",");if(t.length>0){Ve.length=0;for(const e of t)Ve.push(Ye(e));Ve.sort((e,t)=>e-t),n+="|+"+Ve.join(",")}if(s.length>0){Ve.length=0;for(const e of s)Ve.push(Ye(e));Ve.sort((e,t)=>e-t),n+="|-"+Ve.join(",")}return n}class Ge{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw We(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){We(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t){this.tsStorage_.get(s)?.delete(e),this.componentAddedTicks_.get(s)?.delete(e),this.componentChangedTicks_.get(s)?.delete(e);let t=this.componentRemovedBuffer_.get(s);t||(t=[],this.componentRemovedBuffer_.set(s,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){We(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){We(t,`removeParent(entity=${e})`)}}insert(e,t,s){return se(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(se(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(s))}catch(s){We(s,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,s),this.recordChangedTick_(t,e)}get(e,t){return se(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return se(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(se(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return We(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");se(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_,n=s[`add${e}`],i=s[`get${e}`],o=s[`has${e}`],r=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:i.bind(s),has:o.bind(s),remove:r.bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Ue(t._name,t._default,n);if(e.length>0)throw new Error(De(t._name,e))}const i={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,He(i))}catch(s){We(s,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let s=!1;for(const n of Object.keys(t)){const i=t[n];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[n];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){s=!0;break}}}if(!s)return e;const n={};for(const s of Object.keys(e)){const i=e[s],o=t[s];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=i;else{const e=i,t=o;n[s]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return We(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return We(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){We(s,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const i=Ue(t._name,t._default,e);if(i.length>0)throw new Error(De(t._name,i));n=e}const i=t.create(n),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.add(s)}catch{}if(this.cppRegistry_)for(const[s,n]of ne)if(se(n)&&!t.has(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.add(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e=q();for(const n of s)for(const[s,i]of e)if(i._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const i=n??Ne(e,t,s),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;let r=null,a=1/0;for(const t of e)if(!se(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=r?r.keys():this.entities_.keys();for(const n of c){let i=!0;for(const t of e)if(!this.has(n,t)){i=!1;break}if(i)for(const e of t)if(!this.has(n,e)){i=!1;break}if(i)for(const e of s)if(this.has(n,e)){i=!1;break}i&&l.push(n)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,s){const n=this.componentAddedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}getRemovedEntitiesSince(e,t){const s=this.componentRemovedBuffer_.get(e._id);if(!s)return[];const n=[];for(const e of s)e.tick>t&&n.push(e.entity);return n}cleanRemovedBuffer(e){for(const[t,s]of this.componentRemovedBuffer_){let n=0;for(let t=0;t<s.length;t++)s[t].tick>=e&&(s[n++]=s[t]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let s=this.componentAddedTicks_.get(e._id);s||(s=new Map,this.componentAddedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordChangedTick_(e,t){let s=this.componentChangedTicks_.get(e._id);s||(s=new Map,this.componentChangedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordRemovedTick_(e,t){let s=this.componentRemovedBuffer_.get(e._id);s||(s=[],this.componentRemovedBuffer_.set(e._id,s)),s.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function qe(e){return{_type:"mut",_component:e}}function Ke(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Je(e){return{_filterType:"added",_component:e}}function Qe(e){return{_filterType:"changed",_component:e}}function Ze(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function et(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function tt(e){return Ke(e)||Ze(e)||et(e)?e._component:e}function st(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{Ke(e)&&n.push(t),Ze(e)?i.push({index:t,component:e._component}):et(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>st(e,[...t,...n],s),without:(...n)=>st(e,t,[...s,...n])}}function nt(...e){return st(e)}class it{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(tt),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=Ne(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:s}=this.descriptor_;if(0===t.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of t)if(!this.world_.isAddedSince(e,s.component,n))return!1;for(const t of s)if(!this.world_.isChangedSince(e,t.component,n))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of s)if(!o||this.passesChangeFilters_(d)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}r[0]=d;for(let e=0;e<n;e++)r[e+1]=this.world_.get(d,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=d}yield r}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function ot(e){return{_type:"removed",_component:e}}class rt{constructor(e,t,s){this.world_=e,this.component_=t,this.lastRunTick_=s}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function at(){return{_type:"commands"}}class lt{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=se(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ct{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new lt(this,null);return this.spawned_.push(e),e}entity(e){return new lt(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function dt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class ut{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class ht{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new ut)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new ut,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function ft(e){return{_type:"event_writer",_event:e}}function pt(e){return{_type:"event_reader",_event:e}}class mt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class _t{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var gt;function yt(){return{_type:"get_world"}}!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(gt||(gt={}));let wt=0;function xt(e,t,s){const n=++wt;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function vt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function bt(e){vt().push({schedule:gt.Update,system:e})}function St(e){vt().push({schedule:gt.Startup,system:e})}function Mt(e,t){vt().push({schedule:e,system:t})}class Pt{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);const s=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ct&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-s),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new it(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ct(this.world_,this.resources_);case"event_writer":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new mt(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new _t(s)}case"removed":{const t=e;return new rt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Tt{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Et=Ae(new Tt,"Input");class Ct{constructor(e){this.target_=e??null}build(e){const s=new Tt;e.insertResource(Et,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(gt.Last,xt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Rt=new Ct,At=Ae({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var It;function kt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(It||(It={}));let Ft=null,Bt=null,zt=1;const Ut=new Map;function $t(e){Ft=e,Bt=e.getResourceManager(),Nt()}function Dt(){0!==Ht&&Ft&&(Ft._free(Ht),Ht=0),Ut.clear(),zt=1,Wt=!1,jt.clear(),Yt=null,Bt=null,Ft=null}function Lt(){if(!Bt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Bt}const Ot={createShader:(e,t)=>Lt().createShader(e,t),releaseShader(e){e>0&&Lt().releaseShader(e)},create(e){const t=zt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??It.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Ut.set(t,s),t},get:e=>Ut.get(e),setUniform(e,t,s){const n=Ut.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,Ft?.invalidateMaterialCache(e))},getUniform(e,t){const s=Ut.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ut.get(e);s&&(s.blendMode=t,Ft?.invalidateMaterialCache(e))},getBlendMode(e){const t=Ut.get(e);return t?.blendMode??It.Normal},setDepthTest(e,t){const s=Ut.get(e);s&&(s.depthTest=t,Ft?.invalidateMaterialCache(e))},getShader(e){const t=Ut.get(e);return t?.shader??0},release(e){Ut.delete(e),Ft?.invalidateMaterialCache(e)},isValid:e=>Ut.has(e),releaseAll(){Ut.clear(),Ft?.clearMaterialCache()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??It.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ut.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=zt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ut.set(s,n),s},toAssetData(e,t){const s=Ut.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=Ut.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Wt=!1,Ht=0;const Xt=16384,jt=new Map;let Yt=null;function Vt(e){const t=(0===Ht&&Ft&&(Ht=Ft._malloc(Xt)),Ht);if(0===t||!Ft)return{ptr:0,count:0};let s=0,n=0;const i=Ft.HEAPU8,o=Ft.HEAPU32,r=Ft.HEAPF32;for(const[a,l]of e){if(kt(l))continue;let e=jt.get(a);e||(Yt||(Yt=new TextEncoder),e=Yt.encode(a),jt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(s+(4+d+4+16)>Xt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${Xt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.set(e,t+s),s+=d;let u=0,h=[0,0,0,0];if("number"==typeof l)u=0,h[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(u=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,h=[l.x,l.y,l.z,0]):"y"in l&&(u=1,h=[l.x,l.y,0,0]);o[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)r[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Nt(){if(!Ft||Wt)return;Ft.materialDataProvider=(e,t,s,n,i)=>{const o=Ut.get(e);if(!o)return Ft.HEAPU32[t>>2]=0,Ft.HEAPU32[s>>2]=0,Ft.HEAPU32[n>>2]=0,void(Ft.HEAPU32[i>>2]=0);Ft.HEAPU32[t>>2]=o.shader,Ft.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Vt(o.uniforms);Ft.HEAPU32[n>>2]=r,Ft.HEAPU32[i>>2]=a},Wt=!0}const Gt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class qt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),i=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Kt{constructor(e,t=""){this.cache_=new qt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ot.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ot.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const s=await l(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),o=await this.shaderLoader_.load(i);return{handle:Ot.createFromAsset(n,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}function Jt(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function Qt(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>({texture:s.get(e.texture)??0}))}}const Zt=new Map;function es(e){Zt.set(e.name,e)}function ts(e){Zt.delete(e)}function ss(e){return Zt.get(e)}function ns(){Zt.clear()}const is=K("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function os(e,t){const s=e.getEntitiesWithComponents([is]);for(const n of s){const s=e.get(n,is);if(!s.enabled||!s.playing||!s.clip)continue;const i=Zt.get(s.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*s.speed),r=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let a=r;if(s.frameTimer>=o&&(s.frameTimer-=o,s.currentFrame++,s.currentFrame>=i.frames.length&&(s.loop&&i.loop?s.currentFrame=0:(s.currentFrame=i.frames.length-1,s.playing=!1)),a=!0),a&&e.has(n,fe)){const t=i.frames[s.currentFrame],o=e.get(n,fe);o.texture=t.texture,e.insert(n,fe,o)}a&&e.insert(n,is,s)}}class rs{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static playSFX(e,t){const s={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},n=this.bufferCache_.get(e);if(!n){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const n=this.bufferCache_.get(e);n&&t.resolve(this.backend_.play(n,s))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(n,s)}static playBGM(e,t){const s=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const s=t?.volume??1,n=this.bgmVolume_;this.bgmVolume_=s,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,n):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:s,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,s)},n=this.bufferCache_.get(e);n?s(n):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&s(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const s=this.mixer_?.getBus(e);s&&(s.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,s){e.setVolume(0);const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(r*s),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,s){const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(s*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}rs.mixer_=null,rs.bufferCache_=new Map,rs.bgmHandle_=null,rs.bgmVolume_=1,rs.fadeAnimId_=0,rs.disposed_=!1;const as=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}]]);function ls(e,t){as.set(e,t)}function cs(e){const t=as.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function ds(e){return as.get(e)?.fields??[]}function us(e){return as.get(e)?.spine??null}const hs=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function fs(e,t){hs.set(e,t)}function ps(e){return hs.get(e)}function ms(e,t){const s=hs.get(e.type);if(!s)return;const n=e.data;for(const i of s){const s=n[i];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${s} which does not exist`),n[i]=void 0!==o?o:0}}}function _s(e,t){const s=new Map;for(const n of t.entities){if(!1===n.visible)continue;const t=e.spawn();s.set(n.id,t),e.insert(t,ve,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const i of n.components)ms(i,s),xs(e,t,i,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),i=s.get(n.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return s}function gs(e,t){return _s(e,t)}async function ys(e,t,s){const n=s?.assetServer,i=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,i){const o=new Map;for(const e of ws.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=as.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...ws.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),d=r.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...d]),i){for(const e of n.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=as.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const n=s[e.field];if("string"!=typeof n||!n)continue;const i=t.get(n);void 0!==i&&(s[e.field]=i)}}}(t,n,i,o,s?.collectAssets);const r=_s(e,t);if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return r}const ws=new Map([["texture",{async load(e,t,s,n){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,s);n.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["font",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,s);n.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["anim-clip",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=Jt(i),r=new Map,a=o.map(async e=>{try{const i=s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),n.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);es(Qt(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,s){const n=[...e].map(e=>s?`${s}/${e}`:`/${e}`);return await rs.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}]]);function xs(e,t,s,n){if("LocalTransform"!==s.type&&"WorldTransform"!==s.type||(s.type="Transform"),"UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===s.type){const e=s.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=oe(s.type);if(i)e.insert(t,i,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function vs(e,t){const s=e.getEntitiesWithComponents([pe]);for(const n of s){const s=e.get(n,pe);s&&(s.aspectRatio=t,e.insert(n,pe,s))}}function bs(e,t){const s=e.getEntitiesWithComponents([ve]);for(const n of s){const s=e.get(n,ve);if(s&&s.value===t)return n}return null}const Ss=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],Ms={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},Ps=new Map,Ts=new Set;for(const e of Ss)for(const t of e.extensions)Ps.set(t,e),Ts.add(t);function Es(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Cs(e){return Ps.get(Es(e))}function Rs(e){return Cs(e)?.editorType??"unknown"}function As(e){return Cs(e)?.addressableType??null}function Is(e){for(const t of Ss)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function ks(e){return Ts.has(e.toLowerCase())}function Fs(){return Ts}function Bs(e){return"string"==typeof e&&(!!e.includes("/")&&ks(Es(e)))}function zs(){const e=[];for(const t of Ss)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function Us(){return zs().map(e=>({type:"suffix",value:e}))}function $s(e){return Ms[e.toLowerCase()]}function Ds(e){const t=Cs(e);return t?.wechatPackInclude??!1}function Ls(e){const t=Cs(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const s=e.lastIndexOf(".");return s>=0?e.substring(0,s)+".json":e}class Os{constructor(e){this.textureCache_=new qt,this.shaderCache_=new qt,this.jsonCache_=new qt,this.textCache_=new qt,this.binaryCache_=new qt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new qt,this.prefabCache_=new qt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=u(F.textCanvasSize,F.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Kt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),i=this.textureCache_.get(n);if(!i)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Ot.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const i=this.resolveUrl(t,s),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),d="binary"===Cs(e)?.contentType,u=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,d);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),i=l.find(e=>e.name===s);if(i){const s=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,i.info.width,i.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=Cs(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const i=s?`${s}/${n}`:n;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${n}`:n,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,async()=>{const e=await this.fetchJson(s);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const s of e.entities){for(const e of s.components){if(!e.data)continue;for(const s of cs(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=us(e.type);if(s)for(const n of[s.skeletonField,s.atlasField]){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}}if(s.nestedPrefab?.prefabPath){const e=t(s.nestedPrefab.prefabPath);e&&(s.nestedPrefab.prefabPath=e)}}}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return ys(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const i=n.metadata?.atlas;i&&s.push(this.loadSpine(n.path,i).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.loadImageFromSrc(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((s,n)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const i=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.getEmbedded(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:i}=this.parseEsShader(t);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return Ot.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(n);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return Ot.createShader(i,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(Ls(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await l(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let i="";for(const e of n){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ws=Ae(null,"Assets");class Hs{build(e){const t=e.wasmModule;t?e.insertResource(Ws,new Os(t)):console.warn("AssetPlugin: No WASM module available")}}const Xs=new Hs;class js{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Ys(e,t){const s=e.getResource(Ws);s&&s.registerEmbeddedAssets(t)}async function Vs(e,t,s){const{entities:n,rootId:i}=await Gs(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},r=await ys(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=r.get(i);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:r}}const Ns=10;async function Gs(e,t,s,n,i,o=0){if(o>Ns)throw new Error(`Prefab nesting depth exceeded ${Ns}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(i?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Gs(e,n.nestedPrefab.overrides,s,a,i,o+1);r.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?r.get(n.parent)??null:null),l.push(...t.entities);continue}const c=r.get(n.prefabEntityId),d=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:d?null:null!==n.parent?r.get(n.parent)??null:null,children:n.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};qs(u.components,r),Ks(u,t),l.push(u)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function qs(e,t){for(const s of e){const e=ps(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(s.data[n]=i)}}}}function Ks(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class Js{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,i=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Vs(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Qs=Ae(null,"Prefabs");class Zs{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ws]}build(e){const t=e.getResource(Ws);e.insertResource(Qs,new Js(e.world,t))}}const en=new Zs;let tn=null,sn=0,nn=0,on=0;const rn=new Float32Array(256);function an(e){tn=e,sn=tn._malloc(64),nn=tn._malloc(64),on=tn._malloc(1024)}function ln(){tn&&(sn&&(tn._free(sn),sn=0),nn&&(tn._free(nn),nn=0),on&&(tn._free(on),on=0)),tn=null}function cn(){if(!tn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return tn}const dn={r:1,g:1,b:1,a:1},un={begin(e){const t=cn();try{t.HEAPF32.set(e,sn/4),t.draw_begin(sn)}catch(e){We(e,"Draw.begin")}},end(){try{cn().draw_end()}catch(e){We(e,"Draw.end")}},line(e,t,s,n=1){try{cn().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.line")}},rect(e,t,s,n=!0){try{cn().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{cn().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{cn().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){We(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{cn().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){We(e,"Draw.circleOutline")}},texture(e,t,s,n=dn){try{cn().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){We(e,"Draw.texture")}},textureRotated(e,t,s,n,i=dn){try{cn().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){We(e,"Draw.textureRotated")}},setLayer(e){cn().draw_setLayer(e)},setDepth(e){cn().draw_setDepth(e)},getDrawCallCount:()=>tn?tn.draw_getDrawCallCount():0,getPrimitiveCount:()=>tn?tn.draw_getPrimitiveCount():0,setBlendMode(e){cn().draw_setBlendMode(e)},setDepthTest(e){cn().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=cn();n.HEAPF32.set(s,nn/4),n.draw_mesh(e,t,nn)}catch(s){We(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=cn(),i=Ot.get(t);if(!i)return;if(un.setBlendMode(i.blendMode),un.setDepthTest(i.depthTest),0===i.uniforms.size)return void un.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,nn/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=pn(t);if(!(n<0)){if(kt(s))rn[o++]=10,rn[o++]=n,rn[o++]=s.slot??e++,rn[o++]=s.textureId;else if("number"==typeof s)rn[o++]=1,rn[o++]=n,rn[o++]=s;else if(Array.isArray(s)){rn[o++]=s.length,rn[o++]=n;for(let e=0;e<s.length;e++)rn[o++]=s[e]}else"w"in s?(rn[o++]=4,rn[o++]=n,rn[o++]=s.x,rn[o++]=s.y,rn[o++]=s.z,rn[o++]=s.w):"z"in s?(rn[o++]=3,rn[o++]=n,rn[o++]=s.x,rn[o++]=s.y,rn[o++]=s.z):(rn[o++]=2,rn[o++]=n,rn[o++]=s.x,rn[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(rn.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,nn);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),on/4),n.draw_meshWithUniforms(e,i.shader,nn,on,o)}catch(s){We(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},hn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},fn=new Set;function pn(e){const t=hn[e];return void 0!==t?t:(fn.has(e)||(fn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(hn).join(", ")}`)),-1)}const mn=new Map;function _n(e,t,s){mn.set(e,{fn:t,scene:s??""})}function gn(e){mn.delete(e)}function yn(){mn.clear()}var wn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(wn||(wn={}));let xn=null,vn=0,bn=0,Sn=0;function Mn(e){xn=e,vn=xn._malloc(262144),bn=xn._malloc(65536),Sn=xn._malloc(256)}function Pn(){xn&&(vn&&xn._free(vn),bn&&xn._free(bn),Sn&&xn._free(Sn),vn=0,bn=0,Sn=0),xn=null}function Tn(){if(!xn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return xn}const En={create(e){const t=Tn(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,vn/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Sn,i).set(o),t.geometry_init(s,vn,n,Sn,i,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,bn,n).set(e.indices),t.geometry_setIndices16(s,bn,n)}else{new Uint32Array(t.HEAPU8.buffer,bn,n).set(e.indices),t.geometry_setIndices32(s,bn,n)}}return s},updateVertices(e,t,s=0){const n=Tn(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,vn/4),n.geometry_updateVertices(e,vn,i,s)},release(e){e>0&&Tn().geometry_release(e)},isValid:e=>!(!xn||e<=0)&&xn.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return En.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:wn.Float2},{name:"a_texCoord",type:wn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const i=n/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;s.push(o,r,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return En.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:wn.Float2},{name:"a_texCoord",type:wn.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,i=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(n-t),a=(r.y-s)/(i-s);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return En.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:wn.Float2},{name:"a_texCoord",type:wn.Float2}],indices:new Uint16Array(r)})}};let Cn=null;function Rn(e){Cn=e}function An(){Cn&&kn.isInitialized()&&kn.shutdown(),Cn=null}function In(){if(!Cn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Cn}const kn={init(e,t){try{return In().postprocess_init(e,t)}catch(s){return We(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{In().postprocess_shutdown()}catch(e){We(e,"PostProcess.shutdown")}},resize(e,t){try{In().postprocess_resize(e,t)}catch(s){We(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return In().postprocess_addPass(e,t)}catch(t){return We(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{In().postprocess_removePass(e)}catch(t){We(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{In().postprocess_setPassEnabled(e,t)}catch(t){We(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return In().postprocess_isPassEnabled(e)}catch(t){return We(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{In().postprocess_setUniformFloat(e,t,s)}catch(s){We(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{In().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){We(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{In().postprocess_begin()}catch(e){We(e,"PostProcess.begin")}},end(){try{In().postprocess_end()}catch(e){We(e,"PostProcess.end")}},getPassCount(){try{return In().postprocess_getPassCount()}catch(e){return We(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Cn)return!1;try{return Cn.postprocess_isInitialized()}catch(e){return We(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{In().postprocess_setBypass(e)}catch(e){We(e,"PostProcess.setBypass")}},isBypassed(){if(!Cn)return!0;try{return Cn.postprocess_isBypassed()}catch(e){return We(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ot.createShader(Fn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Ot.createShader(Fn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ot.createShader(Fn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ot.createShader(Fn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Fn="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Bn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Bn||(Bn={}));let zn=null,Un=0;function $n(e){zn=e,Un=zn._malloc(64)}function Dn(){zn&&Un&&(zn._free(Un),Un=0),zn=null}const Ln={init(e,t){zn?.renderer_init(e,t)},resize(e,t){zn?.renderer_resize(e,t)},begin(e,t){if(zn&&Un)try{zn.HEAPF32.set(e,Un/4),zn.renderer_begin(Un,t??0)}catch(e){We(e,"Renderer.begin")}},flush(){try{zn?.renderer_flush()}catch(e){We(e,"Renderer.flush")}},end(){try{zn?.renderer_end()}catch(e){We(e,"Renderer.end")}},submitSprites(e){if(zn)try{zn.renderer_submitSprites(e._cpp)}catch(e){We(e,"Renderer.submitSprites")}},submitBitmapText(e){if(zn)try{zn.renderer_submitBitmapText(e._cpp)}catch(e){We(e,"Renderer.submitBitmapText")}},submitSpine(e){if(zn)try{zn.renderer_submitSpine?.(e._cpp)}catch(e){We(e,"Renderer.submitSpine")}},setStage(e){zn?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>zn?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){zn?.renderer_releaseTarget(e)},getTargetTexture:e=>zn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>zn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){zn?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){zn?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){zn?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){zn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>zn?zn.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>zn?{drawCalls:zn.renderer_getDrawCalls(),triangles:zn.renderer_getTriangles(),sprites:zn.renderer_getSprites(),text:zn.renderer_getText(),spine:zn.renderer_getSpine?.()??0,meshes:zn.renderer_getMeshes(),culled:zn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let On=null;function Wn(e){On=e}function Hn(){On=null}const Xn={enable(){On?.gl_enableErrorCheck(!0)},disable(){On?.gl_enableErrorCheck(!1)},check:e=>On?.gl_checkErrors(e)??0,diagnose(){On?.renderer_diagnose()}};class jn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Ln.resize(n,i),kn.isInitialized()&&kn.getPassCount()>0&&kn.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Ln.setViewport(0,0,n,i),Ln.clearBuffers(3),Ln.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),Ln.submitSprites(t),Ln.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ln.submitSpine(t),Ln.flush(),this.executeDrawCallbacks(s,o),Ln.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o}=e;Ln.setViewport(n.x,n.y,n.w,n.h),Ln.setScissor(n.x,n.y,n.w,n.h,!0),Ln.clearBuffers(i),Ln.setScissor(0,0,0,0,!1),Ln.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ln.submitSprites(t),Ln.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ln.submitSpine(t),Ln.flush(),this.executeDrawCallbacks(s,o),Ln.end()}executeDrawCallbacks(e,t){const s=mn;if(s.size>0){un.begin(e);const n=[];for(const[e,i]of s.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}un.end();for(const e of n)gn(e)}}}const Yn="__scene_transition_overlay__";class Vn{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Nn{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,be,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),_n(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=kn.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){kn.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,be)){const s=this.app_.world.get(e,be);s.persistent=t,this.app_.world.insert(e,be,s)}}}class Gn{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??F.sceneTransitionDuration,i=t.color??{...F.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},_n(Yn,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;un.setLayer(9999),un.setDepth(9999),un.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,gn(Yn),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,gn(Yn),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Vn(t);this.scenes_.set(e,s);const n=new Nn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Ws)?this.app_.getResource(Ws):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Vn(t);this.scenes_.set(e,s);const n=new Nn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Ws)?this.app_.getResource(Ws):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const i=t?.keepPersistent??!0;for(const e of s.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,be)){if(this.app_.world.get(e,be).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())gn(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{kn.removePass(e)}catch{}s.postProcessPasses.length=0,this.releaseSceneAssets_(s),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:s};this.app_.hasResource(Ws)&&(i.assetServer=this.app_.getResource(Ws));const o=await ys(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,be,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=Kn(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const i=this.contexts_.get(t);s.setup&&await s.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource(Ws)?this.app_.getResource(Ws):null;if(s){for(const e of t.textureUrls)s.releaseTexture(e);for(const e of t.fontPaths)s.releaseFont(e);for(const e of t.spineKeys)s.releaseSpine(e)}for(const e of t.materialHandles)Ot.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let i=!1;if(s.has(e,fe)){const t=s.get(e,fe);n.sprite=t.color.a,t.color.a=0,s.insert(e,fe,t),i=!0}if(s.has(e,xe)){const t=s.get(e,xe);n.spine=t.color.a,t.color.a=0,s.insert(e,xe,t),i=!0}if(s.has(e,we)){const t=s.get(e,we);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,we,t),i=!0}i&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,fe)){const t=s.get(e,fe);t.color.a=n.sprite,s.insert(e,fe,t)}if(void 0!==n.spine&&s.has(e,xe)){const t=s.get(e,xe);t.color.a=n.spine,s.insert(e,xe,t)}if(void 0!==n.bitmapText&&s.has(e,we)){const t=s.get(e,we);t.color.a=n.bitmapText,s.insert(e,we,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{kn.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const qn=Ae(null,"SceneManager");function Kn(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(qn).getSceneStatus(t)&&s._fn(...n)}}}const Jn=xt([ke(qn),Ie(ze)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Qn={name:"SceneManager",build(e){const t=new Gn(e);e.insertResource(qn,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(qn),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(gt.Startup,s),e.addSystemToSchedule(gt.Last,Jn)}};class Zn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new ht,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(gt.Last);else{this.runSchedule(gt.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(gt.FixedPreUpdate),this.runSchedule(gt.FixedUpdate),this.runSchedule(gt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(gt.PreUpdate),this.runSchedule(gt.Update),this.runSchedule(gt.PostUpdate),this.runSchedule(gt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Ge,this.resources_=new Be;for(const e of Object.values(gt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Zn}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(gt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(gt.Startup,e)}removeSystem(e){let t=!1;for(const[s,n]of this.systems_){const i=n.filter(t=>t.system._id!==e);i.length!==n.length&&(this.systems_.set(s,i),this.sortedSystemsCache_.delete(s),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return Oe(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(qn).register(e),this}setInitialScene(e){return this.getResource(qn).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new Pt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(ze)||this.resources_.insert(ze,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(gt.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(gt.Last);else{this.runSchedule(gt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(gt.FixedPreUpdate),this.runSchedule(gt.FixedUpdate),this.runSchedule(gt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(gt.PreUpdate),this.runSchedule(gt.Update),this.runSchedule(gt.PostUpdate),this.runSchedule(gt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new Pt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(ze,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(gt.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,yn();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Hn,Dn,An,Pn,Dt,ln];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const i=t.get(n);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,i=new Set,o=r=>{if(n.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}i.delete(r),n.add(r),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(ze);t.delta=e,t.elapsed+=e,t.frameCount++}}function ei(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const ti=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function si(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case ce.FixedWidth:return o;case ce.FixedHeight:return r;case ce.Expand:return Math.max(o,r);case ce.Shrink:return Math.min(o,r);case ce.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const ni=[];function ii(e){if(e<ni.length)return ni[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return ni.push(t),t}function oi(e,t,s,n,i,o){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,be);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*s/(i.viewportH*n);let a,d=0,u=0;if(i.projectionType===ae.Orthographic){if(u=i.orthoSize,l){u=si(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}d=u*r,a=ai(-d,d,-u,u,-i.farPlane,i.farPlane)}else a=ci(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=ui(o.position.x,o.position.y,o.position.z),f=ii(c.length);f.entity=e,f.viewProjection.set(fi(a,h)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=d,f.halfH=u,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const ri=new Float32Array(16);function ai(e,t,s,n,i,o){const r=ri;r.fill(0);const a=t-e,l=n-s,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(n+s)/l,r[14]=-(o+i)/c,r[15]=1,r}const li=new Float32Array(16);function ci(e,t,s,n){const i=li;i.fill(0);const o=1/Math.tan(e/2),r=s-n;return i[0]=o/t,i[5]=o,i[10]=(n+s)/r,i[11]=-1,i[14]=2*n*s/r,i}const di=new Float32Array(16);function ui(e,t,s){const n=di;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const hi=new Float32Array(16);function fi(e,t){const s=hi;for(let n=0;n<4;n++)for(let i=0;i<4;i++)s[4*i+n]=e[0+n]*t[4*i+0]+e[4+n]*t[4*i+1]+e[8+n]*t[4*i+2]+e[12+n]*t[4*i+3];return s}const pi={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function mi(e,t,s,n,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,d=o.left+t.x*a,u=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,m,_;e.x===t.x?(f=c+s.x-i.x*r.x,m=f+i.x):(f=c+s.x,m=d+n.x),e.y===t.y?(p=u+s.y-i.y*r.y,_=p+i.y):(p=u+s.y,_=h+n.y);const g=Math.max(0,m-f),y=Math.max(0,_-p);return{originX:f+r.x*g,originY:p+r.y*y,width:g,height:y,rect:{left:f,bottom:p,right:m,top:_}}}const _i=re("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});let gi=null,yi=null;function wi(e,t){e.has(t,fe)||e.insert(t,fe,{texture:D,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function xi(e,t){switch(e){case pi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case pi.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case pi.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function vi(e,t){switch(e){case pi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case pi.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case pi.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function bi(e,t,s,n){switch(e){case pi.BottomToTop:case pi.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}}function Si(e,t,s,n){if(!e.has(t,_i))return;const i=e.get(t,_i),o=xi(s,n);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,_i,i)}function Mi(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Pi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Ti(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),i=[];for(const t of n){if(!t){i.push("");continue}let n="";for(let o=0;o<t.length;o++){const r=t[o],a=n+r;if(e.measureText(a).width>s&&n){if(Pi(r.charCodeAt(0))&&n.length>0&&Pi(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Pi(n.charCodeAt(t))){e=t;break}e>=0?(i.push(n.substring(0,e+1)),n=n.substring(e+1)+r):(i.push(n),n=r)}else i.push(n),n=r}else n=a}n&&i.push(n)}return i.length>0?i:[""]}function Ei(e){let t=1;for(;t<e;)t*=2;return t}function Ci(e,t){let s=0,n=t;for(;e.has(n,ge);){const t=e.get(n,ge).entity;if(!e.valid(t))break;s++,n=t}return s}function Ri(e,t){if(gi&&yi){const e=gi.getUIRectComputedWidth(yi,t);if(e>0)return e}return e.size.x}function Ai(e,t){if(gi&&yi){const e=gi.getUIRectComputedHeight(yi,t);if(e>0)return e}return e.size.y}function Ii(e,t,s,n,i,o){if(!e.has(t,fe))return;const r=e.get(t,fe);let a,l;switch(s){case pi.BottomToTop:case pi.TopToBottom:a=i,l=o*n;break;default:a=i*n,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,fe,r))}function ki(e,t,s){let n=t;for(;e.has(n,ge);){const t=e.get(n,ge).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Fi(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Bi(e,t,s,n,i){if(!e.has(t,_i))return;const o=e.get(t,_i),r=mi(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,fe)){const s=e.get(t,fe);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,fe,s))}if(e.has(t,de)){const s=e.get(t,de);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,de,s)}}function zi(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let i=0;i<t.length;i++)n[t[i]]=s[i](e);return n},changed(e,n){for(let i=0;i<t.length;i++)if(e[t[i]]!==s[i](n))return!0;return!1},update(e,n){for(let i=0;i<t.length;i++)e[t[i]]=s[i](n)}}}const Ui=.1,$i=30,Di={r:.3,g:.5,b:.8,a:1},Li={Left:0,Center:1,Right:2},Oi={Top:0,Middle:1,Bottom:2},Wi={Visible:0,Clip:1,Ellipsis:2},Hi=K("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Li.Left,verticalAlign:Oi.Top,wordWrap:!0,overflow:Wi.Visible,lineHeight:1.2});class Xi{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=u(F.textCanvasSize,F.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Ei(this.frameMaxW_)),e.height=Math.max(e.height,Ei(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ei(this.frameMaxW_),e.height=Ei(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Ti(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=i?Math.ceil(o):u+2*d,p=i?Math.ceil(r):h+2*d;if(i&&e.overflow===Wi.Ellipsis&&h>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(n.width<f||n.height<p)&&(n.width=Math.max(n.width,Ei(f)),n.height=Math.max(n.height,Ei(p)));const m=Math.round(255*e.color.r),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,i&&e.overflow===Wi.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case Oi.Top:x=d;break;case Oi.Middle:x=d+(p-2*d-w)/2;break;case Oi.Bottom:x=p-w-d;break;default:x=d}x<0&&(x=0)}else x=d;let v=x;for(const t of l){let n;switch(e.align){case Li.Left:n=d;break;case Li.Center:n=f/2;break;case Li.Right:n=f-d;break;default:n=d}s.fillText(t,n,v),v+=c}i&&e.overflow===Wi.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const T=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const i=this.renderText(t,s);return this.cache.set(e,i),i}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case Li.Left:return"left";case Li.Center:return"center";case Li.Right:return"right"}}}const ji=zi({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Ri(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Ai(e.uiRect,e.entity):0});class Yi{build(e){ie("Text",Hi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Xi(t),n=e.world,i=new Map;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Hi));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Hi)){if(n.valid(e)&&n.has(e,fe)){const t=n.get(e,fe);n.insert(e,fe,{texture:D,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=n.getEntitiesWithComponents([Hi]);for(const t of e){const e=n.get(t,Hi),o=n.has(t,_i)?n.get(t,_i):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!ji.changed(a,r)){if(n.has(t,fe)&&n.get(t,fe).texture!==D)continue}wi(n,t);const l=o?{size:{x:Ri(o,t),y:Ai(o,t)}}:null,c=s.renderForEntity(t,e,l),d=n.get(t,fe);n.insert(t,fe,{texture:c.textureHandle,color:{r:d.color.r,g:d.color.g,b:d.color.b,a:d.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:d.layer,flipX:d.flipX,flipY:d.flipY,material:d.material,enabled:d.enabled}),i.set(t,ji.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Vi=new Yi,Ni=0,Gi=1,qi=re("UIMask",{enabled:!0,mode:Ni});function Ki(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,i-s),h:Math.max(0,o-n)}}function Ji(e,t){const s=t??new Float32Array(16),n=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],d=e[7],u=e[8],h=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=e[14],y=e[15],w=n*l-i*a,x=n*c-o*a,v=n*d-r*a,b=i*c-o*l,S=i*d-r*l,M=o*d-r*c,P=u*_-h*m,T=u*g-f*m,E=u*y-p*m,C=h*g-f*_,R=h*y-p*_,A=f*y-p*g;let I=w*A-x*R+v*C+b*E-S*T+M*P;return 0===I||(I=1/I,s[0]=(l*A-c*R+d*C)*I,s[1]=(o*R-i*A-r*C)*I,s[2]=(_*M-g*S+y*b)*I,s[3]=(f*S-h*M-p*b)*I,s[4]=(c*E-a*A-d*T)*I,s[5]=(n*A-o*E+r*T)*I,s[6]=(g*v-m*M-y*x)*I,s[7]=(u*M-f*v+p*x)*I,s[8]=(a*R-l*E+d*P)*I,s[9]=(i*E-n*R-r*P)*I,s[10]=(m*S-_*v+y*w)*I,s[11]=(h*v-u*S-p*w)*I,s[12]=(l*T-a*C-c*P)*I,s[13]=(n*C-i*T+o*P)*I,s[14]=(_*x-m*b-g*w)*I,s[15]=(u*b-h*x+f*w)*I),s}function Qi(e,t,s,n,i,o,r){const a=(e-n)/o*2-1,l=(t-i)/r*2-1,c=s[0]*a+s[4]*l+s[12],d=s[1]*a+s[5]*l+s[13],u=s[3]*a+s[7]*l+s[15];return{x:c/u,y:d/u}}function Zi(e,t,s,n,i,o,r,a){return e>=s-i*r&&e<=s+i*(1-r)&&t>=n-o*a&&t<=n+o*(1-a)}function eo(e,t){return 2*Math.atan2(e,t)}function to(e,t,s,n,i,o,r){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function so(e,t,s,n,i,o,r,a,l,c){const d=eo(l,c),u=Math.sin(-d),h=Math.cos(-d),f=e-s,p=t-n,m=f*h-p*u+s,_=f*u+p*h+n;return m>=s-i*r&&m<=s+i*(1-r)&&_>=n-o*a&&_<=n+o*(1-a)}function no(e,t,s,n,i,o,r){if(!e.has(t,_i)||!e.has(t,de))return null;const a=e.get(t,_i),l=e.get(t,de),c=Ri(a,t)*l.worldScale.x,d=Ai(a,t)*l.worldScale.y,u=l.worldPosition.x,h=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,_=c*(1-f),g=-d*p,y=d*(1-p),w=eo(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[u+m*x-g*v,h+m*v+g*x],[u+_*x-g*v,h+_*v+g*x],[u+_*x-y*v,h+_*v+y*x],[u+m*x-y*v,h+m*v+y*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=to(e,t,s,n,i,o,r);S=Math.min(S,a),M=Math.min(M,l),P=Math.max(P,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(P-S),h:Math.round(T-M)}}function io(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([qi]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,qi);s.enabled&&(u.add(e),s.mode===Gi?(d.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,i,o,r,a,l,c){const d=[];for(const e of n){let s=!0;ki(t,e,e=>{if(i.has(e)){if(t.get(e,qi).mode===Ni)return s=!1,!0}return!1}),s&&d.push(e)}function u(n,d){const h=e.getChildEntities(s,n);for(const s of h){let n=d;if(i.has(s)){if(t.get(s,qi).mode===Ni){const e=no(t,s,o,r,a,l,c);e&&(n=Ki(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=no(t,e,o,r,a,l,c);s&&u(e,s)}}(e,t,s,c,u,n,i,o,r,a),d.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;ki(t,e,e=>!!i.has(e)&&(s=!1,!0)),s&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}function d(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,d,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class oo{build(e){if(ie("UIMask",qi),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(io(e.wasmModule,e.world))}}const ro=new oo,ao=re("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),lo=re("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),co={Normal:0,Hovered:1,Pressed:2,Disabled:3},uo=K("Button",{state:co.Normal,transition:null});class ho{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const fo=Ae(new ho,"UIEvents");class po{build(e){ie("UIRect",_i);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){gi=e,yi=t}(s,n);e.addSystemToSchedule(gt.PreUpdate,xt([Ie(At)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n),s.transform_update(n))},{name:"UILayoutSystem"})),e.addSystemToSchedule(gt.PostUpdate,xt([Ie(At)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(gt.PostUpdate,xt([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const mo=new po;let _o=!1,go=!1;function yo(e){_o=e}function wo(){return _o}function xo(){return!_o}function vo(e){go=e}function bo(){return go}const So=function(){const e=new Float32Array(16),t=new Float32Array(16);let s=!0;return{update(e){for(let n=0;n<16;n++)if(t[n]!==e[n]){t.set(e),s=!0;break}},getInverse:t=>(s&&(Ji(t,e),s=!1),e)}}();function Mo(e,t,s,n){t.emit(s,n,s),ki(e,s,i=>{if(!e.has(i,ao))return!1;const o=e.get(i,ao);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Po{build(e){ie("Interactable",ao),ie("Button",uo);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new ho;e.insertResource(fo,i);let o=null,r=null;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Et),Ie(At)],(e,a)=>{if(i.drain(),wo()&&!bo())return;const l=t.getEntitiesWithComponents([lo]);for(const e of l){const s=t.get(e,lo);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,lo,s))}if(!a.valid)return;const c=f(),d=e.mouseX*c,u=a.screenH-e.mouseY*c;So.update(a.viewProjection);const h=Qi(d,u,So.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=h.x,a.worldMouseY=h.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),_=e.isMouseButtonReleased(0);s.uiHitTest_update(n,h.x,h.y,p,m,_);const g=s.uiHitTest_getHitEntity(),y=4294967295===g?null:g;if(null===o||t.valid(o)||(o=null),o!==y){if(null!==o&&t.valid(o)&&t.has(o,lo)){const e=t.get(o,lo);e.hovered=!1,t.insert(o,lo,e),i.emit(o,"hover_exit")}if(null!==y){Fi(t,y,lo);const e=t.get(y,lo);e.hovered=!0,t.insert(y,lo,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,lo);e.pressed=!0,e.justPressed=!0,t.insert(y,lo,e),r=y,Mo(t,i,y,"press")}if(_&&null!==r){if(t.valid(r)&&t.has(r,lo)){const e=t.get(r,lo);e.pressed=!1,e.justReleased=!0,t.insert(r,lo,e),Mo(t,i,r,"release"),r===o&&Mo(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(gt.Update,xt([],()=>{const e=t.getEntitiesWithComponents([uo]);for(const s of e){if(Fi(t,s,ao,{enabled:!0}),!t.has(s,lo))continue;const e=t.get(s,lo),n=t.get(s,uo),i=t.get(s,ao),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=co.Pressed:e.hovered?n.state=co.Hovered:n.state=co.Normal:n.state=co.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,fe)){const o=t.get(s,fe);o.color=Mi(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,fe,o)}}},{name:"ButtonSystem"}))}}const To=new Po,Eo=K("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),Co=K("Focusable",{tabIndex:0,isFocused:!1});class Ro{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Ao=Ae(new Ro,"FocusManager");class Io{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ie("TextInput",Eo),wo()&&!bo())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=u(F.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,d=0,h=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function m(){const t=e.getResource(Ao);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Eo)?n:null}const _=()=>{l||null===m()||v()},g=()=>{l=!0},y=()=>{l=!1,v()},w=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void b();const i=s.get(n,Eo);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(fo).emit(n,"submit"),void b()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,i.dirty=!0,S())},x=()=>{const t=m();if(null!==t){const n=s.get(t,Eo);n.focused=!1,n.dirty=!0;e.getResource(Ao).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,Eo);if(n.readOnly)return;let i=p.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),p.value=i),i!==n.value){n.value=i;e.getResource(fo).emit(t,"change")}n.cursorPos=p.selectionStart??i.length,n.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=s.get(t,Eo);e.focused=!1,e.dirty=!0}e.getResource(Ao).blur(),p.blur()}function S(){c=!0,d=0}p.addEventListener("input",_),p.addEventListener("compositionstart",g),p.addEventListener("compositionend",y),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",_),p.removeEventListener("compositionstart",g),p.removeEventListener("compositionend",y),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,d,u){(i.width<d||i.height<u)&&(i.width=Ei(Math.max(i.width,d)),i.height=Ei(Math.max(i.height,u))),o.clearRect(0,0,i.width,i.height);const h=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,d,u),o.save(),o.beginPath(),o.rect(l.padding,0,d-2*l.padding,u),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=f?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const _=Math.ceil(1.2*l.fontSize),g=l.padding;if(l.multiline){const e=Ti(o,p,d-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=_}else{const e=(u-l.fontSize)/2;o.fillText(p,g,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=Ti(o,l.value,d-2*g);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(i+s>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=s,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const c=r<e.length?e[r].substring(0,a):"";t=g+o.measureText(c).width,s=g+r*_,n=_}else t=g+o.measureText(e).width,s=(u-l.fontSize)/2,n=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,s,2,n)}o.restore();const y=o.getImageData(0,0,d,u),w=new Uint8Array(y.data.buffer),x=t.getResourceManager();w.length>a&&(0!==r&&t._free(r),r=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,r);const v=n.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(d,u,r,w.length,1,!0);n.set(e,b);const S=s.get(e,fe);S.texture=b,S.size.x=d,S.size.y=u,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,fe,S)}e.addSystemToSchedule(gt.Update,xt([Ie(Ao)],e=>{const t=s.getEntitiesWithComponents([Eo]);for(const e of t)Fi(s,e,Co,{tabIndex:0,isFocused:!1}),Fi(s,e,ao,{enabled:!0,blockRaycast:!0});const n=m();if(n!==M){if(null!==M&&s.valid(M)&&s.has(M,Eo)){const e=s.get(M,Eo);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,Eo);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(n),M=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===h?0:(e-h)/1e3;h=e,i=Math.min(i,.1);const o=m();if(null!==o&&(d+=i,d>=.5)){d-=.5,c=!c;s.get(o,Eo).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Eo)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Eo,_i]);for(const e of a){const t=s.get(e,Eo);if(!t.dirty)continue;const n=s.get(e,_i),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(wi(s,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const ko=new Io,Fo={Simple:0,Sliced:1,Tiled:2,Filled:3},Bo={Horizontal:0,Vertical:1},zo={Left:0,Right:1,Bottom:2,Top:3},Uo=K("Image",{texture:D,color:{r:1,g:1,b:1,a:1},imageType:Fo.Simple,fillMethod:Bo.Horizontal,fillOrigin:zo.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),$o=zi({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Ri(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Ai(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Do=new class{build(e){ie("Image",Uo);const t=e.world,s=new Map;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Uo)||s.delete(e);const e=t.getEntitiesWithComponents([Uo]);for(const n of e){const e=t.get(n,Uo),i=t.has(n,_i)?t.get(n,_i):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!$o.changed(r,o))continue;wi(t,n);const a=t.get(n,fe);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=Ri(i,n),a.size.y=Ai(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Fo.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Bo.Horizontal?e.fillOrigin===zo.Left?(a.uvScale.x=t,a.size.x=s*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=s*t):e.fillOrigin===zo.Bottom?(a.uvScale.y=t,a.size.y=n*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=n*t)}else e.imageType===Fo.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(n,fe,a),s.set(n,$o.take(o))}else a.color.a=0,t.insert(n,fe,a),s.set(n,$o.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Lo=K("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Oo=K("ToggleGroup",{allowSwitchOff:!1});const Wo=new class{build(e){ie("Toggle",Lo),ie("ToggleGroup",Oo);const t=e.world,s=new Set;e.addSystemToSchedule(gt.Update,xt([Ie(fo)],e=>{const n=t.getEntitiesWithComponents([Lo]);if(!wo()||bo()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Lo);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,Lo,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Lo);if(0!==s.group&&t.valid(s.group)){let t=o.get(s.group);t||(t=[],o.set(s.group,t)),t.push(e)}}for(const s of n){if(Fi(t,s,ao,{enabled:!0}),!t.has(s,lo))continue;const n=t.get(s,lo),i=t.get(s,Lo),r=t.get(s,ao);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,Oo);if(i.isOn&&r){if(!t.get(n,Oo).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,Lo,i),i.isOn&&r){const i=o.get(n);if(i)for(const n of i){if(n===s)continue;const i=t.get(n,Lo);i.isOn&&(i.isOn=!1,t.insert(n,Lo,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,fe)){const e=t.get(s,fe);e.color=Mi(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,fe,e)}}}for(const e of n){const s=t.get(e,Lo);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,fe)){const e=t.get(s.graphicEntity,fe);e.enabled=s.isOn,t.insert(s.graphicEntity,fe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Ho=pi,Xo=K("ProgressBar",{value:0,fillEntity:0,direction:pi.LeftToRight});function jo(e,t,s,n){if(!e.has(t,_i))return;const i=e.get(t,_i),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=mi(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,fe)){const s=e.get(t,fe);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,fe,s))}if(e.has(t,de)){const s=e.get(t,de),n=s.position;n.x===l.originX&&n.y===l.originY||(s.position={x:l.originX,y:l.originY,z:n.z},e.insert(t,de,s))}}class Yo{build(e){ie("ProgressBar",Xo);const t=e.world;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{const e=t.getEntitiesWithComponents([Xo,_i]);for(const s of e){const e=t.get(s,Xo);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,_i),i=Math.max(0,Math.min(1,e.value));Si(t,e.fillEntity,e.direction,i);const o=Ri(n,s),r=Ai(n,s);jo(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Vo=new Yo,No=K("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Go=K("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});const qo=new class{build(e){ie("Draggable",No),ie("DragState",Go);const t=e.world,s=e.getResource(fo);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Et),Ie(At)],(e,r)=>{if(wo()&&!bo())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([No,lo]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,No).enabled)continue;if(t.get(n,lo).hovered){let e=0;t.has(n,fe)&&(e=t.get(n,fe).layer);const i=Ci(t,n);(e>o||e===o&&i>=r)&&(o=e,r=i,s=n)}}if(null!==s){n=s,i={x:a.x,y:a.y},t.has(s,Go)||t.insert(s,Go);const e=t.get(s,Go),o=t.get(s,de);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,Go)){t.get(n,Go).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),d=t.get(n,No);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,Go).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Go))return void(o=null);const n=t.get(o,Go),i=t.get(o,No),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,d=n.startWorldPos.y+l;const u=function(e,t,s,n){let i=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,n,c,d);c=u.x,d=u.y;const h=n.currentWorldPos.x,f=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:d-f},n.currentWorldPos={x:c,y:d},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:d-n.startWorldPos.y},t.has(o,de)){const e=function(e,t,s,n){if(!e.has(t,ge))return{x:s,y:n};const i=e.get(t,ge).entity;if(!e.valid(i)||!e.has(i,de))return{x:s,y:n};const o=e.get(i,de),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=eo(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(s*d-n*c)/r,y:(s*c+n*d)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,de);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,de,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Ko=K("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Jo(e,t,s,n){return n<=0?1:e<t?Math.max(0,1-(t-e)/n):e>s?Math.max(0,1-(e-s)/n):1}function Qo(e,t,s,n,i){const o=2/(n=Math.max(1e-4,n)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(s+o*l)*i,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(s-o*c)*a}}const Zo=new class{build(e){ie("ScrollView",Ko);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(gt.PostUpdate,xt([Ie(Et),Ie(At),Ie(ze)],(e,i,o)=>{const r=wo()&&!bo(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);i.valid&&(n.x=i.worldMouseX,n.y=i.worldMouseY);const l=t.getEntitiesWithComponents([Ko,_i]);for(const o of l){Fi(t,o,qi,{enabled:!0,mode:Ni});const l=t.get(o,Ko),c=t.get(o,_i);let d=s.get(o);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,d));const u=Ri(c,o),h=Ai(c,o);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ye)){const e=t.get(l.contentEntity,ye).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,de))continue;const e=t.get(r,de);let a=0,l=0,c=.5,d=.5;if(t.has(r,_i)){const e=t.get(r,_i);a=Ri(e,r)||e.size.x,l=Ai(e,r)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(r,fe)){const e=t.get(r,fe);a=e.size.x,l=e.size.y}const u=e.position.x-a*c,h=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);u<s&&(s=u),h>n&&(n=h),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=n-s),0===p&&(p=o-i)}const m=Math.max(0,f-u),_=Math.max(0,p-h);if(!r&&i.valid){Fi(t,o,ao,{enabled:!0,blockRaycast:!0});const s=t.has(o,lo)?t.get(o,lo):null;if(s?.justPressed&&(d.isDragging=!0,d.lastWorldX=n.x,d.lastWorldY=n.y,d.velocityX=0,d.velocityY=0),d.isDragging&&e.isMouseButtonDown(0)){const e=n.x-d.lastWorldX,t=n.y-d.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=Jo(l.scrollX,0,m,u);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const n=a>0?-e*t/a:0;d.velocityX+=(n-d.velocityX)*s}}if(l.verticalEnabled){const e=Jo(l.scrollY,0,_,h);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const n=a>0?t*e/a:0;d.velocityY+=(n-d.velocityY)*s}}d.lastWorldX=n.x,d.lastWorldY=n.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*u,t=5*h;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Jo(l.scrollY,0,_,h);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Jo(l.scrollX,0,m,u);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>_;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=Qo(l.scrollX,e,d.velocityX,.1,a);l.scrollX=t.value,d.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(d.velocityX)<Ui&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Ui?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:_,t=Qo(l.scrollY,e,d.velocityY,.1,a);l.scrollY=t.value,d.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(d.velocityY)<Ui&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Ui?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,_)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*u,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,_+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,de)){const e=t.get(l.contentEntity,de),s=e.position.x,n=e.position.y;(isNaN(d.lastAppliedX)||Math.abs(s-d.lastAppliedX)>.01)&&(d.contentBaseX=s),(isNaN(d.lastAppliedY)||Math.abs(n-d.lastAppliedY)>.01)&&(d.contentBaseY=n),e.position.x=d.contentBaseX-l.scrollX,e.position.y=d.contentBaseY+l.scrollY,d.lastAppliedX=e.position.x,d.lastAppliedY=e.position.y,t.insert(l.contentEntity,de,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},er=pi,tr=K("Slider",{value:0,minValue:0,maxValue:1,direction:pi.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function sr(e,t,s,n,i,o){const r=Ri(n,i)*s.worldScale.x,a=Ai(n,i)*s.worldScale.y,l=eo(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),u=e-s.worldPosition.x,h=t-s.worldPosition.y,f=u*d-h*c,p=u*c+h*d,m=-n.pivot.x*r,_=-n.pivot.y*a;switch(o){case pi.LeftToRight:return r>0?(f-m)/r:0;case pi.RightToLeft:return r>0?1-(f-m)/r:0;case pi.BottomToTop:return a>0?(p-_)/a:0;case pi.TopToBottom:return a>0?1-(p-_)/a:0}}function nr(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case pi.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case pi.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case pi.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case pi.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class ir{build(e){ie("Slider",tr);const t=e.world;let s=null;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Et),Ie(At),Ie(fo)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([tr,_i]);for(const r of o){const o=t.get(r,tr),a=t.get(r,_i);if(!wo()||bo()){if(t.has(r,de)){Fi(t,r,ao,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Fi(t,o.handleEntity,ao,{enabled:!0,blockRaycast:!1});const l=t.get(r,de),c=t.has(r,lo)?t.get(r,lo):null;let d=c?.justPressed??!1;if(!d&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,lo)&&(d=t.get(o.handleEntity,lo).justPressed),d&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=sr(n.worldMouseX,n.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let s=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(s=Math.round(s));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,s)),t.insert(r,tr,o),o.value!==c&&i.emit(r,"change")}s===r&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,d=Ri(a,r),u=Ai(a,r),h={left:-d/2,bottom:-u/2,right:d/2,top:u/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Si(t,o.fillEntity,o.direction,c),Bi(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,_i)){const e=t.get(o.handleEntity,_i);nr(e,o.direction,c),t.insert(o.handleEntity,_i,e),Bi(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const or=new ir;const rr=new class{build(e){ie("Focusable",Co);const t=e.world,s=new Ro;e.insertResource(Ao,s),e.addSystemToSchedule(gt.Update,xt([Ie(Et),Ie(fo)],(e,n)=>{if(wo()&&!bo())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Co]);for(const e of i){if(!t.has(e,lo))continue;t.get(e,lo).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of i){if(!t.valid(s))continue;if(t.has(s,ao)){if(!t.get(s,ao).enabled)continue}const n=t.get(s,Co);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const r=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?n.length-1:0:a?(r-1+n.length)%n.length:(r+1)%n.length,o(n[l])}function o(e){const i=s.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Co)){t.get(i,Co).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Co).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},ar=K("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function lr(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:i}=t;return{top:s.top,bottom:i-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const cr=new class{build(e){ie("SafeArea",ar);const t=e.world;let s=lr(),n=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{s=lr(),n=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{s=lr(),n=!0});e.addSystemToSchedule(gt.PreUpdate,xt([Ie(At)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,n=!0),!n)return;n=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([ar,_i]);for(const e of d){const n=t.get(e,ar),i=t.get(e,_i),o=n.applyTop?s.top*c:0,r=n.applyBottom?s.bottom*c:0,a=n.applyLeft?s.left*c:0,l=n.applyRight?s.right*c:0;let d=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},d=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},d=!0),d&&t.insert(e,_i,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},dr=K("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let ur=null;function hr(e,t){if(!ur)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=ur.get(e);s?s.renderer=t:ur.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const fr=new class{build(e){ie("ListView",dr);const t=e.world,s=new Map;ur=s,e.addSystemToSchedule(gt.PostUpdate,xt([Ie(Et)],e=>{const n=wo()&&!bo();for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const i=t.getEntitiesWithComponents([dr,_i]);for(const o of i){Fi(t,o,ao,{enabled:!0,blockRaycast:!0}),Fi(t,o,qi,{enabled:!0,mode:Ni});let i=s.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,i));const r=t.get(o,dr),a=t.get(o,_i),l=Ai(a,o),c=Ri(a,o);if(!n){const s=t.has(o,lo)?t.get(o,lo):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const d=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,d));const u=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,s]of i.itemEntities)(e<u||e>=h)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=u;e<h;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,ve,{value:`ListItem_${e}`}),t.insert(s,_i,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),i.itemEntities.set(e,s),i.renderer&&i.renderer(e,s)),t.has(s,de)){const n=t.get(s,de);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,de,n)}}i.visibleStart=u,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},pr=K("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const mr=new class{build(e){ie("Dropdown",pr);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,de))return;const s=t.get(e,de);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,de,{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:{x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,fe)){const s=t.get(e,fe);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,fe,{texture:s.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:s.enabled})}}function o(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const i=s.listEntity;if(0===i||!t.valid(i))return;d(i,!0),c(n);const o=t.get(e,fe),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*$i;t.insert(i,_i,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,de,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,fe,{texture:D,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*$i;t.insert(o,ve,{value:`Option_${e}`}),t.insert(o,_i,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*$i},offsetMax:{x:0,y:0},size:{x:r,y:$i},pivot:{x:.5,y:.5}}),t.insert(o,de,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,fe,{texture:D,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:$i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,ao,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);const c=t.spawn();t.insert(c,de,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,Hi,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Li.Left,verticalAlign:Oi.Middle,wordWrap:!1,overflow:Wi.Clip,lineHeight:1.2}),t.insert(c,_i,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:$i},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}u(n)}function r(e,t,s){t.isOpen=!1,c(s),d(t.listEntity,!1)}function a(e,t,s,n,i){t.selectedIndex=n,r(0,t,s),i.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Hi))return;const n=t.get(s,Hi);let i={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(s,Hi,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:i,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function d(e,s){if(0!==e&&t.valid(e)&&(t.has(e,ao)&&t.insert(e,ao,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,fe))){const n=t.get(e,fe);t.insert(e,fe,{texture:n.texture,color:{r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:s})}}function u(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,fe))continue;const i=s===e.highlightIndex?{...Di}:{r:.95,g:.95,b:.95,a:1};t.insert(n,fe,{texture:D,color:i,size:{x:e.ddWidth,y:$i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function h(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,lo))continue;if(t.get(s,lo).hovered)return!0}return!1}e.addSystemToSchedule(gt.Update,xt([Ie(Et),Ie(fo)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=wo()&&!bo(),p=t.getEntitiesWithComponents([pr]);for(const m of p){const p=t.get(m,pr);let _=s.get(m);if(_||(_={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,_)),n(p.listEntity),i(m),p.isOpen||d(p.listEntity,!1),l(p),f)continue;Fi(t,m,ao,{enabled:!0,blockRaycast:!0});const g=t.has(m,lo)?t.get(m,lo):null;if(g?.justPressed&&(p.isOpen?r(m,p,_):o(m,p,_)),p.isOpen){for(let e=0;e<_.optionEntities.length;e++){const s=_.optionEntities[e];if(!t.valid(s)||!t.has(s,lo))continue;if(t.get(s,lo).justPressed){a(m,p,_,e,c);break}}let s=-1;for(let e=0;e<_.optionEntities.length;e++){const n=_.optionEntities[e];if(!t.valid(n)||!t.has(n,lo))continue;if(t.get(n,lo).hovered){s=e;break}}s>=0&&s!==_.highlightIndex&&(_.highlightIndex=s,u(_)),e.isKeyPressed("ArrowDown")?(_.highlightIndex>=p.options.length-1?_.highlightIndex=0:_.highlightIndex++,u(_)):e.isKeyPressed("ArrowUp")?(_.highlightIndex<=0?_.highlightIndex=p.options.length-1:_.highlightIndex--,u(_)):e.isKeyPressed("Enter")&&_.highlightIndex>=0?a(m,p,_,_.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,_),e.isMouseButtonPressed(0)&&(g?.hovered||h(_)||r(m,p,_))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},_r=0,gr=0,yr=2,wr=K("LayoutGroup",{direction:_r,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:gr,reverseOrder:!1});const xr=new class{build(e){ie("LayoutGroup",wr);const t=e.world;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{const e=t.getEntitiesWithComponents([wr,_i,ye]);for(const s of e){const e=t.get(s,wr),n=t.get(s,_i),i=t.get(s,ye);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,_i)&&t.has(e,de)&&o.push({entity:e,rect:t.get(e,_i)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Ri(n,s),a=Ai(n,s),l=n.pivot.x,c=n.pivot.y,d=e.padding,u=e.direction===_r;let h=0;for(let s=0;s<o.length;s++){const n=o[s],i=Ri(n.rect,n.entity),f=Ai(n.rect,n.entity),p=n.rect.pivot.x,m=n.rect.pivot.y;let _,g;u?(_=-l*r+d.left+h+p*i,g=e.childAlignment===gr?(1-c)*a-d.top-(1-m)*f:e.childAlignment===yr?-c*a+d.bottom+m*f:(.5-c)*a+.5*(d.bottom-d.top)+(m-.5)*f,h+=i,s<o.length-1&&(h+=e.spacing)):(_=e.childAlignment===gr?-l*r+d.left+p*i:e.childAlignment===yr?(1-l)*r-d.right-(1-p)*i:(.5-l)*r+.5*(d.left-d.right)+(p-.5)*i,g=(1-c)*a-d.top-h-(1-m)*f,h+=f,s<o.length-1&&(h+=e.spacing));const y=t.get(n.entity,de);y.position.x=_,y.position.y=g,t.insert(n.entity,de,y)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};re("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),re("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class vr{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(gt.PostUpdate,xt([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const br=new vr;async function Sr(e,t,s){const n=e.getResource(qn);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Mr(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Pr=Ae({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Tr=Ae(null,"PhysicsAPI");function Er(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Cr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Rr{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Pr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Mr(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([me]);for(const s of t){const t=e.world.get(s,me);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(gt.PostUpdate,xt([Ie(ze)],a=>{const l=r.getEntitiesWithComponents([Me,de]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Me),l=r.get(i,de);if(t.has(i)){const e=s.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=Er(l.worldRotation);n._physics_createBody(i,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Ar(e,n,i),t.add(i),s.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===Ce.Kinematic){const e=Er(l.worldRotation);n._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<n;i++){const n=o+4*i,r=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(r))continue;const d=e.world.get(r,de);if(!d)continue;let u=a,h=l,f=c;if(e.world.has(r,ge)){const t=e.world.get(r,ge);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,de)){const s=e.world.get(t.entity,de),n=Er(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),d=Math.sin(-n);u=(i*r-o*d)/(0!==s.worldScale.x?s.worldScale.x:1),h=(i*d+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),f=c-n}}d.position.x=u,d.position.y=h;const p=Cr(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(r,de,d)}}(e,n,i),function(e,t,s){t._physics_collectEvents();const n=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;n.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*s,contactY:t.HEAPF32[i+5]*s})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<r;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<d;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Pr,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Tr,Ir._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function Ar(e,t,s){const n=e.world;if(n.has(s,Pe)){const e=n.get(s,Pe);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,Te)){const e=n.get(s,Te);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,Ee)){const e=n.get(s,Ee);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Ir{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Ir.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const kr={nearest:0,linear:1},Fr={repeat:0,clamp:1,mirror:2};function Br(e,t,s=!0,n){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&i.createTextureEx){const e=kr[n.filterMode??"linear"]??1,a=Fr[n.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),r}function zr(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Ur(e,t,s,n){const i=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,u=a+a,h=l+l,f=c+c,p=a*u,m=a*h,_=a*f,g=l*h,y=l*f,w=c*f,x=d*u,v=d*h,b=d*f;return new Float32Array([(1-(g+w))*i,(m+b)*i,(_-v)*i,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*r,(y-x)*r,(1-(p+g))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function $r(e,t,s,n,i,o,r,a,l){const c=await async function(e,t,s){const n={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=ds(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=i?.[o];n[o]=Br(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const i=s[e];if(i&&i>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let d={},u=null;if(i&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(i),d=await async function(e,t,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=us(n.type);if(!r||!n.data)continue;const a=n.data[r.skeletonField],l=n.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),d=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===Cs(c)?.contentType;let u,h;if(r){const e=await i.readBinary(a);h=e.length,u=t._malloc(h),t.HEAPU8.set(e,u)}else{const e=await i.readText(a),s=(new TextEncoder).encode(e);h=s.length,u=t._malloc(h+1),t.HEAPU8.set(s,u),t.HEAPU8[u+h]=0}const f=s.loadSkeleton(u,h,n,n.length,r);if(t._free(u),f<0)continue;o[a]=f;const p=zr(n),m=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=Br(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,i,u,s,n)),o){const t={gravity:r?.gravity??{...A},fixedTimestep:r?.fixedTimestep??I,subStepCount:r?.subStepCount??4};new Rr("",t,()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=ds(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,i;const r=Cs(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await s.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=Br(e,c,!1),u=e.getResourceManager();n[o]=u.loadBitmapFont(t,d,c.width,c.height)}catch{n[o]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=ds(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=n[i];r||(r=Ot.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=Ot.createFromAsset(e,r)}catch{s[o]=0}}return s}(s,n);!function(e,t,s,n){const i={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=ds(e.type);if(0===t.length)continue;const s=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof s[e.field]&&(s[e.field]=t[s[e.field]]||0)}}}(s,c,h,f);const p=gs(e.world,s);if(l&&e.hasResource(qn))for(const t of p.values())e.world.insert(t,be,{scene:l,persistent:!1});if(i&&u){const n=function(e,t,s,n){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=us(t.type);if(!r||!t.data)continue;const a=s[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(u,s,d,p);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=R);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,xe)?c.get(o,xe):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&n.update(r,l*u);let h=0;if(c.has(o,de)){const e=Ur(c.get(o,de),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=n.getMeshBatchCount(r);for(let e=0;e<f;e++){const i=n.getMeshBatchVertexCount(r,e),o=n.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=s._malloc(a),d=s._malloc(l),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(r,e,c,d,u,f);const p=s.HEAPU32[u>>2],m=s.HEAPU32[f>>2],_=new Float32Array(s.HEAPF32.buffer,c,8*i),g=new Uint16Array(s.HEAPU8.buffer,d,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,i,w,o,p,m,h),t._free(y),t._free(w),s._free(c),s._free(d),s._free(u),s._free(f)}h&&t._free(h)}})}(e,t,i,u,n)}if(a){const t=e.getResource(Ws);t&&t.setAddressableManifest(a)}}function Dr(e,t,s){return{name:e,async setup(){await $r(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class Lr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=us(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===Cs(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=ds(e.type);for(const s of o){const i=e.data[s.field];"string"==typeof i&&i&&("font"===s.type?(n.add(i),t.add(i)):"material"===s.type&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of n){const t=Cs(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),i=await createImageBitmap(n),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Or="__preview__";class Wr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(qn);t.register({name:Or,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Or),this.loadPromise_=t.load(Or).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new Lr(this.baseUrl_);await s.prefetch(t);let n=null;const i=this.app_.spineInitPromise;if(i){n=(await i).controller.raw}await $r(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,Or)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([pe]);for(const n of s){if(e.get(n,pe).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([me]);for(const i of n){const n=e.get(i,me);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const i=this.app_.getResource(qn).getScene(Or),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,de,r);const a={isActive:!0,projectionType:ae.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:le.ColorAndDepth};e.insert(o,pe,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(qn);await e.switchTo(Or),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const Hr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ln.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ln.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ln.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ln.releaseRenderTarget(e._handle),Hr.create({width:t,height:s,depth:!0})),begin(e,t){Ln.begin(t,e._handle)},end(){Ln.end()},getDepthTexture:e=>Ln.getTargetDepthTexture(e._handle)};var Xr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Xr||(Xr={}));class jr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Xr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Xr.Debug:console.debug(t,s);break;case Xr.Info:console.log(t,s);break;case Xr.Warn:console.warn(t,s);break;case Xr.Error:console.error(t,s)}}}class Yr{constructor(){this.handlers_=[],this.minLevel_=Xr.Info,this.addHandler(new jr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(Xr.Debug,e,t,s)}info(e,t,s){this.log(Xr.Info,e,t,s)}warn(e,t,s){this.log(Xr.Warn,e,t,s)}error(e,t,s){this.log(Xr.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Vr=new Yr;function Nr(){return Vr}function Gr(e){Vr.setMinLevel(e)}function qr(e,t,s){Vr.debug(e,t,s)}function Kr(e,t,s){Vr.info(e,t,s)}function Jr(e,t,s){Vr.warn(e,t,s)}function Qr(e,t,s){Vr.error(e,t,s)}const Zr={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},ea={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},ta={Running:0,Paused:1,Completed:2,Cancelled:3},sa={None:0,Restart:1,PingPong:2};class na{constructor(e,t,s){this.module_=e,this.registry_=t,this.entity=s}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,s,n){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,s,n),this}then(e){return this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let ia=null,oa=null;function ra(e,t){ia=e,oa=t}function aa(){ia=null,oa=null}function la(){if(!ia)throw new Error("Tween API not initialized");return ia}function ca(){if(!oa)throw new Error("Tween API not initialized");return oa}const da={to(e,t,s,n,i,o){const r=la(),a=ca(),l=o?.easing??Zr.Linear,c=o?.delay??0,d=o?.loop??sa.None,u=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,d,u);return new na(r,a,h)},cancel(e){la()._anim_cancelTween(ca(),e.entity)},cancelAll(e){la()._anim_cancelAllTweens(ca(),e)},update(e){la()._anim_updateTweens(ca(),e)}};class ua{constructor(){this.name="AnimationPlugin"}build(e){ra(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(gt.Update,xt([Ie(ze)],e=>{da.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(gt.Update,xt([Ie(ze)],e=>{os(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){aa()}}const ha=new ua;var fa;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(fa||(fa={}));const pa={model:fa.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function ma(e,t=pa){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case fa.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case fa.Inverse:a=n/Math.max(r,n);break;case fa.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function _a(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const ga=K("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:fa.Inverse,rolloff:1,priority:0,enabled:!0}),ya=K("AudioListener",{enabled:!0});class wa{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.config_=e}build(e){const s=t().createAudioBackend(),n=this.config_;s.initialize({initialPoolSize:n.initialPoolSize});const i=s.mixer;rs.init(s,i),i&&(void 0!==n.masterVolume&&(i.master.volume=n.masterVolume),void 0!==n.musicVolume&&(i.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(i.sfx.volume=n.sfxVolume));const o=new Map;this.activeSourceHandles_=o;let r=!1;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(ze)],t=>{const n=e.world;let i=0,a=0,l=!1;const c=n.getEntitiesWithComponents([ya,he]);for(const e of c){if(n.get(e,ya).enabled){const t=n.get(e,he);i=t.position.x,a=t.position.y,l=!0;break}}const d=n.getEntitiesWithComponents([ga]),u=new Set;for(const e of d){const t=n.get(e,ga);if(t.enabled&&t.clip){if(u.add(e),t.playOnAwake&&!o.has(e)){const n=rs.getBufferHandle(t.clip);if(n){const i=s.play(n,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(e,i)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(e)){const s=o.get(e);if(!s.isPlaying){o.delete(e);continue}l||r||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),r=!0);const c=n.tryGet?.(e,he),d=c?.position.x??0,u=c?.position.y??0,h=d-i,f=u-a,p=ma(Math.sqrt(h*h+f*f),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),m=_a(d,0,i,0,t.maxDistance);s.setVolume(t.volume*p),s.setPan(m)}}}for(const[e,t]of o)u.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}cleanup(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}rs.dispose()}}const xa=new wa;function va(e,t){return e.toFixed(t)}function ba(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class Sa{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${va(e.fps,1)}</span> Frame: <span style="color:#d19a66">${va(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const s=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let n='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of s){n+=`<div>${ba(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${va(t,1)}ms</span></div>`}t.push(n)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}}function Ma(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const Pa=Ae(Ma(),"Stats"),Ta="StatsCollect";class Ea{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Ca{constructor(e){this.name="Stats",this.collector_=new Ea,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Pa,Ma());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Sa(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=xt([Ie(ze),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(Pa);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(Ta),o.systemTimings=e}else o.systemTimings=new Map;const a=Ln.getStats();o.drawCalls=a.drawCalls,o.triangles=a.triangles,o.sprites=a.sprites,o.text=a.text,o.spine=a.spine,o.meshes=a.meshes,o.culled=a.culled,s?.update(o)},{name:Ta});e.addSystemToSchedule(gt.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Ra=new Ca;class Aa{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,s)=>{const n=new Image;n.onload=()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const s=e.getContext("2d");s.drawImage(n,0,0);const i=s.getImageData(0,0,n.width,n.height);t({width:n.width,height:n.height,pixels:new Uint8Array(i.data.buffer)})},n.onerror=s,n.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function Ia(e,t){try{const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(s.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function ka(e){const{app:t,module:s,assets:n,sceneData:i,sceneName:o}=e,r=t.getResource(Ws);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0)),ei(t);const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Ia(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await Ia(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=Dr(o,i,{app:t,module:s,provider:new Aa(n),spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest}),d=t.getResource(qn);d.register(c),d.setInitial(o),await d.load(o);const u=e.canvas.width/e.canvas.height;vs(t.world,u),t.run()}const Fa=[Vi,ro,mo,Do,Vo,To,qo,Zo,or,Wo,ko,rr,cr,fr,mr,xr,br],Ba=[...Fa,ha];function za(e,t){return function(e,t){const s=Zn.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),an(e),$t(e),Mn(e),Rn(e),$n(e),Wn(e);const i=new jn;s.setPipeline(i);let o=h();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=oi(e,n,t,i));const r=s.getResource(At);if(o.length>0){const e=o[0],s=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(s.x*t),r.vpY=Math.round((1-s.y-s.h)*i),r.vpW=Math.round(s.w*t),r.vpH=Math.round(s.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}s.insertResource(At,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(n);if(c>=0){const e=n.getCanvas(c).backgroundColor;Ln.setClearColor(e.x,e.y,e.z,e.w)}const d=(h()-o)/1e3;let u;if(Ln.resize(t,l),kn.isInitialized()&&kn.getPassCount()>0&&!kn.isBypassed()&&kn.resize(t,l),s.hasResource(qn)){const e=s.getResource(qn).getActiveScenes();e.length>0&&(u=new Set(e))}i.setActiveScenes(u??null);const f=oi(e,n,t,l,s.world,u);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:n},viewProjection:ti,width:t,height:l,elapsed:d});else{for(const e of f){const s=e.viewportRect,o=Math.round(s.x*t),r=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);i.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}Ln.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(gt.First,l),s.addSystemToSchedule(gt.Last,c),s.addPlugin(Xs),s.addPlugin(en),s.addPlugin(Rt),s.addPlugin(Qn),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Ba,...t})}e=w;export{Je as Added,ua as AnimationPlugin,Zn as App,Hs as AssetPlugin,js as AssetRefCounter,Os as AssetServer,Ws as Assets,qt as AsyncCache,fa as AttenuationModel,rs as Audio,p as AudioBus,ya as AudioListener,m as AudioMixer,wa as AudioPlugin,_ as AudioPool,ga as AudioSource,we as BitmapText,It as BlendMode,Ce as BodyType,Pe as BoxCollider,uo as Button,co as ButtonState,pe as Camera,me as Canvas,Ee as CapsuleCollider,Qe as Changed,ye as Children,Te as CircleCollider,le as ClearFlags,at as Commands,ct as CommandsInstance,v as DEFAULT_DESIGN_HEIGHT,x as DEFAULT_DESIGN_WIDTH,R as DEFAULT_FALLBACK_DT,I as DEFAULT_FIXED_TIMESTEP,P as DEFAULT_FONT_FAMILY,T as DEFAULT_FONT_SIZE,A as DEFAULT_GRAVITY,E as DEFAULT_LINE_HEIGHT,C as DEFAULT_MAX_DELTA_TIME,b as DEFAULT_PIXELS_PER_UNIT,k as DEFAULT_SPINE_SKIN,M as DEFAULT_SPRITE_SIZE,S as DEFAULT_TEXT_CANVAS_SIZE,wn as DataType,Go as DragState,No as Draggable,un as Draw,pr as Dropdown,Zr as EasingType,lt as EntityCommands,pt as EventReader,_t as EventReaderInstance,ht as EventRegistry,ft as EventWriter,mt as EventWriterInstance,pi as FillDirection,Bo as FillMethod,zo as FillOrigin,Ao as FocusManager,Ro as FocusManagerState,Co as Focusable,Xn as GLDebug,En as Geometry,yt as GetWorld,$ as INVALID_ENTITY,L as INVALID_FONT,O as INVALID_MATERIAL,D as INVALID_TEXTURE,Uo as Image,Fo as ImageType,Et as Input,Ct as InputPlugin,Tt as InputState,ao as Interactable,dr as ListView,ue as LocalTransform,Xr as LogLevel,Yr as Logger,sa as LoopMode,Ot as Material,Kt as MaterialLoader,qe as Mut,ve as Name,ge as Parent,Ir as Physics,Pr as PhysicsEvents,Rr as PhysicsPlugin,kn as PostProcess,Js as PrefabServer,Qs as Prefabs,Zs as PrefabsPlugin,Wr as PreviewPlugin,Xo as ProgressBar,Ho as ProgressBarDirection,Yo as ProgressBarPlugin,ae as ProjectionType,nt as Query,it as QueryInstance,ot as Removed,rt as RemovedQueryInstance,jn as RenderPipeline,Bn as RenderStage,Hr as RenderTexture,Ln as Renderer,Ie as Res,ke as ResMut,Me as RigidBody,F as RuntimeConfig,ar as SafeArea,ce as ScaleMode,qn as SceneManager,Gn as SceneManagerState,be as SceneOwner,gt as Schedule,Ko as ScrollView,Gt as ShaderSources,tr as Slider,er as SliderDirection,ir as SliderPlugin,xe as SpineAnimation,fe as Sprite,is as SpriteAnimator,Pa as Stats,Ea as StatsCollector,Sa as StatsOverlay,Ca as StatsPlugin,Pt as SystemRunner,Hi as Text,Li as TextAlign,Eo as TextInput,Io as TextInputPlugin,Wi as TextOverflow,Yi as TextPlugin,Xi as TextRenderer,Oi as TextVerticalAlign,ze as Time,Lo as Toggle,de as Transform,da as Tween,na as TweenHandle,ta as TweenState,ea as TweenTarget,At as UICameraInfo,ho as UIEventQueue,fo as UIEvents,lo as UIInteraction,Po as UIInteractionPlugin,po as UILayoutPlugin,qi as UIMask,oo as UIMaskPlugin,_i as UIRect,vr as UIRenderOrderPlugin,_e as Velocity,Lr as WebAssetProvider,Ge as World,he as WorldTransform,St as addStartupSystem,bt as addSystem,Mt as addSystemToSchedule,ha as animationPlugin,U as applyBuildRuntimeConfig,Si as applyDirectionalFill,B as applyRuntimeConfig,Xs as assetPlugin,xa as audioPlugin,ma as calculateAttenuation,_a as calculatePanning,ns as clearAnimClips,yn as clearDrawCallbacks,Z as clearUserComponents,j as color,xi as computeFillAnchors,bi as computeFillSize,vi as computeHandleAnchors,mi as computeUIRectLayout,io as createMaskProcessor,Dr as createRuntimeSceneConfig,za as createWebApp,qr as debug,Ma as defaultFrameStats,K as defineComponent,dt as defineEvent,Ae as defineResource,xt as defineSystem,J as defineTag,Qr as error,Jt as extractAnimClipTexturePaths,bs as findEntityByName,ei as flushPendingSystems,As as getAddressableType,Is as getAddressableTypeByEditorType,Fs as getAllAssetExtensions,ss as getAnimClip,$s as getAssetMimeType,Cs as getAssetTypeEntry,oe as getComponent,ds as getComponentAssetFieldDescriptors,cs as getComponentAssetFields,Se as getComponentDefaults,ps as getComponentEntityFields,us as getComponentSpineFieldDescriptor,zs as getCustomExtensions,Rs as getEditorType,Nr as getLogger,t as getPlatform,n as getPlatformType,Q as getUserComponent,Us as getWeChatPackOptions,Kr as info,an as initDrawAPI,Wn as initGLDebugAPI,Mn as initGeometryAPI,$t as initMaterialAPI,ka as initPlayableRuntime,Rn as initPostProcessAPI,$n as initRendererAPI,ra as initTweenAPI,Rt as inputPlugin,Vs as instantiatePrefab,Ki as intersectRects,Ji as invertMatrix4,se as isBuiltinComponent,Ds as isCustomExtension,wo as isEditor,ks as isKnownAssetExtension,s as isPlatformInitialized,bo as isPlayMode,xo as isRuntime,kt as isTextureRef,i as isWeChat,o as isWeb,xs as loadComponent,Mr as loadPhysicsModule,$r as loadRuntimeScene,gs as loadSceneData,ys as loadSceneWithAssets,Bs as looksLikeAssetPath,Qt as parseAnimClipData,r as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,so as pointInOBB,Zi as pointInWorldRect,en as prefabsPlugin,Vo as progressBarPlugin,Y as quat,es as registerAnimClip,ie as registerComponent,ls as registerComponentAssetFields,fs as registerComponentEntityFields,_n as registerDrawCallback,Ys as registerEmbeddedAssets,Nt as registerMaterialCallback,ms as remapEntityFields,Qn as sceneManagerPlugin,Qi as screenToWorld,yo as setEditorMode,hr as setListViewRenderer,Gr as setLogLevel,vo as setPlayMode,Oe as setWasmErrorHandler,ln as shutdownDrawAPI,Hn as shutdownGLDebugAPI,Pn as shutdownGeometryAPI,Dt as shutdownMaterialAPI,An as shutdownPostProcessAPI,Dn as shutdownRendererAPI,aa as shutdownTweenAPI,or as sliderPlugin,os as spriteAnimatorSystemUpdate,Ra as statsPlugin,Ii as syncFillSpriteSize,ko as textInputPlugin,Vi as textPlugin,Ls as toBuildPath,Sr as transitionTo,To as uiInteractionPlugin,mo as uiLayoutPlugin,ro as uiMaskPlugin,Fa as uiPlugins,br as uiRenderOrderPlugin,ts as unregisterAnimClip,ee as unregisterComponent,gn as unregisterDrawCallback,vs as updateCameraAspectRatio,W as vec2,H as vec3,X as vec4,Jr as warn,Kn as wrapSceneSystem};+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return null!==e}function n(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function d(e,s){return t().instantiateWasm(e,s)}function u(e,s){return t().createCanvas(e,s)}function h(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new p(this.context_,e),s=e.parent?this.buses_.get(e.parent):this.master;return s&&s.addChild(t),this.buses_.set(e.name,t),t}}class _{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class g{constructor(e,t,s,n,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=s,this.poolNode_=n,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}class y{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.urlToId_=new Map,this.loadingUrls_=new Map,this.nextBufferId_=0,this.nextHandleId_=0,this.resumeHandler_=null}get mixer(){return this.mixer_}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new m(this.context_,e.mixerConfig),this.pool_=new _(this.context_,e.initialPoolSize),"suspended"===this.context_.state){const e=()=>{this.context_.resume(),document.removeEventListener("touchstart",e),document.removeEventListener("mousedown",e),document.removeEventListener("keydown",e),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}async ensureResumed(){this.context_&&"suspended"===this.context_.state&&await this.context_.resume()}async loadBuffer(e){if(!this.context_)throw new Error("AudioContext not initialized");const t=this.urlToId_.get(e);if(void 0!==t&&this.buffers_.has(t)){return{id:t,duration:this.buffers_.get(t).duration}}const s=this.loadingUrls_.get(e);if(s)return s;const n=this.doLoadBuffer_(e);this.loadingUrls_.set(e,n);try{return await n}finally{this.loadingUrls_.delete(e)}}async doLoadBuffer_(e){const s=await t().readFile(e);let n;try{n=await this.context_.decodeAudioData(s)}catch(t){throw new Error(`Failed to decode audio ${e}: ${t.message}`)}const i=++this.nextBufferId_;return this.buffers_.set(i,n),this.urlToId_.set(e,i),{id:i,duration:n.duration}}unloadBuffer(e){this.buffers_.delete(e.id)}play(e,t){if(!this.context_||!this.pool_||!this.mixer_)throw new Error("Audio system not initialized");const s=this.buffers_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=this.pool_.acquire(),i=this.context_.createBufferSource();i.buffer=s,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(n.gain),n.source=i,n.gain.gain.value=t.volume??1,n.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;n.panner.connect(r.node);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new g(l,i,s,n,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.urlToId_.clear(),this.loadingUrls_.clear(),this.context_?.close(),this.context_=null}}const w=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const s=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),n={};return s.headers.forEach((e,t)=>{n[t]=e}),{ok:s.ok,status:s.status,statusText:s.statusText,headers:n,json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async loadImagePixels(e){const t=this.createImage();await new Promise((s,n)=>{t.crossOrigin="anonymous",t.onload=()=>s(),t.onerror=()=>n(new Error(`Failed to load image: ${e}`)),t.src=e});const s=this.createCanvas(t.width,t.height).getContext("2d");s.drawImage(t,0,0);const n=s.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(n.data.buffer)}}async instantiateWasm(e,t){let s;s="string"==typeof e?await this.readFile(e):e;const n=await WebAssembly.instantiate(s,t);return{instance:n.instance,module:n.module}}createImage(){return new Image}createCanvas(e,t){let s;return s="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),s.width=e,s.height=t,s}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t??document.querySelector("canvas")??document.body,n=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),o=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},r=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},d=()=>{e.onPointerUp(0)},u=t=>{const s=t;let n=s.deltaX,i=s.deltaY;1===s.deltaMode?(n*=16,i*=16):2===s.deltaMode&&(n*=window.innerWidth,i*=window.innerHeight),e.onWheel(n,i)};document.addEventListener("keydown",n),document.addEventListener("keyup",i),s.addEventListener("mousemove",o),s.addEventListener("mousedown",r),document.addEventListener("mouseup",a),s.addEventListener("touchstart",l),s.addEventListener("touchmove",c),s.addEventListener("touchend",d),s.addEventListener("wheel",u),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",i),s.removeEventListener("mousemove",o),s.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),s.removeEventListener("touchstart",l),s.removeEventListener("touchmove",c),s.removeEventListener("touchend",d),s.removeEventListener("wheel",u)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new y}},x=1920,v=1080,b=100,S=512,M={x:100,y:100},P="Arial",T=24,E=1.2,C=.5,R=1/60,A={x:0,y:-9.81},I=1/60,k="default",F={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function B(e){e.Text&&(e.Text._default.fontFamily=F.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=F.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=F.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=F.canvasMatchWidthOrHeight)}const z={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function U(e,t){if(void 0!==t.maxDeltaTime&&(F.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(F.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(F.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(F.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(F.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");F.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(F.canvasScaleMode=z[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(F.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const $=0,D=4294967295,L=4294967295,O=0,W=(e=0,t=0)=>({x:e,y:t}),H=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),X=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),j=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),Y=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function V(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(V);const t={};for(const s in e)t[s]=V(e[s]);return t}let N=0;function G(e,t){const s=++N,n=function(e){for(const t in e){const s=e[t];if(null!==s&&"object"==typeof s)return!0}return!1}(t);return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>n?e?{...V(t),...e}:V(t):e?{...t,...e}:{...t}}}function q(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function K(e,t){const s=ne.get(e)??q().get(e);if(s)return s;const n=G(e,t);return q().set(e,n),ne.set(e,n),te(e,t,!1),n}function J(e){const t=ne.get(e)??q().get(e);if(t)return t;const s=G(e,{});return q().set(e,s),ne.set(e,s),te(e,{},!0),s}function Q(e){return q().get(e)}function Z(){const e=q();for(const t of e.keys())ne.delete(t);e.clear()}function ee(e){q().delete(e),ne.delete(e)}function te(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function se(e){return!0===e._builtin}const ne=new Map;function ie(e,t){ne.set(e,t)}function oe(e){return ne.get(e)??Q(e)}function re(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return ne.set(e,s),s}const ae={Perspective:0,Orthographic:1},le={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ce={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},de=re("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),ue=de,he=de,fe=re("Sprite",{texture:D,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),pe=re("Camera",{projectionType:ae.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:le.ColorAndDepth}),me=re("Canvas",{designResolution:{x:x,y:v},pixelsPerUnit:100,scaleMode:ce.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),_e=re("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),ge=re("Parent",{entity:0}),ye=re("Children",{entities:[]}),we=re("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:L,enabled:!0}),xe=re("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),ve=K("Name",{value:""}),be=K("SceneOwner",{scene:"",persistent:!1});function Se(e){const t=oe(e);return t?V(t._default):null}const Me=re("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Pe=re("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Te=re("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ee=re("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ce={Static:0,Kinematic:1,Dynamic:2};let Re=0;function Ae(e,t){const s=++Re;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Ie(e){return{_type:"res",_resource:e}}function ke(e){return{_type:"res_mut",_resource:e}}class Fe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class Be{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Fe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const ze=Ae({delta:0,elapsed:0,frameCount:0},"Time");function Ue(e,t,s){const n=[];for(const[e,i]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const s=$e(t[e]),o=$e(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function $e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function De(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let Le=null;function Oe(e){Le=e}function We(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Le&&Le(e,t)}function He(e){let t=!1;for(const s of Object.keys(e)){const n=e[s];if(null!=n&&"object"==typeof n&&!Array.isArray(n)){if("r"in n&&"g"in n&&"b"in n&&"a"in n&&!("x"in n)){t=!0;break}}}if(!t)return e;const s={};for(const t of Object.keys(e)){const n=e[t];if(null==n||"object"!=typeof n||Array.isArray(n))s[t]=n;else{const e=n;s[t]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:n}}return s}let Xe=1;const je=new WeakMap;function Ye(e){let t=je.get(e);return void 0===t&&(t=Xe++,je.set(e,t)),t}const Ve=[];function Ne(e,t=[],s=[]){Ve.length=0;for(const t of e)Ve.push(Ye(t));Ve.sort((e,t)=>e-t);let n=Ve.join(",");if(t.length>0){Ve.length=0;for(const e of t)Ve.push(Ye(e));Ve.sort((e,t)=>e-t),n+="|+"+Ve.join(",")}if(s.length>0){Ve.length=0;for(const e of s)Ve.push(Ye(e));Ve.sort((e,t)=>e-t),n+="|-"+Ve.join(",")}return n}class Ge{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw We(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){We(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t){this.tsStorage_.get(s)?.delete(e),this.componentAddedTicks_.get(s)?.delete(e),this.componentChangedTicks_.get(s)?.delete(e);let t=this.componentRemovedBuffer_.get(s);t||(t=[],this.componentRemovedBuffer_.set(s,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){We(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){We(t,`removeParent(entity=${e})`)}}insert(e,t,s){return se(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(se(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(s))}catch(s){We(s,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,s),this.recordChangedTick_(t,e)}get(e,t){return se(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return se(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(se(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return We(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");se(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_,n=s[`add${e}`],i=s[`get${e}`],o=s[`has${e}`],r=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:i.bind(s),has:o.bind(s),remove:r.bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Ue(t._name,t._default,n);if(e.length>0)throw new Error(De(t._name,e))}const i={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,He(i))}catch(s){We(s,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let s=!1;for(const n of Object.keys(t)){const i=t[n];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[n];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){s=!0;break}}}if(!s)return e;const n={};for(const s of Object.keys(e)){const i=e[s],o=t[s];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=i;else{const e=i,t=o;n[s]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return We(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return We(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){We(s,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const i=Ue(t._name,t._default,e);if(i.length>0)throw new Error(De(t._name,i));n=e}const i=t.create(n),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.add(s)}catch{}if(this.cppRegistry_)for(const[s,n]of ne)if(se(n)&&!t.has(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.add(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e=q();for(const n of s)for(const[s,i]of e)if(i._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const i=n??Ne(e,t,s),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;let r=null,a=1/0;for(const t of e)if(!se(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=r?r.keys():this.entities_.keys();for(const n of c){let i=!0;for(const t of e)if(!this.has(n,t)){i=!1;break}if(i)for(const e of t)if(!this.has(n,e)){i=!1;break}if(i)for(const e of s)if(this.has(n,e)){i=!1;break}i&&l.push(n)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,s){const n=this.componentAddedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}getRemovedEntitiesSince(e,t){const s=this.componentRemovedBuffer_.get(e._id);if(!s)return[];const n=[];for(const e of s)e.tick>t&&n.push(e.entity);return n}cleanRemovedBuffer(e){for(const[t,s]of this.componentRemovedBuffer_){let n=0;for(let t=0;t<s.length;t++)s[t].tick>=e&&(s[n++]=s[t]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let s=this.componentAddedTicks_.get(e._id);s||(s=new Map,this.componentAddedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordChangedTick_(e,t){let s=this.componentChangedTicks_.get(e._id);s||(s=new Map,this.componentChangedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordRemovedTick_(e,t){let s=this.componentRemovedBuffer_.get(e._id);s||(s=[],this.componentRemovedBuffer_.set(e._id,s)),s.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function qe(e){return{_type:"mut",_component:e}}function Ke(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Je(e){return{_filterType:"added",_component:e}}function Qe(e){return{_filterType:"changed",_component:e}}function Ze(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function et(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function tt(e){return Ke(e)||Ze(e)||et(e)?e._component:e}function st(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{Ke(e)&&n.push(t),Ze(e)?i.push({index:t,component:e._component}):et(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>st(e,[...t,...n],s),without:(...n)=>st(e,t,[...s,...n])}}function nt(...e){return st(e)}class it{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(tt),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=Ne(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:s}=this.descriptor_;if(0===t.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of t)if(!this.world_.isAddedSince(e,s.component,n))return!1;for(const t of s)if(!this.world_.isChangedSince(e,t.component,n))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of s)if(!o||this.passesChangeFilters_(d)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}r[0]=d;for(let e=0;e<n;e++)r[e+1]=this.world_.get(d,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=d}yield r}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function ot(e){return{_type:"removed",_component:e}}class rt{constructor(e,t,s){this.world_=e,this.component_=t,this.lastRunTick_=s}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function at(){return{_type:"commands"}}class lt{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=se(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ct{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new lt(this,null);return this.spawned_.push(e),e}entity(e){return new lt(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function dt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class ut{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class ht{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new ut)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new ut,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function ft(e){return{_type:"event_writer",_event:e}}function pt(e){return{_type:"event_reader",_event:e}}class mt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class _t{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var gt;function yt(){return{_type:"get_world"}}!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(gt||(gt={}));let wt=0;function xt(e,t,s){const n=++wt;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function vt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function bt(e){vt().push({schedule:gt.Update,system:e})}function St(e){vt().push({schedule:gt.Startup,system:e})}function Mt(e,t){vt().push({schedule:e,system:t})}class Pt{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);const s=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ct&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-s),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new it(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ct(this.world_,this.resources_);case"event_writer":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new mt(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new _t(s)}case"removed":{const t=e;return new rt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Tt{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Et=Ae(new Tt,"Input");class Ct{constructor(e){this.target_=e??null}build(e){const s=new Tt;e.insertResource(Et,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(gt.Last,xt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Rt=new Ct,At=Ae({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var It;function kt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(It||(It={}));let Ft=null,Bt=null,zt=1;const Ut=new Map;function $t(e){Ft=e,Bt=e.getResourceManager(),Nt()}function Dt(){0!==Ht&&Ft&&(Ft._free(Ht),Ht=0),Ut.clear(),zt=1,Wt=!1,jt.clear(),Yt=null,Bt=null,Ft=null}function Lt(){if(!Bt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Bt}const Ot={createShader:(e,t)=>Lt().createShader(e,t),releaseShader(e){e>0&&Lt().releaseShader(e)},create(e){const t=zt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??It.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Ut.set(t,s),t},get:e=>Ut.get(e),setUniform(e,t,s){const n=Ut.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,Ft?.invalidateMaterialCache(e))},getUniform(e,t){const s=Ut.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ut.get(e);s&&(s.blendMode=t,Ft?.invalidateMaterialCache(e))},getBlendMode(e){const t=Ut.get(e);return t?.blendMode??It.Normal},setDepthTest(e,t){const s=Ut.get(e);s&&(s.depthTest=t,Ft?.invalidateMaterialCache(e))},getShader(e){const t=Ut.get(e);return t?.shader??0},release(e){Ut.delete(e),Ft?.invalidateMaterialCache(e)},isValid:e=>Ut.has(e),releaseAll(){Ut.clear(),Ft?.clearMaterialCache()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??It.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ut.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=zt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ut.set(s,n),s},toAssetData(e,t){const s=Ut.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=Ut.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Wt=!1,Ht=0;const Xt=16384,jt=new Map;let Yt=null;function Vt(e){const t=(0===Ht&&Ft&&(Ht=Ft._malloc(Xt)),Ht);if(0===t||!Ft)return{ptr:0,count:0};let s=0,n=0;const i=Ft.HEAPU8,o=Ft.HEAPU32,r=Ft.HEAPF32;for(const[a,l]of e){if(kt(l))continue;let e=jt.get(a);e||(Yt||(Yt=new TextEncoder),e=Yt.encode(a),jt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(s+(4+d+4+16)>Xt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${Xt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.set(e,t+s),s+=d;let u=0,h=[0,0,0,0];if("number"==typeof l)u=0,h[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(u=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,h=[l.x,l.y,l.z,0]):"y"in l&&(u=1,h=[l.x,l.y,0,0]);o[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)r[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Nt(){if(!Ft||Wt)return;Ft.materialDataProvider=(e,t,s,n,i)=>{const o=Ut.get(e);if(!o)return Ft.HEAPU32[t>>2]=0,Ft.HEAPU32[s>>2]=0,Ft.HEAPU32[n>>2]=0,void(Ft.HEAPU32[i>>2]=0);Ft.HEAPU32[t>>2]=o.shader,Ft.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Vt(o.uniforms);Ft.HEAPU32[n>>2]=r,Ft.HEAPU32[i>>2]=a},Wt=!0}const Gt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class qt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),i=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Kt{constructor(e,t=""){this.cache_=new qt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ot.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ot.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const s=await l(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),o=await this.shaderLoader_.load(i);return{handle:Ot.createFromAsset(n,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}function Jt(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function Qt(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>({texture:s.get(e.texture)??0}))}}const Zt=new Map;function es(e){Zt.set(e.name,e)}function ts(e){Zt.delete(e)}function ss(e){return Zt.get(e)}function ns(){Zt.clear()}const is=K("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function os(e,t){const s=e.getEntitiesWithComponents([is]);for(const n of s){const s=e.get(n,is);if(!s.enabled||!s.playing||!s.clip)continue;const i=Zt.get(s.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*s.speed),r=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let a=r;if(s.frameTimer>=o&&(s.frameTimer-=o,s.currentFrame++,s.currentFrame>=i.frames.length&&(s.loop&&i.loop?s.currentFrame=0:(s.currentFrame=i.frames.length-1,s.playing=!1)),a=!0),a&&e.has(n,fe)){const t=i.frames[s.currentFrame],o=e.get(n,fe);o.texture=t.texture,e.insert(n,fe,o)}a&&e.insert(n,is,s)}}class rs{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static playSFX(e,t){const s={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},n=this.bufferCache_.get(e);if(!n){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const n=this.bufferCache_.get(e);n&&t.resolve(this.backend_.play(n,s))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(n,s)}static playBGM(e,t){const s=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const s=t?.volume??1,n=this.bgmVolume_;this.bgmVolume_=s,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,n):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:s,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,s)},n=this.bufferCache_.get(e);n?s(n):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&s(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const s=this.mixer_?.getBus(e);s&&(s.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,s){e.setVolume(0);const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(r*s),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,s){const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(s*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}rs.mixer_=null,rs.bufferCache_=new Map,rs.bgmHandle_=null,rs.bgmVolume_=1,rs.fadeAnimId_=0,rs.disposed_=!1;const as=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}]]);function ls(e,t){as.set(e,t)}function cs(e){const t=as.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function ds(e){return as.get(e)?.fields??[]}function us(e){return as.get(e)?.spine??null}const hs=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function fs(e,t){hs.set(e,t)}function ps(e){return hs.get(e)}function ms(e,t){const s=hs.get(e.type);if(!s)return;const n=e.data;for(const i of s){const s=n[i];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${s} which does not exist`),n[i]=void 0!==o?o:0}}}function _s(e,t){const s=new Map;for(const n of t.entities){if(!1===n.visible)continue;const t=e.spawn();s.set(n.id,t),e.insert(t,ve,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const i of n.components)ms(i,s),xs(e,t,i,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),i=s.get(n.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return s}function gs(e,t){return _s(e,t)}async function ys(e,t,s){const n=s?.assetServer,i=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,i){const o=new Map;for(const e of ws.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=as.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...ws.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),d=r.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...d]),i){for(const e of n.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=as.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const n=s[e.field];if("string"!=typeof n||!n)continue;const i=t.get(n);void 0!==i&&(s[e.field]=i)}}}(t,n,i,o,s?.collectAssets);const r=_s(e,t);if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return r}const ws=new Map([["texture",{async load(e,t,s,n){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,s);n.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["font",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,s);n.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["anim-clip",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=Jt(i),r=new Map,a=o.map(async e=>{try{const i=s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),n.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);es(Qt(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,s){const n=[...e].map(e=>s?`${s}/${e}`:`/${e}`);return await rs.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}]]);function xs(e,t,s,n){if("LocalTransform"!==s.type&&"WorldTransform"!==s.type||(s.type="Transform"),"UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===s.type){const e=s.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=oe(s.type);if(i)e.insert(t,i,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function vs(e,t){const s=e.getEntitiesWithComponents([pe]);for(const n of s){const s=e.get(n,pe);s&&(s.aspectRatio=t,e.insert(n,pe,s))}}function bs(e,t){const s=e.getEntitiesWithComponents([ve]);for(const n of s){const s=e.get(n,ve);if(s&&s.value===t)return n}return null}const Ss=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],Ms={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},Ps=new Map,Ts=new Set;for(const e of Ss)for(const t of e.extensions)Ps.set(t,e),Ts.add(t);function Es(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Cs(e){return Ps.get(Es(e))}function Rs(e){return Cs(e)?.editorType??"unknown"}function As(e){return Cs(e)?.addressableType??null}function Is(e){for(const t of Ss)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function ks(e){return Ts.has(e.toLowerCase())}function Fs(){return Ts}function Bs(e){return"string"==typeof e&&(!!e.includes("/")&&ks(Es(e)))}function zs(){const e=[];for(const t of Ss)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function Us(){return zs().map(e=>({type:"suffix",value:e}))}function $s(e){return Ms[e.toLowerCase()]}function Ds(e){const t=Cs(e);return t?.wechatPackInclude??!1}function Ls(e){const t=Cs(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const s=e.lastIndexOf(".");return s>=0?e.substring(0,s)+".json":e}class Os{constructor(e){this.textureCache_=new qt,this.shaderCache_=new qt,this.jsonCache_=new qt,this.textCache_=new qt,this.binaryCache_=new qt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new qt,this.prefabCache_=new qt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=u(F.textCanvasSize,F.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Kt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),i=this.textureCache_.get(n);if(!i)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Ot.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const i=this.resolveUrl(t,s),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),d="binary"===Cs(e)?.contentType,u=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,d);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),i=l.find(e=>e.name===s);if(i){const s=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,i.info.width,i.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=Cs(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const i=s?`${s}/${n}`:n;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${n}`:n,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,async()=>{const e=await this.fetchJson(s);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const s of e.entities){for(const e of s.components){if(!e.data)continue;for(const s of cs(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=us(e.type);if(s)for(const n of[s.skeletonField,s.atlasField]){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}}if(s.nestedPrefab?.prefabPath){const e=t(s.nestedPrefab.prefabPath);e&&(s.nestedPrefab.prefabPath=e)}}}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return ys(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const i=n.metadata?.atlas;i&&s.push(this.loadSpine(n.path,i).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.loadImageFromSrc(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((s,n)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const i=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.getEmbedded(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:i}=this.parseEsShader(t);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return Ot.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(n);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return Ot.createShader(i,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(Ls(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await l(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let i="";for(const e of n){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ws=Ae(null,"Assets");class Hs{build(e){const t=e.wasmModule;t?e.insertResource(Ws,new Os(t)):console.warn("AssetPlugin: No WASM module available")}}const Xs=new Hs;class js{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Ys(e,t){const s=e.getResource(Ws);s&&s.registerEmbeddedAssets(t)}async function Vs(e,t,s){const{entities:n,rootId:i}=await Gs(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},r=await ys(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=r.get(i);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:r}}const Ns=10;async function Gs(e,t,s,n,i,o=0){if(o>Ns)throw new Error(`Prefab nesting depth exceeded ${Ns}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(i?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Gs(e,n.nestedPrefab.overrides,s,a,i,o+1);r.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?r.get(n.parent)??null:null),l.push(...t.entities);continue}const c=r.get(n.prefabEntityId),d=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:d?null:null!==n.parent?r.get(n.parent)??null:null,children:n.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};qs(u.components,r),Ks(u,t),l.push(u)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function qs(e,t){for(const s of e){const e=ps(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(s.data[n]=i)}}}}function Ks(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class Js{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,i=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Vs(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Qs=Ae(null,"Prefabs");class Zs{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ws]}build(e){const t=e.getResource(Ws);e.insertResource(Qs,new Js(e.world,t))}}const en=new Zs;let tn=null,sn=0,nn=0,on=0;const rn=new Float32Array(256);function an(e){tn=e,sn=tn._malloc(64),nn=tn._malloc(64),on=tn._malloc(1024)}function ln(){tn&&(sn&&(tn._free(sn),sn=0),nn&&(tn._free(nn),nn=0),on&&(tn._free(on),on=0)),tn=null}function cn(){if(!tn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return tn}const dn={r:1,g:1,b:1,a:1},un={begin(e){const t=cn();try{t.HEAPF32.set(e,sn/4),t.draw_begin(sn)}catch(e){We(e,"Draw.begin")}},end(){try{cn().draw_end()}catch(e){We(e,"Draw.end")}},line(e,t,s,n=1){try{cn().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.line")}},rect(e,t,s,n=!0){try{cn().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{cn().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{cn().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){We(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{cn().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){We(e,"Draw.circleOutline")}},texture(e,t,s,n=dn){try{cn().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){We(e,"Draw.texture")}},textureRotated(e,t,s,n,i=dn){try{cn().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){We(e,"Draw.textureRotated")}},setLayer(e){cn().draw_setLayer(e)},setDepth(e){cn().draw_setDepth(e)},getDrawCallCount:()=>tn?tn.draw_getDrawCallCount():0,getPrimitiveCount:()=>tn?tn.draw_getPrimitiveCount():0,setBlendMode(e){cn().draw_setBlendMode(e)},setDepthTest(e){cn().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=cn();n.HEAPF32.set(s,nn/4),n.draw_mesh(e,t,nn)}catch(s){We(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=cn(),i=Ot.get(t);if(!i)return;if(un.setBlendMode(i.blendMode),un.setDepthTest(i.depthTest),0===i.uniforms.size)return void un.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,nn/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=pn(t);if(!(n<0)){if(kt(s))rn[o++]=10,rn[o++]=n,rn[o++]=s.slot??e++,rn[o++]=s.textureId;else if("number"==typeof s)rn[o++]=1,rn[o++]=n,rn[o++]=s;else if(Array.isArray(s)){rn[o++]=s.length,rn[o++]=n;for(let e=0;e<s.length;e++)rn[o++]=s[e]}else"w"in s?(rn[o++]=4,rn[o++]=n,rn[o++]=s.x,rn[o++]=s.y,rn[o++]=s.z,rn[o++]=s.w):"z"in s?(rn[o++]=3,rn[o++]=n,rn[o++]=s.x,rn[o++]=s.y,rn[o++]=s.z):(rn[o++]=2,rn[o++]=n,rn[o++]=s.x,rn[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(rn.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,nn);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),on/4),n.draw_meshWithUniforms(e,i.shader,nn,on,o)}catch(s){We(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},hn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},fn=new Set;function pn(e){const t=hn[e];return void 0!==t?t:(fn.has(e)||(fn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(hn).join(", ")}`)),-1)}const mn=new Map;function _n(e,t,s){mn.set(e,{fn:t,scene:s??""})}function gn(e){mn.delete(e)}function yn(){mn.clear()}var wn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(wn||(wn={}));let xn=null,vn=0,bn=0,Sn=0;function Mn(e){xn=e,vn=xn._malloc(262144),bn=xn._malloc(65536),Sn=xn._malloc(256)}function Pn(){xn&&(vn&&xn._free(vn),bn&&xn._free(bn),Sn&&xn._free(Sn),vn=0,bn=0,Sn=0),xn=null}function Tn(){if(!xn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return xn}const En={create(e){const t=Tn(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,vn/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Sn,i).set(o),t.geometry_init(s,vn,n,Sn,i,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,bn,n).set(e.indices),t.geometry_setIndices16(s,bn,n)}else{new Uint32Array(t.HEAPU8.buffer,bn,n).set(e.indices),t.geometry_setIndices32(s,bn,n)}}return s},updateVertices(e,t,s=0){const n=Tn(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,vn/4),n.geometry_updateVertices(e,vn,i,s)},release(e){e>0&&Tn().geometry_release(e)},isValid:e=>!(!xn||e<=0)&&xn.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return En.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:wn.Float2},{name:"a_texCoord",type:wn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const i=n/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;s.push(o,r,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return En.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:wn.Float2},{name:"a_texCoord",type:wn.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,i=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(n-t),a=(r.y-s)/(i-s);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return En.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:wn.Float2},{name:"a_texCoord",type:wn.Float2}],indices:new Uint16Array(r)})}};let Cn=null;function Rn(e){Cn=e}function An(){Cn&&kn.isInitialized()&&kn.shutdown(),Cn=null}function In(){if(!Cn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Cn}const kn={init(e,t){try{return In().postprocess_init(e,t)}catch(s){return We(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{In().postprocess_shutdown()}catch(e){We(e,"PostProcess.shutdown")}},resize(e,t){try{In().postprocess_resize(e,t)}catch(s){We(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return In().postprocess_addPass(e,t)}catch(t){return We(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{In().postprocess_removePass(e)}catch(t){We(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{In().postprocess_setPassEnabled(e,t)}catch(t){We(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return In().postprocess_isPassEnabled(e)}catch(t){return We(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{In().postprocess_setUniformFloat(e,t,s)}catch(s){We(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{In().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){We(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{In().postprocess_begin()}catch(e){We(e,"PostProcess.begin")}},end(){try{In().postprocess_end()}catch(e){We(e,"PostProcess.end")}},getPassCount(){try{return In().postprocess_getPassCount()}catch(e){return We(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Cn)return!1;try{return Cn.postprocess_isInitialized()}catch(e){return We(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{In().postprocess_setBypass(e)}catch(e){We(e,"PostProcess.setBypass")}},isBypassed(){if(!Cn)return!0;try{return Cn.postprocess_isBypassed()}catch(e){return We(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ot.createShader(Fn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Ot.createShader(Fn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Ot.createShader(Fn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ot.createShader(Fn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Fn="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Bn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Bn||(Bn={}));let zn=null,Un=0;function $n(e){zn=e,Un=zn._malloc(64)}function Dn(){zn&&Un&&(zn._free(Un),Un=0),zn=null}const Ln={init(e,t){zn?.renderer_init(e,t)},resize(e,t){zn?.renderer_resize(e,t)},begin(e,t){if(zn&&Un)try{zn.HEAPF32.set(e,Un/4),zn.renderer_begin(Un,t??0)}catch(e){We(e,"Renderer.begin")}},flush(){try{zn?.renderer_flush()}catch(e){We(e,"Renderer.flush")}},end(){try{zn?.renderer_end()}catch(e){We(e,"Renderer.end")}},submitSprites(e){if(zn)try{zn.renderer_submitSprites(e._cpp)}catch(e){We(e,"Renderer.submitSprites")}},submitBitmapText(e){if(zn)try{zn.renderer_submitBitmapText(e._cpp)}catch(e){We(e,"Renderer.submitBitmapText")}},submitSpine(e){if(zn)try{zn.renderer_submitSpine?.(e._cpp)}catch(e){We(e,"Renderer.submitSpine")}},setStage(e){zn?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>zn?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){zn?.renderer_releaseTarget(e)},getTargetTexture:e=>zn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>zn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){zn?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){zn?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){zn?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){zn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>zn?zn.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>zn?{drawCalls:zn.renderer_getDrawCalls(),triangles:zn.renderer_getTriangles(),sprites:zn.renderer_getSprites(),text:zn.renderer_getText(),spine:zn.renderer_getSpine?.()??0,meshes:zn.renderer_getMeshes(),culled:zn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let On=null;function Wn(e){On=e}function Hn(){On=null}const Xn={enable(){On?.gl_enableErrorCheck(!0)},disable(){On?.gl_enableErrorCheck(!1)},check:e=>On?.gl_checkErrors(e)??0,diagnose(){On?.renderer_diagnose()}};class jn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Ln.resize(n,i),kn.isInitialized()&&kn.getPassCount()>0&&kn.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Ln.setViewport(0,0,n,i),Ln.clearBuffers(3),Ln.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),Ln.submitSprites(t),Ln.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ln.submitSpine(t),Ln.flush(),this.executeDrawCallbacks(s,o),Ln.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o}=e;Ln.setViewport(n.x,n.y,n.w,n.h),Ln.setScissor(n.x,n.y,n.w,n.h,!0),Ln.clearBuffers(i),Ln.setScissor(0,0,0,0,!1),Ln.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ln.submitSprites(t),Ln.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ln.submitSpine(t),Ln.flush(),this.executeDrawCallbacks(s,o),Ln.end()}executeDrawCallbacks(e,t){const s=mn;if(s.size>0){un.begin(e);const n=[];for(const[e,i]of s.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}un.end();for(const e of n)gn(e)}}}const Yn="__scene_transition_overlay__";class Vn{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Nn{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,be,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),_n(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=kn.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){kn.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,be)){const s=this.app_.world.get(e,be);s.persistent=t,this.app_.world.insert(e,be,s)}}}class Gn{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??F.sceneTransitionDuration,i=t.color??{...F.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},_n(Yn,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;un.setLayer(9999),un.setDepth(9999),un.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,gn(Yn),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,gn(Yn),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Vn(t);this.scenes_.set(e,s);const n=new Nn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Ws)?this.app_.getResource(Ws):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Vn(t);this.scenes_.set(e,s);const n=new Nn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Ws)?this.app_.getResource(Ws):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const i=t?.keepPersistent??!0;for(const e of s.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,be)){if(this.app_.world.get(e,be).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())gn(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{kn.removePass(e)}catch{}s.postProcessPasses.length=0,this.releaseSceneAssets_(s),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:s};this.app_.hasResource(Ws)&&(i.assetServer=this.app_.getResource(Ws));const o=await ys(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,be,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=Kn(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const i=this.contexts_.get(t);s.setup&&await s.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource(Ws)?this.app_.getResource(Ws):null;if(s){for(const e of t.textureUrls)s.releaseTexture(e);for(const e of t.fontPaths)s.releaseFont(e);for(const e of t.spineKeys)s.releaseSpine(e)}for(const e of t.materialHandles)Ot.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let i=!1;if(s.has(e,fe)){const t=s.get(e,fe);n.sprite=t.color.a,t.color.a=0,s.insert(e,fe,t),i=!0}if(s.has(e,xe)){const t=s.get(e,xe);n.spine=t.color.a,t.color.a=0,s.insert(e,xe,t),i=!0}if(s.has(e,we)){const t=s.get(e,we);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,we,t),i=!0}i&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,fe)){const t=s.get(e,fe);t.color.a=n.sprite,s.insert(e,fe,t)}if(void 0!==n.spine&&s.has(e,xe)){const t=s.get(e,xe);t.color.a=n.spine,s.insert(e,xe,t)}if(void 0!==n.bitmapText&&s.has(e,we)){const t=s.get(e,we);t.color.a=n.bitmapText,s.insert(e,we,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{kn.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const qn=Ae(null,"SceneManager");function Kn(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(qn).getSceneStatus(t)&&s._fn(...n)}}}const Jn=xt([ke(qn),Ie(ze)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Qn={name:"SceneManager",build(e){const t=new Gn(e);e.insertResource(qn,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(qn),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(gt.Startup,s),e.addSystemToSchedule(gt.Last,Jn)}};class Zn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new ht,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(gt.Last);else{this.runSchedule(gt.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(gt.FixedPreUpdate),this.runSchedule(gt.FixedUpdate),this.runSchedule(gt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(gt.PreUpdate),this.runSchedule(gt.Update),this.runSchedule(gt.PostUpdate),this.runSchedule(gt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Ge,this.resources_=new Be;for(const e of Object.values(gt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Zn}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(gt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(gt.Startup,e)}removeSystem(e){let t=!1;for(const[s,n]of this.systems_){const i=n.filter(t=>t.system._id!==e);i.length!==n.length&&(this.systems_.set(s,i),this.sortedSystemsCache_.delete(s),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return Oe(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(qn).register(e),this}setInitialScene(e){return this.getResource(qn).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new Pt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(ze)||this.resources_.insert(ze,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(gt.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(gt.Last);else{this.runSchedule(gt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(gt.FixedPreUpdate),this.runSchedule(gt.FixedUpdate),this.runSchedule(gt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(gt.PreUpdate),this.runSchedule(gt.Update),this.runSchedule(gt.PostUpdate),this.runSchedule(gt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new Pt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(ze,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(gt.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,yn();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Hn,Dn,An,Pn,Dt,ln];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const i=t.get(n);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,i=new Set,o=r=>{if(n.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}i.delete(r),n.add(r),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(ze);t.delta=e,t.elapsed+=e,t.frameCount++}}function ei(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const ti=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function si(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case ce.FixedWidth:return o;case ce.FixedHeight:return r;case ce.Expand:return Math.max(o,r);case ce.Shrink:return Math.min(o,r);case ce.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const ni=[];function ii(e){if(e<ni.length)return ni[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return ni.push(t),t}function oi(e,t,s,n,i,o){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,be);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*s/(i.viewportH*n);let a,d=0,u=0;if(i.projectionType===ae.Orthographic){if(u=i.orthoSize,l){u=si(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}d=u*r,a=ai(-d,d,-u,u,-i.farPlane,i.farPlane)}else a=ci(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=ui(o.position.x,o.position.y,o.position.z),f=ii(c.length);f.entity=e,f.viewProjection.set(fi(a,h)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=d,f.halfH=u,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const ri=new Float32Array(16);function ai(e,t,s,n,i,o){const r=ri;r.fill(0);const a=t-e,l=n-s,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(n+s)/l,r[14]=-(o+i)/c,r[15]=1,r}const li=new Float32Array(16);function ci(e,t,s,n){const i=li;i.fill(0);const o=1/Math.tan(e/2),r=s-n;return i[0]=o/t,i[5]=o,i[10]=(n+s)/r,i[11]=-1,i[14]=2*n*s/r,i}const di=new Float32Array(16);function ui(e,t,s){const n=di;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const hi=new Float32Array(16);function fi(e,t){const s=hi;for(let n=0;n<4;n++)for(let i=0;i<4;i++)s[4*i+n]=e[0+n]*t[4*i+0]+e[4+n]*t[4*i+1]+e[8+n]*t[4*i+2]+e[12+n]*t[4*i+3];return s}const pi={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function mi(e,t,s,n,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,d=o.left+t.x*a,u=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,m,_;e.x===t.x?(f=c+s.x-i.x*r.x,m=f+i.x):(f=c+s.x,m=d+n.x),e.y===t.y?(p=u+s.y-i.y*r.y,_=p+i.y):(p=u+s.y,_=h+n.y);const g=Math.max(0,m-f),y=Math.max(0,_-p);return{originX:f+r.x*g,originY:p+r.y*y,width:g,height:y,rect:{left:f,bottom:p,right:m,top:_}}}const _i=re("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});let gi=null,yi=null;function wi(e,t){e.has(t,fe)||e.insert(t,fe,{texture:D,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function xi(e,t){switch(e){case pi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case pi.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case pi.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function vi(e,t){switch(e){case pi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case pi.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case pi.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function bi(e,t,s,n){switch(e){case pi.BottomToTop:case pi.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}}function Si(e,t,s,n){if(!e.has(t,_i))return;const i=e.get(t,_i),o=xi(s,n);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,_i,i)}function Mi(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Pi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Ti(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),i=[];for(const t of n){if(!t){i.push("");continue}let n="";for(let o=0;o<t.length;o++){const r=t[o],a=n+r;if(e.measureText(a).width>s&&n){if(Pi(r.charCodeAt(0))&&n.length>0&&Pi(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Pi(n.charCodeAt(t))){e=t;break}e>=0?(i.push(n.substring(0,e+1)),n=n.substring(e+1)+r):(i.push(n),n=r)}else i.push(n),n=r}else n=a}n&&i.push(n)}return i.length>0?i:[""]}function Ei(e){let t=1;for(;t<e;)t*=2;return t}function Ci(e,t){let s=0,n=t;for(;e.has(n,ge);){const t=e.get(n,ge).entity;if(!e.valid(t))break;s++,n=t}return s}function Ri(e,t){if(gi&&yi){const e=gi.getUIRectComputedWidth(yi,t);if(e>0)return e}return e.size.x}function Ai(e,t){if(gi&&yi){const e=gi.getUIRectComputedHeight(yi,t);if(e>0)return e}return e.size.y}function Ii(e,t,s,n,i,o){if(!e.has(t,fe))return;const r=e.get(t,fe);let a,l;switch(s){case pi.BottomToTop:case pi.TopToBottom:a=i,l=o*n;break;default:a=i*n,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,fe,r))}function ki(e,t,s){let n=t;for(;e.has(n,ge);){const t=e.get(n,ge).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Fi(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Bi(e,t,s,n,i){if(!e.has(t,_i))return;const o=e.get(t,_i),r=mi(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,fe)){const s=e.get(t,fe);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,fe,s))}if(e.has(t,de)){const s=e.get(t,de);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,de,s)}}function zi(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let i=0;i<t.length;i++)n[t[i]]=s[i](e);return n},changed(e,n){for(let i=0;i<t.length;i++)if(e[t[i]]!==s[i](n))return!0;return!1},update(e,n){for(let i=0;i<t.length;i++)e[t[i]]=s[i](n)}}}const Ui=.1,$i=30,Di={r:.3,g:.5,b:.8,a:1},Li={Left:0,Center:1,Right:2},Oi={Top:0,Middle:1,Bottom:2},Wi={Visible:0,Clip:1,Ellipsis:2},Hi=K("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Li.Left,verticalAlign:Oi.Top,wordWrap:!0,overflow:Wi.Visible,lineHeight:1.2});class Xi{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=u(F.textCanvasSize,F.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Ei(this.frameMaxW_)),e.height=Math.max(e.height,Ei(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ei(this.frameMaxW_),e.height=Ei(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Ti(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=i?Math.ceil(o):u+2*d,p=i?Math.ceil(r):h+2*d;if(i&&e.overflow===Wi.Ellipsis&&h>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(n.width<f||n.height<p)&&(n.width=Math.max(n.width,Ei(f)),n.height=Math.max(n.height,Ei(p)));const m=Math.round(255*e.color.r),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,i&&e.overflow===Wi.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case Oi.Top:x=d;break;case Oi.Middle:x=d+(p-2*d-w)/2;break;case Oi.Bottom:x=p-w-d;break;default:x=d}x<0&&(x=0)}else x=d;let v=x;for(const t of l){let n;switch(e.align){case Li.Left:n=d;break;case Li.Center:n=f/2;break;case Li.Right:n=f-d;break;default:n=d}s.fillText(t,n,v),v+=c}i&&e.overflow===Wi.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const T=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const i=this.renderText(t,s);return this.cache.set(e,i),i}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case Li.Left:return"left";case Li.Center:return"center";case Li.Right:return"right"}}}const ji=zi({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Ri(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Ai(e.uiRect,e.entity):0});class Yi{build(e){ie("Text",Hi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Xi(t),n=e.world,i=new Map;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Hi));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Hi)){if(n.valid(e)&&n.has(e,fe)){const t=n.get(e,fe);n.insert(e,fe,{texture:D,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=n.getEntitiesWithComponents([Hi]);for(const t of e){const e=n.get(t,Hi),o=n.has(t,_i)?n.get(t,_i):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!ji.changed(a,r)){if(n.has(t,fe)&&n.get(t,fe).texture!==D)continue}wi(n,t);const l=o?{size:{x:Ri(o,t),y:Ai(o,t)}}:null,c=s.renderForEntity(t,e,l),d=n.get(t,fe);n.insert(t,fe,{texture:c.textureHandle,color:{r:d.color.r,g:d.color.g,b:d.color.b,a:d.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:d.layer,flipX:d.flipX,flipY:d.flipY,material:d.material,enabled:d.enabled}),i.set(t,ji.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Vi=new Yi,Ni=0,Gi=1,qi=re("UIMask",{enabled:!0,mode:Ni});function Ki(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,i-s),h:Math.max(0,o-n)}}function Ji(e,t){const s=t??new Float32Array(16),n=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],d=e[7],u=e[8],h=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=e[14],y=e[15],w=n*l-i*a,x=n*c-o*a,v=n*d-r*a,b=i*c-o*l,S=i*d-r*l,M=o*d-r*c,P=u*_-h*m,T=u*g-f*m,E=u*y-p*m,C=h*g-f*_,R=h*y-p*_,A=f*y-p*g;let I=w*A-x*R+v*C+b*E-S*T+M*P;return 0===I||(I=1/I,s[0]=(l*A-c*R+d*C)*I,s[1]=(o*R-i*A-r*C)*I,s[2]=(_*M-g*S+y*b)*I,s[3]=(f*S-h*M-p*b)*I,s[4]=(c*E-a*A-d*T)*I,s[5]=(n*A-o*E+r*T)*I,s[6]=(g*v-m*M-y*x)*I,s[7]=(u*M-f*v+p*x)*I,s[8]=(a*R-l*E+d*P)*I,s[9]=(i*E-n*R-r*P)*I,s[10]=(m*S-_*v+y*w)*I,s[11]=(h*v-u*S-p*w)*I,s[12]=(l*T-a*C-c*P)*I,s[13]=(n*C-i*T+o*P)*I,s[14]=(_*x-m*b-g*w)*I,s[15]=(u*b-h*x+f*w)*I),s}function Qi(e,t,s,n,i,o,r){const a=(e-n)/o*2-1,l=(t-i)/r*2-1,c=s[0]*a+s[4]*l+s[12],d=s[1]*a+s[5]*l+s[13],u=s[3]*a+s[7]*l+s[15];return{x:c/u,y:d/u}}function Zi(e,t,s,n,i,o,r,a){return e>=s-i*r&&e<=s+i*(1-r)&&t>=n-o*a&&t<=n+o*(1-a)}function eo(e,t){return 2*Math.atan2(e,t)}function to(e,t,s,n,i,o,r){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function so(e,t,s,n,i,o,r,a,l,c){const d=eo(l,c),u=Math.sin(-d),h=Math.cos(-d),f=e-s,p=t-n,m=f*h-p*u+s,_=f*u+p*h+n;return m>=s-i*r&&m<=s+i*(1-r)&&_>=n-o*a&&_<=n+o*(1-a)}function no(e,t,s,n,i,o,r){if(!e.has(t,_i)||!e.has(t,de))return null;const a=e.get(t,_i),l=e.get(t,de),c=Ri(a,t)*l.worldScale.x,d=Ai(a,t)*l.worldScale.y,u=l.worldPosition.x,h=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,_=c*(1-f),g=-d*p,y=d*(1-p),w=eo(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[u+m*x-g*v,h+m*v+g*x],[u+_*x-g*v,h+_*v+g*x],[u+_*x-y*v,h+_*v+y*x],[u+m*x-y*v,h+m*v+y*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=to(e,t,s,n,i,o,r);S=Math.min(S,a),M=Math.min(M,l),P=Math.max(P,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(P-S),h:Math.round(T-M)}}function io(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([qi]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,qi);s.enabled&&(u.add(e),s.mode===Gi?(d.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,i,o,r,a,l,c){const d=[];for(const e of n){let s=!0;ki(t,e,e=>{if(i.has(e)){if(t.get(e,qi).mode===Ni)return s=!1,!0}return!1}),s&&d.push(e)}function u(n,d){const h=e.getChildEntities(s,n);for(const s of h){let n=d;if(i.has(s)){if(t.get(s,qi).mode===Ni){const e=no(t,s,o,r,a,l,c);e&&(n=Ki(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=no(t,e,o,r,a,l,c);s&&u(e,s)}}(e,t,s,c,u,n,i,o,r,a),d.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;ki(t,e,e=>!!i.has(e)&&(s=!1,!0)),s&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}function d(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,d,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class oo{build(e){if(ie("UIMask",qi),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(io(e.wasmModule,e.world))}}const ro=new oo,ao=re("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),lo=re("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),co={Normal:0,Hovered:1,Pressed:2,Disabled:3},uo=K("Button",{state:co.Normal,transition:null});class ho{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const fo=Ae(new ho,"UIEvents");class po{build(e){ie("UIRect",_i);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){gi=e,yi=t}(s,n);e.addSystemToSchedule(gt.PreUpdate,xt([Ie(At)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n),s.transform_update(n))},{name:"UILayoutSystem"})),e.addSystemToSchedule(gt.PostUpdate,xt([Ie(At)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(gt.PostUpdate,xt([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const mo=new po;let _o=!1,go=!1;function yo(e){_o=e}function wo(){return _o}function xo(){return!_o}function vo(e){go=e}function bo(){return go}const So=function(){const e=new Float32Array(16),t=new Float32Array(16);let s=!0;return{update(e){for(let n=0;n<16;n++)if(t[n]!==e[n]){t.set(e),s=!0;break}},getInverse:t=>(s&&(Ji(t,e),s=!1),e)}}();function Mo(e,t,s,n){t.emit(s,n,s),ki(e,s,i=>{if(!e.has(i,ao))return!1;const o=e.get(i,ao);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Po{build(e){ie("Interactable",ao),ie("Button",uo);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new ho;e.insertResource(fo,i);let o=null,r=null;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Et),Ie(At)],(e,a)=>{if(i.drain(),wo()&&!bo())return;const l=t.getEntitiesWithComponents([lo]);for(const e of l){const s=t.get(e,lo);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,lo,s))}if(!a.valid)return;const c=f(),d=e.mouseX*c,u=a.screenH-e.mouseY*c;So.update(a.viewProjection);const h=Qi(d,u,So.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=h.x,a.worldMouseY=h.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),_=e.isMouseButtonReleased(0);s.uiHitTest_update(n,h.x,h.y,p,m,_);const g=s.uiHitTest_getHitEntity(),y=4294967295===g?null:g;if(null===o||t.valid(o)||(o=null),o!==y){if(null!==o&&t.valid(o)&&t.has(o,lo)){const e=t.get(o,lo);e.hovered=!1,t.insert(o,lo,e),i.emit(o,"hover_exit")}if(null!==y){Fi(t,y,lo);const e=t.get(y,lo);e.hovered=!0,t.insert(y,lo,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,lo);e.pressed=!0,e.justPressed=!0,t.insert(y,lo,e),r=y,Mo(t,i,y,"press")}if(_&&null!==r){if(t.valid(r)&&t.has(r,lo)){const e=t.get(r,lo);e.pressed=!1,e.justReleased=!0,t.insert(r,lo,e),Mo(t,i,r,"release"),r===o&&Mo(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(gt.Update,xt([],()=>{const e=t.getEntitiesWithComponents([uo]);for(const s of e){if(Fi(t,s,ao,{enabled:!0}),!t.has(s,lo))continue;const e=t.get(s,lo),n=t.get(s,uo),i=t.get(s,ao),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=co.Pressed:e.hovered?n.state=co.Hovered:n.state=co.Normal:n.state=co.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,fe)){const o=t.get(s,fe);o.color=Mi(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,fe,o)}}},{name:"ButtonSystem"}))}}const To=new Po,Eo=K("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),Co=K("Focusable",{tabIndex:0,isFocused:!1});class Ro{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Ao=Ae(new Ro,"FocusManager");class Io{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ie("TextInput",Eo),wo()&&!bo())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=u(F.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,d=0,h=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function m(){const t=e.getResource(Ao);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Eo)?n:null}const _=()=>{l||null===m()||v()},g=()=>{l=!0},y=()=>{l=!1,v()},w=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void b();const i=s.get(n,Eo);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(fo).emit(n,"submit"),void b()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,i.dirty=!0,S())},x=()=>{const t=m();if(null!==t){const n=s.get(t,Eo);n.focused=!1,n.dirty=!0;e.getResource(Ao).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,Eo);if(n.readOnly)return;let i=p.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),p.value=i),i!==n.value){n.value=i;e.getResource(fo).emit(t,"change")}n.cursorPos=p.selectionStart??i.length,n.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=s.get(t,Eo);e.focused=!1,e.dirty=!0}e.getResource(Ao).blur(),p.blur()}function S(){c=!0,d=0}p.addEventListener("input",_),p.addEventListener("compositionstart",g),p.addEventListener("compositionend",y),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",_),p.removeEventListener("compositionstart",g),p.removeEventListener("compositionend",y),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,d,u){(i.width<d||i.height<u)&&(i.width=Ei(Math.max(i.width,d)),i.height=Ei(Math.max(i.height,u))),o.clearRect(0,0,i.width,i.height);const h=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,d,u),o.save(),o.beginPath(),o.rect(l.padding,0,d-2*l.padding,u),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=f?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const _=Math.ceil(1.2*l.fontSize),g=l.padding;if(l.multiline){const e=Ti(o,p,d-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=_}else{const e=(u-l.fontSize)/2;o.fillText(p,g,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=Ti(o,l.value,d-2*g);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(i+s>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=s,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const c=r<e.length?e[r].substring(0,a):"";t=g+o.measureText(c).width,s=g+r*_,n=_}else t=g+o.measureText(e).width,s=(u-l.fontSize)/2,n=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,s,2,n)}o.restore();const y=o.getImageData(0,0,d,u),w=new Uint8Array(y.data.buffer),x=t.getResourceManager();w.length>a&&(0!==r&&t._free(r),r=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,r);const v=n.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(d,u,r,w.length,1,!0);n.set(e,b);const S=s.get(e,fe);S.texture=b,S.size.x=d,S.size.y=u,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,fe,S)}e.addSystemToSchedule(gt.Update,xt([Ie(Ao)],e=>{const t=s.getEntitiesWithComponents([Eo]);for(const e of t)Fi(s,e,Co,{tabIndex:0,isFocused:!1}),Fi(s,e,ao,{enabled:!0,blockRaycast:!0});const n=m();if(n!==M){if(null!==M&&s.valid(M)&&s.has(M,Eo)){const e=s.get(M,Eo);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,Eo);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(n),M=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===h?0:(e-h)/1e3;h=e,i=Math.min(i,.1);const o=m();if(null!==o&&(d+=i,d>=.5)){d-=.5,c=!c;s.get(o,Eo).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Eo)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Eo,_i]);for(const e of a){const t=s.get(e,Eo);if(!t.dirty)continue;const n=s.get(e,_i),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(wi(s,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const ko=new Io,Fo={Simple:0,Sliced:1,Tiled:2,Filled:3},Bo={Horizontal:0,Vertical:1},zo={Left:0,Right:1,Bottom:2,Top:3},Uo=K("Image",{texture:D,color:{r:1,g:1,b:1,a:1},imageType:Fo.Simple,fillMethod:Bo.Horizontal,fillOrigin:zo.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),$o=zi({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Ri(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Ai(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Do=new class{build(e){ie("Image",Uo);const t=e.world,s=new Map;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Uo)||s.delete(e);const e=t.getEntitiesWithComponents([Uo]);for(const n of e){const e=t.get(n,Uo),i=t.has(n,_i)?t.get(n,_i):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!$o.changed(r,o))continue;wi(t,n);const a=t.get(n,fe);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=Ri(i,n),a.size.y=Ai(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Fo.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Bo.Horizontal?e.fillOrigin===zo.Left?(a.uvScale.x=t,a.size.x=s*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=s*t):e.fillOrigin===zo.Bottom?(a.uvScale.y=t,a.size.y=n*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=n*t)}else e.imageType===Fo.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(n,fe,a),s.set(n,$o.take(o))}else a.color.a=0,t.insert(n,fe,a),s.set(n,$o.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Lo=K("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Oo=K("ToggleGroup",{allowSwitchOff:!1});const Wo=new class{build(e){ie("Toggle",Lo),ie("ToggleGroup",Oo);const t=e.world,s=new Set;e.addSystemToSchedule(gt.Update,xt([Ie(fo)],e=>{const n=t.getEntitiesWithComponents([Lo]);if(!wo()||bo()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Lo);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,Lo,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Lo);if(0!==s.group&&t.valid(s.group)){let t=o.get(s.group);t||(t=[],o.set(s.group,t)),t.push(e)}}for(const s of n){if(Fi(t,s,ao,{enabled:!0}),!t.has(s,lo))continue;const n=t.get(s,lo),i=t.get(s,Lo),r=t.get(s,ao);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,Oo);if(i.isOn&&r){if(!t.get(n,Oo).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,Lo,i),i.isOn&&r){const i=o.get(n);if(i)for(const n of i){if(n===s)continue;const i=t.get(n,Lo);i.isOn&&(i.isOn=!1,t.insert(n,Lo,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,fe)){const e=t.get(s,fe);e.color=Mi(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,fe,e)}}}for(const e of n){const s=t.get(e,Lo);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,fe)){const e=t.get(s.graphicEntity,fe);e.enabled=s.isOn,t.insert(s.graphicEntity,fe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Ho=pi,Xo=K("ProgressBar",{value:0,fillEntity:0,direction:pi.LeftToRight});function jo(e,t,s,n){if(!e.has(t,_i))return;const i=e.get(t,_i),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=mi(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,fe)){const s=e.get(t,fe);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,fe,s))}if(e.has(t,de)){const s=e.get(t,de),n=s.position;n.x===l.originX&&n.y===l.originY||(s.position={x:l.originX,y:l.originY,z:n.z},e.insert(t,de,s))}}class Yo{build(e){ie("ProgressBar",Xo);const t=e.world;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{const e=t.getEntitiesWithComponents([Xo,_i]);for(const s of e){const e=t.get(s,Xo);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,_i),i=Math.max(0,Math.min(1,e.value));Si(t,e.fillEntity,e.direction,i);const o=Ri(n,s),r=Ai(n,s);jo(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Vo=new Yo,No=K("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Go=K("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});const qo=new class{build(e){ie("Draggable",No),ie("DragState",Go);const t=e.world,s=e.getResource(fo);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Et),Ie(At)],(e,r)=>{if(wo()&&!bo())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([No,lo]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,No).enabled)continue;if(t.get(n,lo).hovered){let e=0;t.has(n,fe)&&(e=t.get(n,fe).layer);const i=Ci(t,n);(e>o||e===o&&i>=r)&&(o=e,r=i,s=n)}}if(null!==s){n=s,i={x:a.x,y:a.y},t.has(s,Go)||t.insert(s,Go);const e=t.get(s,Go),o=t.get(s,de);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,Go)){t.get(n,Go).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),d=t.get(n,No);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,Go).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Go))return void(o=null);const n=t.get(o,Go),i=t.get(o,No),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,d=n.startWorldPos.y+l;const u=function(e,t,s,n){let i=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,n,c,d);c=u.x,d=u.y;const h=n.currentWorldPos.x,f=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:d-f},n.currentWorldPos={x:c,y:d},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:d-n.startWorldPos.y},t.has(o,de)){const e=function(e,t,s,n){if(!e.has(t,ge))return{x:s,y:n};const i=e.get(t,ge).entity;if(!e.valid(i)||!e.has(i,de))return{x:s,y:n};const o=e.get(i,de),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=eo(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(s*d-n*c)/r,y:(s*c+n*d)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,de);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,de,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Ko=K("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Jo(e,t,s,n){return n<=0?1:e<t?Math.max(0,1-(t-e)/n):e>s?Math.max(0,1-(e-s)/n):1}function Qo(e,t,s,n,i){const o=2/(n=Math.max(1e-4,n)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(s+o*l)*i,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(s-o*c)*a}}const Zo=new class{build(e){ie("ScrollView",Ko);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(gt.PostUpdate,xt([Ie(Et),Ie(At),Ie(ze)],(e,i,o)=>{const r=wo()&&!bo(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);i.valid&&(n.x=i.worldMouseX,n.y=i.worldMouseY);const l=t.getEntitiesWithComponents([Ko,_i]);for(const o of l){Fi(t,o,qi,{enabled:!0,mode:Ni});const l=t.get(o,Ko),c=t.get(o,_i);let d=s.get(o);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,d));const u=Ri(c,o),h=Ai(c,o);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ye)){const e=t.get(l.contentEntity,ye).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,de))continue;const e=t.get(r,de);let a=0,l=0,c=.5,d=.5;if(t.has(r,_i)){const e=t.get(r,_i);a=Ri(e,r)||e.size.x,l=Ai(e,r)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(r,fe)){const e=t.get(r,fe);a=e.size.x,l=e.size.y}const u=e.position.x-a*c,h=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);u<s&&(s=u),h>n&&(n=h),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=n-s),0===p&&(p=o-i)}const m=Math.max(0,f-u),_=Math.max(0,p-h);if(!r&&i.valid){Fi(t,o,ao,{enabled:!0,blockRaycast:!0});const s=t.has(o,lo)?t.get(o,lo):null;if(s?.justPressed&&(d.isDragging=!0,d.lastWorldX=n.x,d.lastWorldY=n.y,d.velocityX=0,d.velocityY=0),d.isDragging&&e.isMouseButtonDown(0)){const e=n.x-d.lastWorldX,t=n.y-d.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=Jo(l.scrollX,0,m,u);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const n=a>0?-e*t/a:0;d.velocityX+=(n-d.velocityX)*s}}if(l.verticalEnabled){const e=Jo(l.scrollY,0,_,h);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const n=a>0?t*e/a:0;d.velocityY+=(n-d.velocityY)*s}}d.lastWorldX=n.x,d.lastWorldY=n.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*u,t=5*h;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Jo(l.scrollY,0,_,h);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Jo(l.scrollX,0,m,u);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>_;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=Qo(l.scrollX,e,d.velocityX,.1,a);l.scrollX=t.value,d.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(d.velocityX)<Ui&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Ui?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:_,t=Qo(l.scrollY,e,d.velocityY,.1,a);l.scrollY=t.value,d.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(d.velocityY)<Ui&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Ui?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,_)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*u,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,_+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,de)){const e=t.get(l.contentEntity,de),s=e.position.x,n=e.position.y;(isNaN(d.lastAppliedX)||Math.abs(s-d.lastAppliedX)>.01)&&(d.contentBaseX=s),(isNaN(d.lastAppliedY)||Math.abs(n-d.lastAppliedY)>.01)&&(d.contentBaseY=n),e.position.x=d.contentBaseX-l.scrollX,e.position.y=d.contentBaseY+l.scrollY,d.lastAppliedX=e.position.x,d.lastAppliedY=e.position.y,t.insert(l.contentEntity,de,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},er=pi,tr=K("Slider",{value:0,minValue:0,maxValue:1,direction:pi.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function sr(e,t,s,n,i,o){const r=Ri(n,i)*s.worldScale.x,a=Ai(n,i)*s.worldScale.y,l=eo(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),u=e-s.worldPosition.x,h=t-s.worldPosition.y,f=u*d-h*c,p=u*c+h*d,m=-n.pivot.x*r,_=-n.pivot.y*a;switch(o){case pi.LeftToRight:return r>0?(f-m)/r:0;case pi.RightToLeft:return r>0?1-(f-m)/r:0;case pi.BottomToTop:return a>0?(p-_)/a:0;case pi.TopToBottom:return a>0?1-(p-_)/a:0}}function nr(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case pi.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case pi.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case pi.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case pi.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class ir{build(e){ie("Slider",tr);const t=e.world;let s=null;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(Et),Ie(At),Ie(fo)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([tr,_i]);for(const r of o){const o=t.get(r,tr),a=t.get(r,_i);if(!wo()||bo()){if(t.has(r,de)){Fi(t,r,ao,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Fi(t,o.handleEntity,ao,{enabled:!0,blockRaycast:!1});const l=t.get(r,de),c=t.has(r,lo)?t.get(r,lo):null;let d=c?.justPressed??!1;if(!d&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,lo)&&(d=t.get(o.handleEntity,lo).justPressed),d&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=sr(n.worldMouseX,n.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let s=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(s=Math.round(s));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,s)),t.insert(r,tr,o),o.value!==c&&i.emit(r,"change")}s===r&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,d=Ri(a,r),u=Ai(a,r),h={left:-d/2,bottom:-u/2,right:d/2,top:u/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Si(t,o.fillEntity,o.direction,c),Bi(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,_i)){const e=t.get(o.handleEntity,_i);nr(e,o.direction,c),t.insert(o.handleEntity,_i,e),Bi(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const or=new ir;const rr=new class{build(e){ie("Focusable",Co);const t=e.world,s=new Ro;e.insertResource(Ao,s),e.addSystemToSchedule(gt.Update,xt([Ie(Et),Ie(fo)],(e,n)=>{if(wo()&&!bo())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Co]);for(const e of i){if(!t.has(e,lo))continue;t.get(e,lo).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of i){if(!t.valid(s))continue;if(t.has(s,ao)){if(!t.get(s,ao).enabled)continue}const n=t.get(s,Co);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const r=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?n.length-1:0:a?(r-1+n.length)%n.length:(r+1)%n.length,o(n[l])}function o(e){const i=s.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Co)){t.get(i,Co).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Co).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},ar=K("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function lr(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:i}=t;return{top:s.top,bottom:i-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const cr=new class{build(e){ie("SafeArea",ar);const t=e.world;let s=lr(),n=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{s=lr(),n=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{s=lr(),n=!0});e.addSystemToSchedule(gt.PreUpdate,xt([Ie(At)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,n=!0),!n)return;n=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([ar,_i]);for(const e of d){const n=t.get(e,ar),i=t.get(e,_i),o=n.applyTop?s.top*c:0,r=n.applyBottom?s.bottom*c:0,a=n.applyLeft?s.left*c:0,l=n.applyRight?s.right*c:0;let d=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},d=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},d=!0),d&&t.insert(e,_i,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},dr=K("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let ur=null;function hr(e,t){if(!ur)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=ur.get(e);s?s.renderer=t:ur.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const fr=new class{build(e){ie("ListView",dr);const t=e.world,s=new Map;ur=s,e.addSystemToSchedule(gt.PostUpdate,xt([Ie(Et)],e=>{const n=wo()&&!bo();for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const i=t.getEntitiesWithComponents([dr,_i]);for(const o of i){Fi(t,o,ao,{enabled:!0,blockRaycast:!0}),Fi(t,o,qi,{enabled:!0,mode:Ni});let i=s.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,i));const r=t.get(o,dr),a=t.get(o,_i),l=Ai(a,o),c=Ri(a,o);if(!n){const s=t.has(o,lo)?t.get(o,lo):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const d=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,d));const u=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,s]of i.itemEntities)(e<u||e>=h)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=u;e<h;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,ve,{value:`ListItem_${e}`}),t.insert(s,_i,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),i.itemEntities.set(e,s),i.renderer&&i.renderer(e,s)),t.has(s,de)){const n=t.get(s,de);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,de,n)}}i.visibleStart=u,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},pr=K("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const mr=new class{build(e){ie("Dropdown",pr);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,de))return;const s=t.get(e,de);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,de,{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:{x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,fe)){const s=t.get(e,fe);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,fe,{texture:s.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:s.enabled})}}function o(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const i=s.listEntity;if(0===i||!t.valid(i))return;d(i,!0),c(n);const o=t.get(e,fe),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*$i;t.insert(i,_i,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,de,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,fe,{texture:D,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*$i;t.insert(o,ve,{value:`Option_${e}`}),t.insert(o,_i,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*$i},offsetMax:{x:0,y:0},size:{x:r,y:$i},pivot:{x:.5,y:.5}}),t.insert(o,de,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,fe,{texture:D,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:$i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,ao,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);const c=t.spawn();t.insert(c,de,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,Hi,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Li.Left,verticalAlign:Oi.Middle,wordWrap:!1,overflow:Wi.Clip,lineHeight:1.2}),t.insert(c,_i,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:$i},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}u(n)}function r(e,t,s){t.isOpen=!1,c(s),d(t.listEntity,!1)}function a(e,t,s,n,i){t.selectedIndex=n,r(0,t,s),i.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Hi))return;const n=t.get(s,Hi);let i={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(s,Hi,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:i,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function d(e,s){if(0!==e&&t.valid(e)&&(t.has(e,ao)&&t.insert(e,ao,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,fe))){const n=t.get(e,fe);t.insert(e,fe,{texture:n.texture,color:{r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:s})}}function u(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,fe))continue;const i=s===e.highlightIndex?{...Di}:{r:.95,g:.95,b:.95,a:1};t.insert(n,fe,{texture:D,color:i,size:{x:e.ddWidth,y:$i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function h(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,lo))continue;if(t.get(s,lo).hovered)return!0}return!1}e.addSystemToSchedule(gt.Update,xt([Ie(Et),Ie(fo)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=wo()&&!bo(),p=t.getEntitiesWithComponents([pr]);for(const m of p){const p=t.get(m,pr);let _=s.get(m);if(_||(_={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,_)),n(p.listEntity),i(m),p.isOpen||d(p.listEntity,!1),l(p),f)continue;Fi(t,m,ao,{enabled:!0,blockRaycast:!0});const g=t.has(m,lo)?t.get(m,lo):null;if(g?.justPressed&&(p.isOpen?r(m,p,_):o(m,p,_)),p.isOpen){for(let e=0;e<_.optionEntities.length;e++){const s=_.optionEntities[e];if(!t.valid(s)||!t.has(s,lo))continue;if(t.get(s,lo).justPressed){a(m,p,_,e,c);break}}let s=-1;for(let e=0;e<_.optionEntities.length;e++){const n=_.optionEntities[e];if(!t.valid(n)||!t.has(n,lo))continue;if(t.get(n,lo).hovered){s=e;break}}s>=0&&s!==_.highlightIndex&&(_.highlightIndex=s,u(_)),e.isKeyPressed("ArrowDown")?(_.highlightIndex>=p.options.length-1?_.highlightIndex=0:_.highlightIndex++,u(_)):e.isKeyPressed("ArrowUp")?(_.highlightIndex<=0?_.highlightIndex=p.options.length-1:_.highlightIndex--,u(_)):e.isKeyPressed("Enter")&&_.highlightIndex>=0?a(m,p,_,_.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,_),e.isMouseButtonPressed(0)&&(g?.hovered||h(_)||r(m,p,_))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},_r=0,gr=0,yr=2,wr=K("LayoutGroup",{direction:_r,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:gr,reverseOrder:!1});const xr=new class{build(e){ie("LayoutGroup",wr);const t=e.world;e.addSystemToSchedule(gt.PreUpdate,xt([],()=>{const e=t.getEntitiesWithComponents([wr,_i,ye]);for(const s of e){const e=t.get(s,wr),n=t.get(s,_i),i=t.get(s,ye);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,_i)&&t.has(e,de)&&o.push({entity:e,rect:t.get(e,_i)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Ri(n,s),a=Ai(n,s),l=n.pivot.x,c=n.pivot.y,d=e.padding,u=e.direction===_r;let h=0;for(let s=0;s<o.length;s++){const n=o[s],i=Ri(n.rect,n.entity),f=Ai(n.rect,n.entity),p=n.rect.pivot.x,m=n.rect.pivot.y;let _,g;u?(_=-l*r+d.left+h+p*i,g=e.childAlignment===gr?(1-c)*a-d.top-(1-m)*f:e.childAlignment===yr?-c*a+d.bottom+m*f:(.5-c)*a+.5*(d.bottom-d.top)+(m-.5)*f,h+=i,s<o.length-1&&(h+=e.spacing)):(_=e.childAlignment===gr?-l*r+d.left+p*i:e.childAlignment===yr?(1-l)*r-d.right-(1-p)*i:(.5-l)*r+.5*(d.left-d.right)+(p-.5)*i,g=(1-c)*a-d.top-h-(1-m)*f,h+=f,s<o.length-1&&(h+=e.spacing));const y=t.get(n.entity,de);y.position.x=_,y.position.y=g,t.insert(n.entity,de,y)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};re("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),re("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class vr{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(gt.PostUpdate,xt([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const br=new vr;async function Sr(e,t,s){const n=e.getResource(qn);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Mr(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Pr=Ae({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Tr=Ae(null,"PhysicsAPI");function Er(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Cr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Rr{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Pr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Mr(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([me]);for(const s of t){const t=e.world.get(s,me);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(gt.PostUpdate,xt([Ie(ze)],a=>{const l=r.getEntitiesWithComponents([Me,de]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Me),l=r.get(i,de);if(t.has(i)){const e=s.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=Er(l.worldRotation);n._physics_createBody(i,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Ar(e,n,i),t.add(i),s.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===Ce.Kinematic){const e=Er(l.worldRotation);n._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<n;i++){const n=o+4*i,r=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(r))continue;const d=e.world.get(r,de);if(!d)continue;let u=a,h=l,f=c;if(e.world.has(r,ge)){const t=e.world.get(r,ge);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,de)){const s=e.world.get(t.entity,de),n=Er(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),d=Math.sin(-n);u=(i*r-o*d)/(0!==s.worldScale.x?s.worldScale.x:1),h=(i*d+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),f=c-n}}d.position.x=u,d.position.y=h;const p=Cr(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(r,de,d)}}(e,n,i),function(e,t,s){t._physics_collectEvents();const n=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;n.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*s,contactY:t.HEAPF32[i+5]*s})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<r;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<d;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Pr,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Tr,Ir._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function Ar(e,t,s){const n=e.world;if(n.has(s,Pe)){const e=n.get(s,Pe);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,Te)){const e=n.get(s,Te);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,Ee)){const e=n.get(s,Ee);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Ir{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Ir.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const kr={nearest:0,linear:1},Fr={repeat:0,clamp:1,mirror:2};function Br(e,t,s=!0,n){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&i.createTextureEx){const e=kr[n.filterMode??"linear"]??1,a=Fr[n.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),r}function zr(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Ur(e,t,s,n){const i=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,u=a+a,h=l+l,f=c+c,p=a*u,m=a*h,_=a*f,g=l*h,y=l*f,w=c*f,x=d*u,v=d*h,b=d*f;return new Float32Array([(1-(g+w))*i,(m+b)*i,(_-v)*i,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*r,(y-x)*r,(1-(p+g))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function $r(e,t,s,n,i,o,r,a,l){const c=await async function(e,t,s){const n={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=ds(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=i?.[o];n[o]=Br(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const i=s[e];if(i&&i>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let d={},u=null;if(i&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(i),d=await async function(e,t,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=us(n.type);if(!r||!n.data)continue;const a=n.data[r.skeletonField],l=n.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),d=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===Cs(c)?.contentType;let u,h;if(r){const e=await i.readBinary(a);h=e.length,u=t._malloc(h),t.HEAPU8.set(e,u)}else{const e=await i.readText(a),s=(new TextEncoder).encode(e);h=s.length,u=t._malloc(h+1),t.HEAPU8.set(s,u),t.HEAPU8[u+h]=0}const f=s.loadSkeleton(u,h,n,n.length,r);if(t._free(u),f<0)continue;o[a]=f;const p=zr(n),m=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=Br(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,i,u,s,n)),o){const t={gravity:r?.gravity??{...A},fixedTimestep:r?.fixedTimestep??I,subStepCount:r?.subStepCount??4};new Rr("",t,()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=ds(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,i;const r=Cs(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await s.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=Br(e,c,!1),u=e.getResourceManager();n[o]=u.loadBitmapFont(t,d,c.width,c.height)}catch{n[o]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=ds(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=n[i];r||(r=Ot.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=Ot.createFromAsset(e,r)}catch{s[o]=0}}return s}(s,n);!function(e,t,s,n){const i={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=ds(e.type);if(0===t.length)continue;const s=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof s[e.field]&&(s[e.field]=t[s[e.field]]||0)}}}(s,c,h,f);const p=gs(e.world,s);if(l&&e.hasResource(qn))for(const t of p.values())e.world.insert(t,be,{scene:l,persistent:!1});if(i&&u){const n=function(e,t,s,n){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=us(t.type);if(!r||!t.data)continue;const a=s[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(u,s,d,p);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=R);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,xe)?c.get(o,xe):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&n.update(r,l*u);let h=0;if(c.has(o,de)){const e=Ur(c.get(o,de),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=n.getMeshBatchCount(r);for(let e=0;e<f;e++){const i=n.getMeshBatchVertexCount(r,e),o=n.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=s._malloc(a),d=s._malloc(l),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(r,e,c,d,u,f);const p=s.HEAPU32[u>>2],m=s.HEAPU32[f>>2],_=new Float32Array(s.HEAPF32.buffer,c,8*i),g=new Uint16Array(s.HEAPU8.buffer,d,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,i,w,o,p,m,h),t._free(y),t._free(w),s._free(c),s._free(d),s._free(u),s._free(f)}h&&t._free(h)}})}(e,t,i,u,n)}if(a){const t=e.getResource(Ws);t&&t.setAddressableManifest(a)}}function Dr(e,t,s){return{name:e,async setup(){await $r(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class Lr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=us(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===Cs(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=ds(e.type);for(const s of o){const i=e.data[s.field];"string"==typeof i&&i&&("font"===s.type?(n.add(i),t.add(i)):"material"===s.type&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of n){const t=Cs(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),i=await createImageBitmap(n),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Or="__preview__";class Wr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(qn);t.register({name:Or,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Or),this.loadPromise_=t.load(Or).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new Lr(this.baseUrl_);await s.prefetch(t);let n=null;const i=this.app_.spineInitPromise;if(i){n=(await i).controller.raw}await $r(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,Or)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([pe]);for(const n of s){if(e.get(n,pe).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([me]);for(const i of n){const n=e.get(i,me);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const i=this.app_.getResource(qn).getScene(Or),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,de,r);const a={isActive:!0,projectionType:ae.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:le.ColorAndDepth};e.insert(o,pe,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(qn);await e.switchTo(Or),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const Hr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ln.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ln.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ln.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ln.releaseRenderTarget(e._handle),Hr.create({width:t,height:s,depth:!0})),begin(e,t){Ln.begin(t,e._handle)},end(){Ln.end()},getDepthTexture:e=>Ln.getTargetDepthTexture(e._handle)};var Xr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Xr||(Xr={}));class jr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Xr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Xr.Debug:console.debug(t,s);break;case Xr.Info:console.log(t,s);break;case Xr.Warn:console.warn(t,s);break;case Xr.Error:console.error(t,s)}}}class Yr{constructor(){this.handlers_=[],this.minLevel_=Xr.Info,this.addHandler(new jr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(Xr.Debug,e,t,s)}info(e,t,s){this.log(Xr.Info,e,t,s)}warn(e,t,s){this.log(Xr.Warn,e,t,s)}error(e,t,s){this.log(Xr.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Vr=new Yr;function Nr(){return Vr}function Gr(e){Vr.setMinLevel(e)}function qr(e,t,s){Vr.debug(e,t,s)}function Kr(e,t,s){Vr.info(e,t,s)}function Jr(e,t,s){Vr.warn(e,t,s)}function Qr(e,t,s){Vr.error(e,t,s)}const Zr={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},ea={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},ta={Running:0,Paused:1,Completed:2,Cancelled:3},sa={None:0,Restart:1,PingPong:2};class na{constructor(e,t,s){this.module_=e,this.registry_=t,this.entity=s}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,s,n){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,s,n),this}then(e){return this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let ia=null,oa=null;function ra(e,t){ia=e,oa=t}function aa(){ia=null,oa=null}function la(){if(!ia)throw new Error("Tween API not initialized");return ia}function ca(){if(!oa)throw new Error("Tween API not initialized");return oa}const da={to(e,t,s,n,i,o){const r=la(),a=ca(),l=o?.easing??Zr.Linear,c=o?.delay??0,d=o?.loop??sa.None,u=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,d,u);return new na(r,a,h)},cancel(e){la()._anim_cancelTween(ca(),e.entity)},cancelAll(e){la()._anim_cancelAllTweens(ca(),e)},update(e){la()._anim_updateTweens(ca(),e)}};class ua{constructor(){this.name="AnimationPlugin"}build(e){ra(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(gt.Update,xt([Ie(ze)],e=>{da.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(gt.Update,xt([Ie(ze)],e=>{os(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){aa()}}const ha=new ua;var fa;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(fa||(fa={}));const pa={model:fa.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function ma(e,t=pa){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case fa.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case fa.Inverse:a=n/Math.max(r,n);break;case fa.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function _a(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const ga=K("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:fa.Inverse,rolloff:1,priority:0,enabled:!0}),ya=K("AudioListener",{enabled:!0});class wa{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.config_=e}build(e){const s=t().createAudioBackend(),n=this.config_;s.initialize({initialPoolSize:n.initialPoolSize});const i=s.mixer;rs.init(s,i),i&&(void 0!==n.masterVolume&&(i.master.volume=n.masterVolume),void 0!==n.musicVolume&&(i.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(i.sfx.volume=n.sfxVolume));const o=new Map;this.activeSourceHandles_=o;let r=!1;e.addSystemToSchedule(gt.PreUpdate,xt([Ie(ze)],t=>{const n=e.world;let i=0,a=0,l=!1;const c=n.getEntitiesWithComponents([ya,he]);for(const e of c){if(n.get(e,ya).enabled){const t=n.get(e,he);i=t.position.x,a=t.position.y,l=!0;break}}const d=n.getEntitiesWithComponents([ga]),u=new Set;for(const e of d){const t=n.get(e,ga);if(t.enabled&&t.clip){if(u.add(e),t.playOnAwake&&!o.has(e)){const n=rs.getBufferHandle(t.clip);if(n){const i=s.play(n,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(e,i)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(e)){const s=o.get(e);if(!s.isPlaying){o.delete(e);continue}l||r||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),r=!0);const c=n.tryGet?.(e,he),d=c?.position.x??0,u=c?.position.y??0,h=d-i,f=u-a,p=ma(Math.sqrt(h*h+f*f),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),m=_a(d,0,i,0,t.maxDistance);s.setVolume(t.volume*p),s.setPan(m)}}}for(const[e,t]of o)u.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}cleanup(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}rs.dispose()}}const xa=new wa;function va(e,t){return e.toFixed(t)}function ba(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class Sa{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${va(e.fps,1)}</span> Frame: <span style="color:#d19a66">${va(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const s=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let n='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of s){n+=`<div>${ba(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${va(t,1)}ms</span></div>`}t.push(n)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}}function Ma(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const Pa=Ae(Ma(),"Stats"),Ta="StatsCollect";class Ea{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Ca{constructor(e){this.name="Stats",this.collector_=new Ea,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Pa,Ma());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Sa(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=xt([Ie(ze),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(Pa);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(Ta),o.systemTimings=e}else o.systemTimings=new Map;const a=Ln.getStats();o.drawCalls=a.drawCalls,o.triangles=a.triangles,o.sprites=a.sprites,o.text=a.text,o.spine=a.spine,o.meshes=a.meshes,o.culled=a.culled,s?.update(o)},{name:Ta});e.addSystemToSchedule(gt.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Ra=new Ca;class Aa{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,s)=>{const n=new Image;n.onload=()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const s=e.getContext("2d");s.drawImage(n,0,0);const i=s.getImageData(0,0,n.width,n.height);t({width:n.width,height:n.height,pixels:new Uint8Array(i.data.buffer)})},n.onerror=s,n.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function Ia(e,t){try{const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(s.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function ka(e){const{app:t,module:s,assets:n,sceneData:i,sceneName:o}=e,r=t.getResource(Ws);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0)),ei(t);const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Ia(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await Ia(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=Dr(o,i,{app:t,module:s,provider:new Aa(n),spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest}),d=t.getResource(qn);d.register(c),d.setInitial(o),await d.load(o);const u=e.canvas.width/e.canvas.height;vs(t.world,u),t.run()}const Fa=[Vi,ro,mo,Do,Vo,To,qo,Zo,or,Wo,ko,rr,cr,fr,mr,xr,br],Ba=[...Fa,ha];function za(e,t){return function(e,t){const s=Zn.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),an(e),$t(e),Mn(e),Rn(e),$n(e),Wn(e);const i=new jn;s.setPipeline(i);let o=h();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=oi(e,n,t,i));const r=s.getResource(At);if(o.length>0){const e=o[0],s=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(s.x*t),r.vpY=Math.round((1-s.y-s.h)*i),r.vpW=Math.round(s.w*t),r.vpH=Math.round(s.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}s.insertResource(At,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(n);if(c>=0){const e=n.getCanvas(c).backgroundColor;Ln.setClearColor(e.x,e.y,e.z,e.w)}const d=(h()-o)/1e3;let u;if(Ln.resize(t,l),kn.isInitialized()&&kn.getPassCount()>0&&!kn.isBypassed()&&kn.resize(t,l),s.hasResource(qn)){const e=s.getResource(qn).getActiveScenes();e.length>0&&(u=new Set(e))}i.setActiveScenes(u??null);const f=oi(e,n,t,l,s.world,u);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:n},viewProjection:ti,width:t,height:l,elapsed:d});else{for(const e of f){const s=e.viewportRect,o=Math.round(s.x*t),r=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);i.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}Ln.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(gt.First,l),s.addSystemToSchedule(gt.Last,c),s.addPlugin(Xs),s.addPlugin(en),s.addPlugin(Rt),s.addPlugin(Qn),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Ba,...t})}e=w;export{Je as Added,ua as AnimationPlugin,Zn as App,Hs as AssetPlugin,js as AssetRefCounter,Os as AssetServer,Ws as Assets,qt as AsyncCache,fa as AttenuationModel,rs as Audio,p as AudioBus,ya as AudioListener,m as AudioMixer,wa as AudioPlugin,_ as AudioPool,ga as AudioSource,we as BitmapText,It as BlendMode,Ce as BodyType,Pe as BoxCollider,uo as Button,co as ButtonState,pe as Camera,me as Canvas,Ee as CapsuleCollider,Qe as Changed,ye as Children,Te as CircleCollider,le as ClearFlags,at as Commands,ct as CommandsInstance,v as DEFAULT_DESIGN_HEIGHT,x as DEFAULT_DESIGN_WIDTH,R as DEFAULT_FALLBACK_DT,I as DEFAULT_FIXED_TIMESTEP,P as DEFAULT_FONT_FAMILY,T as DEFAULT_FONT_SIZE,A as DEFAULT_GRAVITY,E as DEFAULT_LINE_HEIGHT,C as DEFAULT_MAX_DELTA_TIME,b as DEFAULT_PIXELS_PER_UNIT,k as DEFAULT_SPINE_SKIN,M as DEFAULT_SPRITE_SIZE,S as DEFAULT_TEXT_CANVAS_SIZE,wn as DataType,Go as DragState,No as Draggable,un as Draw,pr as Dropdown,Zr as EasingType,lt as EntityCommands,pt as EventReader,_t as EventReaderInstance,ht as EventRegistry,ft as EventWriter,mt as EventWriterInstance,pi as FillDirection,Bo as FillMethod,zo as FillOrigin,Ao as FocusManager,Ro as FocusManagerState,Co as Focusable,Xn as GLDebug,En as Geometry,yt as GetWorld,$ as INVALID_ENTITY,L as INVALID_FONT,O as INVALID_MATERIAL,D as INVALID_TEXTURE,Uo as Image,Fo as ImageType,Et as Input,Ct as InputPlugin,Tt as InputState,ao as Interactable,dr as ListView,ue as LocalTransform,Xr as LogLevel,Yr as Logger,sa as LoopMode,Ot as Material,Kt as MaterialLoader,qe as Mut,ve as Name,ge as Parent,Ir as Physics,Pr as PhysicsEvents,Rr as PhysicsPlugin,kn as PostProcess,Js as PrefabServer,Qs as Prefabs,Zs as PrefabsPlugin,Wr as PreviewPlugin,Xo as ProgressBar,Ho as ProgressBarDirection,Yo as ProgressBarPlugin,ae as ProjectionType,nt as Query,it as QueryInstance,ot as Removed,rt as RemovedQueryInstance,jn as RenderPipeline,Bn as RenderStage,Hr as RenderTexture,Ln as Renderer,Ie as Res,ke as ResMut,Me as RigidBody,F as RuntimeConfig,ar as SafeArea,ce as ScaleMode,qn as SceneManager,Gn as SceneManagerState,be as SceneOwner,gt as Schedule,Ko as ScrollView,Gt as ShaderSources,tr as Slider,er as SliderDirection,ir as SliderPlugin,xe as SpineAnimation,fe as Sprite,is as SpriteAnimator,Pa as Stats,Ea as StatsCollector,Sa as StatsOverlay,Ca as StatsPlugin,Pt as SystemRunner,Hi as Text,Li as TextAlign,Eo as TextInput,Io as TextInputPlugin,Wi as TextOverflow,Yi as TextPlugin,Xi as TextRenderer,Oi as TextVerticalAlign,ze as Time,Lo as Toggle,de as Transform,da as Tween,na as TweenHandle,ta as TweenState,ea as TweenTarget,At as UICameraInfo,ho as UIEventQueue,fo as UIEvents,lo as UIInteraction,Po as UIInteractionPlugin,po as UILayoutPlugin,qi as UIMask,oo as UIMaskPlugin,_i as UIRect,vr as UIRenderOrderPlugin,_e as Velocity,Lr as WebAssetProvider,Ge as World,he as WorldTransform,St as addStartupSystem,bt as addSystem,Mt as addSystemToSchedule,ha as animationPlugin,U as applyBuildRuntimeConfig,Si as applyDirectionalFill,B as applyRuntimeConfig,Xs as assetPlugin,xa as audioPlugin,ma as calculateAttenuation,_a as calculatePanning,ns as clearAnimClips,yn as clearDrawCallbacks,Z as clearUserComponents,j as color,xi as computeFillAnchors,bi as computeFillSize,vi as computeHandleAnchors,mi as computeUIRectLayout,io as createMaskProcessor,Dr as createRuntimeSceneConfig,za as createWebApp,qr as debug,Ma as defaultFrameStats,K as defineComponent,dt as defineEvent,Ae as defineResource,xt as defineSystem,J as defineTag,Qr as error,Jt as extractAnimClipTexturePaths,bs as findEntityByName,ei as flushPendingSystems,As as getAddressableType,Is as getAddressableTypeByEditorType,Fs as getAllAssetExtensions,ss as getAnimClip,$s as getAssetMimeType,Cs as getAssetTypeEntry,oe as getComponent,ds as getComponentAssetFieldDescriptors,cs as getComponentAssetFields,Se as getComponentDefaults,ps as getComponentEntityFields,us as getComponentSpineFieldDescriptor,zs as getCustomExtensions,Rs as getEditorType,Nr as getLogger,t as getPlatform,n as getPlatformType,Q as getUserComponent,Us as getWeChatPackOptions,Kr as info,an as initDrawAPI,Wn as initGLDebugAPI,Mn as initGeometryAPI,$t as initMaterialAPI,ka as initPlayableRuntime,Rn as initPostProcessAPI,$n as initRendererAPI,ra as initTweenAPI,Rt as inputPlugin,Vs as instantiatePrefab,Ki as intersectRects,Ji as invertMatrix4,se as isBuiltinComponent,Ds as isCustomExtension,wo as isEditor,ks as isKnownAssetExtension,s as isPlatformInitialized,bo as isPlayMode,xo as isRuntime,kt as isTextureRef,i as isWeChat,o as isWeb,xs as loadComponent,Mr as loadPhysicsModule,$r as loadRuntimeScene,gs as loadSceneData,ys as loadSceneWithAssets,Bs as looksLikeAssetPath,Qt as parseAnimClipData,r as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,so as pointInOBB,Zi as pointInWorldRect,en as prefabsPlugin,Vo as progressBarPlugin,Y as quat,es as registerAnimClip,ie as registerComponent,ls as registerComponentAssetFields,fs as registerComponentEntityFields,_n as registerDrawCallback,Ys as registerEmbeddedAssets,Nt as registerMaterialCallback,ms as remapEntityFields,Qn as sceneManagerPlugin,Qi as screenToWorld,yo as setEditorMode,hr as setListViewRenderer,Gr as setLogLevel,vo as setPlayMode,Oe as setWasmErrorHandler,ln as shutdownDrawAPI,Hn as shutdownGLDebugAPI,Pn as shutdownGeometryAPI,Dt as shutdownMaterialAPI,An as shutdownPostProcessAPI,Dn as shutdownRendererAPI,aa as shutdownTweenAPI,or as sliderPlugin,os as spriteAnimatorSystemUpdate,Ra as statsPlugin,Ii as syncFillSpriteSize,ko as textInputPlugin,Vi as textPlugin,Ls as toBuildPath,Sr as transitionTo,To as uiInteractionPlugin,mo as uiLayoutPlugin,ro as uiMaskPlugin,Fa as uiPlugins,br as uiRenderOrderPlugin,ts as unregisterAnimClip,ee as unregisterComponent,gn as unregisterDrawCallback,vs as updateCameraAspectRatio,W as vec2,H as vec3,X as vec4,Jr as warn,Kn as wrapSceneSystem};//# sourceMappingURL=index.js.map