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
feat: add runtime Storage API for persistent data
esengine6148c6e3b588
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.jsindex aa9bf2530..338fb627a 100644--- a/desktop/public/sdk/cjs/esengine.wechat.js+++ b/desktop/public/sdk/cjs/esengine.wechat.js@@ -1,2 +1,2 @@-"use strict";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"wechat"===e?.name}async function n(e,s){return t().fetch(e,s)}async function i(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function r(e){return t().fileExists(e)}async function a(e,s){return t().instantiateWasm(e,s)}function l(e,s){return t().createCanvas(e,s)}function c(){return t().now()}function u(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class d{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 d?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class h{constructor(e,t,s){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=s}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class p{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}async loadBufferFromData(e,t){return this.loadBuffer(e)}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const s=this.urlCache_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=wx.createInnerAudioContext();n.loop=t.loop??!1,n.volume=t.volume??1,n.playbackRate=t.playbackRate??1,n.startTime=t.startOffset??0,n.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,n);const o=new h(i,n,this.contexts_);return n.onEnded(()=>{o.onEnd?.(),n.loop||(n.destroy(),this.contexts_.delete(i))}),n.onError(e=>{console.error(`[WeChatAudio] Playback error for "${s}":`,e.errMsg)}),n.src=s,n.play(),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function f(e,t){return new Promise((s,n)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function m(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const g=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],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},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],y={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",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",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"},_=new Map,x=new Set;for(const e of g)for(const t of e.extensions)_.set(t,e),x.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function b(e){return _.get(w(e))}function v(e){return x.has(e.toLowerCase())}function S(){const e=[];for(const t of g)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function P(e){const t=b(e);return t?.wechatPackInclude??!1}function M(e){const t=b(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}let T=null;function C(){return T||(T=wx.getFileSystemManager()),T}function E(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(P(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return s.includes("no such file")||s.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function A(e){const t=C();try{return t.accessSync(e),!0}catch{return!1}}function R(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function I(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const i=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(i.data.buffer)}}async function F(e){return I(await R(e))}let k=!1;const B=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return f(e,t)}async readFile(e){return function(e){return C().readFileSync(e)}(M(e))}async readTextFile(e){return function(e,t="utf-8"){return C().readFileSync(e,t)}(M(e))}async fileExists(e){return A(M(e))}async loadImagePixels(e){return F(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return m(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t=>e.onKeyDown(t.code),n=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(s),wx.onKeyUp(n));const o=t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)},r=t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)},a=t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(s),wx.offKeyUp(n)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new p}},D=1920,L=1080,U=1/60,W={x:0,y:-9.81},z=1/60,$={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const O={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function H(e,t){if(void 0!==t.maxDeltaTime&&($.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&($.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&($.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&($.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&($.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");$.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&&($.canvasScaleMode=O[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&($.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const V=4294967295,j=4294967295;function N(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(N);const t={};for(const s in e)t[s]=N(e[s]);return t}let X=0;function Y(e,t){const s=++X,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?{...N(t),...e}:N(t):e?{...t,...e}:{...t}}}function G(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function q(e,t){const s=Z.get(e)??G().get(e);if(s)return s;const n=Y(e,t);return G().set(e,n),Z.set(e,n),J(e,t,!1),n}function K(e){return G().get(e)}function J(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function Q(e){return!0===e._builtin}const Z=new Map;function ee(e,t){Z.set(e,t)}function te(e){return Z.get(e)??K(e)}function se(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Z.set(e,s),s}const ne={Perspective:0,Orthographic:1},ie={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},oe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},re=se("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}}),ae=re,le=re,ce=se("Sprite",{texture:V,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}),ue=se("Camera",{projectionType:ne.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:ie.ColorAndDepth}),de=se("Canvas",{designResolution:{x:D,y:L},pixelsPerUnit:100,scaleMode:oe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),he=se("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),pe=se("Parent",{entity:0}),fe=se("Children",{entities:[]}),me=se("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:j,enabled:!0}),ge=se("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}),ye={Point:0,Circle:1,Rectangle:2,Cone:3},_e={World:0,Local:1},xe={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},we=se("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:ye.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:xe.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:xe.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:V,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:_e.World,enabled:!0}),be=q("Name",{value:""}),ve=q("SceneOwner",{scene:"",persistent:!1}),Se=q("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});const Pe=se("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Me=se("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Te=se("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ce=se("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ee={Static:0,Kinematic:1,Dynamic:2};let Ae=0;function Re(e,t){const s=++Ae;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Ie(e){return{_type:"res",_resource:e}}function Fe(e){return{_type:"res_mut",_resource:e}}class ke{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 ke(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const De=Re({delta:0,elapsed:0,frameCount:0},"Time");function Le(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=Ue(t[e]),o=Ue(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function Ue(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function We(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 ze=null;function $e(e){ze=e}function Oe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ze&&ze(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 Ve=1;const je=new WeakMap;function Ne(e){let t=je.get(e);return void 0===t&&(t=Ve++,je.set(e,t)),t}const Xe=[];function Ye(e,t=[],s=[]){Xe.length=0;for(const t of e)Xe.push(Ne(t));Xe.sort((e,t)=>e-t);let n=Xe.join(",");if(t.length>0){Xe.length=0;for(const e of t)Xe.push(Ne(e));Xe.sort((e,t)=>e-t),n+="|+"+Xe.join(",")}if(s.length>0){Xe.length=0;for(const e of s)Xe.push(Ne(e));Xe.sort((e,t)=>e-t),n+="|-"+Xe.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 Oe(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){Oe(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){Oe(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Oe(t,`removeParent(entity=${e})`)}}insert(e,t,s){return Q(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(Q(t)){if(this.cppRegistry_)try{const n=t._default,i=s;let o=i;for(const e of Object.keys(i))e in n||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,He(o))}catch(s){Oe(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 Q(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Q(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Q(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Oe(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.");Q(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=t._default,i={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&e in n&&(i[e]=t);const e=Le(t._name,n,i);if(e.length>0)throw new Error(We(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);r=!s.has(e),s.add(e,He(o))}catch(s){Oe(s,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}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 Oe(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 Oe(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Oe(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=Le(t._name,t._default,e);if(i.length>0)throw new Error(We(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 Z)if(Q(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=G();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??Ye(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(!Q(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"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ke(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Je(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Qe(e){return qe(e)||Ke(e)||Je(e)?e._component:e}function Ze(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{qe(e)&&n.push(t),Ke(e)?i.push({index:t,component:e._component}):Je(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>Ze(e,[...t,...n],s),without:(...n)=>Ze(e,t,[...s,...n])}}function et(...e){return Ze(e)}class tt{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(Qe),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_=Ye(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 u of s)if(!o||this.passesChangeFilters_(u)){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]=u;for(let e=0;e<n;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}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}}class st{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_)}}class nt{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=Q(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 it{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new nt(this,null);return this.spawned_.push(e),e}entity(e){return new nt(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)}}}class ot{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 rt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new ot)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new ot,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class at{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class lt{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var ct;function ut(){return{_type:"get_world"}}exports.Schedule=void 0,(ct=exports.Schedule||(exports.Schedule={}))[ct.Startup=0]="Startup",ct[ct.First=1]="First",ct[ct.PreUpdate=2]="PreUpdate",ct[ct.Update=3]="Update",ct[ct.PostUpdate=4]="PostUpdate",ct[ct.Last=5]="Last",ct[ct.FixedPreUpdate=10]="FixedPreUpdate",ct[ct.FixedUpdate=11]="FixedUpdate",ct[ct.FixedPostUpdate=12]="FixedPostUpdate";let dt=0;function ht(e,t,s){const n=++dt;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function pt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}class ft{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 it&&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 tt(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 it(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 at(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new lt(s)}case"removed":{const t=e;return new st(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class mt{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 gt=Re(new mt,"Input");class yt{constructor(e){this.target_=e??null}build(e){const s=new mt;e.insertResource(gt,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(exports.Schedule.Last,ht([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const _t=new yt,xt=Re({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 wt;function bt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(wt=exports.BlendMode||(exports.BlendMode={}))[wt.Normal=0]="Normal",wt[wt.Additive=1]="Additive",wt[wt.Multiply=2]="Multiply",wt[wt.Screen=3]="Screen",wt[wt.PremultipliedAlpha=4]="PremultipliedAlpha";let vt=null,St=null,Pt=1;const Mt=new Map;function Tt(e){vt=e,St=e.getResourceManager(),Lt()}function Ct(){0!==It&&vt&&(vt._free(It),It=0),Mt.clear(),Pt=1,Rt=!1,kt.clear(),Bt=null,St=null,vt=null}function Et(){if(!St)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return St}const At={createShader:(e,t)=>Et().createShader(e,t),releaseShader(e){e>0&&Et().releaseShader(e)},create(e){const t=Pt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.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 Mt.set(t,s),t},get:e=>Mt.get(e),setUniform(e,t,s){const n=Mt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,vt?.invalidateMaterialCache(e))},getUniform(e,t){const s=Mt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Mt.get(e);s&&(s.blendMode=t,vt?.invalidateMaterialCache(e))},getBlendMode(e){const t=Mt.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Mt.get(e);s&&(s.depthTest=t,vt?.invalidateMaterialCache(e))},getShader(e){const t=Mt.get(e);return t?.shader??0},release(e){Mt.delete(e),vt?.invalidateMaterialCache(e)},isValid:e=>Mt.has(e),releaseAll(){Mt.clear(),vt?.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??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Mt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Pt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Mt.set(s,n),s},toAssetData(e,t){const s=Mt.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=Mt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Rt=!1,It=0;const Ft=16384,kt=new Map;let Bt=null;function Dt(e){const t=(0===It&&vt&&(It=vt._malloc(Ft)),It);if(0===t||!vt)return{ptr:0,count:0};let s=0,n=0;const i=vt.HEAPU8,o=vt.HEAPU32,r=vt.HEAPF32;for(const[a,l]of e){if(bt(l))continue;let e=kt.get(a);e||(Bt||(Bt=new TextEncoder),e=Bt.encode(a),kt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>Ft){console.warn(`[ESEngine] Material uniform buffer full (${s}/${Ft} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=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?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)r[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Lt(){if(!vt||Rt)return;vt.materialDataProvider=(e,t,s,n,i)=>{const o=Mt.get(e);if(!o)return vt.HEAPU32[t>>2]=0,vt.HEAPU32[s>>2]=0,vt.HEAPU32[n>>2]=0,void(vt.HEAPU32[i>>2]=0);vt.HEAPU32[t>>2]=o.shader,vt.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Dt(o.uniforms);vt.HEAPU32[n>>2]=r,vt.HEAPU32[i>>2]=a},Rt=!0}const Ut={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 Wt{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const n=t(),i=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{r.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+5e3}),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(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class zt{constructor(e,t=""){this.cache_=new Wt,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&&(At.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())At.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await r(t))throw new Error(`Material file not found: ${t}`);const s=await o(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),a=await this.shaderLoader_.load(i);return{handle:At.createFromAsset(n,a),shaderHandle:a,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 $t(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function Ot(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:s.get(e.texture)??0};if(e.atlasFrame){const s=e.atlasFrame;t.uvOffset={x:s.x/s.pageWidth,y:1-(s.y+s.height)/s.pageHeight},t.uvScale={x:s.width/s.pageWidth,y:s.height/s.pageHeight}}return t})}}const Ht=new Map;function Vt(e){Ht.set(e.name,e)}const jt=q("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Nt(e,t){const s=e.getEntitiesWithComponents([jt]);for(const n of s){const s=e.get(n,jt);if(!s.enabled||!s.playing||!s.clip)continue;const i=Ht.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,ce)){const t=i.frames[s.currentFrame],o=e.get(n,ce);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(n,ce,o)}a&&e.insert(n,jt,s)}}class Xt{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 async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const s=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,s)}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 stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}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}}}}Xt.mixer_=null,Xt.bufferCache_=new Map,Xt.bgmHandle_=null,Xt.bgmVolume_=1,Xt.fadeAnimId_=0,Xt.disposed_=!1;const Yt=new Map,Gt=new Map;function qt(e,t,s){Yt.set(e,{width:t,height:s})}function Kt(e){return Yt.get(e)}function Jt(){Yt.clear()}function Qt(e,t){Gt.set(e,t)}function Zt(e){return Gt.get(e)}let es=null;function ts(e){es=e}function ss(){es=null}const ns={initLayer(e,t,s,n,i){es?.tilemap_initLayer(e,t,s,n,i)},destroyLayer(e){es?.tilemap_destroyLayer(e)},setTile(e,t,s,n){es?.tilemap_setTile(e,t,s,n)},getTile:(e,t,s)=>es?es.tilemap_getTile(e,t,s):0,fillRect(e,t,s,n,i,o){es?.tilemap_fillRect(e,t,s,n,i,o)},setTiles(e,t){if(!es)return;const s=t.byteLength,n=es._malloc(s);new Uint16Array(es.HEAPU8.buffer,n,t.length).set(t),es.tilemap_setTiles(e,n,t.length),es._free(n)},hasLayer:e=>!!es&&es.tilemap_hasLayer(e),submitLayer(e,t,s,n,i,o,r,a,l,c,u,d,h,p,f,m,g,y,_,x){es?.tilemap_submitLayer(e,t,s,n,i,o,r,a,l,c,u,d,h,p,f,m,g,y,_,x)}},is=q("Tilemap",{source:""}),os=q("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function rs(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function as(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function ls(e,t){if(0===e)return 0;let s=0;2147483648&e&&(s|=8192),1073741824&e&&(s|=16384),536870912&e&&(s|=32768);return(536870911&e)-t+1|s}function cs(e){const t=e.width,s=e.height,n=e.tilewidth??0,i=e.tileheight??0;if(!(t&&s&&n&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??n,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const n=e.width??t,i=e.height??s,o=!1!==e.visible,r=e.data,l=new Uint16Array(n*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=ls(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,d=as(e.tintcolor),h="number"==typeof e.parallaxx?e.parallaxx:1,p="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:n,height:i,visible:o,tiles:l,opacity:u,tintColor:d,parallaxX:h,parallaxY:p})}const u=[],d=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const s=[];for(const e of t){const t=new Map,n=e.properties;if(n)for(const e of n)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}s.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:s})}if(o)for(const e of o){const t=e.firstgid??1,s=e.tiles;if(s)for(const e of s){const s=e.properties;if(s)for(const n of s)"collision"===n.name&&!0===n.value&&d.push(e.id+t)}}return{width:t,height:s,tileWidth:n,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:d}}function us(e,t){const s=e.lastIndexOf("/"),n=((s>=0?e.substring(0,s+1):"")+t).split("/"),i=[];for(const e of n)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}const ds=Math.PI/180;function hs(e,t,s,n,i,o){const r=function(e,t,s,n){const i=new Uint8Array(t*s),o=[],r=(o,r)=>{if(o>=t||r>=s)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&n.has(l)};for(let e=0;e<s;e++)for(let n=0;n<t;n++){if(!r(n,e))continue;let a=1;for(;r(n+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=s)break;for(let e=0;e<a;e++)if(!r(n+e,t)){c=!1;break}c&&l++}for(let s=0;s<l;s++)for(let o=0;o<a;o++)i[(e+s)*t+(n+o)]=1;o.push({col:n,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,n),a=[],l=s.tileWidth,c=s.tileHeight,u=s.height*c;for(const t of r){const s=t.width*l,n=t.height*c,r=i+t.col*l+.5*s,d=o+(u-t.row*c)-.5*n,h=e.spawn();e.insert(h,re,{position:{x:r,y:d,z:0}}),e.insert(h,Pe,{bodyType:Ee.Static}),e.insert(h,Me,{halfExtents:{x:.5*s,y:.5*n}}),a.push(h)}return a}const ps=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"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function fs(e){const t=ps.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 ms(e){return ps.get(e)?.fields??[]}function gs(e){return ps.get(e)?.spine??null}const ys=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function _s(e){return ys.get(e)}function xs(e,t){const s=ys.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 ws(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,be,{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)xs(i,s),Ps(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 bs(e,t){return ws(e,t)}async function vs(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 Ss.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=ps.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=[...Ss.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),u=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,...u]),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=ps.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=ws(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 Ss=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),qt(r.handle,r.width,r.height)}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=$t(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);Vt(Ot(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 Xt.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=cs(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=us(e,r.image);let a=0;try{const e=s?`${s}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,n.set(i,e),qt(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}Qt(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Ps(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=te(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 Ms(e,t){const s=e.getEntitiesWithComponents([ue]);for(const n of s){const s=e.get(n,ue);s&&(s.aspectRatio=t,e.insert(n,ue,s))}}class Ts{constructor(e){this.textureCache_=new Wt,this.shaderCache_=new Wt,this.jsonCache_=new Wt,this.textCache_=new Wt,this.binaryCache_=new Wt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Wt,this.prefabCache_=new Wt,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_=l($.textCanvasSize,$.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 zt(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(),At.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),u="binary"===b(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);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=b(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 fs(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=gs(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 vs(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 At.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await r(t))throw new Error(`Shader file not found: ${e}`);const n=await o(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return At.createShader(i,a)}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(M(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 o(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(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 o(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(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 i(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(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 Cs=Re(null,"Assets");class Es{build(e){const t=e.wasmModule;t?e.insertResource(Cs,new Ts(t)):console.warn("AssetPlugin: No WASM module available")}}const As=new Es;async function Rs(e,t,s){const{entities:n,rootId:i}=await Fs(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 vs(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 Is=10;async function Fs(e,t,s,n,i,o=0){if(o>Is)throw new Error(`Prefab nesting depth exceeded ${Is}. 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 Fs(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),u=n.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?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};ks(d.components,r),Bs(d,t),l.push(d)}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 ks(e,t){for(const s of e){const e=_s(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 Bs(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 Ds{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 Rs(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Ls=Re(null,"Prefabs");class Us{constructor(){this.name="PrefabsPlugin",this.dependencies=[Cs]}build(e){const t=e.getResource(Cs);e.insertResource(Ls,new Ds(e.world,t))}}const Ws=new Us;let zs=null,$s=0,Os=0,Hs=0;const Vs=new Float32Array(256);function js(e){zs=e,$s=zs._malloc(64),Os=zs._malloc(64),Hs=zs._malloc(1024)}function Ns(){zs&&($s&&(zs._free($s),$s=0),Os&&(zs._free(Os),Os=0),Hs&&(zs._free(Hs),Hs=0)),zs=null}function Xs(){if(!zs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return zs}const Ys={r:1,g:1,b:1,a:1},Gs={begin(e){const t=Xs();try{t.HEAPF32.set(e,$s/4),t.draw_begin($s)}catch(e){Oe(e,"Draw.begin")}},end(){try{Xs().draw_end()}catch(e){Oe(e,"Draw.end")}},line(e,t,s,n=1){try{Xs().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.line")}},rect(e,t,s,n=!0){try{Xs().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Xs().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{Xs().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Oe(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{Xs().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Oe(e,"Draw.circleOutline")}},texture(e,t,s,n=Ys){try{Xs().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Oe(e,"Draw.texture")}},textureRotated(e,t,s,n,i=Ys){try{Xs().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){Oe(e,"Draw.textureRotated")}},setLayer(e){Xs().draw_setLayer(e)},setDepth(e){Xs().draw_setDepth(e)},getDrawCallCount:()=>zs?zs.draw_getDrawCallCount():0,getPrimitiveCount:()=>zs?zs.draw_getPrimitiveCount():0,setBlendMode(e){Xs().draw_setBlendMode(e)},setDepthTest(e){Xs().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Xs();n.HEAPF32.set(s,Os/4),n.draw_mesh(e,t,Os)}catch(s){Oe(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Xs(),i=At.get(t);if(!i)return;if(Gs.setBlendMode(i.blendMode),Gs.setDepthTest(i.depthTest),0===i.uniforms.size)return void Gs.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,Os/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=Js(t);if(!(n<0)){if(bt(s))Vs[o++]=10,Vs[o++]=n,Vs[o++]=s.slot??e++,Vs[o++]=s.textureId;else if("number"==typeof s)Vs[o++]=1,Vs[o++]=n,Vs[o++]=s;else if(Array.isArray(s)){Vs[o++]=s.length,Vs[o++]=n;for(let e=0;e<s.length;e++)Vs[o++]=s[e]}else"w"in s?(Vs[o++]=4,Vs[o++]=n,Vs[o++]=s.x,Vs[o++]=s.y,Vs[o++]=s.z,Vs[o++]=s.w):"z"in s?(Vs[o++]=3,Vs[o++]=n,Vs[o++]=s.x,Vs[o++]=s.y,Vs[o++]=s.z):(Vs[o++]=2,Vs[o++]=n,Vs[o++]=s.x,Vs[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(Vs.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,Os);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Hs/4),n.draw_meshWithUniforms(e,i.shader,Os,Hs,o)}catch(s){Oe(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},qs={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},Ks=new Set;function Js(e){const t=qs[e];return void 0!==t?t:(Ks.has(e)||(Ks.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(qs).join(", ")}`)),-1)}const Qs=new Map;function Zs(e,t,s){Qs.set(e,{fn:t,scene:s??""})}function en(e){Qs.delete(e)}function tn(){Qs.clear()}var sn;exports.DataType=void 0,(sn=exports.DataType||(exports.DataType={}))[sn.Float=1]="Float",sn[sn.Float2=2]="Float2",sn[sn.Float3=3]="Float3",sn[sn.Float4=4]="Float4",sn[sn.Int=5]="Int",sn[sn.Int2=6]="Int2",sn[sn.Int3=7]="Int3",sn[sn.Int4=8]="Int4";let nn=null,on=0,rn=0,an=0;function ln(e){nn=e,on=nn._malloc(262144),rn=nn._malloc(65536),an=nn._malloc(256)}function cn(){nn&&(on&&nn._free(on),rn&&nn._free(rn),an&&nn._free(an),on=0,rn=0,an=0),nn=null}function un(){if(!nn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return nn}const dn={create(e){const t=un(),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,on/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,an,i).set(o),t.geometry_init(s,on,n,an,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,rn,n).set(e.indices),t.geometry_setIndices16(s,rn,n)}else{new Uint32Array(t.HEAPU8.buffer,rn,n).set(e.indices),t.geometry_setIndices32(s,rn,n)}}return s},updateVertices(e,t,s=0){const n=un(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,on/4),n.geometry_updateVertices(e,on,i,s)},release(e){e>0&&un().geometry_release(e)},isValid:e=>!(!nn||e<=0)&&nn.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return dn.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:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.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 dn.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.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 dn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(r)})}};let hn=1;const pn=new Map,fn=new Map;function mn(){return pn}function gn(){return fn}class yn{constructor(){this.passes_=[],this.destroyed_=!1,this.id=hn++,pn.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const s=this.passes_.find(t=>t.name===e);return s&&(s.enabled=t),this}setUniform(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.floatUniforms.set(t,s),this}setUniformVec4(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.vec4Uniforms.set(t,{...s}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of fn)t===this&&fn.delete(e);pn.delete(this.id)}}}const _n="#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";let xn=null;function wn(e){xn=e}function bn(){for(const e of mn().values())e.destroy();mn().clear(),gn().clear(),xn&&Sn.isInitialized()&&Sn.shutdown(),xn=null}function vn(){if(!xn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return xn}const Sn={createStack:()=>new yn,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");gn().set(e,t)},unbind(e){gn().delete(e)},getStack:e=>gn().get(e)??null,init(e,t){try{return vn().postprocess_init(e,t)}catch(s){return Oe(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{vn().postprocess_shutdown()}catch(e){Oe(e,"PostProcess.shutdown")}},resize(e,t){try{vn().postprocess_resize(e,t)}catch(s){Oe(s,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!xn)return!1;try{return xn.postprocess_isInitialized()}catch(e){return Oe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{vn().postprocess_setBypass(e)}catch(e){Oe(e,"PostProcess.setBypass")}},setOutputViewport(e,t,s,n){try{vn().postprocess_setOutputViewport(e,t,s,n)}catch(e){Oe(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=gn().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(Sn.isInitialized()||Sn.init(1,1),Sn.setBypass(!1),function(e){const t=vn();try{t.postprocess_clearPasses()}catch(e){return void Oe(e,"PostProcess._applyForCamera:clearPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addPass(s.name,s.shader)}catch(e){Oe(e,`PostProcess._applyForCamera:addPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setUniformFloat(s.name,e,n)}catch(t){Oe(t,`PostProcess._applyForCamera:setUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Oe(t,`PostProcess._applyForCamera:setUniformVec4("${s.name}", "${e}")`)}}}(t)):Sn.setBypass(!0)},_resetAfterCamera(){try{vn().postprocess_clearPasses(),vn().postprocess_setBypass(!0)}catch(e){Oe(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of gn().keys())e(t)||gn().delete(t)},screenStack:null,setScreenStack(e){Sn.screenStack=e},_beginScreenCapture(){try{vn().postprocess_beginScreenCapture()}catch(e){Oe(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{vn().postprocess_endScreenCapture()}catch(e){Oe(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=Sn.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=vn();try{t.postprocess_clearScreenPasses()}catch(e){return void Oe(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addScreenPass(s.name,s.shader)}catch(e){Oe(e,`PostProcess._applyScreenStack:addScreenPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setScreenUniformFloat(s.name,e,n)}catch(t){Oe(t,`PostProcess._applyScreenStack:setScreenUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Oe(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${s.name}", "${e}")`)}}},_executeScreenPasses(){try{vn().postprocess_executeScreenPasses()}catch(e){Oe(e,"PostProcess._executeScreenPasses")}},createBlur:()=>At.createShader(_n,"#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:()=>At.createShader(_n,"#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:()=>At.createShader(_n,"#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"),createBloom:()=>At.createShader(_n,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>At.createShader(_n,"#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")},Pn=new Map;function Mn(e){Pn.set(e.type,e)}function Tn(e){return Pn.get(e)}Mn({type:"blur",label:"Blur",factory:()=>Sn.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),Mn({type:"bloom",label:"Bloom",factory:()=>Sn.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),Mn({type:"vignette",label:"Vignette",factory:()=>Sn.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),Mn({type:"grayscale",label:"Grayscale",factory:()=>Sn.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),Mn({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>Sn.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const Cn=new Map,En=new Map;function An(e){const t=Cn.get(e);t&&(Sn.unbind(e),t.destroy(),Cn.delete(e));const s=En.get(e);if(s){for(const e of s.values())At.releaseShader(e);En.delete(e)}}function Rn(){for(const e of Cn.keys())An(e)}const In=Re({enabled:!0},"PostProcessVolumeConfig"),Fn=new Map,kn=new Map;function Bn(e){const t=kn.get(e);if(void 0!==t)return t;const s=Tn(e);if(!s)return null;const n=s.factory();return kn.set(e,n),n}function Dn(e,t){if(0===t.size){const t=Fn.get(e);return void(t&&(Sn.unbind(e),t.destroy(),Fn.delete(e)))}let s=Fn.get(e);for(s||(s=Sn.createStack(),Fn.set(e,s));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const[e,n]of t){if(!n.enabled)continue;const t=Bn(e);if(null!==t){s.addPass(e,t);for(const[t,i]of n.uniforms)s.setUniform(e,t,i)}}s.enabledPassCount>0?Sn.bind(e,s):Sn.unbind(e)}const Ln=ht([et(Se,re)],e=>{const t=[];for(const[s,n,i]of e)t.push({data:n,tx:{x:i.position.x,y:i.position.y}});if(0===t.length)return;const s=[];for(const{data:e,tx:n}of t)e.isGlobal&&s.push({data:e,factor:1});if(s.length>0){const e=function(e){const t=new Map,s=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:n}of s)if(!(n<=0))for(const s of e.effects){if(!s.enabled)continue;const e=t.get(s.type);if(e)for(const[t,i]of Object.entries(s.uniforms)){const s=e.uniforms.get(t)??0;e.uniforms.set(t,s+(i-s)*n)}else{const e=new Map;for(const[t,i]of Object.entries(s.uniforms))e.set(t,i*n);t.set(s.type,{enabled:!0,uniforms:e})}}return t}(s);for(const[t]of Fn)Dn(t,e)}},{name:"PostProcessVolumeSystem"});class Un{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(In,{enabled:!0}),e.addSystemToSchedule(exports.Schedule.PostUpdate,Ln)}cleanup(){Rn(),function(){for(const[e,t]of Fn)Sn.unbind(e),t.destroy();Fn.clear();for(const e of kn.values())At.releaseShader(e);kn.clear()}(),Sn.setScreenStack(null)}}const Wn=new Un;var zn;exports.RenderStage=void 0,(zn=exports.RenderStage||(exports.RenderStage={}))[zn.Background=0]="Background",zn[zn.Opaque=1]="Opaque",zn[zn.Transparent=2]="Transparent",zn[zn.Overlay=3]="Overlay";let $n=null,On=0;function Hn(e){$n=e,On=$n._malloc(64)}function Vn(){$n&&On&&($n._free(On),On=0),$n=null}const jn={init(e,t){$n?.renderer_init(e,t)},resize(e,t){$n?.renderer_resize(e,t)},begin(e,t){if($n&&On)try{$n.HEAPF32.set(e,On/4),$n.renderer_begin(On,t??0)}catch(e){Oe(e,"Renderer.begin")}},flush(){try{$n?.renderer_flush()}catch(e){Oe(e,"Renderer.flush")}},end(){try{$n?.renderer_end()}catch(e){Oe(e,"Renderer.end")}},submitSprites(e){if($n)try{$n.renderer_submitSprites(e._cpp)}catch(e){Oe(e,"Renderer.submitSprites")}},submitBitmapText(e){if($n)try{$n.renderer_submitBitmapText(e._cpp)}catch(e){Oe(e,"Renderer.submitBitmapText")}},submitSpine(e){if($n)try{$n.renderer_submitSpine?.(e._cpp)}catch(e){Oe(e,"Renderer.submitSpine")}},submitParticles(e){if($n)try{$n.renderer_submitParticles?.(e._cpp)}catch(e){Oe(e,"Renderer.submitParticles")}},setStage(e){$n?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>$n?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){$n?.renderer_releaseTarget(e)},getTargetTexture:e=>$n?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>$n?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){$n?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){$n?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){$n?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){$n?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>$n?$n.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>$n?{drawCalls:$n.renderer_getDrawCalls(),triangles:$n.renderer_getTriangles(),sprites:$n.renderer_getSprites(),text:$n.renderer_getText(),spine:$n.renderer_getSpine?.()??0,meshes:$n.renderer_getMeshes(),culled:$n.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Nn=null;function Xn(e){Nn=e}function Yn(){Nn=null}const Gn={enable(){Nn?.gl_enableErrorCheck(!0)},disable(){Nn?.gl_enableErrorCheck(!1)},check:e=>Nn?.gl_checkErrors(e)??0,diagnose(){Nn?.renderer_diagnose()}};class qn{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}beginScreenCapture(){Sn.screenStack&&Sn.screenStack.enabledPassCount>0&&(Sn.isInitialized()||Sn.init(1,1),Sn._applyScreenStack(),Sn._beginScreenCapture())}endScreenCapture(){Sn.screenStack&&Sn.screenStack.enabledPassCount>0&&(Sn._endScreenCapture(),Sn._executeScreenPasses())}render(e){const{registry:t,viewProjection:s,width:n,height:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(jn.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),jn.setViewport(0,0,n,i),jn.clearBuffers(3),jn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),this.tilemapRenderer_&&this.tilemapRenderer_(),jn.submitSprites(t),jn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):jn.submitSpine(t),jn.submitParticles(t),jn.flush(),this.executeDrawCallbacks(s,o),jn.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==Sn.getStack(r);a&&(Sn._applyForCamera(r),Sn.resize(n.w,n.h),Sn.setOutputViewport(n.x,n.y,n.w,n.h)),jn.setViewport(n.x,n.y,n.w,n.h),jn.setScissor(n.x,n.y,n.w,n.h,!0),jn.clearBuffers(i),jn.setScissor(0,0,0,0,!1),jn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),this.tilemapRenderer_&&this.tilemapRenderer_(),jn.submitSprites(t),jn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):jn.submitSpine(t),jn.submitParticles(t),jn.flush(),this.executeDrawCallbacks(s,o),jn.end(),a&&Sn._resetAfterCamera()}executeDrawCallbacks(e,t){const s=Qs;if(s.size>0){Gs.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)}Gs.end();for(const e of n)en(e)}}}const Kn="__scene_transition_overlay__";class Jn{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Qn{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,ve,{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),Zs(e,t,this.instance_.config.name)}bindPostProcess(e,t){Sn.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){Sn.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,ve)){const s=this.app_.world.get(e,ve);s.persistent=t,this.app_.world.insert(e,ve,s)}}}class Zn{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}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())en(t);for(const t of e.postProcessBindings.keys())Sn.unbind(t)}this.transition_&&(en(Kn),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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??$.sceneTransitionDuration,i=t.color??{...$.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},Zs(Kn,()=>{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;Gs.setLayer(9999),Gs.setDepth(9999),Gs.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,en(Kn),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,en(Kn),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 Jn(t);this.scenes_.set(e,s);const n=new Qn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Cs)?this.app_.getResource(Cs):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 Jn(t);this.scenes_.set(e,s);const n=new Qn(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Cs)?this.app_.getResource(Cs):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,ve)){if(this.app_.world.get(e,ve).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())en(e);s.drawCallbacks.clear();for(const e of s.postProcessBindings.keys())Sn.unbind(e);s.postProcessBindings.clear(),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(Cs)&&(i.assetServer=this.app_.getResource(Cs));const o=await vs(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,ve,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=ti(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(Cs)?this.app_.getResource(Cs):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)At.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,ce)){const t=s.get(e,ce);n.sprite=t.color.a,t.color.a=0,s.insert(e,ce,t),i=!0}if(s.has(e,ge)){const t=s.get(e,ge);n.spine=t.color.a,t.color.a=0,s.insert(e,ge,t),i=!0}if(s.has(e,me)){const t=s.get(e,me);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,me,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,ce)){const t=s.get(e,ce);t.color.a=n.sprite,s.insert(e,ce,t)}if(void 0!==n.spine&&s.has(e,ge)){const t=s.get(e,ge);t.color.a=n.spine,s.insert(e,ge,t)}if(void 0!==n.bitmapText&&s.has(e,me)){const t=s.get(e,me);t.color.a=n.bitmapText,s.insert(e,me,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessBindings.values())s.setAllPassesEnabled(t)}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 ei=Re(null,"SceneManager");function ti(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(ei).getSceneStatus(t)&&s._fn(...n)}}}const si=ht([Fe(ei),Ie(De)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),ni={name:"SceneManager",build(e){const t=new Zn(e);e.insertResource(ei,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ei),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,si)}};class ii{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 rt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=c(),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(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.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(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ii}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(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.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 $e(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.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}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(ei).register(e),this}setInitialScene(e){return this.getResource(ei).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new ft(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(De)||this.resources_.insert(De,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.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(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new ft(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(De,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=c(),this.mainLoop())}quit(){this.running_=!1,tn();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=[Yn,Vn,bn,cn,Ct,Ns];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));const n=this.phaseTimings_?performance.now():0;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)}}this.phaseTimings_&&this.phaseTimings_.set(exports.Schedule[e],performance.now()-n)}updateTime(e){const t=this.resources_.get(De);t.delta=e,t.elapsed+=e,t.frameCount++}}function oi(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 ri=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ai(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case oe.FixedWidth:return o;case oe.FixedHeight:return r;case oe.Expand:return Math.max(o,r);case oe.Shrink:return Math.min(o,r);case oe.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const li=[];function ci(e){if(e<li.length)return li[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 li.push(t),t}function ui(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,ve);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,u=0,d=0;if(i.projectionType===ne.Orthographic){if(d=i.orthoSize,l){d=ai(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=hi(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=fi(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=gi(o.position.x,o.position.y,o.position.z),p=ci(c.length);p.entity=e,p.viewProjection.set(_i(a,h)),p.viewportRect.x=i.viewportX,p.viewportRect.y=i.viewportY,p.viewportRect.w=i.viewportW,p.viewportRect.h=i.viewportH,p.clearFlags=i.clearFlags,p.priority=i.priority,p.halfW=u,p.halfH=d,p.cameraX=o.position.x,p.cameraY=o.position.y,c.push(p)}return c.sort((e,t)=>e.priority-t.priority),c}const di=new Float32Array(16);function hi(e,t,s,n,i,o){const r=di;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 pi=new Float32Array(16);function fi(e,t,s,n){const i=pi;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 mi=new Float32Array(16);function gi(e,t,s){const n=mi;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 yi=new Float32Array(16);function _i(e,t){const s=yi;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 xi={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function wi(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,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let p,f,m,g;e.x===t.x?(p=c+s.x-i.x*r.x,m=p+i.x):(p=c+s.x,m=u+n.x),e.y===t.y?(f=d+s.y-i.y*r.y,g=f+i.y):(f=d+s.y,g=h+n.y);const y=Math.max(0,m-p),_=Math.max(0,g-f);return{originX:p+r.x*y,originY:f+r.y*_,width:y,height:_,rect:{left:p,bottom:f,right:m,top:g}}}const bi=se("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 vi=null,Si=null;function Pi(e,t){e.has(t,ce)||e.insert(t,ce,{texture:V,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 Mi(e,t){switch(e){case xi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case xi.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case xi.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 Ti(e,t,s,n){if(!e.has(t,bi))return;const i=e.get(t,bi),o=Mi(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,bi,i)}function Ci(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Ei(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Ai(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(Ei(r.charCodeAt(0))&&n.length>0&&Ei(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Ei(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 Ri(e){let t=1;for(;t<e;)t*=2;return t}function Ii(e,t){let s=0,n=t;for(;e.has(n,pe);){const t=e.get(n,pe).entity;if(!e.valid(t))break;s++,n=t}return s}function Fi(e,t){if(vi&&Si){const e=vi.getUIRectComputedWidth(Si,t);if(e>0)return e}return e.size.x}function ki(e,t){if(vi&&Si){const e=vi.getUIRectComputedHeight(Si,t);if(e>0)return e}return e.size.y}function Bi(e,t,s){let n=t;for(;e.has(n,pe);){const t=e.get(n,pe).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Di(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Li(e,t,s,n,i){if(!e.has(t,bi))return;const o=e.get(t,bi),r=wi(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,ce)){const s=e.get(t,ce);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,ce,s))}if(e.has(t,re)){const s=e.get(t,re);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,re,s)}}function Ui(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 Wi=.1,zi=30,$i={r:.3,g:.5,b:.8,a:1},Oi={Left:0,Center:1,Right:2},Hi={Top:0,Middle:1,Bottom:2},Vi={Visible:0,Clip:1,Ellipsis:2},ji=q("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Oi.Left,verticalAlign:Hi.Top,wordWrap:!0,overflow:Vi.Visible,lineHeight:1.2});class Ni{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=l($.textCanvasSize,$.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,Ri(this.frameMaxW_)),e.height=Math.max(e.height,Ri(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ri(this.frameMaxW_),e.height=Ri(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=Ai(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=i?Math.ceil(o):d+2*u,f=i?Math.ceil(r):h+2*u;if(i&&e.overflow===Vi.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_,p),this.frameMaxH_=Math.max(this.frameMaxH_,f),(n.width<p||n.height<f)&&(n.width=Math.max(n.width,Ri(p)),n.height=Math.max(n.height,Ri(f)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=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===Vi.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case Hi.Top:w=u;break;case Hi.Middle:w=u+(f-2*u-x)/2;break;case Hi.Bottom:w=f-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let b=w;for(const t of l){let n;switch(e.align){case Oi.Left:n=u;break;case Oi.Center:n=p/2;break;case Oi.Right:n=p-u;break;default:n=u}s.fillText(t,n,b),b+=c}i&&e.overflow===Vi.Clip&&s.restore();const v=s.getImageData(0,0,p,f),S=new Uint8Array(v.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(p,f,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:p,height:f}}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 Oi.Left:return"left";case Oi.Center:return"center";case Oi.Right:return"right"}}}const Xi=Ui({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?Fi(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?ki(e.uiRect,e.entity):0});class Yi{build(e){ee("Text",ji);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Ni(t),n=e.world,i=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,ji));for(const e of i.keys())if(!n.valid(e)||!n.has(e,ji)){if(n.valid(e)&&n.has(e,ce)){const t=n.get(e,ce);n.insert(e,ce,{texture:V,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([ji]);for(const t of e){const e=n.get(t,ji),o=n.has(t,bi)?n.get(t,bi):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Xi.changed(a,r)){if(n.has(t,ce)&&n.get(t,ce).texture!==V)continue}Pi(n,t);const l=o?{size:{x:Fi(o,t),y:ki(o,t)}}:null,c=s.renderForEntity(t,e,l),u=n.get(t,ce);n.insert(t,ce,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,Xi.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Gi=new Yi,qi=0,Ki=1,Ji=se("UIMask",{enabled:!0,mode:qi});function Qi(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 Zi(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],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],m=e[12],g=e[13],y=e[14],_=e[15],x=n*l-i*a,w=n*c-o*a,b=n*u-r*a,v=i*c-o*l,S=i*u-r*l,P=o*u-r*c,M=d*g-h*m,T=d*y-p*m,C=d*_-f*m,E=h*y-p*g,A=h*_-f*g,R=p*_-f*y;let I=x*R-w*A+b*E+v*C-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*R-c*A+u*E)*I,s[1]=(o*A-i*R-r*E)*I,s[2]=(g*P-y*S+_*v)*I,s[3]=(p*S-h*P-f*v)*I,s[4]=(c*C-a*R-u*T)*I,s[5]=(n*R-o*C+r*T)*I,s[6]=(y*b-m*P-_*w)*I,s[7]=(d*P-p*b+f*w)*I,s[8]=(a*A-l*C+u*M)*I,s[9]=(i*C-n*A-r*M)*I,s[10]=(m*S-g*b+_*x)*I,s[11]=(h*b-d*S-f*x)*I,s[12]=(l*T-a*E-c*M)*I,s[13]=(n*E-i*T+o*M)*I,s[14]=(g*w-m*v-y*x)*I,s[15]=(d*v-h*w+p*x)*I),s}function eo(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],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function to(e,t){return 2*Math.atan2(e,t)}function so(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 no(e,t,s,n,i,o,r){if(!e.has(t,bi)||!e.has(t,re))return null;const a=e.get(t,bi),l=e.get(t,re),c=Fi(a,t)*l.worldScale.x,u=ki(a,t)*l.worldScale.y,d=l.worldPosition.x,h=l.worldPosition.y,p=a.pivot.x,f=a.pivot.y,m=-c*p,g=c*(1-p),y=-u*f,_=u*(1-f),x=to(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),b=Math.sin(x),v=[[d+m*w-y*b,h+m*b+y*w],[d+g*w-y*b,h+g*b+y*w],[d+g*w-_*b,h+g*b+_*w],[d+m*w-_*b,h+m*b+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of v){const[a,l]=so(e,t,s,n,i,o,r);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function io(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ji]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const s=t.get(e,Ji);s.enabled&&(d.add(e),s.mode===Ki?(u.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,i,o,r,a,l,c){const u=[];for(const e of n){let s=!0;Bi(t,e,e=>{if(i.has(e)){if(t.get(e,Ji).mode===qi)return s=!1,!0}return!1}),s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(i.has(s)){if(t.get(s,Ji).mode===qi){const e=no(t,s,o,r,a,l,c);e&&(n=Qi(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=no(t,e,o,r,a,l,c);s&&d(e,s)}}(e,t,s,c,d,n,i,o,r,a),u.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Bi(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),u(t,n)}function u(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),u(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,u,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class oo{build(e){if(ee("UIMask",Ji),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(io(e.wasmModule,e.world))}}const ro=new oo,ao=se("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),lo=se("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),co={Normal:0,Hovered:1,Pressed:2,Disabled:3},uo=q("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 po=Re(new ho,"UIEvents");class fo{build(e){ee("UIRect",bi);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){vi=e,Si=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([Ie(xt)],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(exports.Schedule.PostUpdate,ht([Ie(xt)],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(exports.Schedule.PostUpdate,ht([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const mo=new fo;let go=!1,yo=!1;function _o(){return go}function xo(){return yo}const wo=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&&(Zi(t,e),s=!1),e)}}();function bo(e,t,s,n){t.emit(s,n,s),Bi(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 vo{build(e){ee("Interactable",ao),ee("Button",uo);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new ho;e.insertResource(po,i);let o=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([Ie(gt),Ie(xt)],(e,a)=>{if(i.drain(),_o()&&!xo())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=u(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;wo.update(a.viewProjection);const p=eo(d,h,wo.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=p.x,a.worldMouseY=p.y;const f=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);s.uiHitTest_update(n,p.x,p.y,f,m,g);const y=s.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){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!==_){Di(t,_,lo);const e=t.get(_,lo);e.hovered=!0,t.insert(_,lo,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,lo);e.pressed=!0,e.justPressed=!0,t.insert(_,lo,e),r=_,bo(t,i,_,"press")}if(g&&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),bo(t,i,r,"release"),r===o&&bo(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,ht([],()=>{const e=t.getEntitiesWithComponents([uo]);for(const s of e){if(Di(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,ce)){const o=t.get(s,ce);o.color=Ci(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,ce,o)}}},{name:"ButtonSystem"}))}}const So=new vo,Po=q("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}),Mo=q("Focusable",{tabIndex:0,isFocused:!1});class To{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 Co=Re(new To,"FocusManager");class Eo{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ee("TextInput",Po),_o()&&!xo())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=l($.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,c=!1,u=!0,d=0,h=0;const p=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(!p)return;const f=p;function m(){const t=e.getResource(Co);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Po)?n:null}const g=()=>{c||null===m()||b()},y=()=>{c=!0},_=()=>{c=!1,b()},x=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void v();const i=s.get(n,Po);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(po).emit(n,"submit"),void v()}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,f.selectionStart=o,f.selectionEnd=o,i.dirty=!0,S())},w=()=>{const t=m();if(null!==t){const n=s.get(t,Po);n.focused=!1,n.dirty=!0;e.getResource(Co).blur()}};function b(){const t=m();if(null===t)return;const n=s.get(t,Po);if(n.readOnly)return;let i=f.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),f.value=i),i!==n.value){n.value=i;e.getResource(po).emit(t,"change")}n.cursorPos=f.selectionStart??i.length,n.dirty=!0,S()}function v(){const t=m();if(null!==t){const e=s.get(t,Po);e.focused=!1,e.dirty=!0}e.getResource(Co).blur(),f.blur()}function S(){u=!0,d=0}f.addEventListener("input",g),f.addEventListener("compositionstart",y),f.addEventListener("compositionend",_),f.addEventListener("keydown",x),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",g),f.removeEventListener("compositionstart",y),f.removeEventListener("compositionend",_),f.removeEventListener("keydown",x),f.removeEventListener("blur",w),f.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 P=null;function M(e,l,c,d){(i.width<c||i.height<d)&&(i.width=Ri(Math.max(i.width,c)),i.height=Ri(Math.max(i.height,d))),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,c,d),o.save(),o.beginPath(),o.rect(l.padding,0,c-2*l.padding,d),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const p=0===l.value.length,f=p?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=p?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 g=Math.ceil(1.2*l.fontSize),y=l.padding;if(l.multiline){const e=Ai(o,f,c-2*y);let t=y;for(const s of e)o.fillText(s,y,t),t+=g}else{const e=(d-l.fontSize)/2;o.fillText(f,y,e)}if(l.focused&&u){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=Ai(o,l.value,c-2*y);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 u=r<e.length?e[r].substring(0,a):"";t=y+o.measureText(u).width,s=y+r*g,n=g}else t=y+o.measureText(e).width,s=(d-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 _=o.getImageData(0,0,c,d),x=new Uint8Array(_.data.buffer),w=t.getResourceManager();x.length>a&&(0!==r&&t._free(r),r=t._malloc(x.length),a=x.length),t.HEAPU8.set(x,r);const b=n.get(e);void 0!==b&&w.releaseTexture(b);const v=w.createTexture(c,d,r,x.length,1,!0);n.set(e,v);const S=s.get(e,ce);S.texture=v,S.size.x=c,S.size.y=d,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,ce,S)}e.addSystemToSchedule(exports.Schedule.Update,ht([Ie(Co)],e=>{const t=s.getEntitiesWithComponents([Po]);for(const e of t)Di(s,e,Mo,{tabIndex:0,isFocused:!1}),Di(s,e,ao,{enabled:!0,blockRaycast:!0});const n=m();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,Po)){const e=s.get(P,Po);e.focused=!1,e.dirty=!0,f.blur()}null!==n&&function(e){const t=s.get(e,Po);t.readOnly||(t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),S())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([],()=>{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,u=!u;s.get(o,Po).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Po)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Po,bi]);for(const e of a){const t=s.get(e,Po);if(!t.dirty)continue;const n=s.get(e,bi),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(Pi(s,e),M(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Ao=new Eo,Ro={Simple:0,Sliced:1,Tiled:2,Filled:3},Io={Horizontal:0,Vertical:1},Fo={Left:0,Right:1,Bottom:2,Top:3},ko=q("Image",{texture:V,color:{r:1,g:1,b:1,a:1},imageType:Ro.Simple,fillMethod:Io.Horizontal,fillOrigin:Fo.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Bo=Ui({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?Fi(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?ki(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Do{build(e){ee("Image",ko);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,ko)||s.delete(e);const e=t.getEntitiesWithComponents([ko]);for(const n of e){const e=t.get(n,ko),i=t.has(n,bi)?t.get(n,bi):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!Bo.changed(r,o))continue;Pi(t,n);const a=t.get(n,ce);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=Fi(i,n),a.size.y=ki(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Ro.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Io.Horizontal?e.fillOrigin===Fo.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===Fo.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===Ro.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,ce,a),s.set(n,Bo.take(o))}else a.color.a=0,t.insert(n,ce,a),s.set(n,Bo.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Lo=new Do,Uo=q("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Wo=q("ToggleGroup",{allowSwitchOff:!1});class zo{build(e){ee("Toggle",Uo),ee("ToggleGroup",Wo);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,ht([Ie(po)],e=>{const n=t.getEntitiesWithComponents([Uo]);if(!_o()||xo()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Uo);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,Uo,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Uo);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(Di(t,s,ao,{enabled:!0}),!t.has(s,lo))continue;const n=t.get(s,lo),i=t.get(s,Uo),r=t.get(s,ao);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,Wo);if(i.isOn&&r){if(!t.get(n,Wo).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,Uo,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,Uo);i.isOn&&(i.isOn=!1,t.insert(n,Uo,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,ce)){const e=t.get(s,ce);e.color=Ci(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,ce,e)}}}for(const e of n){const s=t.get(e,Uo);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,ce)){const e=t.get(s.graphicEntity,ce);e.enabled=s.isOn,t.insert(s.graphicEntity,ce,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const $o=new zo,Oo=xi,Ho=q("ProgressBar",{value:0,fillEntity:0,direction:xi.LeftToRight});function Vo(e,t,s,n){if(!e.has(t,bi))return;const i=e.get(t,bi),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=wi(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,ce)){const s=e.get(t,ce);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,ce,s))}if(e.has(t,re)){const s=e.get(t,re),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,re,s))}}class jo{build(e){ee("ProgressBar",Ho);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([],()=>{const e=t.getEntitiesWithComponents([Ho,bi]);for(const s of e){const e=t.get(s,Ho);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,bi),i=Math.max(0,Math.min(1,e.value));Ti(t,e.fillEntity,e.direction,i);const o=Fi(n,s),r=ki(n,s);Vo(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const No=new jo,Xo=q("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Yo=q("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}});class Go{build(e){ee("Draggable",Xo),ee("DragState",Yo);const t=e.world,s=e.getResource(po);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([Ie(gt),Ie(xt)],(e,r)=>{if(_o()&&!xo())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Xo,lo]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Xo).enabled)continue;if(t.get(n,lo).hovered){let e=0;t.has(n,ce)&&(e=t.get(n,ce).layer);const i=Ii(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,Yo)||t.insert(s,Yo);const e=t.get(s,Yo),o=t.get(s,re);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,Yo)){t.get(n,Yo).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),u=t.get(n,Xo);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Yo).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Yo))return void(o=null);const n=t.get(o,Yo),i=t.get(o,Xo),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,u=n.startWorldPos.y+l;const d=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,u);c=d.x,u=d.y;const h=n.currentWorldPos.x,p=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:u-p},n.currentWorldPos={x:c,y:u},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:u-n.startWorldPos.y},t.has(o,re)){const e=function(e,t,s,n){if(!e.has(t,pe))return{x:s,y:n};const i=e.get(t,pe).entity;if(!e.valid(i)||!e.has(i,re))return{x:s,y:n};const o=e.get(i,re),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=to(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(s*u-n*c)/r,y:(s*c+n*u)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,re);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,re,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const qo=new Go,Ko=q("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,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(s-o*c)*a}}class Zo{build(e){ee("ScrollView",Ko);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,ht([Ie(gt),Ie(xt),Ie(De)],(e,i,o)=>{const r=_o()&&!xo(),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,bi]);for(const o of l){Di(t,o,Ji,{enabled:!0,mode:qi});const l=t.get(o,Ko),c=t.get(o,bi);let u=s.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,u));const d=Fi(c,o),h=ki(c,o);let p=l.contentWidth,f=l.contentHeight;if((0===p||0===f)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,fe)){const e=t.get(l.contentEntity,fe).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,re))continue;const e=t.get(r,re);let a=0,l=0,c=.5,u=.5;if(t.has(r,bi)){const e=t.get(r,bi);a=Fi(e,r)||e.size.x,l=ki(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,ce)){const e=t.get(r,ce);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),p=e.position.y-l*u,f=e.position.y+l*(1-u);d<s&&(s=d),h>n&&(n=h),p<i&&(i=p),f>o&&(o=f)}0===p&&(p=n-s),0===f&&(f=o-i)}const m=Math.max(0,p-d),g=Math.max(0,f-h);if(!r&&i.valid){Di(t,o,ao,{enabled:!0,blockRaycast:!0});const s=t.has(o,lo)?t.get(o,lo):null;if(s?.justPressed&&(u.isDragging=!0,u.lastWorldX=n.x,u.lastWorldY=n.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=n.x-u.lastWorldX,t=n.y-u.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=Jo(l.scrollX,0,m,d);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const n=a>0?-e*t/a:0;u.velocityX+=(n-u.velocityX)*s}}if(l.verticalEnabled){const e=Jo(l.scrollY,0,g,h);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const n=a>0?t*e/a:0;u.velocityY+=(n-u.velocityY)*s}}u.lastWorldX=n.x,u.lastWorldY=n.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*d,t=5*h;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Jo(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Jo(l.scrollX,0,m,d);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=Qo(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Wi&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Wi?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=Qo(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Wi&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Wi?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.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,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*d,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,re)){const e=t.get(l.contentEntity,re),s=e.position.x,n=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(n-u.lastAppliedY)>.01)&&(u.contentBaseY=n),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,re,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const er=new Zo,tr=xi,sr=q("Slider",{value:0,minValue:0,maxValue:1,direction:xi.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function nr(e,t,s,n,i,o){const r=Fi(n,i)*s.worldScale.x,a=ki(n,i)*s.worldScale.y,l=to(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-s.worldPosition.x,h=t-s.worldPosition.y,p=d*u-h*c,f=d*c+h*u,m=-n.pivot.x*r,g=-n.pivot.y*a;switch(o){case xi.LeftToRight:return r>0?(p-m)/r:0;case xi.RightToLeft:return r>0?1-(p-m)/r:0;case xi.BottomToTop:return a>0?(f-g)/a:0;case xi.TopToBottom:return a>0?1-(f-g)/a:0}}function ir(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case xi.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case xi.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case xi.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case xi.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class or{build(e){ee("Slider",sr);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([Ie(gt),Ie(xt),Ie(po)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([sr,bi]);for(const r of o){const o=t.get(r,sr),a=t.get(r,bi);if(!_o()||xo()){if(t.has(r,re)){Di(t,r,ao,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Di(t,o.handleEntity,ao,{enabled:!0,blockRaycast:!1});const l=t.get(r,re),c=t.has(r,lo)?t.get(r,lo):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,lo)&&(u=t.get(o.handleEntity,lo).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=nr(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,sr,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,u=Fi(a,r),d=ki(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Ti(t,o.fillEntity,o.direction,c),Li(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,bi)){const e=t.get(o.handleEntity,bi);ir(e,o.direction,c),t.insert(o.handleEntity,bi,e),Li(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const rr=new or;class ar{build(e){ee("Focusable",Mo);const t=e.world,s=new To;e.insertResource(Co,s),e.addSystemToSchedule(exports.Schedule.Update,ht([Ie(gt),Ie(po)],(e,n)=>{if(_o()&&!xo())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Mo]);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,Mo);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,Mo)){t.get(i,Mo).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Mo).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const lr=new ar,cr=q("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function ur(){return s()?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")}}()}class dr{build(e){ee("SafeArea",cr);const t=e.world;let n=ur(),i=!0,o=0,r=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=ur(),i=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=ur(),i=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([Ie(xt)],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,i=!0),!i)return;i=!1;const l=u(),c=s()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([cr,bi]);for(const e of d){const s=t.get(e,cr),i=t.get(e,bi),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,bi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const hr=new dr,pr=q("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let fr=null;class mr{build(e){ee("ListView",pr);const t=e.world,s=new Map;fr=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,ht([Ie(gt)],e=>{const n=_o()&&!xo();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([pr,bi]);for(const o of i){Di(t,o,ao,{enabled:!0,blockRaycast:!0}),Di(t,o,Ji,{enabled:!0,mode:qi});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,pr),a=t.get(o,bi),l=ki(a,o),c=Fi(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 u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const d=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<d||e>=h)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=d;e<h;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,be,{value:`ListItem_${e}`}),t.insert(s,bi,{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,re)){const n=t.get(s,re);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,re,n)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const gr=new mr,yr=q("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class _r{build(e){ee("Dropdown",yr);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,re))return;const s=t.get(e,re);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,re,{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,ce)){const s=t.get(e,ce);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,ce,{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;u(i,!0),c(n);const o=t.get(e,ce),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*zi;t.insert(i,bi,{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,re,{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,ce,{texture:V,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)*zi;t.insert(o,be,{value:`Option_${e}`}),t.insert(o,bi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*zi},offsetMax:{x:0,y:0},size:{x:r,y:zi},pivot:{x:.5,y:.5}}),t.insert(o,re,{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,ce,{texture:V,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:zi},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,re,{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,ji,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Oi.Left,verticalAlign:Hi.Middle,wordWrap:!1,overflow:Vi.Clip,lineHeight:1.2}),t.insert(c,bi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:zi},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}d(n)}function r(e,t,s){t.isOpen=!1,c(s),u(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,ji))return;const n=t.get(s,ji);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,ji,{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 u(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,ce))){const n=t.get(e,ce);t.insert(e,ce,{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 d(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,ce))continue;const i=s===e.highlightIndex?{...$i}:{r:.95,g:.95,b:.95,a:1};t.insert(n,ce,{texture:V,color:i,size:{x:e.ddWidth,y:zi},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(exports.Schedule.Update,ht([Ie(gt),Ie(po)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const p=_o()&&!xo(),f=t.getEntitiesWithComponents([yr]);for(const m of f){const f=t.get(m,yr);let g=s.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,g)),n(f.listEntity),i(m),f.isOpen||u(f.listEntity,!1),l(f),p)continue;Di(t,m,ao,{enabled:!0,blockRaycast:!0});const y=t.has(m,lo)?t.get(m,lo):null;if(y?.justPressed&&(f.isOpen?r(m,f,g):o(m,f,g)),f.isOpen){for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,lo))continue;if(t.get(s,lo).justPressed){a(m,f,g,e,c);break}}let s=-1;for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,lo))continue;if(t.get(n,lo).hovered){s=e;break}}s>=0&&s!==g.highlightIndex&&(g.highlightIndex=s,d(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=f.options.length-1?g.highlightIndex=0:g.highlightIndex++,d(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=f.options.length-1:g.highlightIndex--,d(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,f,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,f,g),e.isMouseButtonPressed(0)&&(y?.hovered||h(g)||r(m,f,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const xr=new _r,wr=0,br=0,vr=2,Sr=q("LayoutGroup",{direction:wr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:br,reverseOrder:!1});class Pr{build(e){ee("LayoutGroup",Sr);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([],()=>{const e=t.getEntitiesWithComponents([Sr,bi,fe]);for(const s of e){const e=t.get(s,Sr),n=t.get(s,bi),i=t.get(s,fe);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,bi)&&t.has(e,re)&&o.push({entity:e,rect:t.get(e,bi)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Fi(n,s),a=ki(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,d=e.direction===wr;let h=0;for(let s=0;s<o.length;s++){const n=o[s],i=Fi(n.rect,n.entity),p=ki(n.rect,n.entity),f=n.rect.pivot.x,m=n.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+f*i,y=e.childAlignment===br?(1-c)*a-u.top-(1-m)*p:e.childAlignment===vr?-c*a+u.bottom+m*p:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*p,h+=i,s<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===br?-l*r+u.left+f*i:e.childAlignment===vr?(1-l)*r-u.right-(1-f)*i:(.5-l)*r+.5*(u.left-u.right)+(f-.5)*i,y=(1-c)*a-u.top-h-(1-m)*p,h+=p,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,re);_.position.x=g,_.position.y=y,t.insert(n.entity,re,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Mr=new Pr;class Tr{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,ht([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Cr=new Tr;async function Er(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 Ar=Re({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),Rr={r:.2,g:.4,b:1,a:.7},Ir={r:.2,g:1,b:.2,a:.7},Fr={r:.2,g:1,b:1,a:.7},kr={r:1,g:1,b:.2,a:.5},Br={r:1,g:.2,b:.2,a:.8},Dr={r:1,g:.2,b:.2,a:1},Lr=1.5,Ur=16;function Wr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function zr(e){switch(e){case Ee.Static:return Rr;case Ee.Kinematic:return Fr;default:return Ir}}function $r(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-s,y:-n},{x:s,y:-n},{x:s,y:n},{x:-s,y:n}].map(s=>({x:e+s.x*r-s.y*a,y:t+s.x*a+s.y*r}));for(let e=0;e<4;e++)Gs.line(l[e],l[(e+1)%4],o,Lr)}function Or(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=(s,n)=>({x:e+s*r-n*a,y:t+s*a+n*r}),c=l(-s,n),u=l(s,n),d=l(-s,-n),h=l(s,-n);Gs.line(c,d,o,Lr),Gs.line(u,h,o,Lr);for(let e=0;e<Ur;e++){const t=e/Ur*Math.PI,i=(e+1)/Ur*Math.PI,r=l(-s*Math.cos(t),n+s*Math.sin(t)),a=l(-s*Math.cos(i),n+s*Math.sin(i));Gs.line(r,a,o,Lr)}for(let e=0;e<Ur;e++){const t=Math.PI+e/Ur*Math.PI,i=Math.PI+(e+1)/Ur*Math.PI,r=l(-s*Math.cos(t),-n+s*Math.sin(t)),a=l(-s*Math.cos(i),-n+s*Math.sin(i));Gs.line(r,a,o,Lr)}}function Hr(e,t,s,n){const i=e+.5*s,o=t+.5*n;Gs.line({x:e,y:t},{x:i,y:o},Br,Lr);const r=Math.sqrt(s*s+n*n);if(r<1)return;const a=Math.PI/6,l=s/r,c=n/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),d=o-6*(l*Math.sin(a)+c*Math.cos(a)),h=i-6*(l*Math.cos(a)+c*Math.sin(a)),p=o-6*(-l*Math.sin(a)+c*Math.cos(a));Gs.line({x:i,y:o},{x:u,y:d},Br,Lr),Gs.line({x:i,y:o},{x:h,y:p},Br,Lr)}function Vr(e,t,s){const n=e.getResource(Ar);if(!n||!n.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([de]);for(const s of t){const t=e.world.get(s,de);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([Pe,re]);let r=null;n.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const s=e.world.get(t,Pe);if(!s.enabled)continue;const o=e.world.get(t,re),a=o.worldPosition.x,l=o.worldPosition.y,c=Wr(o.worldRotation);if(n.showColliders){if(e.world.has(t,Me)){const n=e.world.get(t,Me),o=n.isSensor?kr:zr(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c);$r(a+r*d-u*h,l+r*h+u*d,n.halfExtents.x*i,n.halfExtents.y*i,c,o)}if(e.world.has(t,Te)){const n=e.world.get(t,Te),o=n.isSensor?kr:zr(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c),p=a+r*d-u*h,f=l+r*h+u*d;Gs.circleOutline({x:p,y:f},n.radius*i,o,Lr,32)}if(e.world.has(t,Ce)){const n=e.world.get(t,Ce),o=n.isSensor?kr:zr(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c);Or(a+r*d-u*h,l+r*h+u*d,n.radius*i,n.halfHeight*i,c,o)}}if(n.showVelocity&&r&&s.bodyType===Ee.Dynamic){const e=r.getLinearVelocity(t);Hr(a,l,e.x*i,e.y*i)}}if(n.showContacts&&e.hasResource(s)){const t=e.getResource(s);for(const e of t.collisionEnters)Gs.circle({x:e.contactX,y:e.contactY},3,Dr,!0,32)}}const jr=Re({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Nr=Re(null,"PhysicsAPI");function Xr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Yr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Gr{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(jr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Er(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([de]);for(const s of t){const t=e.world.get(s,de);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(exports.Schedule.PostUpdate,ht([Ie(De)],a=>{const l=r.getEntitiesWithComponents([Pe,re]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Pe),l=r.get(i,re);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=Xr(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),qr(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===Ee.Kinematic){const e=Xr(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 u=e.world.get(r,re);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(r,pe)){const t=e.world.get(r,pe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,re)){const s=e.world.get(t.entity,re),n=Xr(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),u=Math.sin(-n);d=(i*r-o*u)/(0!==s.worldScale.x?s.worldScale.x:1),h=(i*u+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=Yr(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(r,re,u)}}(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=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(jr,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Nr,Kr._fromModule(n)),function(e,t,s){e.insertResource(Ar,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),Zs("physics-debug-draw",()=>{Vr(e,t,s)})}(e,Nr,jr),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function qr(e,t,s){const n=e.world;if(n.has(s,Me)){const e=n.get(s,Me);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,Ce)){const e=n.get(s,Ce);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 Kr{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(Kr.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)}static setDebugDraw(e,t){const s=e.getResource(Ar);s&&(s.enabled=t,e.insertResource(Ar,s))}static setDebugDrawConfig(e,t){const s=e.getResource(Ar);s&&e.insertResource(Ar,{...s,...t})}}const Jr={nearest:0,linear:1},Qr={repeat:0,clamp:1,mirror:2};function Zr(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=Jr[n.filterMode??"linear"]??1,a=Qr[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 ea(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 ta(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,u=e.worldRotation.w,d=a+a,h=l+l,p=c+c,f=a*d,m=a*h,g=a*p,y=l*h,_=l*p,x=c*p,w=u*d,b=u*h,v=u*p;return new Float32Array([(1-(y+x))*i,(m+v)*i,(g-b)*i,0,(m-v)*o,(1-(f+x))*o,(_+w)*o,0,(g+b)*r,(_-w)*r,(1-(f+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function sa(e){const{app:t,module:s,sceneData:n,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=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=ms(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]=Zr(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(s,n,i);!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)}}}}(s,n,u);let d={},h=null;if(o&&(h=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"])}}(o),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=gs(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),u=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===b(c)?.contentType;let d,h;if(r){const e=await i.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await i.readText(a),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,n,n.length,r);if(t._free(d),p<0)continue;o[a]=p;const f=ea(n),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=Zr(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(s,o,h,n,i)),r){const e={gravity:a?.gravity??{...W},fixedTimestep:a?.fixedTimestep??z,subStepCount:a?.subStepCount??4};new Gr("",e,()=>Promise.resolve(r)).build(t)}const p=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=ms(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=b(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),u=Zr(e,c,!1),d=e.getResourceManager();n[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{n[o]=0}}return n}(s,n,i),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=ms(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=At.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=At.createFromAsset(e,r)}catch{s[o]=0}}return s}(n,i);await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=ms(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=JSON.parse(t),o=$t(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,Zr(e,n))}catch{r.set(t,0)}Vt(Ot(i,n,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(s,n,i),await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=ms(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=cs(JSON.parse(t));if(!n)continue;const o=[];for(const t of n.tilesets){const n=us(i,t.image);let r=0;try{const t=await s.loadPixels(n);r=Zr(e,t),qt(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}Qt(i,{tileWidth:n.tileWidth,tileHeight:n.tileHeight,layers:n.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(s,n,i),await async function(e,t){const s=[],n=new Set;for(const t of e.entities)for(const e of t.components){const t=ms(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!n.has(t)&&(n.add(t),s.push(t))}}0!==s.length&&(t?await Promise.all(s.map(async e=>{try{const s=await t.readBinary(e);await Xt.preloadFromData(e,s.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await Xt.preloadAll(s).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(n,i),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=ms(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)}}}(n,u,p,f);const m=bs(t.world,n);if(c&&t.hasResource(ei))for(const e of m.values())t.world.insert(e,ve,{scene:c,persistent:!1});if(o&&h){const e=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=gs(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}(h,n,d,m);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=U);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,ge)?c.get(o,ge):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(r,l*d);let h=0;if(c.has(o,re)){const e=ta(c.get(o,re),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(r);for(let e=0;e<p;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),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(r,e,c,u,d,p);const f=s.HEAPU32[d>>2],m=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*i),y=new Uint16Array(s.HEAPU8.buffer,u,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(y),t.renderer_submitTriangles(_,i,x,o,f,m,h),t._free(_),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(t,s,o,h,e)}if(l){const e=t.getResource(Cs);e&&e.setAddressableManifest(l)}}function na(e,t,s){return{name:e,async setup(){await sa({...s,sceneData:t,sceneName:e})}}}async function ia(e){const{app:t,firstScene:s,aspectRatio:n}=e;oi(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(ei);for(const t of e.scenes)o.register(na(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&Ms(t.world,n)}class oa{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=gs(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===b(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=ms(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(n.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&s.add(o))}}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=b(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 ra="__preview__";const aa={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=jn.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:jn.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){jn.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(jn.releaseRenderTarget(e._handle),aa.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){jn.begin(t,e._handle)},end(){jn.end()},getDepthTexture:e=>jn.getTargetDepthTexture(e._handle)};var la;exports.LogLevel=void 0,(la=exports.LogLevel||(exports.LogLevel={}))[la.Debug=0]="Debug",la[la.Info=1]="Info",la[la.Warn=2]="Warn",la[la.Error=3]="Error";class ca{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,s);break;case exports.LogLevel.Info:console.log(t,s);break;case exports.LogLevel.Warn:console.warn(t,s);break;case exports.LogLevel.Error:console.error(t,s)}}}class ua{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new ca)}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(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.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 da=new ua;const ha={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},pa={Running:0,Paused:1,Completed:2,Cancelled:3},fa={None:0,Restart:1,PingPong:2};const ma=1.70158,ga=2.70158,ya=2.5949095;const _a=2*Math.PI/3,xa=2*Math.PI/4.5;const wa=7.5625,ba=2.75;const va=1e-6;function Sa(e,t,s){switch(e){case ha.Linear:return t;case ha.EaseInQuad:return function(e){return e*e}(t);case ha.EaseOutQuad:return function(e){return e*(2-e)}(t);case ha.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case ha.EaseInCubic:return function(e){return e*e*e}(t);case ha.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case ha.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case ha.EaseInBack:return function(e){return ga*e*e*e-ma*e*e}(t);case ha.EaseOutBack:return function(e){const t=e-1;return 1+ga*t*t*t+ma*t*t}(t);case ha.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-ya)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+ya)+2)/2}(t);case ha.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*_a)}(t);case ha.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*_a)+1}(t);case ha.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*xa)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*xa)/2+1}(t);case ha.EaseOutBounce:return function(e){return e<1/ba?wa*e*e:e<2/ba?wa*(e-=1.5/ba)*e+.75:e<2.5/ba?wa*(e-=2.25/ba)*e+.9375:wa*(e-=2.625/ba)*e+.984375}(t);case ha.CubicBezier:return s?function(e,t,s,n,i){let o=e;for(let s=0;s<8;s++){const s=1-o,i=3*t*s*s*o+3*n*s*o*o+o*o*o-e;if(Math.abs(i)<va)break;const r=3*t*(1-2*o)*(1-o)+6*n*o*(1-o)-3*n*o*o+3*o*o;if(Math.abs(r)<va)break;o-=i/r}const r=1-o;return 3*s*r*r*o+3*i*r*o*o+o*o*o}(t,s.p1x,s.p1y,s.p2x,s.p2y):t;case ha.Step:return function(e){return e<1?0:1}(t);default:return t}}const Pa=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,s,n,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:s,elapsed:0,delay:i?.delay??0,easing:i?.easing??ha.Linear,bezierPoints:null,state:pa.Running,loop:i?.loop??fa.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:n,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===pa.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==pa.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const s=Math.min(t.elapsed/t.duration,1),n=Sa(t.easing,s,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*n),s>=1){if(t.loop!==fa.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===fa.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=pa.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===pa.Running&&(t.state=pa.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===pa.Paused&&(t.state=pa.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=pa.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:pa.Cancelled}setBezier(e,t,s,n,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:s,p2x:n,p2y:i})}setSequenceNext(e,t){const s=this.entries_.get(e);s&&(s.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const s=this.entries_.get(e);s&&(s.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Ma{constructor(e){this.id=e}get state(){return Pa.getState(this.id)}bezier(e,t,s,n){return Pa.setBezier(this.id,e,t,s,n),this}then(e){return e instanceof Ma?Pa.setSequenceNext(this.id,e.id):Pa.setSequenceNextExternal(this.id,e),this}pause(){Pa.pause(this.id)}resume(){Pa.resume(this.id)}cancel(){Pa.cancel(this.id)}}class Ta{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 e instanceof Ma?(Pa.registerCppSequence(this.entity,e.id),this):(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 Ca=null,Ea=null;function Aa(e,t){Ca=e,Ea=t,Pa.init(e,t)}function Ra(){Pa.shutdown(),Ca=null,Ea=null}function Ia(){if(!Ca)throw new Error("Tween API not initialized");return Ca}function Fa(){if(!Ea)throw new Error("Tween API not initialized");return Ea}const ka={to(e,t,s,n,i,o){const r=Ia(),a=Fa(),l=o?.easing??ha.Linear,c=o?.delay??0,u=o?.loop??fa.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,u,d);return new Ta(r,a,h)},value(e,t,s,n,i){const o=Pa.create(e,t,s,n,i);return new Ma(o)},cancel(e){Ia()._anim_cancelTween(Fa(),e.entity)},cancelAll(e){Ia()._anim_cancelAllTweens(Fa(),e)},update(e){Ia()._anim_updateTweens(Fa(),e),Pa.update(e)}};class Ba{constructor(){this.name="AnimationPlugin"}build(e){Aa(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,ht([Ie(De)],e=>{ka.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,ht([Ie(De)],e=>{Nt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Ra()}}const Da=new Ba;var La;exports.AttenuationModel=void 0,(La=exports.AttenuationModel||(exports.AttenuationModel={}))[La.Linear=0]="Linear",La[La.Inverse=1]="Inverse",La[La.Exponential=2]="Exponential";const Ua={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Wa(e,t=Ua){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case exports.AttenuationModel.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case exports.AttenuationModel.Inverse:a=n/Math.max(r,n);break;case exports.AttenuationModel.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function za(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const $a=q("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:exports.AttenuationModel.Inverse,rolloff:1,priority:0,enabled:!0}),Oa=q("AudioListener",{enabled:!0});class Ha{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const s=t().createAudioBackend(),n=this.config_;s.initialize({initialPoolSize:n.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=s.mixer;Xt.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;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(exports.Schedule.PreUpdate,ht([Ie(De)],t=>{if(!(!_o()||xo()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,d=!1;const h=n.getEntitiesWithComponents([Oa,le]);for(const e of h){if(n.get(e,Oa).enabled){const t=n.get(e,le);i=t.position.x,u=t.position.y,d=!0;break}}const p=n.getEntitiesWithComponents([$a]);a.clear();for(const e of p){const t=n.get(e,$a);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&s.isReady){const e=Xt.getBufferHandle(t.clip);if(e){const n=s.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,n),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const s=o.get(c);if(!s.isPlaying){o.delete(c);continue}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=n.tryGet?.(e,le),a=r?.position.x??0,h=r?.position.y??0,p=a-i,f=h-u,m=Wa(Math.sqrt(p*p+f*f),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=za(a,0,i,0,t.maxDistance);s.setVolume(t.volume*m),s.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),Xt.dispose()}}const Va=new Ha;let ja=null,Na=null;function Xa(e,t){ja=e,Na=t}function Ya(){ja=null,Na=null}const Ga={update(e){ja&&Na&&ja.particle_update?.(Na,e)},play(e){ja&&Na&&ja.particle_play?.(Na,e)},stop(e){ja&&Na&&ja.particle_stop?.(Na,e)},reset(e){ja&&Na&&ja.particle_reset?.(Na,e)},getAliveCount:e=>ja?ja.particle_getAliveCount?.(e)??0:0};class qa{constructor(){this.name="ParticlePlugin"}build(e){Xa(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(exports.Schedule.Update,ht([Ie(De)],e=>{Ga.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){Ya()}}const Ka=new qa,Ja=1e6;class Qa{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){ts(e.wasmModule);const t=e.world,s=this.initializedLayers_,n=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(xt),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:Ja,l=i?.valid?i.worldTop:Ja,c=t.getEntitiesWithComponents([os,re]);for(const e of c){const n=t.tryGet(e,os),i=t.tryGet(e,re);if(!n||!i)continue;if(!n.visible)continue;const c=n.texture;if(!c)continue;const u=Kt(c);if(!u)continue;if(!s.has(e)){if(ns.initLayer(e,n.width,n.height,n.tileWidth,n.tileHeight),n.tiles.length>0){const t=new Uint16Array(n.tiles.length);for(let e=0;e<n.tiles.length;e++)t[e]=n.tiles[e];ns.setTiles(e,t)}s.add(e)}const d=n.tileWidth/u.width,h=n.tileHeight/u.height,p=n.tint,f=n.parallaxFactor;ns.submitLayer(e,c,n.layer,0,n.tilesetColumns,d,h,i.worldPosition.x,i.worldPosition.y,o,r,a,l,p.r,p.g,p.b,p.a,n.opacity,f.x,f.y)}const u=t.getEntitiesWithComponents([is,re]);for(const e of u){if(t.tryGet(e,os))continue;const i=t.tryGet(e,is),c=t.tryGet(e,re);if(!i?.source||!c)continue;const u=Zt(i.source);if(!u)continue;if(!n.has(e)){const t=[];for(let n=0;n<u.layers.length;n++){const i=1073741824+256*e+n,o=u.layers[n];ns.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&ns.setTiles(i,o.tiles),t.push(i),s.add(i)}n.set(e,t)}const d=n.get(e);for(let e=0;e<u.layers.length&&e<d.length;e++){const t=d[e],s=u.tilesets[0];if(!s)continue;const n=Kt(s.textureHandle);if(!n)continue;const i=u.tileWidth/n.width,h=u.tileHeight/n.height;ns.submitLayer(t,s.textureHandle,e,0,s.columns,i,h,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)ns.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),Jt(),ss()}}const Za=new Qa;function el(e,t){return e.toFixed(t)}function tl(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class sl{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">${el(e.fps,1)}</span> Frame: <span style="color:#d19a66">${el(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>${tl(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${el(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 nl(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const il=Re(nl(),"Stats");const ol="StatsCollect";class rl{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 al{constructor(e){this.name="Stats",this.collector_=new rl,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(il,nl());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new sl(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=ht([Ie(De),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(il);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(ol),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=jn.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,s?.update(o)},{name:ol});e.addSystemToSchedule(exports.Schedule.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const ll=new al;class cl{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 ul(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}}const dl=[Gi,ro,mo,Lo,No,So,qo,er,rr,$o,Ao,lr,hr,gr,xr,Mr,Cr],hl=[...dl,Da,Va,Ka,Za,Wn];function pl(e,t){return function(e,t){const s=ii.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),js(e),Tt(e),ln(e),wn(e),Hn(e),Xn(e);const i=new qn;s.setPipeline(i);let o=c();const r=t?.getViewportSize??(()=>{const e=u();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=ui(e,n,t,i));const r=s.getResource(xt);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(xt,{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)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;jn.setClearColor(e.x,e.y,e.z,e.w)}const d=(c()-o)/1e3;let h;if(jn.resize(t,l),s.hasResource(ei)){const e=s.getResource(ei).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const p=ui(e,n,t,l,s.world,h);if(a(t,l,p),0===p.length)i.render({registry:{_cpp:n},viewProjection:ri,width:t,height:l,elapsed:d});else{i.beginScreenCapture();for(const e of p){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,cameraEntity:e.entity})}i.endScreenCapture(),jn.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(As),s.addPlugin(Ws),s.addPlugin(_t),s.addPlugin(ni),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:hl,...t})}class fl{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return o(this.resolvePath_(e))}async readBinary(e){const t=await i(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function ml(e){return(t,s)=>(a(e,t).then(e=>{s(e.instance,e.module)}),{})}async function gl(e,t){try{return await e({instantiateWasm:ml(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}k||(k=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},i=await f(s,n);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return m(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i<128?s[n++]=i:i<2048?(s[n++]=192|i>>6,s[n++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,s[n++]=240|i>>18,s[n++]=128|i>>12&63,s[n++]=128|i>>6&63,s[n++]=128|63&i):(s[n++]=224|i>>12,s[n++]=128|i>>6&63,s[n++]=128|63&i)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const i=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=B,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.AnimationPlugin=Ba,exports.App=ii,exports.AssetPlugin=Es,exports.AssetRefCounter=class{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}}},exports.AssetServer=Ts,exports.Assets=Cs,exports.AsyncCache=Wt,exports.Audio=Xt,exports.AudioBus=d,exports.AudioListener=Oa,exports.AudioMixer=class{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new d(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new d(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new d(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new d(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new d(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 d(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}},exports.AudioPlugin=Ha,exports.AudioPool=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}},exports.AudioSource=$a,exports.BitmapText=me,exports.BodyType=Ee,exports.BoxCollider=Me,exports.Button=uo,exports.ButtonState=co,exports.Camera=ue,exports.Canvas=de,exports.CapsuleCollider=Ce,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=fe,exports.CircleCollider=Te,exports.ClearFlags=ie,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=it,exports.DEFAULT_DESIGN_HEIGHT=L,exports.DEFAULT_DESIGN_WIDTH=D,exports.DEFAULT_FALLBACK_DT=U,exports.DEFAULT_FIXED_TIMESTEP=z,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=W,exports.DEFAULT_LINE_HEIGHT=1.2,exports.DEFAULT_MAX_DELTA_TIME=.5,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_SPINE_SKIN="default",exports.DEFAULT_SPRITE_SIZE={x:100,y:100},exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragPlugin=Go,exports.DragState=Yo,exports.Draggable=Xo,exports.Draw=Gs,exports.Dropdown=yr,exports.DropdownPlugin=_r,exports.EasingType=ha,exports.EmitterShape=ye,exports.EntityCommands=nt,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=lt,exports.EventRegistry=rt,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=at,exports.FillDirection=xi,exports.FillMethod=Io,exports.FillOrigin=Fo,exports.FocusManager=Co,exports.FocusManagerState=To,exports.FocusPlugin=ar,exports.Focusable=Mo,exports.FrameHistory=class{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,s){const n={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:s?new Map(s):new Map};this.count_<this.capacity_?(this.buffer_.push(n),this.count_++):this.buffer_[this.cursor_]=n,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}},exports.GLDebug=Gn,exports.Geometry=dn,exports.GetWorld=ut,exports.INVALID_ENTITY=0,exports.INVALID_FONT=j,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=V,exports.Image=ko,exports.ImagePlugin=Do,exports.ImageType=Ro,exports.Input=gt,exports.InputPlugin=yt,exports.InputState=mt,exports.Interactable=ao,exports.LayoutGroupPlugin=Pr,exports.ListView=pr,exports.ListViewPlugin=mr,exports.LocalTransform=ae,exports.Logger=ua,exports.LoopMode=fa,exports.Material=At,exports.MaterialLoader=zt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=be,exports.Parent=pe,exports.Particle=Ga,exports.ParticleEasing=xe,exports.ParticleEmitter=we,exports.ParticlePlugin=qa,exports.Physics=Kr,exports.PhysicsEvents=jr,exports.PhysicsPlugin=Gr,exports.PostProcess=Sn,exports.PostProcessPlugin=Un,exports.PostProcessStack=yn,exports.PostProcessVolume=Se,exports.PrefabServer=Ds,exports.Prefabs=Ls,exports.PrefabsPlugin=Us,exports.PreviewPlugin=class{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(ei);t.register({name:ra,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(ra),this.loadPromise_=t.load(ra).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await n(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new oa(this.baseUrl_);await s.prefetch(t);let i=null;const o=this.app_.spineInitPromise;if(o){i=(await o).controller.raw}await sa({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:i,sceneName:ra})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([ue]);for(const n of s){if(e.get(n,ue).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([de]);for(const i of n){const n=e.get(i,de);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(ei).getScene(ra),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,re,r);const a={isActive:!0,projectionType:ne.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:ie.ColorAndDepth};e.insert(o,ue,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(ei);await e.switchTo(ra),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}`)}}},exports.ProgressBar=Ho,exports.ProgressBarDirection=Oo,exports.ProgressBarPlugin=jo,exports.ProjectionType=ne,exports.Query=et,exports.QueryInstance=tt,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=st,exports.RenderPipeline=qn,exports.RenderTexture=aa,exports.Renderer=jn,exports.Res=Ie,exports.ResMut=Fe,exports.RigidBody=Pe,exports.RuntimeConfig=$,exports.SafeArea=cr,exports.SafeAreaPlugin=dr,exports.ScaleMode=oe,exports.SceneManager=ei,exports.SceneManagerState=Zn,exports.SceneOwner=ve,exports.ScrollView=Ko,exports.ScrollViewPlugin=Zo,exports.ShaderSources=Ut,exports.SimulationSpace=_e,exports.Slider=sr,exports.SliderDirection=tr,exports.SliderPlugin=or,exports.SpineAnimation=ge,exports.Sprite=ce,exports.SpriteAnimator=jt,exports.Stats=il,exports.StatsCollector=rl,exports.StatsOverlay=sl,exports.StatsPlugin=al,exports.SystemRunner=ft,exports.Text=ji,exports.TextAlign=Oi,exports.TextInput=Po,exports.TextInputPlugin=Eo,exports.TextOverflow=Vi,exports.TextPlugin=Yi,exports.TextRenderer=Ni,exports.TextVerticalAlign=Hi,exports.Tilemap=is,exports.TilemapAPI=ns,exports.TilemapLayer=os,exports.TilemapPlugin=Qa,exports.Time=De,exports.Toggle=Uo,exports.TogglePlugin=zo,exports.Transform=re,exports.Tween=ka,exports.TweenHandle=Ta,exports.TweenState=pa,exports.TweenTarget={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},exports.UICameraInfo=xt,exports.UIEventQueue=ho,exports.UIEvents=po,exports.UIInteraction=lo,exports.UIInteractionPlugin=vo,exports.UILayoutPlugin=fo,exports.UIMask=Ji,exports.UIMaskPlugin=oo,exports.UIRect=bi,exports.UIRenderOrderPlugin=Tr,exports.Velocity=he,exports.WeChatAssetProvider=fl,exports.WebAssetProvider=oa,exports.World=Ge,exports.WorldTransform=le,exports.addStartupSystem=function(e){pt().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){pt().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){pt().push({schedule:e,system:t})},exports.animationPlugin=Da,exports.applyBuildRuntimeConfig=H,exports.applyDirectionalFill=Ti,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=$.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=$.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=$.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=$.canvasMatchWidthOrHeight)},exports.assetPlugin=As,exports.audioPlugin=Va,exports.calculateAttenuation=Wa,exports.calculatePanning=za,exports.cleanupAllPostProcessVolumes=Rn,exports.cleanupPostProcessVolume=An,exports.clearAnimClips=function(){Ht.clear()},exports.clearDrawCallbacks=tn,exports.clearTextureDimensionsCache=Jt,exports.clearTilemapSourceCache=function(){Gt.clear()},exports.clearUserComponents=function(){const e=G();for(const t of e.keys())Z.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=Mi,exports.computeFillSize=function(e,t,s,n){switch(e){case xi.BottomToTop:case xi.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case xi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case xi.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case xi.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}}}},exports.computeUIRectLayout=wi,exports.createMaskProcessor=io,exports.createRuntimeSceneConfig=na,exports.createWebApp=pl,exports.debug=function(e,t,s){da.debug(e,t,s)},exports.defaultFrameStats=nl,exports.defineComponent=q,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=Re,exports.defineSystem=ht,exports.defineTag=function(e){const t=Z.get(e)??G().get(e);if(t)return t;const s=Y(e,{});return G().set(e,s),Z.set(e,s),J(e,{},!0),s},exports.dragPlugin=qo,exports.dropdownPlugin=xr,exports.error=function(e,t,s){da.error(e,t,s)},exports.extractAnimClipTexturePaths=$t,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([be]);for(const n of s){const s=e.get(n,be);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=oi,exports.focusPlugin=lr,exports.getAddressableType=function(e){return b(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of g)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return x},exports.getAllEffectDefs=function(){return Array.from(Pn.values())},exports.getAnimClip=function(e){return Ht.get(e)},exports.getAssetBuildTransform=function(e){return b(e)?.buildTransform},exports.getAssetMimeType=function(e){return y[e.toLowerCase()]},exports.getAssetTypeEntry=b,exports.getComponent=te,exports.getComponentAssetFieldDescriptors=ms,exports.getComponentAssetFields=fs,exports.getComponentDefaults=function(e){const t=te(e);return t?N(t._default):null},exports.getComponentEntityFields=_s,exports.getComponentSpineFieldDescriptor=gs,exports.getCustomExtensions=S,exports.getEditorType=function(e){return b(e)?.editorType??"unknown"},exports.getEffectDef=Tn,exports.getEffectTypes=function(){return Array.from(Pn.keys())},exports.getLogger=function(){return da},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getTextureDimensions=Kt,exports.getTilemapSource=Zt,exports.getUserComponent=K,exports.getWeChatPackOptions=function(){return S().map(e=>({type:"suffix",value:e}))},exports.imagePlugin=Lo,exports.info=function(e,t,s){da.info(e,t,s)},exports.initDrawAPI=js,exports.initGLDebugAPI=Xn,exports.initGeometryAPI=ln,exports.initMaterialAPI=Tt,exports.initParticleAPI=Xa,exports.initPlayableRuntime=async function(e){const{app:t,module:s,assets:n,scenes:i,firstScene:o}=e,r=t.getResource(Cs);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await ul(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 ul(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new cl(n);await ia({app:t,module:s,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()},exports.initPostProcessAPI=wn,exports.initRendererAPI=Hn,exports.initRuntime=ia,exports.initTilemapAPI=ts,exports.initTweenAPI=Aa,exports.initWeChatRuntime=async function(e){const t=await o("asset-manifest.json"),s=JSON.parse(t),n=function(e){const{assetIndex:t,pathIndex:s}=e;return e=>{const n=M(e),i=t[e]||t[n]||s[n]||s[e];return i?i.path:n}}(function(e){const t={},s={};for(const n in e.groups){const i=e.groups[n];for(const e in i.assets){const n=i.assets[e];t[e]=n,s[n.path]=n}}return{assetIndex:t,pathIndex:s}}(s)),i=wx.createCanvas(),r=wx.getSystemInfoSync();i.width=r.windowWidth*r.pixelRatio,i.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:i,instantiateWasm:ml("esengine.wasm")}),l=i.getContext("webgl2")||i.getContext("webgl");if(!l)return void console.error("[ESEngine] Failed to create WebGL context");const c=a.GL.registerContext(l,{majorVersion:0===l.getParameter(l.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),u=pl(a,{glContextHandle:c,getViewportSize:()=>({width:i.width,height:i.height})});e.runtimeConfig&&H(u,e.runtimeConfig);let d=null;e.spineFactory&&(d=await gl(e.spineFactory,"spine.wasm"));let h=null;e.physicsFactory&&(h=await gl(e.physicsFactory,"physics.wasm"));const p=new fl(n),f=[];for(const t of e.sceneNames){const e=await o(`scenes/${t}.json`);f.push({name:t,data:JSON.parse(e)})}await ia({app:u,module:a,provider:p,scenes:f,firstScene:e.firstScene,spineModule:d,physicsModule:h,physicsConfig:e.physicsConfig,manifest:s,aspectRatio:i.width/i.height}),u.run()},exports.inputPlugin=_t,exports.instantiatePrefab=Rs,exports.intersectRects=Qi,exports.invertMatrix4=Zi,exports.isBuiltinComponent=Q,exports.isCustomExtension=P,exports.isEditor=_o,exports.isKnownAssetExtension=v,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=xo,exports.isRuntime=function(){return!go},exports.isTextureRef=bt,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.layoutGroupPlugin=Mr,exports.listViewPlugin=gr,exports.loadComponent=Ps,exports.loadPhysicsModule=Er,exports.loadRuntimeScene=sa,exports.loadSceneData=bs,exports.loadSceneWithAssets=vs,exports.loadTiledMap=function(e,t,s,n={}){const i=[],o=t.tilesets[0];let r=0;for(const n of t.layers){if(!n.visible)continue;const a=e.spawn();e.insert(a,re,{});const l=o?s.get(o.image)??0:0,c=o?.columns??1;e.insert(a,os,{width:n.width,height:n.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(n.tiles),tint:{...n.tintColor},opacity:n.opacity,visible:n.visible,parallaxFactor:{x:n.parallaxX,y:n.parallaxY}}),i.push(a),r++}if(!1!==n.generateObjectCollision&&t.objectGroups.length>0){const s=function(e,t,s,n){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=s+a+.5*t.width,u=n+(o-l)-.5*t.height,d=-t.rotation*ds;if(e.insert(r,re,{position:{x:c,y:u,z:0}}),e.insert(r,Pe,{bodyType:Ee.Static}),"ellipse"===t.shape){const s=.5*Math.max(t.width,t.height);e.insert(r,Te,{radius:s})}else if("polygon"===t.shape&&t.vertices){let s=1/0,n=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<s&&(s=r),r>i&&(i=r),a<n&&(n=a),a>o&&(o=a)}const a=i-s,l=o-n,c=.5*(s+i),u=.5*(n+o);e.insert(r,Me,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,Me,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==d){const t=.5*d;e.insert(r,re,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...s)}const a=new Set(n.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const s of t.layers){if(!s.visible)continue;const n=hs(e,s,t,a,0,0);i.push(...n)}return i},exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&v(w(e)))},exports.parseAnimClipData=Ot,exports.parseTiledMap=async function(e,t){const s=es;if(!s)return null;const n=new TextEncoder,i=n.encode(e),o=s._malloc(i.byteLength);s.HEAPU8.set(i,o);const r=s.tiled_loadMap(o,i.byteLength);if(s._free(o),0===r)return null;try{const e=s.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=s.tiled_getExternalTilesetSource(r,i);if(!t)return s.tiled_freeMap(r),null;const o=await t(e),a=n.encode(o),l=s._malloc(a.byteLength);s.HEAPU8.set(a,l);const c=s.tiled_loadExternalTileset(r,i,l,a.byteLength);if(s._free(l),!c)return s.tiled_freeMap(r),null}if(!s.tiled_finalize(r))return s.tiled_freeMap(r),null;const i={width:s.tiled_getMapWidth(r),height:s.tiled_getMapHeight(r),tileWidth:s.tiled_getMapTileWidth(r),tileHeight:s.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},o=s.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=s.tiled_getLayerWidth(r,e),n=s.tiled_getLayerHeight(r,e),o=t*n,a=2*o,l=s._malloc(a);s.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(s.HEAPU8.buffer,l,o)),s._free(l),i.layers.push({name:s.tiled_getLayerName(r,e),width:t,height:n,visible:s.tiled_getLayerVisible(r,e),tiles:c,opacity:s.tiled_getLayerOpacity(r,e),tintColor:s.tiled_getLayerTintColor?rs(s.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:s.tiled_getLayerParallaxX(r,e),parallaxY:s.tiled_getLayerParallaxY(r,e)})}const a=s.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:s.tiled_getTilesetName(r,e),image:s.tiled_getTilesetImage(r,e),tileWidth:s.tiled_getTilesetTileWidth(r,e),tileHeight:s.tiled_getTilesetTileHeight(r,e),columns:s.tiled_getTilesetColumns(r,e),tileCount:s.tiled_getTilesetTileCount(r,e)});return s.tiled_freeMap(r),i}catch{return s.tiled_freeMap(r),null}},exports.parseTmjJson=cs,exports.particlePlugin=Ka,exports.platformFetch=n,exports.platformFileExists=r,exports.platformInstantiateWasm=a,exports.platformReadFile=i,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,i,o,r,a,l,c){const u=to(l,c),d=Math.sin(-u),h=Math.cos(-u),p=e-s,f=t-n,m=p*h-f*d+s,g=p*d+f*h+n;return m>=s-i*r&&m<=s+i*(1-r)&&g>=n-o*a&&g<=n+o*(1-a)},exports.pointInWorldRect=function(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)},exports.postProcessPlugin=Wn,exports.prefabsPlugin=Ws,exports.progressBarPlugin=No,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerAnimClip=Vt,exports.registerAssetBuildTransform=function(e,t){for(const s of g)s.editorType===e&&(s.buildTransform=t)},exports.registerComponent=ee,exports.registerComponentAssetFields=function(e,t){ps.set(e,t)},exports.registerComponentEntityFields=function(e,t){ys.set(e,t)},exports.registerDrawCallback=Zs,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(Cs);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Lt,exports.registerTextureDimensions=qt,exports.registerTilemapSource=Qt,exports.remapEntityFields=xs,exports.resolveRelativePath=us,exports.safeAreaPlugin=hr,exports.sceneManagerPlugin=ni,exports.screenToWorld=eo,exports.scrollViewPlugin=er,exports.setEditorMode=function(e){go=e},exports.setListViewRenderer=function(e,t){if(!fr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=fr.get(e);s?s.renderer=t:fr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){da.setMinLevel(e)},exports.setPlayMode=function(e){yo=e},exports.setWasmErrorHandler=$e,exports.shutdownDrawAPI=Ns,exports.shutdownGLDebugAPI=Yn,exports.shutdownGeometryAPI=cn,exports.shutdownMaterialAPI=Ct,exports.shutdownParticleAPI=Ya,exports.shutdownPostProcessAPI=bn,exports.shutdownRendererAPI=Vn,exports.shutdownTilemapAPI=ss,exports.shutdownTweenAPI=Ra,exports.sliderPlugin=rr,exports.spriteAnimatorSystemUpdate=Nt,exports.statsPlugin=ll,exports.syncFillSpriteSize=function(e,t,s,n,i,o){if(!e.has(t,ce))return;const r=e.get(t,ce);let a,l;switch(s){case xi.BottomToTop:case xi.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,ce,r))},exports.syncPostProcessVolume=function(e,t){let s=Cn.get(e),n=En.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(s||(s=Sn.createStack(),Cn.set(e,s)),n||(n=new Map,En.set(e,n));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const e of i){const t=Tn(e.type);if(!t)continue;let i=n.get(e.type);void 0===i&&(i=t.factory(),n.set(e.type,i)),s.addPass(e.type,i);for(const n of t.uniforms){const t=e.uniforms[n.name]??n.defaultValue;s.setUniform(e.type,n.name,t)}}Sn.bind(e,s)}else if(s&&(Sn.unbind(e),s.destroy(),Cn.delete(e)),n){for(const e of n.values())At.releaseShader(e);En.delete(e)}},exports.textInputPlugin=Ao,exports.textPlugin=Gi,exports.tilemapPlugin=Za,exports.toBuildPath=M,exports.togglePlugin=$o,exports.transitionTo=async function(e,t,s){const n=e.getResource(ei);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=So,exports.uiLayoutPlugin=mo,exports.uiMaskPlugin=ro,exports.uiPlugins=dl,exports.uiRenderOrderPlugin=Cr,exports.unregisterAnimClip=function(e){Ht.delete(e)},exports.unregisterComponent=function(e){G().delete(e),Z.delete(e)},exports.unregisterDrawCallback=en,exports.updateCameraAspectRatio=Ms,exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){da.warn(e,t,s)},exports.wrapSceneSystem=ti,exports.wxFileExists=function(e){return new Promise(t=>{C().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})},exports.wxFileExistsSync=A,exports.wxGetImagePixels=I,exports.wxLoadImage=R,exports.wxLoadImagePixels=F,exports.wxReadFile=function(e){return new Promise((t,s)=>{C().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(E(e,t.errMsg)))}})})},exports.wxReadTextFile=function(e,t="utf-8"){return new Promise((s,n)=>{C().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(E(e,t.errMsg)))}})})},exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{C().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};+"use strict";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"wechat"===e?.name}async function n(e,s){return t().fetch(e,s)}async function i(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function r(e){return t().fileExists(e)}async function a(e,s){return t().instantiateWasm(e,s)}function l(e,s){return t().createCanvas(e,s)}function c(){return t().now()}function u(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class d{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 d?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class h{constructor(e,t,s){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=s}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class p{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}async loadBufferFromData(e,t){return this.loadBuffer(e)}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const s=this.urlCache_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=wx.createInnerAudioContext();n.loop=t.loop??!1,n.volume=t.volume??1,n.playbackRate=t.playbackRate??1,n.startTime=t.startOffset??0,n.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,n);const o=new h(i,n,this.contexts_);return n.onEnded(()=>{o.onEnd?.(),n.loop||(n.destroy(),this.contexts_.delete(i))}),n.onError(e=>{console.error(`[WeChatAudio] Playback error for "${s}":`,e.errMsg)}),n.src=s,n.play(),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function f(e,t){return new Promise((s,n)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function m(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const g=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],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},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],y={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",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",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"},_=new Map,x=new Set;for(const e of g)for(const t of e.extensions)_.set(t,e),x.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function b(e){return _.get(w(e))}function v(e){return x.has(e.toLowerCase())}function S(){const e=[];for(const t of g)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function P(e){const t=b(e);return t?.wechatPackInclude??!1}function M(e){const t=b(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}let T=null;function C(){return T||(T=wx.getFileSystemManager()),T}function E(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(P(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return s.includes("no such file")||s.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function A(e){const t=C();try{return t.accessSync(e),!0}catch{return!1}}function R(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function I(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const i=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(i.data.buffer)}}async function F(e){return I(await R(e))}let k=!1;const B=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return f(e,t)}async readFile(e){return function(e){return C().readFileSync(e)}(M(e))}async readTextFile(e){return function(e,t="utf-8"){return C().readFileSync(e,t)}(M(e))}async fileExists(e){return A(M(e))}async loadImagePixels(e){return F(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return m(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t=>e.onKeyDown(t.code),n=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(s),wx.onKeyUp(n));const o=t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)},r=t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)},a=t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(s),wx.offKeyUp(n)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new p}getStorageItem(e){try{const t=wx.getStorageSync(e);return"string"==typeof t?t:null}catch{return null}}setStorageItem(e,t){try{wx.setStorageSync(e,t)}catch{}}removeStorageItem(e){try{wx.removeStorageSync(e)}catch{}}clearStorage(e){try{const{keys:t}=wx.getStorageInfoSync();for(const s of t)s.startsWith(e)&&wx.removeStorageSync(s)}catch{}}},D=1920,L=1080,U=1/60,W={x:0,y:-9.81},z=1/60,$={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const O={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function H(e,t){if(void 0!==t.maxDeltaTime&&($.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&($.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&($.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&($.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&($.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");$.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&&($.canvasScaleMode=O[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&($.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const V=4294967295,N=4294967295;function j(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(j);const t={};for(const s in e)t[s]=j(e[s]);return t}let X=0;function Y(e,t){const s=++X,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?{...j(t),...e}:j(t):e?{...t,...e}:{...t}}}function G(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function q(e,t){const s=Z.get(e)??G().get(e);if(s)return s;const n=Y(e,t);return G().set(e,n),Z.set(e,n),J(e,t,!1),n}function K(e){return G().get(e)}function J(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function Q(e){return!0===e._builtin}const Z=new Map;function ee(e,t){Z.set(e,t)}function te(e){return Z.get(e)??K(e)}function se(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Z.set(e,s),s}const ne={Perspective:0,Orthographic:1},ie={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},oe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},re=se("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}}),ae=re,le=re,ce=se("Sprite",{texture:V,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}),ue=se("Camera",{projectionType:ne.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:ie.ColorAndDepth}),de=se("Canvas",{designResolution:{x:D,y:L},pixelsPerUnit:100,scaleMode:oe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),he=se("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),pe=se("Parent",{entity:0}),fe=se("Children",{entities:[]}),me=se("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:N,enabled:!0}),ge=se("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}),ye={Point:0,Circle:1,Rectangle:2,Cone:3},_e={World:0,Local:1},xe={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},we=se("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:ye.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:xe.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:xe.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:V,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:_e.World,enabled:!0}),be=q("Name",{value:""}),ve=q("SceneOwner",{scene:"",persistent:!1}),Se=q("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});const Pe=se("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Me=se("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Te=se("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ce=se("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ee={Static:0,Kinematic:1,Dynamic:2};let Ae=0;function Re(e,t){const s=++Ae;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Ie(e){return{_type:"res",_resource:e}}function Fe(e){return{_type:"res_mut",_resource:e}}class ke{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 ke(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const De=Re({delta:0,elapsed:0,frameCount:0},"Time"),Le="esengine:",Ue={getString(e,s){const n=t().getStorageItem(Le+e);return null!==n?n:s},setString(e,s){t().setStorageItem(Le+e,s)},getNumber(e,s){const n=t().getStorageItem(Le+e);if(null===n)return s;const i=Number(n);return Number.isNaN(i)?s:i},setNumber(e,s){t().setStorageItem(Le+e,String(s))},getBoolean(e,s){const n=t().getStorageItem(Le+e);return null===n?s:"true"===n},setBoolean(e,s){t().setStorageItem(Le+e,String(s))},getJSON(e,s){const n=t().getStorageItem(Le+e);if(null===n)return s;try{return JSON.parse(n)}catch{return s}},setJSON(e,s){t().setStorageItem(Le+e,JSON.stringify(s))},remove(e){t().removeStorageItem(Le+e)},has:e=>null!==t().getStorageItem(Le+e),clear(){t().clearStorage(Le)}};function We(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=ze(t[e]),o=ze(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function ze(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function $e(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 Oe=null;function He(e){Oe=e}function Ve(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Oe&&Oe(e,t)}function Ne(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 je=1;const Xe=new WeakMap;function Ye(e){let t=Xe.get(e);return void 0===t&&(t=je++,Xe.set(e,t)),t}const Ge=[];function qe(e,t=[],s=[]){Ge.length=0;for(const t of e)Ge.push(Ye(t));Ge.sort((e,t)=>e-t);let n=Ge.join(",");if(t.length>0){Ge.length=0;for(const e of t)Ge.push(Ye(e));Ge.sort((e,t)=>e-t),n+="|+"+Ge.join(",")}if(s.length>0){Ge.length=0;for(const e of s)Ge.push(Ye(e));Ge.sort((e,t)=>e-t),n+="|-"+Ge.join(",")}return n}class Ke{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 Ve(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){Ve(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){Ve(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ve(t,`removeParent(entity=${e})`)}}insert(e,t,s){return Q(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(Q(t)){if(this.cppRegistry_)try{const n=t._default,i=s;let o=i;for(const e of Object.keys(i))e in n||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,Ne(o))}catch(s){Ve(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 Q(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Q(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Q(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Ve(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.");Q(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=t._default,i={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&e in n&&(i[e]=t);const e=We(t._name,n,i);if(e.length>0)throw new Error($e(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);r=!s.has(e),s.add(e,Ne(o))}catch(s){Ve(s,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}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 Ve(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 Ve(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ve(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=We(t._name,t._default,e);if(i.length>0)throw new Error($e(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 Z)if(Q(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=G();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??qe(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(!Q(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 Je(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Qe(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Ze(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function et(e){return Je(e)||Qe(e)||Ze(e)?e._component:e}function tt(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{Je(e)&&n.push(t),Qe(e)?i.push({index:t,component:e._component}):Ze(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>tt(e,[...t,...n],s),without:(...n)=>tt(e,t,[...s,...n])}}function st(...e){return tt(e)}class nt{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(et),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_=qe(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 u of s)if(!o||this.passesChangeFilters_(u)){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]=u;for(let e=0;e<n;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}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}}class it{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_)}}class ot{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=Q(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 rt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ot(this,null);return this.spawned_.push(e),e}entity(e){return new ot(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)}}}class at{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 lt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new at)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new at,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class ct{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class ut{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var dt;function ht(){return{_type:"get_world"}}exports.Schedule=void 0,(dt=exports.Schedule||(exports.Schedule={}))[dt.Startup=0]="Startup",dt[dt.First=1]="First",dt[dt.PreUpdate=2]="PreUpdate",dt[dt.Update=3]="Update",dt[dt.PostUpdate=4]="PostUpdate",dt[dt.Last=5]="Last",dt[dt.FixedPreUpdate=10]="FixedPreUpdate",dt[dt.FixedUpdate=11]="FixedUpdate",dt[dt.FixedPostUpdate=12]="FixedPostUpdate";let pt=0;function ft(e,t,s){const n=++pt;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function mt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}class gt{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 rt&&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 nt(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 rt(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 ct(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new ut(s)}case"removed":{const t=e;return new it(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class yt{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 _t=Re(new yt,"Input");class xt{constructor(e){this.target_=e??null}build(e){const s=new yt;e.insertResource(_t,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(exports.Schedule.Last,ft([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const wt=new xt,bt=Re({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 vt;function St(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(vt=exports.BlendMode||(exports.BlendMode={}))[vt.Normal=0]="Normal",vt[vt.Additive=1]="Additive",vt[vt.Multiply=2]="Multiply",vt[vt.Screen=3]="Screen",vt[vt.PremultipliedAlpha=4]="PremultipliedAlpha";let Pt=null,Mt=null,Tt=1;const Ct=new Map;function Et(e){Pt=e,Mt=e.getResourceManager(),Wt()}function At(){0!==kt&&Pt&&(Pt._free(kt),kt=0),Ct.clear(),Tt=1,Ft=!1,Dt.clear(),Lt=null,Mt=null,Pt=null}function Rt(){if(!Mt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Mt}const It={createShader:(e,t)=>Rt().createShader(e,t),releaseShader(e){e>0&&Rt().releaseShader(e)},create(e){const t=Tt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.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 Ct.set(t,s),t},get:e=>Ct.get(e),setUniform(e,t,s){const n=Ct.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,Pt?.invalidateMaterialCache(e))},getUniform(e,t){const s=Ct.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ct.get(e);s&&(s.blendMode=t,Pt?.invalidateMaterialCache(e))},getBlendMode(e){const t=Ct.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ct.get(e);s&&(s.depthTest=t,Pt?.invalidateMaterialCache(e))},getShader(e){const t=Ct.get(e);return t?.shader??0},release(e){Ct.delete(e),Pt?.invalidateMaterialCache(e)},isValid:e=>Ct.has(e),releaseAll(){Ct.clear(),Pt?.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??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ct.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Tt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ct.set(s,n),s},toAssetData(e,t){const s=Ct.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=Ct.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ft=!1,kt=0;const Bt=16384,Dt=new Map;let Lt=null;function Ut(e){const t=(0===kt&&Pt&&(kt=Pt._malloc(Bt)),kt);if(0===t||!Pt)return{ptr:0,count:0};let s=0,n=0;const i=Pt.HEAPU8,o=Pt.HEAPU32,r=Pt.HEAPF32;for(const[a,l]of e){if(St(l))continue;let e=Dt.get(a);e||(Lt||(Lt=new TextEncoder),e=Lt.encode(a),Dt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>Bt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${Bt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=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?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)r[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Wt(){if(!Pt||Ft)return;Pt.materialDataProvider=(e,t,s,n,i)=>{const o=Ct.get(e);if(!o)return Pt.HEAPU32[t>>2]=0,Pt.HEAPU32[s>>2]=0,Pt.HEAPU32[n>>2]=0,void(Pt.HEAPU32[i>>2]=0);Pt.HEAPU32[t>>2]=o.shader,Pt.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Ut(o.uniforms);Pt.HEAPU32[n>>2]=r,Pt.HEAPU32[i>>2]=a},Ft=!0}const zt={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 $t{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const n=t(),i=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{r.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+5e3}),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(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Ot{constructor(e,t=""){this.cache_=new $t,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&&(It.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())It.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await r(t))throw new Error(`Material file not found: ${t}`);const s=await o(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),a=await this.shaderLoader_.load(i);return{handle:It.createFromAsset(n,a),shaderHandle:a,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 Ht(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function Vt(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:s.get(e.texture)??0};if(e.atlasFrame){const s=e.atlasFrame;t.uvOffset={x:s.x/s.pageWidth,y:1-(s.y+s.height)/s.pageHeight},t.uvScale={x:s.width/s.pageWidth,y:s.height/s.pageHeight}}return t})}}const Nt=new Map;function jt(e){Nt.set(e.name,e)}const Xt=q("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Yt(e,t){const s=e.getEntitiesWithComponents([Xt]);for(const n of s){const s=e.get(n,Xt);if(!s.enabled||!s.playing||!s.clip)continue;const i=Nt.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,ce)){const t=i.frames[s.currentFrame],o=e.get(n,ce);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(n,ce,o)}a&&e.insert(n,Xt,s)}}class Gt{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 async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const s=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,s)}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 stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}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}}}}Gt.mixer_=null,Gt.bufferCache_=new Map,Gt.bgmHandle_=null,Gt.bgmVolume_=1,Gt.fadeAnimId_=0,Gt.disposed_=!1;const qt=new Map,Kt=new Map;function Jt(e,t,s){qt.set(e,{width:t,height:s})}function Qt(e){return qt.get(e)}function Zt(){qt.clear()}function es(e,t){Kt.set(e,t)}function ts(e){return Kt.get(e)}let ss=null;function ns(e){ss=e}function is(){ss=null}const os={initLayer(e,t,s,n,i){ss?.tilemap_initLayer(e,t,s,n,i)},destroyLayer(e){ss?.tilemap_destroyLayer(e)},setTile(e,t,s,n){ss?.tilemap_setTile(e,t,s,n)},getTile:(e,t,s)=>ss?ss.tilemap_getTile(e,t,s):0,fillRect(e,t,s,n,i,o){ss?.tilemap_fillRect(e,t,s,n,i,o)},setTiles(e,t){if(!ss)return;const s=t.byteLength,n=ss._malloc(s);new Uint16Array(ss.HEAPU8.buffer,n,t.length).set(t),ss.tilemap_setTiles(e,n,t.length),ss._free(n)},hasLayer:e=>!!ss&&ss.tilemap_hasLayer(e),submitLayer(e,t,s,n,i,o,r,a,l,c,u,d,h,p,f,m,g,y,_,x){ss?.tilemap_submitLayer(e,t,s,n,i,o,r,a,l,c,u,d,h,p,f,m,g,y,_,x)}},rs=q("Tilemap",{source:""}),as=q("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function ls(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function cs(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function us(e,t){if(0===e)return 0;let s=0;2147483648&e&&(s|=8192),1073741824&e&&(s|=16384),536870912&e&&(s|=32768);return(536870911&e)-t+1|s}function ds(e){const t=e.width,s=e.height,n=e.tilewidth??0,i=e.tileheight??0;if(!(t&&s&&n&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??n,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const n=e.width??t,i=e.height??s,o=!1!==e.visible,r=e.data,l=new Uint16Array(n*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=us(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,d=cs(e.tintcolor),h="number"==typeof e.parallaxx?e.parallaxx:1,p="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:n,height:i,visible:o,tiles:l,opacity:u,tintColor:d,parallaxX:h,parallaxY:p})}const u=[],d=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const s=[];for(const e of t){const t=new Map,n=e.properties;if(n)for(const e of n)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}s.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:s})}if(o)for(const e of o){const t=e.firstgid??1,s=e.tiles;if(s)for(const e of s){const s=e.properties;if(s)for(const n of s)"collision"===n.name&&!0===n.value&&d.push(e.id+t)}}return{width:t,height:s,tileWidth:n,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:d}}function hs(e,t){const s=e.lastIndexOf("/"),n=((s>=0?e.substring(0,s+1):"")+t).split("/"),i=[];for(const e of n)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}const ps=Math.PI/180;function fs(e,t,s,n,i,o){const r=function(e,t,s,n){const i=new Uint8Array(t*s),o=[],r=(o,r)=>{if(o>=t||r>=s)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&n.has(l)};for(let e=0;e<s;e++)for(let n=0;n<t;n++){if(!r(n,e))continue;let a=1;for(;r(n+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=s)break;for(let e=0;e<a;e++)if(!r(n+e,t)){c=!1;break}c&&l++}for(let s=0;s<l;s++)for(let o=0;o<a;o++)i[(e+s)*t+(n+o)]=1;o.push({col:n,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,n),a=[],l=s.tileWidth,c=s.tileHeight,u=s.height*c;for(const t of r){const s=t.width*l,n=t.height*c,r=i+t.col*l+.5*s,d=o+(u-t.row*c)-.5*n,h=e.spawn();e.insert(h,re,{position:{x:r,y:d,z:0}}),e.insert(h,Pe,{bodyType:Ee.Static}),e.insert(h,Me,{halfExtents:{x:.5*s,y:.5*n}}),a.push(h)}return a}const ms=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"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function gs(e){const t=ms.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 ys(e){return ms.get(e)?.fields??[]}function _s(e){return ms.get(e)?.spine??null}const xs=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function ws(e){return xs.get(e)}function bs(e,t){const s=xs.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 vs(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,be,{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)bs(i,s),Ts(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 Ss(e,t){return vs(e,t)}async function Ps(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 Ms.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=ms.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=[...Ms.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),u=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,...u]),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=ms.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=vs(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 Ms=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),Jt(r.handle,r.width,r.height)}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=Ht(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);jt(Vt(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 Gt.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=ds(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=hs(e,r.image);let a=0;try{const e=s?`${s}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,n.set(i,e),Jt(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}es(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Ts(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=te(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 Cs(e,t){const s=e.getEntitiesWithComponents([ue]);for(const n of s){const s=e.get(n,ue);s&&(s.aspectRatio=t,e.insert(n,ue,s))}}class Es{constructor(e){this.textureCache_=new $t,this.shaderCache_=new $t,this.jsonCache_=new $t,this.textCache_=new $t,this.binaryCache_=new $t,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new $t,this.prefabCache_=new $t,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_=l($.textCanvasSize,$.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 Ot(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(),It.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),u="binary"===b(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);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=b(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 gs(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=_s(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 Ps(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 It.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await r(t))throw new Error(`Shader file not found: ${e}`);const n=await o(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return It.createShader(i,a)}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(M(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 o(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(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 o(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(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 i(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(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 As=Re(null,"Assets");class Rs{build(e){const t=e.wasmModule;t?e.insertResource(As,new Es(t)):console.warn("AssetPlugin: No WASM module available")}}const Is=new Rs;async function Fs(e,t,s){const{entities:n,rootId:i}=await Bs(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 Ps(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 ks=10;async function Bs(e,t,s,n,i,o=0){if(o>ks)throw new Error(`Prefab nesting depth exceeded ${ks}. 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 Bs(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),u=n.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?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};Ds(d.components,r),Ls(d,t),l.push(d)}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 Ds(e,t){for(const s of e){const e=ws(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 Ls(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 Us{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 Fs(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Ws=Re(null,"Prefabs");class zs{constructor(){this.name="PrefabsPlugin",this.dependencies=[As]}build(e){const t=e.getResource(As);e.insertResource(Ws,new Us(e.world,t))}}const $s=new zs;let Os=null,Hs=0,Vs=0,Ns=0;const js=new Float32Array(256);function Xs(e){Os=e,Hs=Os._malloc(64),Vs=Os._malloc(64),Ns=Os._malloc(1024)}function Ys(){Os&&(Hs&&(Os._free(Hs),Hs=0),Vs&&(Os._free(Vs),Vs=0),Ns&&(Os._free(Ns),Ns=0)),Os=null}function Gs(){if(!Os)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Os}const qs={r:1,g:1,b:1,a:1},Ks={begin(e){const t=Gs();try{t.HEAPF32.set(e,Hs/4),t.draw_begin(Hs)}catch(e){Ve(e,"Draw.begin")}},end(){try{Gs().draw_end()}catch(e){Ve(e,"Draw.end")}},line(e,t,s,n=1){try{Gs().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ve(e,"Draw.line")}},rect(e,t,s,n=!0){try{Gs().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ve(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Gs().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ve(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{Gs().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ve(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{Gs().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ve(e,"Draw.circleOutline")}},texture(e,t,s,n=qs){try{Gs().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ve(e,"Draw.texture")}},textureRotated(e,t,s,n,i=qs){try{Gs().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){Ve(e,"Draw.textureRotated")}},setLayer(e){Gs().draw_setLayer(e)},setDepth(e){Gs().draw_setDepth(e)},getDrawCallCount:()=>Os?Os.draw_getDrawCallCount():0,getPrimitiveCount:()=>Os?Os.draw_getPrimitiveCount():0,setBlendMode(e){Gs().draw_setBlendMode(e)},setDepthTest(e){Gs().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Gs();n.HEAPF32.set(s,Vs/4),n.draw_mesh(e,t,Vs)}catch(s){Ve(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Gs(),i=It.get(t);if(!i)return;if(Ks.setBlendMode(i.blendMode),Ks.setDepthTest(i.depthTest),0===i.uniforms.size)return void Ks.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,Vs/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=Zs(t);if(!(n<0)){if(St(s))js[o++]=10,js[o++]=n,js[o++]=s.slot??e++,js[o++]=s.textureId;else if("number"==typeof s)js[o++]=1,js[o++]=n,js[o++]=s;else if(Array.isArray(s)){js[o++]=s.length,js[o++]=n;for(let e=0;e<s.length;e++)js[o++]=s[e]}else"w"in s?(js[o++]=4,js[o++]=n,js[o++]=s.x,js[o++]=s.y,js[o++]=s.z,js[o++]=s.w):"z"in s?(js[o++]=3,js[o++]=n,js[o++]=s.x,js[o++]=s.y,js[o++]=s.z):(js[o++]=2,js[o++]=n,js[o++]=s.x,js[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(js.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,Vs);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Ns/4),n.draw_meshWithUniforms(e,i.shader,Vs,Ns,o)}catch(s){Ve(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Js={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},Qs=new Set;function Zs(e){const t=Js[e];return void 0!==t?t:(Qs.has(e)||(Qs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Js).join(", ")}`)),-1)}const en=new Map;function tn(e,t,s){en.set(e,{fn:t,scene:s??""})}function sn(e){en.delete(e)}function nn(){en.clear()}var on;exports.DataType=void 0,(on=exports.DataType||(exports.DataType={}))[on.Float=1]="Float",on[on.Float2=2]="Float2",on[on.Float3=3]="Float3",on[on.Float4=4]="Float4",on[on.Int=5]="Int",on[on.Int2=6]="Int2",on[on.Int3=7]="Int3",on[on.Int4=8]="Int4";let rn=null,an=0,ln=0,cn=0;function un(e){rn=e,an=rn._malloc(262144),ln=rn._malloc(65536),cn=rn._malloc(256)}function dn(){rn&&(an&&rn._free(an),ln&&rn._free(ln),cn&&rn._free(cn),an=0,ln=0,cn=0),rn=null}function hn(){if(!rn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return rn}const pn={create(e){const t=hn(),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,an/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,cn,i).set(o),t.geometry_init(s,an,n,cn,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,ln,n).set(e.indices),t.geometry_setIndices16(s,ln,n)}else{new Uint32Array(t.HEAPU8.buffer,ln,n).set(e.indices),t.geometry_setIndices32(s,ln,n)}}return s},updateVertices(e,t,s=0){const n=hn(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,an/4),n.geometry_updateVertices(e,an,i,s)},release(e){e>0&&hn().geometry_release(e)},isValid:e=>!(!rn||e<=0)&&rn.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return pn.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:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.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 pn.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.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 pn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(r)})}};let fn=1;const mn=new Map,gn=new Map;function yn(){return mn}function _n(){return gn}class xn{constructor(){this.passes_=[],this.destroyed_=!1,this.id=fn++,mn.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const s=this.passes_.find(t=>t.name===e);return s&&(s.enabled=t),this}setUniform(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.floatUniforms.set(t,s),this}setUniformVec4(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.vec4Uniforms.set(t,{...s}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of gn)t===this&&gn.delete(e);mn.delete(this.id)}}}const wn="#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";let bn=null;function vn(e){bn=e}function Sn(){for(const e of yn().values())e.destroy();yn().clear(),_n().clear(),bn&&Mn.isInitialized()&&Mn.shutdown(),bn=null}function Pn(){if(!bn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return bn}const Mn={createStack:()=>new xn,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");_n().set(e,t)},unbind(e){_n().delete(e)},getStack:e=>_n().get(e)??null,init(e,t){try{return Pn().postprocess_init(e,t)}catch(s){return Ve(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Pn().postprocess_shutdown()}catch(e){Ve(e,"PostProcess.shutdown")}},resize(e,t){try{Pn().postprocess_resize(e,t)}catch(s){Ve(s,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!bn)return!1;try{return bn.postprocess_isInitialized()}catch(e){return Ve(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Pn().postprocess_setBypass(e)}catch(e){Ve(e,"PostProcess.setBypass")}},setOutputViewport(e,t,s,n){try{Pn().postprocess_setOutputViewport(e,t,s,n)}catch(e){Ve(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=_n().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(Mn.isInitialized()||Mn.init(1,1),Mn.setBypass(!1),function(e){const t=Pn();try{t.postprocess_clearPasses()}catch(e){return void Ve(e,"PostProcess._applyForCamera:clearPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addPass(s.name,s.shader)}catch(e){Ve(e,`PostProcess._applyForCamera:addPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setUniformFloat(s.name,e,n)}catch(t){Ve(t,`PostProcess._applyForCamera:setUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Ve(t,`PostProcess._applyForCamera:setUniformVec4("${s.name}", "${e}")`)}}}(t)):Mn.setBypass(!0)},_resetAfterCamera(){try{Pn().postprocess_clearPasses(),Pn().postprocess_setBypass(!0)}catch(e){Ve(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of _n().keys())e(t)||_n().delete(t)},screenStack:null,setScreenStack(e){Mn.screenStack=e},_beginScreenCapture(){try{Pn().postprocess_beginScreenCapture()}catch(e){Ve(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{Pn().postprocess_endScreenCapture()}catch(e){Ve(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=Mn.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=Pn();try{t.postprocess_clearScreenPasses()}catch(e){return void Ve(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addScreenPass(s.name,s.shader)}catch(e){Ve(e,`PostProcess._applyScreenStack:addScreenPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setScreenUniformFloat(s.name,e,n)}catch(t){Ve(t,`PostProcess._applyScreenStack:setScreenUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Ve(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${s.name}", "${e}")`)}}},_executeScreenPasses(){try{Pn().postprocess_executeScreenPasses()}catch(e){Ve(e,"PostProcess._executeScreenPasses")}},createBlur:()=>It.createShader(wn,"#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:()=>It.createShader(wn,"#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:()=>It.createShader(wn,"#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"),createBloom:()=>It.createShader(wn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>It.createShader(wn,"#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")},Tn=new Map;function Cn(e){Tn.set(e.type,e)}function En(e){return Tn.get(e)}Cn({type:"blur",label:"Blur",factory:()=>Mn.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),Cn({type:"bloom",label:"Bloom",factory:()=>Mn.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),Cn({type:"vignette",label:"Vignette",factory:()=>Mn.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),Cn({type:"grayscale",label:"Grayscale",factory:()=>Mn.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),Cn({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>Mn.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const An=new Map,Rn=new Map;function In(e){const t=An.get(e);t&&(Mn.unbind(e),t.destroy(),An.delete(e));const s=Rn.get(e);if(s){for(const e of s.values())It.releaseShader(e);Rn.delete(e)}}function Fn(){for(const e of An.keys())In(e)}const kn=Re({enabled:!0},"PostProcessVolumeConfig"),Bn=new Map,Dn=new Map;function Ln(e){const t=Dn.get(e);if(void 0!==t)return t;const s=En(e);if(!s)return null;const n=s.factory();return Dn.set(e,n),n}function Un(e,t){if(0===t.size){const t=Bn.get(e);return void(t&&(Mn.unbind(e),t.destroy(),Bn.delete(e)))}let s=Bn.get(e);for(s||(s=Mn.createStack(),Bn.set(e,s));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const[e,n]of t){if(!n.enabled)continue;const t=Ln(e);if(null!==t){s.addPass(e,t);for(const[t,i]of n.uniforms)s.setUniform(e,t,i)}}s.enabledPassCount>0?Mn.bind(e,s):Mn.unbind(e)}const Wn=ft([st(Se,re)],e=>{const t=[];for(const[s,n,i]of e)t.push({data:n,tx:{x:i.position.x,y:i.position.y}});if(0===t.length)return;const s=[];for(const{data:e,tx:n}of t)e.isGlobal&&s.push({data:e,factor:1});if(s.length>0){const e=function(e){const t=new Map,s=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:n}of s)if(!(n<=0))for(const s of e.effects){if(!s.enabled)continue;const e=t.get(s.type);if(e)for(const[t,i]of Object.entries(s.uniforms)){const s=e.uniforms.get(t)??0;e.uniforms.set(t,s+(i-s)*n)}else{const e=new Map;for(const[t,i]of Object.entries(s.uniforms))e.set(t,i*n);t.set(s.type,{enabled:!0,uniforms:e})}}return t}(s);for(const[t]of Bn)Un(t,e)}},{name:"PostProcessVolumeSystem"});class zn{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(kn,{enabled:!0}),e.addSystemToSchedule(exports.Schedule.PostUpdate,Wn)}cleanup(){Fn(),function(){for(const[e,t]of Bn)Mn.unbind(e),t.destroy();Bn.clear();for(const e of Dn.values())It.releaseShader(e);Dn.clear()}(),Mn.setScreenStack(null)}}const $n=new zn;var On;exports.RenderStage=void 0,(On=exports.RenderStage||(exports.RenderStage={}))[On.Background=0]="Background",On[On.Opaque=1]="Opaque",On[On.Transparent=2]="Transparent",On[On.Overlay=3]="Overlay";let Hn=null,Vn=0;function Nn(e){Hn=e,Vn=Hn._malloc(64)}function jn(){Hn&&Vn&&(Hn._free(Vn),Vn=0),Hn=null}const Xn={init(e,t){Hn?.renderer_init(e,t)},resize(e,t){Hn?.renderer_resize(e,t)},begin(e,t){if(Hn&&Vn)try{Hn.HEAPF32.set(e,Vn/4),Hn.renderer_begin(Vn,t??0)}catch(e){Ve(e,"Renderer.begin")}},flush(){try{Hn?.renderer_flush()}catch(e){Ve(e,"Renderer.flush")}},end(){try{Hn?.renderer_end()}catch(e){Ve(e,"Renderer.end")}},submitSprites(e){if(Hn)try{Hn.renderer_submitSprites(e._cpp)}catch(e){Ve(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Hn)try{Hn.renderer_submitBitmapText(e._cpp)}catch(e){Ve(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Hn)try{Hn.renderer_submitSpine?.(e._cpp)}catch(e){Ve(e,"Renderer.submitSpine")}},submitParticles(e){if(Hn)try{Hn.renderer_submitParticles?.(e._cpp)}catch(e){Ve(e,"Renderer.submitParticles")}},setStage(e){Hn?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Hn?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Hn?.renderer_releaseTarget(e)},getTargetTexture:e=>Hn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Hn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Hn?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Hn?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){Hn?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){Hn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Hn?Hn.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Hn?{drawCalls:Hn.renderer_getDrawCalls(),triangles:Hn.renderer_getTriangles(),sprites:Hn.renderer_getSprites(),text:Hn.renderer_getText(),spine:Hn.renderer_getSpine?.()??0,meshes:Hn.renderer_getMeshes(),culled:Hn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Yn=null;function Gn(e){Yn=e}function qn(){Yn=null}const Kn={enable(){Yn?.gl_enableErrorCheck(!0)},disable(){Yn?.gl_enableErrorCheck(!1)},check:e=>Yn?.gl_checkErrors(e)??0,diagnose(){Yn?.renderer_diagnose()}};class Jn{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}beginScreenCapture(){Mn.screenStack&&Mn.screenStack.enabledPassCount>0&&(Mn.isInitialized()||Mn.init(1,1),Mn._applyScreenStack(),Mn._beginScreenCapture())}endScreenCapture(){Mn.screenStack&&Mn.screenStack.enabledPassCount>0&&(Mn._endScreenCapture(),Mn._executeScreenPasses())}render(e){const{registry:t,viewProjection:s,width:n,height:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Xn.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Xn.setViewport(0,0,n,i),Xn.clearBuffers(3),Xn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),this.tilemapRenderer_&&this.tilemapRenderer_(),Xn.submitSprites(t),Xn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Xn.submitSpine(t),Xn.submitParticles(t),Xn.flush(),this.executeDrawCallbacks(s,o),Xn.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==Mn.getStack(r);a&&(Mn._applyForCamera(r),Mn.resize(n.w,n.h),Mn.setOutputViewport(n.x,n.y,n.w,n.h)),Xn.setViewport(n.x,n.y,n.w,n.h),Xn.setScissor(n.x,n.y,n.w,n.h,!0),Xn.clearBuffers(i),Xn.setScissor(0,0,0,0,!1),Xn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),this.tilemapRenderer_&&this.tilemapRenderer_(),Xn.submitSprites(t),Xn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Xn.submitSpine(t),Xn.submitParticles(t),Xn.flush(),this.executeDrawCallbacks(s,o),Xn.end(),a&&Mn._resetAfterCamera()}executeDrawCallbacks(e,t){const s=en;if(s.size>0){Ks.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)}Ks.end();for(const e of n)sn(e)}}}const Qn="__scene_transition_overlay__";class Zn{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class ei{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,ve,{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),tn(e,t,this.instance_.config.name)}bindPostProcess(e,t){Mn.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){Mn.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,ve)){const s=this.app_.world.get(e,ve);s.persistent=t,this.app_.world.insert(e,ve,s)}}}class ti{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}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())sn(t);for(const t of e.postProcessBindings.keys())Mn.unbind(t)}this.transition_&&(sn(Qn),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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??$.sceneTransitionDuration,i=t.color??{...$.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},tn(Qn,()=>{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;Ks.setLayer(9999),Ks.setDepth(9999),Ks.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,sn(Qn),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,sn(Qn),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 Zn(t);this.scenes_.set(e,s);const n=new ei(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(As)?this.app_.getResource(As):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 Zn(t);this.scenes_.set(e,s);const n=new ei(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(As)?this.app_.getResource(As):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,ve)){if(this.app_.world.get(e,ve).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())sn(e);s.drawCallbacks.clear();for(const e of s.postProcessBindings.keys())Mn.unbind(e);s.postProcessBindings.clear(),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(As)&&(i.assetServer=this.app_.getResource(As));const o=await Ps(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,ve,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=ni(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(As)?this.app_.getResource(As):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)It.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,ce)){const t=s.get(e,ce);n.sprite=t.color.a,t.color.a=0,s.insert(e,ce,t),i=!0}if(s.has(e,ge)){const t=s.get(e,ge);n.spine=t.color.a,t.color.a=0,s.insert(e,ge,t),i=!0}if(s.has(e,me)){const t=s.get(e,me);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,me,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,ce)){const t=s.get(e,ce);t.color.a=n.sprite,s.insert(e,ce,t)}if(void 0!==n.spine&&s.has(e,ge)){const t=s.get(e,ge);t.color.a=n.spine,s.insert(e,ge,t)}if(void 0!==n.bitmapText&&s.has(e,me)){const t=s.get(e,me);t.color.a=n.bitmapText,s.insert(e,me,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessBindings.values())s.setAllPassesEnabled(t)}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 si=Re(null,"SceneManager");function ni(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(si).getSceneStatus(t)&&s._fn(...n)}}}const ii=ft([Fe(si),Ie(De)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),oi={name:"SceneManager",build(e){const t=new ti(e);e.insertResource(si,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(si),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,ii)}};class ri{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 lt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=c(),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(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Ke,this.resources_=new Be;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ri}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(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.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 He(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.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}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(si).register(e),this}setInitialScene(e){return this.getResource(si).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new gt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(De)||this.resources_.insert(De,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.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(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new gt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(De,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=c(),this.mainLoop())}quit(){this.running_=!1,nn();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=[qn,jn,Sn,dn,At,Ys];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));const n=this.phaseTimings_?performance.now():0;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)}}this.phaseTimings_&&this.phaseTimings_.set(exports.Schedule[e],performance.now()-n)}updateTime(e){const t=this.resources_.get(De);t.delta=e,t.elapsed+=e,t.frameCount++}}function ai(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 li=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ci(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case oe.FixedWidth:return o;case oe.FixedHeight:return r;case oe.Expand:return Math.max(o,r);case oe.Shrink:return Math.min(o,r);case oe.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const ui=[];function di(e){if(e<ui.length)return ui[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 ui.push(t),t}function hi(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,ve);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,u=0,d=0;if(i.projectionType===ne.Orthographic){if(d=i.orthoSize,l){d=ci(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=fi(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=gi(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=_i(o.position.x,o.position.y,o.position.z),p=di(c.length);p.entity=e,p.viewProjection.set(wi(a,h)),p.viewportRect.x=i.viewportX,p.viewportRect.y=i.viewportY,p.viewportRect.w=i.viewportW,p.viewportRect.h=i.viewportH,p.clearFlags=i.clearFlags,p.priority=i.priority,p.halfW=u,p.halfH=d,p.cameraX=o.position.x,p.cameraY=o.position.y,c.push(p)}return c.sort((e,t)=>e.priority-t.priority),c}const pi=new Float32Array(16);function fi(e,t,s,n,i,o){const r=pi;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 mi=new Float32Array(16);function gi(e,t,s,n){const i=mi;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 yi=new Float32Array(16);function _i(e,t,s){const n=yi;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 xi=new Float32Array(16);function wi(e,t){const s=xi;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 bi={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function vi(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,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let p,f,m,g;e.x===t.x?(p=c+s.x-i.x*r.x,m=p+i.x):(p=c+s.x,m=u+n.x),e.y===t.y?(f=d+s.y-i.y*r.y,g=f+i.y):(f=d+s.y,g=h+n.y);const y=Math.max(0,m-p),_=Math.max(0,g-f);return{originX:p+r.x*y,originY:f+r.y*_,width:y,height:_,rect:{left:p,bottom:f,right:m,top:g}}}const Si=se("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 Pi=null,Mi=null;function Ti(e,t){e.has(t,ce)||e.insert(t,ce,{texture:V,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 Ci(e,t){switch(e){case bi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case bi.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case bi.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 Ei(e,t,s,n){if(!e.has(t,Si))return;const i=e.get(t,Si),o=Ci(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,Si,i)}function Ai(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Ri(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Ii(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(Ri(r.charCodeAt(0))&&n.length>0&&Ri(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Ri(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 Fi(e){let t=1;for(;t<e;)t*=2;return t}function ki(e,t){let s=0,n=t;for(;e.has(n,pe);){const t=e.get(n,pe).entity;if(!e.valid(t))break;s++,n=t}return s}function Bi(e,t){if(Pi&&Mi){const e=Pi.getUIRectComputedWidth(Mi,t);if(e>0)return e}return e.size.x}function Di(e,t){if(Pi&&Mi){const e=Pi.getUIRectComputedHeight(Mi,t);if(e>0)return e}return e.size.y}function Li(e,t,s){let n=t;for(;e.has(n,pe);){const t=e.get(n,pe).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Ui(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Wi(e,t,s,n,i){if(!e.has(t,Si))return;const o=e.get(t,Si),r=vi(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,ce)){const s=e.get(t,ce);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,ce,s))}if(e.has(t,re)){const s=e.get(t,re);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,re,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 $i=.1,Oi=30,Hi={r:.3,g:.5,b:.8,a:1},Vi={Left:0,Center:1,Right:2},Ni={Top:0,Middle:1,Bottom:2},ji={Visible:0,Clip:1,Ellipsis:2},Xi=q("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Vi.Left,verticalAlign:Ni.Top,wordWrap:!0,overflow:ji.Visible,lineHeight:1.2});class Yi{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=l($.textCanvasSize,$.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,Fi(this.frameMaxW_)),e.height=Math.max(e.height,Fi(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Fi(this.frameMaxW_),e.height=Fi(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=Ii(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=i?Math.ceil(o):d+2*u,f=i?Math.ceil(r):h+2*u;if(i&&e.overflow===ji.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_,p),this.frameMaxH_=Math.max(this.frameMaxH_,f),(n.width<p||n.height<f)&&(n.width=Math.max(n.width,Fi(p)),n.height=Math.max(n.height,Fi(f)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=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===ji.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case Ni.Top:w=u;break;case Ni.Middle:w=u+(f-2*u-x)/2;break;case Ni.Bottom:w=f-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let b=w;for(const t of l){let n;switch(e.align){case Vi.Left:n=u;break;case Vi.Center:n=p/2;break;case Vi.Right:n=p-u;break;default:n=u}s.fillText(t,n,b),b+=c}i&&e.overflow===ji.Clip&&s.restore();const v=s.getImageData(0,0,p,f),S=new Uint8Array(v.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(p,f,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:p,height:f}}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 Vi.Left:return"left";case Vi.Center:return"center";case Vi.Right:return"right"}}}const Gi=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?Bi(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Di(e.uiRect,e.entity):0});class qi{build(e){ee("Text",Xi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Yi(t),n=e.world,i=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,ft([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Xi));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Xi)){if(n.valid(e)&&n.has(e,ce)){const t=n.get(e,ce);n.insert(e,ce,{texture:V,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([Xi]);for(const t of e){const e=n.get(t,Xi),o=n.has(t,Si)?n.get(t,Si):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Gi.changed(a,r)){if(n.has(t,ce)&&n.get(t,ce).texture!==V)continue}Ti(n,t);const l=o?{size:{x:Bi(o,t),y:Di(o,t)}}:null,c=s.renderForEntity(t,e,l),u=n.get(t,ce);n.insert(t,ce,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,Gi.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ki=new qi,Ji=0,Qi=1,Zi=se("UIMask",{enabled:!0,mode:Ji});function eo(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 to(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],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],m=e[12],g=e[13],y=e[14],_=e[15],x=n*l-i*a,w=n*c-o*a,b=n*u-r*a,v=i*c-o*l,S=i*u-r*l,P=o*u-r*c,M=d*g-h*m,T=d*y-p*m,C=d*_-f*m,E=h*y-p*g,A=h*_-f*g,R=p*_-f*y;let I=x*R-w*A+b*E+v*C-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*R-c*A+u*E)*I,s[1]=(o*A-i*R-r*E)*I,s[2]=(g*P-y*S+_*v)*I,s[3]=(p*S-h*P-f*v)*I,s[4]=(c*C-a*R-u*T)*I,s[5]=(n*R-o*C+r*T)*I,s[6]=(y*b-m*P-_*w)*I,s[7]=(d*P-p*b+f*w)*I,s[8]=(a*A-l*C+u*M)*I,s[9]=(i*C-n*A-r*M)*I,s[10]=(m*S-g*b+_*x)*I,s[11]=(h*b-d*S-f*x)*I,s[12]=(l*T-a*E-c*M)*I,s[13]=(n*E-i*T+o*M)*I,s[14]=(g*w-m*v-y*x)*I,s[15]=(d*v-h*w+p*x)*I),s}function so(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],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function no(e,t){return 2*Math.atan2(e,t)}function io(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 oo(e,t,s,n,i,o,r){if(!e.has(t,Si)||!e.has(t,re))return null;const a=e.get(t,Si),l=e.get(t,re),c=Bi(a,t)*l.worldScale.x,u=Di(a,t)*l.worldScale.y,d=l.worldPosition.x,h=l.worldPosition.y,p=a.pivot.x,f=a.pivot.y,m=-c*p,g=c*(1-p),y=-u*f,_=u*(1-f),x=no(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),b=Math.sin(x),v=[[d+m*w-y*b,h+m*b+y*w],[d+g*w-y*b,h+g*b+y*w],[d+g*w-_*b,h+g*b+_*w],[d+m*w-_*b,h+m*b+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of v){const[a,l]=io(e,t,s,n,i,o,r);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function ro(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Zi]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const s=t.get(e,Zi);s.enabled&&(d.add(e),s.mode===Qi?(u.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,i,o,r,a,l,c){const u=[];for(const e of n){let s=!0;Li(t,e,e=>{if(i.has(e)){if(t.get(e,Zi).mode===Ji)return s=!1,!0}return!1}),s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(i.has(s)){if(t.get(s,Zi).mode===Ji){const e=oo(t,s,o,r,a,l,c);e&&(n=eo(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=oo(t,e,o,r,a,l,c);s&&d(e,s)}}(e,t,s,c,d,n,i,o,r,a),u.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Li(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),u(t,n)}function u(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),u(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,u,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class ao{build(e){if(ee("UIMask",Zi),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ro(e.wasmModule,e.world))}}const lo=new ao,co=se("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),uo=se("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),ho={Normal:0,Hovered:1,Pressed:2,Disabled:3},po=q("Button",{state:ho.Normal,transition:null});class fo{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 mo=Re(new fo,"UIEvents");class go{build(e){ee("UIRect",Si);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){Pi=e,Mi=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,ft([Ie(bt)],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(exports.Schedule.PostUpdate,ft([Ie(bt)],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(exports.Schedule.PostUpdate,ft([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const yo=new go;let _o=!1,xo=!1;function wo(){return _o}function bo(){return xo}const vo=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&&(to(t,e),s=!1),e)}}();function So(e,t,s,n){t.emit(s,n,s),Li(e,s,i=>{if(!e.has(i,co))return!1;const o=e.get(i,co);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Po{build(e){ee("Interactable",co),ee("Button",po);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new fo;e.insertResource(mo,i);let o=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,ft([Ie(_t),Ie(bt)],(e,a)=>{if(i.drain(),wo()&&!bo())return;const l=t.getEntitiesWithComponents([uo]);for(const e of l){const s=t.get(e,uo);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,uo,s))}if(!a.valid)return;const c=u(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;vo.update(a.viewProjection);const p=so(d,h,vo.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=p.x,a.worldMouseY=p.y;const f=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);s.uiHitTest_update(n,p.x,p.y,f,m,g);const y=s.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,uo)){const e=t.get(o,uo);e.hovered=!1,t.insert(o,uo,e),i.emit(o,"hover_exit")}if(null!==_){Ui(t,_,uo);const e=t.get(_,uo);e.hovered=!0,t.insert(_,uo,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,uo);e.pressed=!0,e.justPressed=!0,t.insert(_,uo,e),r=_,So(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,uo)){const e=t.get(r,uo);e.pressed=!1,e.justReleased=!0,t.insert(r,uo,e),So(t,i,r,"release"),r===o&&So(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,ft([],()=>{const e=t.getEntitiesWithComponents([po]);for(const s of e){if(Ui(t,s,co,{enabled:!0}),!t.has(s,uo))continue;const e=t.get(s,uo),n=t.get(s,po),i=t.get(s,co),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=ho.Pressed:e.hovered?n.state=ho.Hovered:n.state=ho.Normal:n.state=ho.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,ce)){const o=t.get(s,ce);o.color=Ai(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,ce,o)}}},{name:"ButtonSystem"}))}}const Mo=new Po,To=q("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=q("Focusable",{tabIndex:0,isFocused:!1});class Eo{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=Re(new Eo,"FocusManager");class Ro{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ee("TextInput",To),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=l($.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,c=!1,u=!0,d=0,h=0;const p=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(!p)return;const f=p;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,To)?n:null}const g=()=>{c||null===m()||b()},y=()=>{c=!0},_=()=>{c=!1,b()},x=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void v();const i=s.get(n,To);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(mo).emit(n,"submit"),void v()}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,f.selectionStart=o,f.selectionEnd=o,i.dirty=!0,S())},w=()=>{const t=m();if(null!==t){const n=s.get(t,To);n.focused=!1,n.dirty=!0;e.getResource(Ao).blur()}};function b(){const t=m();if(null===t)return;const n=s.get(t,To);if(n.readOnly)return;let i=f.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),f.value=i),i!==n.value){n.value=i;e.getResource(mo).emit(t,"change")}n.cursorPos=f.selectionStart??i.length,n.dirty=!0,S()}function v(){const t=m();if(null!==t){const e=s.get(t,To);e.focused=!1,e.dirty=!0}e.getResource(Ao).blur(),f.blur()}function S(){u=!0,d=0}f.addEventListener("input",g),f.addEventListener("compositionstart",y),f.addEventListener("compositionend",_),f.addEventListener("keydown",x),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",g),f.removeEventListener("compositionstart",y),f.removeEventListener("compositionend",_),f.removeEventListener("keydown",x),f.removeEventListener("blur",w),f.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 P=null;function M(e,l,c,d){(i.width<c||i.height<d)&&(i.width=Fi(Math.max(i.width,c)),i.height=Fi(Math.max(i.height,d))),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,c,d),o.save(),o.beginPath(),o.rect(l.padding,0,c-2*l.padding,d),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const p=0===l.value.length,f=p?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=p?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 g=Math.ceil(1.2*l.fontSize),y=l.padding;if(l.multiline){const e=Ii(o,f,c-2*y);let t=y;for(const s of e)o.fillText(s,y,t),t+=g}else{const e=(d-l.fontSize)/2;o.fillText(f,y,e)}if(l.focused&&u){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=Ii(o,l.value,c-2*y);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 u=r<e.length?e[r].substring(0,a):"";t=y+o.measureText(u).width,s=y+r*g,n=g}else t=y+o.measureText(e).width,s=(d-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 _=o.getImageData(0,0,c,d),x=new Uint8Array(_.data.buffer),w=t.getResourceManager();x.length>a&&(0!==r&&t._free(r),r=t._malloc(x.length),a=x.length),t.HEAPU8.set(x,r);const b=n.get(e);void 0!==b&&w.releaseTexture(b);const v=w.createTexture(c,d,r,x.length,1,!0);n.set(e,v);const S=s.get(e,ce);S.texture=v,S.size.x=c,S.size.y=d,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,ce,S)}e.addSystemToSchedule(exports.Schedule.Update,ft([Ie(Ao)],e=>{const t=s.getEntitiesWithComponents([To]);for(const e of t)Ui(s,e,Co,{tabIndex:0,isFocused:!1}),Ui(s,e,co,{enabled:!0,blockRaycast:!0});const n=m();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,To)){const e=s.get(P,To);e.focused=!1,e.dirty=!0,f.blur()}null!==n&&function(e){const t=s.get(e,To);t.readOnly||(t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),S())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,ft([],()=>{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,u=!u;s.get(o,To).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,To)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([To,Si]);for(const e of a){const t=s.get(e,To);if(!t.dirty)continue;const n=s.get(e,Si),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(Ti(s,e),M(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Io=new Ro,Fo={Simple:0,Sliced:1,Tiled:2,Filled:3},ko={Horizontal:0,Vertical:1},Bo={Left:0,Right:1,Bottom:2,Top:3},Do=q("Image",{texture:V,color:{r:1,g:1,b:1,a:1},imageType:Fo.Simple,fillMethod:ko.Horizontal,fillOrigin:Bo.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Lo=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?Bi(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Di(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Uo{build(e){ee("Image",Do);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,ft([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Do)||s.delete(e);const e=t.getEntitiesWithComponents([Do]);for(const n of e){const e=t.get(n,Do),i=t.has(n,Si)?t.get(n,Si):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!Lo.changed(r,o))continue;Ti(t,n);const a=t.get(n,ce);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=Bi(i,n),a.size.y=Di(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===ko.Horizontal?e.fillOrigin===Bo.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===Bo.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,ce,a),s.set(n,Lo.take(o))}else a.color.a=0,t.insert(n,ce,a),s.set(n,Lo.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Wo=new Uo,zo=q("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),$o=q("ToggleGroup",{allowSwitchOff:!1});class Oo{build(e){ee("Toggle",zo),ee("ToggleGroup",$o);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,ft([Ie(mo)],e=>{const n=t.getEntitiesWithComponents([zo]);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,zo);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,zo,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,zo);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(Ui(t,s,co,{enabled:!0}),!t.has(s,uo))continue;const n=t.get(s,uo),i=t.get(s,zo),r=t.get(s,co);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,$o);if(i.isOn&&r){if(!t.get(n,$o).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,zo,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,zo);i.isOn&&(i.isOn=!1,t.insert(n,zo,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,ce)){const e=t.get(s,ce);e.color=Ai(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,ce,e)}}}for(const e of n){const s=t.get(e,zo);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,ce)){const e=t.get(s.graphicEntity,ce);e.enabled=s.isOn,t.insert(s.graphicEntity,ce,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const Ho=new Oo,Vo=bi,No=q("ProgressBar",{value:0,fillEntity:0,direction:bi.LeftToRight});function jo(e,t,s,n){if(!e.has(t,Si))return;const i=e.get(t,Si),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=vi(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,ce)){const s=e.get(t,ce);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,ce,s))}if(e.has(t,re)){const s=e.get(t,re),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,re,s))}}class Xo{build(e){ee("ProgressBar",No);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,ft([],()=>{const e=t.getEntitiesWithComponents([No,Si]);for(const s of e){const e=t.get(s,No);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,Si),i=Math.max(0,Math.min(1,e.value));Ei(t,e.fillEntity,e.direction,i);const o=Bi(n,s),r=Di(n,s);jo(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Yo=new Xo,Go=q("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),qo=q("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}});class Ko{build(e){ee("Draggable",Go),ee("DragState",qo);const t=e.world,s=e.getResource(mo);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,ft([Ie(_t),Ie(bt)],(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([Go,uo]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Go).enabled)continue;if(t.get(n,uo).hovered){let e=0;t.has(n,ce)&&(e=t.get(n,ce).layer);const i=ki(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,qo)||t.insert(s,qo);const e=t.get(s,qo),o=t.get(s,re);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,qo)){t.get(n,qo).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),u=t.get(n,Go);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,qo).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,qo))return void(o=null);const n=t.get(o,qo),i=t.get(o,Go),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,u=n.startWorldPos.y+l;const d=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,u);c=d.x,u=d.y;const h=n.currentWorldPos.x,p=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:u-p},n.currentWorldPos={x:c,y:u},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:u-n.startWorldPos.y},t.has(o,re)){const e=function(e,t,s,n){if(!e.has(t,pe))return{x:s,y:n};const i=e.get(t,pe).entity;if(!e.valid(i)||!e.has(i,re))return{x:s,y:n};const o=e.get(i,re),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=no(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(s*u-n*c)/r,y:(s*c+n*u)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,re);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,re,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const Jo=new Ko,Qo=q("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Zo(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 er(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,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(s-o*c)*a}}class tr{build(e){ee("ScrollView",Qo);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,ft([Ie(_t),Ie(bt),Ie(De)],(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([Qo,Si]);for(const o of l){Ui(t,o,Zi,{enabled:!0,mode:Ji});const l=t.get(o,Qo),c=t.get(o,Si);let u=s.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,u));const d=Bi(c,o),h=Di(c,o);let p=l.contentWidth,f=l.contentHeight;if((0===p||0===f)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,fe)){const e=t.get(l.contentEntity,fe).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,re))continue;const e=t.get(r,re);let a=0,l=0,c=.5,u=.5;if(t.has(r,Si)){const e=t.get(r,Si);a=Bi(e,r)||e.size.x,l=Di(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,ce)){const e=t.get(r,ce);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),p=e.position.y-l*u,f=e.position.y+l*(1-u);d<s&&(s=d),h>n&&(n=h),p<i&&(i=p),f>o&&(o=f)}0===p&&(p=n-s),0===f&&(f=o-i)}const m=Math.max(0,p-d),g=Math.max(0,f-h);if(!r&&i.valid){Ui(t,o,co,{enabled:!0,blockRaycast:!0});const s=t.has(o,uo)?t.get(o,uo):null;if(s?.justPressed&&(u.isDragging=!0,u.lastWorldX=n.x,u.lastWorldY=n.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=n.x-u.lastWorldX,t=n.y-u.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=Zo(l.scrollX,0,m,d);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const n=a>0?-e*t/a:0;u.velocityX+=(n-u.velocityX)*s}}if(l.verticalEnabled){const e=Zo(l.scrollY,0,g,h);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const n=a>0?t*e/a:0;u.velocityY+=(n-u.velocityY)*s}}u.lastWorldX=n.x,u.lastWorldY=n.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*d,t=5*h;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Zo(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Zo(l.scrollX,0,m,d);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=er(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<$i&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>$i?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=er(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<$i&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>$i?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.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,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*d,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,re)){const e=t.get(l.contentEntity,re),s=e.position.x,n=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(n-u.lastAppliedY)>.01)&&(u.contentBaseY=n),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,re,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const sr=new tr,nr=bi,ir=q("Slider",{value:0,minValue:0,maxValue:1,direction:bi.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function or(e,t,s,n,i,o){const r=Bi(n,i)*s.worldScale.x,a=Di(n,i)*s.worldScale.y,l=no(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-s.worldPosition.x,h=t-s.worldPosition.y,p=d*u-h*c,f=d*c+h*u,m=-n.pivot.x*r,g=-n.pivot.y*a;switch(o){case bi.LeftToRight:return r>0?(p-m)/r:0;case bi.RightToLeft:return r>0?1-(p-m)/r:0;case bi.BottomToTop:return a>0?(f-g)/a:0;case bi.TopToBottom:return a>0?1-(f-g)/a:0}}function rr(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case bi.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case bi.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case bi.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case bi.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class ar{build(e){ee("Slider",ir);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,ft([Ie(_t),Ie(bt),Ie(mo)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([ir,Si]);for(const r of o){const o=t.get(r,ir),a=t.get(r,Si);if(!wo()||bo()){if(t.has(r,re)){Ui(t,r,co,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Ui(t,o.handleEntity,co,{enabled:!0,blockRaycast:!1});const l=t.get(r,re),c=t.has(r,uo)?t.get(r,uo):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,uo)&&(u=t.get(o.handleEntity,uo).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=or(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,ir,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,u=Bi(a,r),d=Di(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Ei(t,o.fillEntity,o.direction,c),Wi(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Si)){const e=t.get(o.handleEntity,Si);rr(e,o.direction,c),t.insert(o.handleEntity,Si,e),Wi(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const lr=new ar;class cr{build(e){ee("Focusable",Co);const t=e.world,s=new Eo;e.insertResource(Ao,s),e.addSystemToSchedule(exports.Schedule.Update,ft([Ie(_t),Ie(mo)],(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,uo))continue;t.get(e,uo).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,co)){if(!t.get(s,co).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"}))}}const ur=new cr,dr=q("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function hr(){return s()?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")}}()}class pr{build(e){ee("SafeArea",dr);const t=e.world;let n=hr(),i=!0,o=0,r=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=hr(),i=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=hr(),i=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,ft([Ie(bt)],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,i=!0),!i)return;i=!1;const l=u(),c=s()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([dr,Si]);for(const e of d){const s=t.get(e,dr),i=t.get(e,Si),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Si,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const fr=new pr,mr=q("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let gr=null;class yr{build(e){ee("ListView",mr);const t=e.world,s=new Map;gr=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,ft([Ie(_t)],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([mr,Si]);for(const o of i){Ui(t,o,co,{enabled:!0,blockRaycast:!0}),Ui(t,o,Zi,{enabled:!0,mode:Ji});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,mr),a=t.get(o,Si),l=Di(a,o),c=Bi(a,o);if(!n){const s=t.has(o,uo)?t.get(o,uo):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const d=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<d||e>=h)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=d;e<h;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,be,{value:`ListItem_${e}`}),t.insert(s,Si,{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,re)){const n=t.get(s,re);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,re,n)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const _r=new yr,xr=q("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class wr{build(e){ee("Dropdown",xr);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,re))return;const s=t.get(e,re);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,re,{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,ce)){const s=t.get(e,ce);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,ce,{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;u(i,!0),c(n);const o=t.get(e,ce),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*Oi;t.insert(i,Si,{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,re,{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,ce,{texture:V,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)*Oi;t.insert(o,be,{value:`Option_${e}`}),t.insert(o,Si,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Oi},offsetMax:{x:0,y:0},size:{x:r,y:Oi},pivot:{x:.5,y:.5}}),t.insert(o,re,{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,ce,{texture:V,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Oi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,co,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);const c=t.spawn();t.insert(c,re,{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,Xi,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Vi.Left,verticalAlign:Ni.Middle,wordWrap:!1,overflow:ji.Clip,lineHeight:1.2}),t.insert(c,Si,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Oi},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}d(n)}function r(e,t,s){t.isOpen=!1,c(s),u(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,Xi))return;const n=t.get(s,Xi);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,Xi,{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 u(e,s){if(0!==e&&t.valid(e)&&(t.has(e,co)&&t.insert(e,co,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,ce))){const n=t.get(e,ce);t.insert(e,ce,{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 d(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,ce))continue;const i=s===e.highlightIndex?{...Hi}:{r:.95,g:.95,b:.95,a:1};t.insert(n,ce,{texture:V,color:i,size:{x:e.ddWidth,y:Oi},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,uo))continue;if(t.get(s,uo).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,ft([Ie(_t),Ie(mo)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const p=wo()&&!bo(),f=t.getEntitiesWithComponents([xr]);for(const m of f){const f=t.get(m,xr);let g=s.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,g)),n(f.listEntity),i(m),f.isOpen||u(f.listEntity,!1),l(f),p)continue;Ui(t,m,co,{enabled:!0,blockRaycast:!0});const y=t.has(m,uo)?t.get(m,uo):null;if(y?.justPressed&&(f.isOpen?r(m,f,g):o(m,f,g)),f.isOpen){for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,uo))continue;if(t.get(s,uo).justPressed){a(m,f,g,e,c);break}}let s=-1;for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,uo))continue;if(t.get(n,uo).hovered){s=e;break}}s>=0&&s!==g.highlightIndex&&(g.highlightIndex=s,d(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=f.options.length-1?g.highlightIndex=0:g.highlightIndex++,d(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=f.options.length-1:g.highlightIndex--,d(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,f,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,f,g),e.isMouseButtonPressed(0)&&(y?.hovered||h(g)||r(m,f,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const br=new wr,vr=0,Sr=0,Pr=2,Mr=q("LayoutGroup",{direction:vr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Sr,reverseOrder:!1});class Tr{build(e){ee("LayoutGroup",Mr);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,ft([],()=>{const e=t.getEntitiesWithComponents([Mr,Si,fe]);for(const s of e){const e=t.get(s,Mr),n=t.get(s,Si),i=t.get(s,fe);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Si)&&t.has(e,re)&&o.push({entity:e,rect:t.get(e,Si)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Bi(n,s),a=Di(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,d=e.direction===vr;let h=0;for(let s=0;s<o.length;s++){const n=o[s],i=Bi(n.rect,n.entity),p=Di(n.rect,n.entity),f=n.rect.pivot.x,m=n.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+f*i,y=e.childAlignment===Sr?(1-c)*a-u.top-(1-m)*p:e.childAlignment===Pr?-c*a+u.bottom+m*p:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*p,h+=i,s<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===Sr?-l*r+u.left+f*i:e.childAlignment===Pr?(1-l)*r-u.right-(1-f)*i:(.5-l)*r+.5*(u.left-u.right)+(f-.5)*i,y=(1-c)*a-u.top-h-(1-m)*p,h+=p,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,re);_.position.x=g,_.position.y=y,t.insert(n.entity,re,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Cr=new Tr;class Er{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,ft([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Ar=new Er;async function Rr(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 Ir=Re({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),Fr={r:.2,g:.4,b:1,a:.7},kr={r:.2,g:1,b:.2,a:.7},Br={r:.2,g:1,b:1,a:.7},Dr={r:1,g:1,b:.2,a:.5},Lr={r:1,g:.2,b:.2,a:.8},Ur={r:1,g:.2,b:.2,a:1},Wr=1.5,zr=16;function $r(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Or(e){switch(e){case Ee.Static:return Fr;case Ee.Kinematic:return Br;default:return kr}}function Hr(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-s,y:-n},{x:s,y:-n},{x:s,y:n},{x:-s,y:n}].map(s=>({x:e+s.x*r-s.y*a,y:t+s.x*a+s.y*r}));for(let e=0;e<4;e++)Ks.line(l[e],l[(e+1)%4],o,Wr)}function Vr(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=(s,n)=>({x:e+s*r-n*a,y:t+s*a+n*r}),c=l(-s,n),u=l(s,n),d=l(-s,-n),h=l(s,-n);Ks.line(c,d,o,Wr),Ks.line(u,h,o,Wr);for(let e=0;e<zr;e++){const t=e/zr*Math.PI,i=(e+1)/zr*Math.PI,r=l(-s*Math.cos(t),n+s*Math.sin(t)),a=l(-s*Math.cos(i),n+s*Math.sin(i));Ks.line(r,a,o,Wr)}for(let e=0;e<zr;e++){const t=Math.PI+e/zr*Math.PI,i=Math.PI+(e+1)/zr*Math.PI,r=l(-s*Math.cos(t),-n+s*Math.sin(t)),a=l(-s*Math.cos(i),-n+s*Math.sin(i));Ks.line(r,a,o,Wr)}}function Nr(e,t,s,n){const i=e+.5*s,o=t+.5*n;Ks.line({x:e,y:t},{x:i,y:o},Lr,Wr);const r=Math.sqrt(s*s+n*n);if(r<1)return;const a=Math.PI/6,l=s/r,c=n/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),d=o-6*(l*Math.sin(a)+c*Math.cos(a)),h=i-6*(l*Math.cos(a)+c*Math.sin(a)),p=o-6*(-l*Math.sin(a)+c*Math.cos(a));Ks.line({x:i,y:o},{x:u,y:d},Lr,Wr),Ks.line({x:i,y:o},{x:h,y:p},Lr,Wr)}function jr(e,t,s){const n=e.getResource(Ir);if(!n||!n.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([de]);for(const s of t){const t=e.world.get(s,de);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([Pe,re]);let r=null;n.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const s=e.world.get(t,Pe);if(!s.enabled)continue;const o=e.world.get(t,re),a=o.worldPosition.x,l=o.worldPosition.y,c=$r(o.worldRotation);if(n.showColliders){if(e.world.has(t,Me)){const n=e.world.get(t,Me),o=n.isSensor?Dr:Or(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c);Hr(a+r*d-u*h,l+r*h+u*d,n.halfExtents.x*i,n.halfExtents.y*i,c,o)}if(e.world.has(t,Te)){const n=e.world.get(t,Te),o=n.isSensor?Dr:Or(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c),p=a+r*d-u*h,f=l+r*h+u*d;Ks.circleOutline({x:p,y:f},n.radius*i,o,Wr,32)}if(e.world.has(t,Ce)){const n=e.world.get(t,Ce),o=n.isSensor?Dr:Or(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c);Vr(a+r*d-u*h,l+r*h+u*d,n.radius*i,n.halfHeight*i,c,o)}}if(n.showVelocity&&r&&s.bodyType===Ee.Dynamic){const e=r.getLinearVelocity(t);Nr(a,l,e.x*i,e.y*i)}}if(n.showContacts&&e.hasResource(s)){const t=e.getResource(s);for(const e of t.collisionEnters)Ks.circle({x:e.contactX,y:e.contactY},3,Ur,!0,32)}}const Xr=Re({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Yr=Re(null,"PhysicsAPI");function Gr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function qr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Kr{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(Xr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Rr(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([de]);for(const s of t){const t=e.world.get(s,de);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(exports.Schedule.PostUpdate,ft([Ie(De)],a=>{const l=r.getEntitiesWithComponents([Pe,re]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Pe),l=r.get(i,re);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=Gr(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),Jr(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===Ee.Kinematic){const e=Gr(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 u=e.world.get(r,re);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(r,pe)){const t=e.world.get(r,pe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,re)){const s=e.world.get(t.entity,re),n=Gr(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),u=Math.sin(-n);d=(i*r-o*u)/(0!==s.worldScale.x?s.worldScale.x:1),h=(i*u+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=qr(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(r,re,u)}}(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=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Xr,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Yr,Qr._fromModule(n)),function(e,t,s){e.insertResource(Ir,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),tn("physics-debug-draw",()=>{jr(e,t,s)})}(e,Yr,Xr),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function Jr(e,t,s){const n=e.world;if(n.has(s,Me)){const e=n.get(s,Me);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,Ce)){const e=n.get(s,Ce);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 Qr{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(Qr.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)}static setDebugDraw(e,t){const s=e.getResource(Ir);s&&(s.enabled=t,e.insertResource(Ir,s))}static setDebugDrawConfig(e,t){const s=e.getResource(Ir);s&&e.insertResource(Ir,{...s,...t})}}const Zr={nearest:0,linear:1},ea={repeat:0,clamp:1,mirror:2};function ta(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=Zr[n.filterMode??"linear"]??1,a=ea[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 sa(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 na(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,u=e.worldRotation.w,d=a+a,h=l+l,p=c+c,f=a*d,m=a*h,g=a*p,y=l*h,_=l*p,x=c*p,w=u*d,b=u*h,v=u*p;return new Float32Array([(1-(y+x))*i,(m+v)*i,(g-b)*i,0,(m-v)*o,(1-(f+x))*o,(_+w)*o,0,(g+b)*r,(_-w)*r,(1-(f+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function ia(e){const{app:t,module:s,sceneData:n,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=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=ys(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]=ta(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(s,n,i);!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)}}}}(s,n,u);let d={},h=null;if(o&&(h=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"])}}(o),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=_s(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),u=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===b(c)?.contentType;let d,h;if(r){const e=await i.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await i.readText(a),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,n,n.length,r);if(t._free(d),p<0)continue;o[a]=p;const f=sa(n),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=ta(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(s,o,h,n,i)),r){const e={gravity:a?.gravity??{...W},fixedTimestep:a?.fixedTimestep??z,subStepCount:a?.subStepCount??4};new Kr("",e,()=>Promise.resolve(r)).build(t)}const p=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=ys(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=b(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),u=ta(e,c,!1),d=e.getResourceManager();n[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{n[o]=0}}return n}(s,n,i),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=ys(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=It.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=It.createFromAsset(e,r)}catch{s[o]=0}}return s}(n,i);await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=ys(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=JSON.parse(t),o=Ht(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,ta(e,n))}catch{r.set(t,0)}jt(Vt(i,n,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(s,n,i),await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=ys(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=ds(JSON.parse(t));if(!n)continue;const o=[];for(const t of n.tilesets){const n=hs(i,t.image);let r=0;try{const t=await s.loadPixels(n);r=ta(e,t),Jt(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}es(i,{tileWidth:n.tileWidth,tileHeight:n.tileHeight,layers:n.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(s,n,i),await async function(e,t){const s=[],n=new Set;for(const t of e.entities)for(const e of t.components){const t=ys(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!n.has(t)&&(n.add(t),s.push(t))}}0!==s.length&&(t?await Promise.all(s.map(async e=>{try{const s=await t.readBinary(e);await Gt.preloadFromData(e,s.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await Gt.preloadAll(s).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(n,i),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=ys(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)}}}(n,u,p,f);const m=Ss(t.world,n);if(c&&t.hasResource(si))for(const e of m.values())t.world.insert(e,ve,{scene:c,persistent:!1});if(o&&h){const e=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=_s(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}(h,n,d,m);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=U);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,ge)?c.get(o,ge):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(r,l*d);let h=0;if(c.has(o,re)){const e=na(c.get(o,re),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(r);for(let e=0;e<p;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),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(r,e,c,u,d,p);const f=s.HEAPU32[d>>2],m=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*i),y=new Uint16Array(s.HEAPU8.buffer,u,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(y),t.renderer_submitTriangles(_,i,x,o,f,m,h),t._free(_),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(t,s,o,h,e)}if(l){const e=t.getResource(As);e&&e.setAddressableManifest(l)}}function oa(e,t,s){return{name:e,async setup(){await ia({...s,sceneData:t,sceneName:e})}}}async function ra(e){const{app:t,firstScene:s,aspectRatio:n}=e;ai(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(si);for(const t of e.scenes)o.register(oa(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&Cs(t.world,n)}class aa{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=_s(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===b(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=ys(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(n.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&s.add(o))}}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=b(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 la="__preview__";const ca={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=Xn.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:Xn.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){Xn.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Xn.releaseRenderTarget(e._handle),ca.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){Xn.begin(t,e._handle)},end(){Xn.end()},getDepthTexture:e=>Xn.getTargetDepthTexture(e._handle)};var ua;exports.LogLevel=void 0,(ua=exports.LogLevel||(exports.LogLevel={}))[ua.Debug=0]="Debug",ua[ua.Info=1]="Info",ua[ua.Warn=2]="Warn",ua[ua.Error=3]="Error";class da{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,s);break;case exports.LogLevel.Info:console.log(t,s);break;case exports.LogLevel.Warn:console.warn(t,s);break;case exports.LogLevel.Error:console.error(t,s)}}}class ha{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new da)}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(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.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 pa=new ha;const fa={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},ma={Running:0,Paused:1,Completed:2,Cancelled:3},ga={None:0,Restart:1,PingPong:2};const ya=1.70158,_a=2.70158,xa=2.5949095;const wa=2*Math.PI/3,ba=2*Math.PI/4.5;const va=7.5625,Sa=2.75;const Pa=1e-6;function Ma(e,t,s){switch(e){case fa.Linear:return t;case fa.EaseInQuad:return function(e){return e*e}(t);case fa.EaseOutQuad:return function(e){return e*(2-e)}(t);case fa.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case fa.EaseInCubic:return function(e){return e*e*e}(t);case fa.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case fa.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case fa.EaseInBack:return function(e){return _a*e*e*e-ya*e*e}(t);case fa.EaseOutBack:return function(e){const t=e-1;return 1+_a*t*t*t+ya*t*t}(t);case fa.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-xa)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+xa)+2)/2}(t);case fa.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*wa)}(t);case fa.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*wa)+1}(t);case fa.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*ba)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*ba)/2+1}(t);case fa.EaseOutBounce:return function(e){return e<1/Sa?va*e*e:e<2/Sa?va*(e-=1.5/Sa)*e+.75:e<2.5/Sa?va*(e-=2.25/Sa)*e+.9375:va*(e-=2.625/Sa)*e+.984375}(t);case fa.CubicBezier:return s?function(e,t,s,n,i){let o=e;for(let s=0;s<8;s++){const s=1-o,i=3*t*s*s*o+3*n*s*o*o+o*o*o-e;if(Math.abs(i)<Pa)break;const r=3*t*(1-2*o)*(1-o)+6*n*o*(1-o)-3*n*o*o+3*o*o;if(Math.abs(r)<Pa)break;o-=i/r}const r=1-o;return 3*s*r*r*o+3*i*r*o*o+o*o*o}(t,s.p1x,s.p1y,s.p2x,s.p2y):t;case fa.Step:return function(e){return e<1?0:1}(t);default:return t}}const Ta=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,s,n,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:s,elapsed:0,delay:i?.delay??0,easing:i?.easing??fa.Linear,bezierPoints:null,state:ma.Running,loop:i?.loop??ga.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:n,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===ma.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==ma.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const s=Math.min(t.elapsed/t.duration,1),n=Ma(t.easing,s,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*n),s>=1){if(t.loop!==ga.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===ga.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=ma.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===ma.Running&&(t.state=ma.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===ma.Paused&&(t.state=ma.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=ma.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:ma.Cancelled}setBezier(e,t,s,n,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:s,p2x:n,p2y:i})}setSequenceNext(e,t){const s=this.entries_.get(e);s&&(s.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const s=this.entries_.get(e);s&&(s.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Ca{constructor(e){this.id=e}get state(){return Ta.getState(this.id)}bezier(e,t,s,n){return Ta.setBezier(this.id,e,t,s,n),this}then(e){return e instanceof Ca?Ta.setSequenceNext(this.id,e.id):Ta.setSequenceNextExternal(this.id,e),this}pause(){Ta.pause(this.id)}resume(){Ta.resume(this.id)}cancel(){Ta.cancel(this.id)}}class Ea{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 e instanceof Ca?(Ta.registerCppSequence(this.entity,e.id),this):(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 Aa=null,Ra=null;function Ia(e,t){Aa=e,Ra=t,Ta.init(e,t)}function Fa(){Ta.shutdown(),Aa=null,Ra=null}function ka(){if(!Aa)throw new Error("Tween API not initialized");return Aa}function Ba(){if(!Ra)throw new Error("Tween API not initialized");return Ra}const Da={to(e,t,s,n,i,o){const r=ka(),a=Ba(),l=o?.easing??fa.Linear,c=o?.delay??0,u=o?.loop??ga.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,u,d);return new Ea(r,a,h)},value(e,t,s,n,i){const o=Ta.create(e,t,s,n,i);return new Ca(o)},cancel(e){ka()._anim_cancelTween(Ba(),e.entity)},cancelAll(e){ka()._anim_cancelAllTweens(Ba(),e)},update(e){ka()._anim_updateTweens(Ba(),e),Ta.update(e)}};class La{constructor(){this.name="AnimationPlugin"}build(e){Ia(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,ft([Ie(De)],e=>{Da.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,ft([Ie(De)],e=>{Yt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Fa()}}const Ua=new La;var Wa;exports.AttenuationModel=void 0,(Wa=exports.AttenuationModel||(exports.AttenuationModel={}))[Wa.Linear=0]="Linear",Wa[Wa.Inverse=1]="Inverse",Wa[Wa.Exponential=2]="Exponential";const za={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function $a(e,t=za){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case exports.AttenuationModel.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case exports.AttenuationModel.Inverse:a=n/Math.max(r,n);break;case exports.AttenuationModel.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Oa(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const Ha=q("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:exports.AttenuationModel.Inverse,rolloff:1,priority:0,enabled:!0}),Va=q("AudioListener",{enabled:!0});class Na{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const s=t().createAudioBackend(),n=this.config_;s.initialize({initialPoolSize:n.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=s.mixer;Gt.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;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(exports.Schedule.PreUpdate,ft([Ie(De)],t=>{if(!(!wo()||bo()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,d=!1;const h=n.getEntitiesWithComponents([Va,le]);for(const e of h){if(n.get(e,Va).enabled){const t=n.get(e,le);i=t.position.x,u=t.position.y,d=!0;break}}const p=n.getEntitiesWithComponents([Ha]);a.clear();for(const e of p){const t=n.get(e,Ha);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&s.isReady){const e=Gt.getBufferHandle(t.clip);if(e){const n=s.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,n),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const s=o.get(c);if(!s.isPlaying){o.delete(c);continue}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=n.tryGet?.(e,le),a=r?.position.x??0,h=r?.position.y??0,p=a-i,f=h-u,m=$a(Math.sqrt(p*p+f*f),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Oa(a,0,i,0,t.maxDistance);s.setVolume(t.volume*m),s.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),Gt.dispose()}}const ja=new Na;let Xa=null,Ya=null;function Ga(e,t){Xa=e,Ya=t}function qa(){Xa=null,Ya=null}const Ka={update(e){Xa&&Ya&&Xa.particle_update?.(Ya,e)},play(e){Xa&&Ya&&Xa.particle_play?.(Ya,e)},stop(e){Xa&&Ya&&Xa.particle_stop?.(Ya,e)},reset(e){Xa&&Ya&&Xa.particle_reset?.(Ya,e)},getAliveCount:e=>Xa?Xa.particle_getAliveCount?.(e)??0:0};class Ja{constructor(){this.name="ParticlePlugin"}build(e){Ga(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(exports.Schedule.Update,ft([Ie(De)],e=>{Ka.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){qa()}}const Qa=new Ja,Za=1e6;class el{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){ns(e.wasmModule);const t=e.world,s=this.initializedLayers_,n=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(bt),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:Za,l=i?.valid?i.worldTop:Za,c=t.getEntitiesWithComponents([as,re]);for(const e of c){const n=t.tryGet(e,as),i=t.tryGet(e,re);if(!n||!i)continue;if(!n.visible)continue;const c=n.texture;if(!c)continue;const u=Qt(c);if(!u)continue;if(!s.has(e)){if(os.initLayer(e,n.width,n.height,n.tileWidth,n.tileHeight),n.tiles.length>0){const t=new Uint16Array(n.tiles.length);for(let e=0;e<n.tiles.length;e++)t[e]=n.tiles[e];os.setTiles(e,t)}s.add(e)}const d=n.tileWidth/u.width,h=n.tileHeight/u.height,p=n.tint,f=n.parallaxFactor;os.submitLayer(e,c,n.layer,0,n.tilesetColumns,d,h,i.worldPosition.x,i.worldPosition.y,o,r,a,l,p.r,p.g,p.b,p.a,n.opacity,f.x,f.y)}const u=t.getEntitiesWithComponents([rs,re]);for(const e of u){if(t.tryGet(e,as))continue;const i=t.tryGet(e,rs),c=t.tryGet(e,re);if(!i?.source||!c)continue;const u=ts(i.source);if(!u)continue;if(!n.has(e)){const t=[];for(let n=0;n<u.layers.length;n++){const i=1073741824+256*e+n,o=u.layers[n];os.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&os.setTiles(i,o.tiles),t.push(i),s.add(i)}n.set(e,t)}const d=n.get(e);for(let e=0;e<u.layers.length&&e<d.length;e++){const t=d[e],s=u.tilesets[0];if(!s)continue;const n=Qt(s.textureHandle);if(!n)continue;const i=u.tileWidth/n.width,h=u.tileHeight/n.height;os.submitLayer(t,s.textureHandle,e,0,s.columns,i,h,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)os.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),Zt(),is()}}const tl=new el;function sl(e,t){return e.toFixed(t)}function nl(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class il{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">${sl(e.fps,1)}</span> Frame: <span style="color:#d19a66">${sl(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>${nl(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${sl(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 ol(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const rl=Re(ol(),"Stats");const al="StatsCollect";class ll{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 cl{constructor(e){this.name="Stats",this.collector_=new ll,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(rl,ol());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new il(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=ft([Ie(De),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(rl);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(al),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Xn.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,s?.update(o)},{name:al});e.addSystemToSchedule(exports.Schedule.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const ul=new cl;class dl{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 hl(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}}const pl=[Ki,lo,yo,Wo,Yo,Mo,Jo,sr,lr,Ho,Io,ur,fr,_r,br,Cr,Ar],fl=[...pl,Ua,ja,Qa,tl,$n];function ml(e,t){return function(e,t){const s=ri.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Xs(e),Et(e),un(e),vn(e),Nn(e),Gn(e);const i=new Jn;s.setPipeline(i);let o=c();const r=t?.getViewportSize??(()=>{const e=u();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=hi(e,n,t,i));const r=s.getResource(bt);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(bt,{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)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;Xn.setClearColor(e.x,e.y,e.z,e.w)}const d=(c()-o)/1e3;let h;if(Xn.resize(t,l),s.hasResource(si)){const e=s.getResource(si).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const p=hi(e,n,t,l,s.world,h);if(a(t,l,p),0===p.length)i.render({registry:{_cpp:n},viewProjection:li,width:t,height:l,elapsed:d});else{i.beginScreenCapture();for(const e of p){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,cameraEntity:e.entity})}i.endScreenCapture(),Xn.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(Is),s.addPlugin($s),s.addPlugin(wt),s.addPlugin(oi),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:fl,...t})}class gl{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return o(this.resolvePath_(e))}async readBinary(e){const t=await i(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function yl(e){return(t,s)=>(a(e,t).then(e=>{s(e.instance,e.module)}),{})}async function _l(e,t){try{return await e({instantiateWasm:yl(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}k||(k=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},i=await f(s,n);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return m(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i<128?s[n++]=i:i<2048?(s[n++]=192|i>>6,s[n++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,s[n++]=240|i>>18,s[n++]=128|i>>12&63,s[n++]=128|i>>6&63,s[n++]=128|63&i):(s[n++]=224|i>>12,s[n++]=128|i>>6&63,s[n++]=128|63&i)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const i=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=B,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.AnimationPlugin=La,exports.App=ri,exports.AssetPlugin=Rs,exports.AssetRefCounter=class{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}}},exports.AssetServer=Es,exports.Assets=As,exports.AsyncCache=$t,exports.Audio=Gt,exports.AudioBus=d,exports.AudioListener=Va,exports.AudioMixer=class{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new d(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new d(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new d(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new d(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new d(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 d(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}},exports.AudioPlugin=Na,exports.AudioPool=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}},exports.AudioSource=Ha,exports.BitmapText=me,exports.BodyType=Ee,exports.BoxCollider=Me,exports.Button=po,exports.ButtonState=ho,exports.Camera=ue,exports.Canvas=de,exports.CapsuleCollider=Ce,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=fe,exports.CircleCollider=Te,exports.ClearFlags=ie,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=rt,exports.DEFAULT_DESIGN_HEIGHT=L,exports.DEFAULT_DESIGN_WIDTH=D,exports.DEFAULT_FALLBACK_DT=U,exports.DEFAULT_FIXED_TIMESTEP=z,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=W,exports.DEFAULT_LINE_HEIGHT=1.2,exports.DEFAULT_MAX_DELTA_TIME=.5,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_SPINE_SKIN="default",exports.DEFAULT_SPRITE_SIZE={x:100,y:100},exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragPlugin=Ko,exports.DragState=qo,exports.Draggable=Go,exports.Draw=Ks,exports.Dropdown=xr,exports.DropdownPlugin=wr,exports.EasingType=fa,exports.EmitterShape=ye,exports.EntityCommands=ot,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=ut,exports.EventRegistry=lt,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=ct,exports.FillDirection=bi,exports.FillMethod=ko,exports.FillOrigin=Bo,exports.FocusManager=Ao,exports.FocusManagerState=Eo,exports.FocusPlugin=cr,exports.Focusable=Co,exports.FrameHistory=class{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,s){const n={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:s?new Map(s):new Map};this.count_<this.capacity_?(this.buffer_.push(n),this.count_++):this.buffer_[this.cursor_]=n,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}},exports.GLDebug=Kn,exports.Geometry=pn,exports.GetWorld=ht,exports.INVALID_ENTITY=0,exports.INVALID_FONT=N,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=V,exports.Image=Do,exports.ImagePlugin=Uo,exports.ImageType=Fo,exports.Input=_t,exports.InputPlugin=xt,exports.InputState=yt,exports.Interactable=co,exports.LayoutGroupPlugin=Tr,exports.ListView=mr,exports.ListViewPlugin=yr,exports.LocalTransform=ae,exports.Logger=ha,exports.LoopMode=ga,exports.Material=It,exports.MaterialLoader=Ot,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=be,exports.Parent=pe,exports.Particle=Ka,exports.ParticleEasing=xe,exports.ParticleEmitter=we,exports.ParticlePlugin=Ja,exports.Physics=Qr,exports.PhysicsEvents=Xr,exports.PhysicsPlugin=Kr,exports.PostProcess=Mn,exports.PostProcessPlugin=zn,exports.PostProcessStack=xn,exports.PostProcessVolume=Se,exports.PrefabServer=Us,exports.Prefabs=Ws,exports.PrefabsPlugin=zs,exports.PreviewPlugin=class{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(si);t.register({name:la,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(la),this.loadPromise_=t.load(la).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await n(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new aa(this.baseUrl_);await s.prefetch(t);let i=null;const o=this.app_.spineInitPromise;if(o){i=(await o).controller.raw}await ia({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:i,sceneName:la})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([ue]);for(const n of s){if(e.get(n,ue).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([de]);for(const i of n){const n=e.get(i,de);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(si).getScene(la),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,re,r);const a={isActive:!0,projectionType:ne.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:ie.ColorAndDepth};e.insert(o,ue,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(si);await e.switchTo(la),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}`)}}},exports.ProgressBar=No,exports.ProgressBarDirection=Vo,exports.ProgressBarPlugin=Xo,exports.ProjectionType=ne,exports.Query=st,exports.QueryInstance=nt,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=it,exports.RenderPipeline=Jn,exports.RenderTexture=ca,exports.Renderer=Xn,exports.Res=Ie,exports.ResMut=Fe,exports.RigidBody=Pe,exports.RuntimeConfig=$,exports.SafeArea=dr,exports.SafeAreaPlugin=pr,exports.ScaleMode=oe,exports.SceneManager=si,exports.SceneManagerState=ti,exports.SceneOwner=ve,exports.ScrollView=Qo,exports.ScrollViewPlugin=tr,exports.ShaderSources=zt,exports.SimulationSpace=_e,exports.Slider=ir,exports.SliderDirection=nr,exports.SliderPlugin=ar,exports.SpineAnimation=ge,exports.Sprite=ce,exports.SpriteAnimator=Xt,exports.Stats=rl,exports.StatsCollector=ll,exports.StatsOverlay=il,exports.StatsPlugin=cl,exports.Storage=Ue,exports.SystemRunner=gt,exports.Text=Xi,exports.TextAlign=Vi,exports.TextInput=To,exports.TextInputPlugin=Ro,exports.TextOverflow=ji,exports.TextPlugin=qi,exports.TextRenderer=Yi,exports.TextVerticalAlign=Ni,exports.Tilemap=rs,exports.TilemapAPI=os,exports.TilemapLayer=as,exports.TilemapPlugin=el,exports.Time=De,exports.Toggle=zo,exports.TogglePlugin=Oo,exports.Transform=re,exports.Tween=Da,exports.TweenHandle=Ea,exports.TweenState=ma,exports.TweenTarget={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},exports.UICameraInfo=bt,exports.UIEventQueue=fo,exports.UIEvents=mo,exports.UIInteraction=uo,exports.UIInteractionPlugin=Po,exports.UILayoutPlugin=go,exports.UIMask=Zi,exports.UIMaskPlugin=ao,exports.UIRect=Si,exports.UIRenderOrderPlugin=Er,exports.Velocity=he,exports.WeChatAssetProvider=gl,exports.WebAssetProvider=aa,exports.World=Ke,exports.WorldTransform=le,exports.addStartupSystem=function(e){mt().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){mt().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){mt().push({schedule:e,system:t})},exports.animationPlugin=Ua,exports.applyBuildRuntimeConfig=H,exports.applyDirectionalFill=Ei,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=$.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=$.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=$.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=$.canvasMatchWidthOrHeight)},exports.assetPlugin=Is,exports.audioPlugin=ja,exports.calculateAttenuation=$a,exports.calculatePanning=Oa,exports.cleanupAllPostProcessVolumes=Fn,exports.cleanupPostProcessVolume=In,exports.clearAnimClips=function(){Nt.clear()},exports.clearDrawCallbacks=nn,exports.clearTextureDimensionsCache=Zt,exports.clearTilemapSourceCache=function(){Kt.clear()},exports.clearUserComponents=function(){const e=G();for(const t of e.keys())Z.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=Ci,exports.computeFillSize=function(e,t,s,n){switch(e){case bi.BottomToTop:case bi.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case bi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case bi.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case bi.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}}}},exports.computeUIRectLayout=vi,exports.createMaskProcessor=ro,exports.createRuntimeSceneConfig=oa,exports.createWebApp=ml,exports.debug=function(e,t,s){pa.debug(e,t,s)},exports.defaultFrameStats=ol,exports.defineComponent=q,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=Re,exports.defineSystem=ft,exports.defineTag=function(e){const t=Z.get(e)??G().get(e);if(t)return t;const s=Y(e,{});return G().set(e,s),Z.set(e,s),J(e,{},!0),s},exports.dragPlugin=Jo,exports.dropdownPlugin=br,exports.error=function(e,t,s){pa.error(e,t,s)},exports.extractAnimClipTexturePaths=Ht,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([be]);for(const n of s){const s=e.get(n,be);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=ai,exports.focusPlugin=ur,exports.getAddressableType=function(e){return b(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of g)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return x},exports.getAllEffectDefs=function(){return Array.from(Tn.values())},exports.getAnimClip=function(e){return Nt.get(e)},exports.getAssetBuildTransform=function(e){return b(e)?.buildTransform},exports.getAssetMimeType=function(e){return y[e.toLowerCase()]},exports.getAssetTypeEntry=b,exports.getComponent=te,exports.getComponentAssetFieldDescriptors=ys,exports.getComponentAssetFields=gs,exports.getComponentDefaults=function(e){const t=te(e);return t?j(t._default):null},exports.getComponentEntityFields=ws,exports.getComponentSpineFieldDescriptor=_s,exports.getCustomExtensions=S,exports.getEditorType=function(e){return b(e)?.editorType??"unknown"},exports.getEffectDef=En,exports.getEffectTypes=function(){return Array.from(Tn.keys())},exports.getLogger=function(){return pa},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getTextureDimensions=Qt,exports.getTilemapSource=ts,exports.getUserComponent=K,exports.getWeChatPackOptions=function(){return S().map(e=>({type:"suffix",value:e}))},exports.imagePlugin=Wo,exports.info=function(e,t,s){pa.info(e,t,s)},exports.initDrawAPI=Xs,exports.initGLDebugAPI=Gn,exports.initGeometryAPI=un,exports.initMaterialAPI=Et,exports.initParticleAPI=Ga,exports.initPlayableRuntime=async function(e){const{app:t,module:s,assets:n,scenes:i,firstScene:o}=e,r=t.getResource(As);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await hl(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 hl(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new dl(n);await ra({app:t,module:s,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()},exports.initPostProcessAPI=vn,exports.initRendererAPI=Nn,exports.initRuntime=ra,exports.initTilemapAPI=ns,exports.initTweenAPI=Ia,exports.initWeChatRuntime=async function(e){const t=await o("asset-manifest.json"),s=JSON.parse(t),n=function(e){const{assetIndex:t,pathIndex:s}=e;return e=>{const n=M(e),i=t[e]||t[n]||s[n]||s[e];return i?i.path:n}}(function(e){const t={},s={};for(const n in e.groups){const i=e.groups[n];for(const e in i.assets){const n=i.assets[e];t[e]=n,s[n.path]=n}}return{assetIndex:t,pathIndex:s}}(s)),i=wx.createCanvas(),r=wx.getSystemInfoSync();i.width=r.windowWidth*r.pixelRatio,i.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:i,instantiateWasm:yl("esengine.wasm")}),l=i.getContext("webgl2")||i.getContext("webgl");if(!l)return void console.error("[ESEngine] Failed to create WebGL context");const c=a.GL.registerContext(l,{majorVersion:0===l.getParameter(l.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),u=ml(a,{glContextHandle:c,getViewportSize:()=>({width:i.width,height:i.height})});e.runtimeConfig&&H(u,e.runtimeConfig);let d=null;e.spineFactory&&(d=await _l(e.spineFactory,"spine.wasm"));let h=null;e.physicsFactory&&(h=await _l(e.physicsFactory,"physics.wasm"));const p=new gl(n),f=[];for(const t of e.sceneNames){const e=await o(`scenes/${t}.json`);f.push({name:t,data:JSON.parse(e)})}await ra({app:u,module:a,provider:p,scenes:f,firstScene:e.firstScene,spineModule:d,physicsModule:h,physicsConfig:e.physicsConfig,manifest:s,aspectRatio:i.width/i.height}),u.run()},exports.inputPlugin=wt,exports.instantiatePrefab=Fs,exports.intersectRects=eo,exports.invertMatrix4=to,exports.isBuiltinComponent=Q,exports.isCustomExtension=P,exports.isEditor=wo,exports.isKnownAssetExtension=v,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=bo,exports.isRuntime=function(){return!_o},exports.isTextureRef=St,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.layoutGroupPlugin=Cr,exports.listViewPlugin=_r,exports.loadComponent=Ts,exports.loadPhysicsModule=Rr,exports.loadRuntimeScene=ia,exports.loadSceneData=Ss,exports.loadSceneWithAssets=Ps,exports.loadTiledMap=function(e,t,s,n={}){const i=[],o=t.tilesets[0];let r=0;for(const n of t.layers){if(!n.visible)continue;const a=e.spawn();e.insert(a,re,{});const l=o?s.get(o.image)??0:0,c=o?.columns??1;e.insert(a,as,{width:n.width,height:n.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(n.tiles),tint:{...n.tintColor},opacity:n.opacity,visible:n.visible,parallaxFactor:{x:n.parallaxX,y:n.parallaxY}}),i.push(a),r++}if(!1!==n.generateObjectCollision&&t.objectGroups.length>0){const s=function(e,t,s,n){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=s+a+.5*t.width,u=n+(o-l)-.5*t.height,d=-t.rotation*ps;if(e.insert(r,re,{position:{x:c,y:u,z:0}}),e.insert(r,Pe,{bodyType:Ee.Static}),"ellipse"===t.shape){const s=.5*Math.max(t.width,t.height);e.insert(r,Te,{radius:s})}else if("polygon"===t.shape&&t.vertices){let s=1/0,n=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<s&&(s=r),r>i&&(i=r),a<n&&(n=a),a>o&&(o=a)}const a=i-s,l=o-n,c=.5*(s+i),u=.5*(n+o);e.insert(r,Me,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,Me,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==d){const t=.5*d;e.insert(r,re,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...s)}const a=new Set(n.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const s of t.layers){if(!s.visible)continue;const n=fs(e,s,t,a,0,0);i.push(...n)}return i},exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&v(w(e)))},exports.parseAnimClipData=Vt,exports.parseTiledMap=async function(e,t){const s=ss;if(!s)return null;const n=new TextEncoder,i=n.encode(e),o=s._malloc(i.byteLength);s.HEAPU8.set(i,o);const r=s.tiled_loadMap(o,i.byteLength);if(s._free(o),0===r)return null;try{const e=s.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=s.tiled_getExternalTilesetSource(r,i);if(!t)return s.tiled_freeMap(r),null;const o=await t(e),a=n.encode(o),l=s._malloc(a.byteLength);s.HEAPU8.set(a,l);const c=s.tiled_loadExternalTileset(r,i,l,a.byteLength);if(s._free(l),!c)return s.tiled_freeMap(r),null}if(!s.tiled_finalize(r))return s.tiled_freeMap(r),null;const i={width:s.tiled_getMapWidth(r),height:s.tiled_getMapHeight(r),tileWidth:s.tiled_getMapTileWidth(r),tileHeight:s.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},o=s.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=s.tiled_getLayerWidth(r,e),n=s.tiled_getLayerHeight(r,e),o=t*n,a=2*o,l=s._malloc(a);s.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(s.HEAPU8.buffer,l,o)),s._free(l),i.layers.push({name:s.tiled_getLayerName(r,e),width:t,height:n,visible:s.tiled_getLayerVisible(r,e),tiles:c,opacity:s.tiled_getLayerOpacity(r,e),tintColor:s.tiled_getLayerTintColor?ls(s.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:s.tiled_getLayerParallaxX(r,e),parallaxY:s.tiled_getLayerParallaxY(r,e)})}const a=s.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:s.tiled_getTilesetName(r,e),image:s.tiled_getTilesetImage(r,e),tileWidth:s.tiled_getTilesetTileWidth(r,e),tileHeight:s.tiled_getTilesetTileHeight(r,e),columns:s.tiled_getTilesetColumns(r,e),tileCount:s.tiled_getTilesetTileCount(r,e)});return s.tiled_freeMap(r),i}catch{return s.tiled_freeMap(r),null}},exports.parseTmjJson=ds,exports.particlePlugin=Qa,exports.platformFetch=n,exports.platformFileExists=r,exports.platformInstantiateWasm=a,exports.platformReadFile=i,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,i,o,r,a,l,c){const u=no(l,c),d=Math.sin(-u),h=Math.cos(-u),p=e-s,f=t-n,m=p*h-f*d+s,g=p*d+f*h+n;return m>=s-i*r&&m<=s+i*(1-r)&&g>=n-o*a&&g<=n+o*(1-a)},exports.pointInWorldRect=function(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)},exports.postProcessPlugin=$n,exports.prefabsPlugin=$s,exports.progressBarPlugin=Yo,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerAnimClip=jt,exports.registerAssetBuildTransform=function(e,t){for(const s of g)s.editorType===e&&(s.buildTransform=t)},exports.registerComponent=ee,exports.registerComponentAssetFields=function(e,t){ms.set(e,t)},exports.registerComponentEntityFields=function(e,t){xs.set(e,t)},exports.registerDrawCallback=tn,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(As);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Wt,exports.registerTextureDimensions=Jt,exports.registerTilemapSource=es,exports.remapEntityFields=bs,exports.resolveRelativePath=hs,exports.safeAreaPlugin=fr,exports.sceneManagerPlugin=oi,exports.screenToWorld=so,exports.scrollViewPlugin=sr,exports.setEditorMode=function(e){_o=e},exports.setListViewRenderer=function(e,t){if(!gr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=gr.get(e);s?s.renderer=t:gr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){pa.setMinLevel(e)},exports.setPlayMode=function(e){xo=e},exports.setWasmErrorHandler=He,exports.shutdownDrawAPI=Ys,exports.shutdownGLDebugAPI=qn,exports.shutdownGeometryAPI=dn,exports.shutdownMaterialAPI=At,exports.shutdownParticleAPI=qa,exports.shutdownPostProcessAPI=Sn,exports.shutdownRendererAPI=jn,exports.shutdownTilemapAPI=is,exports.shutdownTweenAPI=Fa,exports.sliderPlugin=lr,exports.spriteAnimatorSystemUpdate=Yt,exports.statsPlugin=ul,exports.syncFillSpriteSize=function(e,t,s,n,i,o){if(!e.has(t,ce))return;const r=e.get(t,ce);let a,l;switch(s){case bi.BottomToTop:case bi.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,ce,r))},exports.syncPostProcessVolume=function(e,t){let s=An.get(e),n=Rn.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(s||(s=Mn.createStack(),An.set(e,s)),n||(n=new Map,Rn.set(e,n));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const e of i){const t=En(e.type);if(!t)continue;let i=n.get(e.type);void 0===i&&(i=t.factory(),n.set(e.type,i)),s.addPass(e.type,i);for(const n of t.uniforms){const t=e.uniforms[n.name]??n.defaultValue;s.setUniform(e.type,n.name,t)}}Mn.bind(e,s)}else if(s&&(Mn.unbind(e),s.destroy(),An.delete(e)),n){for(const e of n.values())It.releaseShader(e);Rn.delete(e)}},exports.textInputPlugin=Io,exports.textPlugin=Ki,exports.tilemapPlugin=tl,exports.toBuildPath=M,exports.togglePlugin=Ho,exports.transitionTo=async function(e,t,s){const n=e.getResource(si);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=Mo,exports.uiLayoutPlugin=yo,exports.uiMaskPlugin=lo,exports.uiPlugins=pl,exports.uiRenderOrderPlugin=Ar,exports.unregisterAnimClip=function(e){Nt.delete(e)},exports.unregisterComponent=function(e){G().delete(e),Z.delete(e)},exports.unregisterDrawCallback=sn,exports.updateCameraAspectRatio=Cs,exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){pa.warn(e,t,s)},exports.wrapSceneSystem=ni,exports.wxFileExists=function(e){return new Promise(t=>{C().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})},exports.wxFileExistsSync=A,exports.wxGetImagePixels=I,exports.wxLoadImage=R,exports.wxLoadImagePixels=F,exports.wxReadFile=function(e){return new Promise((t,s)=>{C().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(E(e,t.errMsg)))}})})},exports.wxReadTextFile=function(e,t="utf-8"){return new Promise((s,n)=>{C().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(E(e,t.errMsg)))}})})},exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{C().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};//# sourceMappingURL=index.wechat.cjs.js.mapdiff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.jsindex 87ad6e81d..80132aec2 100644--- a/desktop/public/sdk/cjs/index.wechat.js+++ b/desktop/public/sdk/cjs/index.wechat.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 n(){return null!==e}function s(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,n){return t().fetch(e,n)}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 u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}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),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class g{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 y{constructor(e,t,n){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=n}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class _{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}async loadBufferFromData(e,t){return this.loadBuffer(e)}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const n=this.urlCache_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=wx.createInnerAudioContext();s.loop=t.loop??!1,s.volume=t.volume??1,s.playbackRate=t.playbackRate??1,s.startTime=t.startOffset??0,s.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,s);const o=new y(i,s,this.contexts_);return s.onEnded(()=>{o.onEnd?.(),s.loop||(s.destroy(),this.contexts_.delete(i))}),s.onError(e=>{console.error(`[WeChatAudio] Playback error for "${n}":`,e.errMsg)}),s.src=n,s.play(),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function w(e,t){return new Promise((n,s)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function x(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const b=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],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},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],v={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",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",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"},S=new Map,M=new Set;for(const e of b)for(const t of e.extensions)S.set(t,e),M.add(t);function P(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function T(e){return S.get(P(e))}function C(e){return T(e)?.editorType??"unknown"}function E(e){return T(e)?.addressableType??null}function A(e){for(const t of b)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function R(e){return M.has(e.toLowerCase())}function I(){return M}function k(e){return"string"==typeof e&&(!!e.includes("/")&&R(P(e)))}function F(){const e=[];for(const t of b)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function B(){return F().map(e=>({type:"suffix",value:e}))}function z(e){return v[e.toLowerCase()]}function U(e){const t=T(e);return t?.wechatPackInclude??!1}function W(e){const t=T(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}function $(e,t){for(const n of b)n.editorType===e&&(n.buildTransform=t)}function D(e){return T(e)?.buildTransform}let L=null;function O(){return L||(L=wx.getFileSystemManager()),L}function H(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(U(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function j(e){return new Promise((t,n)=>{O().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(H(e,t.errMsg)))}})})}function V(e,t="utf-8"){return new Promise((n,s)=>{O().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(H(e,t.errMsg)))}})})}function X(e){return new Promise(t=>{O().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function N(e){const t=O();try{return t.accessSync(e),!0}catch{return!1}}function Y(e,t){return new Promise((n,s)=>{O().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function q(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function G(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const i=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(i.data.buffer)}}async function K(e){return G(await q(e))}let J=!1;const Q=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return w(e,t)}async readFile(e){return function(e){return O().readFileSync(e)}(W(e))}async readTextFile(e){return function(e,t="utf-8"){return O().readFileSync(e,t)}(W(e))}async fileExists(e){return N(W(e))}async loadImagePixels(e){return K(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return x(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t=>e.onKeyDown(t.code),s=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(n),wx.onKeyUp(s));const o=t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)},r=t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)},a=t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(n),wx.offKeyUp(s)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new _}},Z=1920,ee=1080,te=100,ne=512,se={x:100,y:100},ie="Arial",oe=24,re=1.2,ae=.5,le=1/60,ce={x:0,y:-9.81},ue=1/60,de="default",he={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function fe(e){e.Text&&(e.Text._default.fontFamily=he.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=he.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=he.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=he.canvasMatchWidthOrHeight)}const pe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function me(e,t){if(void 0!==t.maxDeltaTime&&(he.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(he.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(he.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(he.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(he.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");he.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&&(he.canvasScaleMode=pe[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(he.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const ge=0,ye=4294967295,_e=4294967295,we=0,xe=(e=0,t=0)=>({x:e,y:t}),be=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),ve=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),Se=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),Me=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function Pe(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Pe);const t={};for(const n in e)t[n]=Pe(e[n]);return t}let Te=0;function Ce(e,t){const n=++Te,s=function(e){for(const t in e){const n=e[t];if(null!==n&&"object"==typeof n)return!0}return!1}(t);return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>s?e?{...Pe(t),...e}:Pe(t):e?{...t,...e}:{...t}}}function Ee(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Ae(e,t){const n=Ue.get(e)??Ee().get(e);if(n)return n;const s=Ce(e,t);return Ee().set(e,s),Ue.set(e,s),Be(e,t,!1),s}function Re(e){const t=Ue.get(e)??Ee().get(e);if(t)return t;const n=Ce(e,{});return Ee().set(e,n),Ue.set(e,n),Be(e,{},!0),n}function Ie(e){return Ee().get(e)}function ke(){const e=Ee();for(const t of e.keys())Ue.delete(t);e.clear()}function Fe(e){Ee().delete(e),Ue.delete(e)}function Be(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function ze(e){return!0===e._builtin}const Ue=new Map;function We(e,t){Ue.set(e,t)}function $e(e){return Ue.get(e)??Ie(e)}function De(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Ue.set(e,n),n}const Le={Perspective:0,Orthographic:1},Oe={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},He={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},je=De("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}}),Ve=je,Xe=je,Ne=De("Sprite",{texture:ye,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}),Ye=De("Camera",{projectionType:Le.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:Oe.ColorAndDepth}),qe=De("Canvas",{designResolution:{x:Z,y:ee},pixelsPerUnit:100,scaleMode:He.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Ge=De("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ke=De("Parent",{entity:0}),Je=De("Children",{entities:[]}),Qe=De("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:_e,enabled:!0}),Ze=De("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}),et={Point:0,Circle:1,Rectangle:2,Cone:3},tt={World:0,Local:1},nt={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},st=De("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:et.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:nt.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:nt.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:ye,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:tt.World,enabled:!0}),it=Ae("Name",{value:""}),ot=Ae("SceneOwner",{scene:"",persistent:!1}),rt=Ae("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function at(e){const t=$e(e);return t?Pe(t._default):null}const lt=De("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ct=De("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ut=De("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),dt=De("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ht={Static:0,Kinematic:1,Dynamic:2};let ft=0;function pt(e,t){const n=++ft;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function mt(e){return{_type:"res",_resource:e}}function gt(e){return{_type:"res_mut",_resource:e}}class yt{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 _t{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 yt(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const wt=pt({delta:0,elapsed:0,frameCount:0},"Time");function xt(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=bt(t[e]),o=bt(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function bt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function vt(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let St=null;function Mt(e){St=e}function Pt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),St&&St(e,t)}function Tt(e){let t=!1;for(const n of Object.keys(e)){const s=e[n];if(null!=s&&"object"==typeof s&&!Array.isArray(s)){if("r"in s&&"g"in s&&"b"in s&&"a"in s&&!("x"in s)){t=!0;break}}}if(!t)return e;const n={};for(const t of Object.keys(e)){const s=e[t];if(null==s||"object"!=typeof s||Array.isArray(s))n[t]=s;else{const e=s;n[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}:s}}return n}let Ct=1;const Et=new WeakMap;function At(e){let t=Et.get(e);return void 0===t&&(t=Ct++,Et.set(e,t)),t}const Rt=[];function It(e,t=[],n=[]){Rt.length=0;for(const t of e)Rt.push(At(t));Rt.sort((e,t)=>e-t);let s=Rt.join(",");if(t.length>0){Rt.length=0;for(const e of t)Rt.push(At(e));Rt.sort((e,t)=>e-t),s+="|+"+Rt.join(",")}if(n.length>0){Rt.length=0;for(const e of n)Rt.push(At(e));Rt.sort((e,t)=>e-t),s+="|-"+Rt.join(",")}return s}class kt{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 Pt(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){Pt(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,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(n){Pt(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Pt(t,`removeParent(entity=${e})`)}}insert(e,t,n){return ze(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(ze(t)){if(this.cppRegistry_)try{const s=t._default,i=n;let o=i;for(const e of Object.keys(i))e in s||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,Tt(o))}catch(n){Pt(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return ze(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return ze(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(ze(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Pt(n,`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.");ze(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],o=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"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:s.bind(n),get:i.bind(n),has:o.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s=t._default,i={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(i[e]=t);const e=xt(t._name,s,i);if(e.length>0)throw new Error(vt(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,Tt(o))}catch(n){Pt(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],o=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))s[n]=i;else{const e=i,t=o;s[n]="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 s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return Pt(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return Pt(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Pt(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const i=xt(t._name,t._default,e);if(i.length>0)throw new Error(vt(t._name,i));s=e}const i=t.create(s),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 n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.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[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of Ue)if(ze(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e=Ee();for(const s of n)for(const[n,i]of e)if(i._id===s){t.add(n);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const i=s??It(e,t,n),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(!ze(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,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 s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Ft(e){return{_type:"mut",_component:e}}function Bt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function zt(e){return{_filterType:"added",_component:e}}function Ut(e){return{_filterType:"changed",_component:e}}function Wt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function $t(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Dt(e){return Bt(e)||Wt(e)||$t(e)?e._component:e}function Lt(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{Bt(e)&&s.push(t),Wt(e)?i.push({index:t,component:e._component}):$t(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>Lt(e,[...t,...s],n),without:(...s)=>Lt(e,t,[...n,...s])}}function Ot(...e){return Lt(e)}class Ht{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Dt),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_=It(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=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 u of n)if(!o||this.passesChangeFilters_(u)){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]=u;for(let e=0;e<s;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}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,...n]of this)e(t,...n)}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 jt(e){return{_type:"removed",_component:e}}class Vt{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n}*[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 Xt(){return{_type:"commands"}}class Nt{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 n;return n=ze(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),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 Yt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Nt(this,null);return this.spawned_.push(e),e}entity(e){return new Nt(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,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,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 qt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class Gt{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 Kt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Gt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Gt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function Jt(e){return{_type:"event_writer",_event:e}}function Qt(e){return{_type:"event_reader",_event:e}}class Zt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class en{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var tn;function nn(){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"}(tn||(tn={}));let sn=0;function on(e,t,n){const s=++sn;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function rn(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function an(e){rn().push({schedule:tn.Update,system:e})}function ln(e){rn().push({schedule:tn.Startup,system:e})}function cn(e,t){rn().push({schedule:e,system:t})}class un{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??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 n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);const n=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Yt&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new Ht(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 Yt(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Zt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new en(n)}case"removed":{const t=e;return new Vt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class dn{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 hn=pt(new dn,"Input");class fn{constructor(e){this.target_=e??null}build(e){const n=new dn;e.insertResource(hn,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(tn.Last,on([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const pn=new fn,mn=pt({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 gn;function yn(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"}(gn||(gn={}));let _n=null,wn=null,xn=1;const bn=new Map;function vn(e){_n=e,wn=e.getResourceManager(),kn()}function Sn(){0!==Cn&&_n&&(_n._free(Cn),Cn=0),bn.clear(),xn=1,Tn=!1,An.clear(),Rn=null,wn=null,_n=null}function Mn(){if(!wn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return wn}const Pn={createShader:(e,t)=>Mn().createShader(e,t),releaseShader(e){e>0&&Mn().releaseShader(e)},create(e){const t=xn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??gn.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return bn.set(t,n),t},get:e=>bn.get(e),setUniform(e,t,n){const s=bn.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,_n?.invalidateMaterialCache(e))},getUniform(e,t){const n=bn.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=bn.get(e);n&&(n.blendMode=t,_n?.invalidateMaterialCache(e))},getBlendMode(e){const t=bn.get(e);return t?.blendMode??gn.Normal},setDepthTest(e,t){const n=bn.get(e);n&&(n.depthTest=t,_n?.invalidateMaterialCache(e))},getShader(e){const t=bn.get(e);return t?.shader??0},release(e){bn.delete(e),_n?.invalidateMaterialCache(e)},isValid:e=>bn.has(e),releaseAll(){bn.clear(),_n?.clearMaterialCache()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??gn.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=bn.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=xn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return bn.set(n,s),n},toAssetData(e,t){const n=bn.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=bn.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Tn=!1,Cn=0;const En=16384,An=new Map;let Rn=null;function In(e){const t=(0===Cn&&_n&&(Cn=_n._malloc(En)),Cn);if(0===t||!_n)return{ptr:0,count:0};let n=0,s=0;const i=_n.HEAPU8,o=_n.HEAPU32,r=_n.HEAPF32;for(const[a,l]of e){if(yn(l))continue;let e=An.get(a);e||(Rn||(Rn=new TextEncoder),e=Rn.encode(a),An.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>En){console.warn(`[ESEngine] Material uniform buffer full (${n}/${En} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=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?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function kn(){if(!_n||Tn)return;_n.materialDataProvider=(e,t,n,s,i)=>{const o=bn.get(e);if(!o)return _n.HEAPU32[t>>2]=0,_n.HEAPU32[n>>2]=0,_n.HEAPU32[s>>2]=0,void(_n.HEAPU32[i>>2]=0);_n.HEAPU32[t>>2]=o.shader,_n.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=In(o.uniforms);_n.HEAPU32[s>>2]=r,_n.HEAPU32[i>>2]=a},Tn=!0}const Fn={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 Bn{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+5e3}),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(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class zn{constructor(e,t=""){this.cache_=new Bn,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&&(Pn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Pn.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 n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:Pn.createFromAsset(s,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 n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Un(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Wn(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const $n=new Map;function Dn(e){$n.set(e.name,e)}function Ln(e){$n.delete(e)}function On(e){return $n.get(e)}function Hn(){$n.clear()}const jn=Ae("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Vn(e,t){const n=e.getEntitiesWithComponents([jn]);for(const s of n){const n=e.get(s,jn);if(!n.enabled||!n.playing||!n.clip)continue;const i=$n.get(n.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*n.speed),r=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let a=r;if(n.frameTimer>=o&&(n.frameTimer-=o,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),a=!0),a&&e.has(s,Ne)){const t=i.frames[n.currentFrame],o=e.get(s,Ne);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,Ne,o)}a&&e.insert(s,jn,n)}}class Xn{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 async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:n,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}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 n=this.mixer_?.getBus(e);n&&(n.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,n){e.setVolume(0);const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(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}}}}Xn.mixer_=null,Xn.bufferCache_=new Map,Xn.bgmHandle_=null,Xn.bgmVolume_=1,Xn.fadeAnimId_=0,Xn.disposed_=!1;const Nn=new Map,Yn=new Map;function qn(e,t,n){Nn.set(e,{width:t,height:n})}function Gn(e){return Nn.get(e)}function Kn(){Nn.clear()}function Jn(e,t){Yn.set(e,t)}function Qn(e){return Yn.get(e)}function Zn(){Yn.clear()}let es=null;function ts(e){es=e}function ns(){es=null}const ss={initLayer(e,t,n,s,i){es?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){es?.tilemap_destroyLayer(e)},setTile(e,t,n,s){es?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>es?es.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){es?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!es)return;const n=t.byteLength,s=es._malloc(n);new Uint16Array(es.HEAPU8.buffer,s,t.length).set(t),es.tilemap_setTiles(e,s,t.length),es._free(s)},hasLayer:e=>!!es&&es.tilemap_hasLayer(e),submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h,f,p,m,g,y,_,w){es?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h,f,p,m,g,y,_,w)}},is=Ae("Tilemap",{source:""}),os=Ae("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function rs(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function as(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function ls(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function cs(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=ls(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,d=as(e.tintcolor),h="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l,opacity:u,tintColor:d,parallaxX:h,parallaxY:f})}const u=[],d=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}n.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:n})}if(o)for(const e of o){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.properties;if(n)for(const s of n)"collision"===s.name&&!0===s.value&&d.push(e.id+t)}}return{width:t,height:n,tileWidth:s,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:d}}function us(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function ds(e,t){const n=es;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?rs(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch{return n.tiled_freeMap(r),null}}const hs=Math.PI/180;function fs(e,t,n,s,i,o){const r=function(e,t,n,s){const i=new Uint8Array(t*n),o=[],r=(o,r)=>{if(o>=t||r>=n)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let o=0;o<a;o++)i[(e+n)*t+(s+o)]=1;o.push({col:s,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,u=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=i+t.col*l+.5*n,d=o+(u-t.row*c)-.5*s,h=e.spawn();e.insert(h,je,{position:{x:r,y:d,z:0}}),e.insert(h,lt,{bodyType:ht.Static}),e.insert(h,ct,{halfExtents:{x:.5*n,y:.5*s}}),a.push(h)}return a}function ps(e,t,n,s={}){const i=[],o=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,je,{});const l=o?n.get(o.image)??0:0,c=o?.columns??1;e.insert(a,os,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),i.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,u=s+(o-l)-.5*t.height,d=-t.rotation*hs;if(e.insert(r,je,{position:{x:c,y:u,z:0}}),e.insert(r,lt,{bodyType:ht.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,ut,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>i&&(i=r),a<s&&(s=a),a>o&&(o=a)}const a=i-n,l=o-s,c=.5*(n+i),u=.5*(s+o);e.insert(r,ct,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,ct,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==d){const t=.5*d;e.insert(r,je,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=fs(e,n,t,a,0,0);i.push(...s)}return i}const ms=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"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function gs(e,t){ms.set(e,t)}function ys(e){const t=ms.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function _s(e){return ms.get(e)?.fields??[]}function ws(e){return ms.get(e)?.spine??null}const xs=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function bs(e,t){xs.set(e,t)}function vs(e){return xs.get(e)}function Ss(e,t){const n=xs.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const o=t.get(n);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==o?o:0}}}function Ms(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,it,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const i of s.components)Ss(i,n),Es(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function Ps(e,t){return Ms(e,t)}async function Ts(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,o=new Map;s&&await async function(e,t,n,s,i){const o=new Map;for(const e of Cs.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=ms.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Cs.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),i){for(const e of s.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=ms.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,o,n?.collectAssets);const r=Ms(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const Cs=new Map([["texture",{async load(e,t,n,s){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o),qn(r.handle,r.width,r.height)}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,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=Un(i),r=new Map,a=o.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);Dn(Wn(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,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await Xn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=cs(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=us(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),qn(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}Jn(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Es(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=$e(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function As(e,t){const n=e.getEntitiesWithComponents([Ye]);for(const s of n){const n=e.get(s,Ye);n&&(n.aspectRatio=t,e.insert(s,Ye,n))}}function Rs(e,t){const n=e.getEntitiesWithComponents([it]);for(const s of n){const n=e.get(s,it);if(n&&n.value===t)return s}return null}class Is{constructor(e){this.textureCache_=new Bn,this.shaderCache_=new Bn,this.jsonCache_=new Bn,this.textCache_=new Bn,this.binaryCache_=new Bn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Bn,this.prefabCache_=new Bn,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_=d(he.textCanvasSize,he.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 zn(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);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 n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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(),Pn.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 n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),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,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===T(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,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 n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=T(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}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),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const i=n?`${n}/${s}`:s;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,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 n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of ys(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=ws(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.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 n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Ts(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.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},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"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 n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((n,s)=>{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 n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,n,s,t):this.createTextureFallback(e,n,s,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,n,s,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,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),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,n),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,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return Pn.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return Pn.createShader(i,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.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(W(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.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 n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let i="";for(const e of s){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 n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const ks=pt(null,"Assets");class Fs{build(e){const t=e.wasmModule;t?e.insertResource(ks,new Is(t)):console.warn("AssetPlugin: No WASM module available")}}const Bs=new Fs;class zs{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.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 n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.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 n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.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,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});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 Us(e,t){const n=e.getResource(ks);n&&n.registerEmbeddedAssets(t)}async function Ws(e,t,n){const{entities:s,rootId:i}=await Ds(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},r=await Ts(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=r.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:r}}const $s=10;async function Ds(e,t,n,s,i,o=0){if(o>$s)throw new Error(`Prefab nesting depth exceeded ${$s}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===s){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=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Ds(e,s.nestedPrefab.overrides,n,a,i,o+1);r.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?r.get(s.parent)??null:null),l.push(...t.entities);continue}const c=r.get(s.prefabEntityId),u=s.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:u?null:null!==s.parent?r.get(s.parent)??null:null,children:s.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Ls(d.components,r),Os(d,t),l.push(d)}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 Ls(e,t){for(const n of e){const e=vs(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function Os(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Hs{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Ws(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const js=pt(null,"Prefabs");class Vs{constructor(){this.name="PrefabsPlugin",this.dependencies=[ks]}build(e){const t=e.getResource(ks);e.insertResource(js,new Hs(e.world,t))}}const Xs=new Vs;let Ns=null,Ys=0,qs=0,Gs=0;const Ks=new Float32Array(256);function Js(e){Ns=e,Ys=Ns._malloc(64),qs=Ns._malloc(64),Gs=Ns._malloc(1024)}function Qs(){Ns&&(Ys&&(Ns._free(Ys),Ys=0),qs&&(Ns._free(qs),qs=0),Gs&&(Ns._free(Gs),Gs=0)),Ns=null}function Zs(){if(!Ns)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ns}const ei={r:1,g:1,b:1,a:1},ti={begin(e){const t=Zs();try{t.HEAPF32.set(e,Ys/4),t.draw_begin(Ys)}catch(e){Pt(e,"Draw.begin")}},end(){try{Zs().draw_end()}catch(e){Pt(e,"Draw.end")}},line(e,t,n,s=1){try{Zs().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Pt(e,"Draw.line")}},rect(e,t,n,s=!0){try{Zs().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Pt(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{Zs().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Pt(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{Zs().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Pt(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{Zs().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Pt(e,"Draw.circleOutline")}},texture(e,t,n,s=ei){try{Zs().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Pt(e,"Draw.texture")}},textureRotated(e,t,n,s,i=ei){try{Zs().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){Pt(e,"Draw.textureRotated")}},setLayer(e){Zs().draw_setLayer(e)},setDepth(e){Zs().draw_setDepth(e)},getDrawCallCount:()=>Ns?Ns.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ns?Ns.draw_getPrimitiveCount():0,setBlendMode(e){Zs().draw_setBlendMode(e)},setDepthTest(e){Zs().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=Zs();s.HEAPF32.set(n,qs/4),s.draw_mesh(e,t,qs)}catch(n){Pt(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Zs(),i=Pn.get(t);if(!i)return;if(ti.setBlendMode(i.blendMode),ti.setDepthTest(i.depthTest),0===i.uniforms.size)return void ti.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,qs/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=ii(t);if(!(s<0)){if(yn(n))Ks[o++]=10,Ks[o++]=s,Ks[o++]=n.slot??e++,Ks[o++]=n.textureId;else if("number"==typeof n)Ks[o++]=1,Ks[o++]=s,Ks[o++]=n;else if(Array.isArray(n)){Ks[o++]=n.length,Ks[o++]=s;for(let e=0;e<n.length;e++)Ks[o++]=n[e]}else"w"in n?(Ks[o++]=4,Ks[o++]=s,Ks[o++]=n.x,Ks[o++]=n.y,Ks[o++]=n.z,Ks[o++]=n.w):"z"in n?(Ks[o++]=3,Ks[o++]=s,Ks[o++]=n.x,Ks[o++]=n.y,Ks[o++]=n.z):(Ks[o++]=2,Ks[o++]=s,Ks[o++]=n.x,Ks[o++]=n.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(Ks.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,qs);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Gs/4),s.draw_meshWithUniforms(e,i.shader,qs,Gs,o)}catch(n){Pt(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},ni={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},si=new Set;function ii(e){const t=ni[e];return void 0!==t?t:(si.has(e)||(si.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(ni).join(", ")}`)),-1)}const oi=new Map;function ri(e,t,n){oi.set(e,{fn:t,scene:n??""})}function ai(e){oi.delete(e)}function li(){oi.clear()}var ci;!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"}(ci||(ci={}));let ui=null,di=0,hi=0,fi=0;function pi(e){ui=e,di=ui._malloc(262144),hi=ui._malloc(65536),fi=ui._malloc(256)}function mi(){ui&&(di&&ui._free(di),hi&&ui._free(hi),fi&&ui._free(fi),di=0,hi=0,fi=0),ui=null}function gi(){if(!ui)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ui}const yi={create(e){const t=gi(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,di/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,fi,i).set(o),t.geometry_init(n,di,s,fi,i,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,hi,s).set(e.indices),t.geometry_setIndices16(n,hi,s)}else{new Uint32Array(t.HEAPU8.buffer,hi,s).set(e.indices),t.geometry_setIndices32(n,hi,s)}}return n},updateVertices(e,t,n=0){const s=gi(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,di/4),s.geometry_updateVertices(e,di,i,n)},release(e){e>0&&gi().geometry_release(e)},isValid:e=>!(!ui||e<=0)&&ui.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return yi.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:ci.Float2},{name:"a_texCoord",type:ci.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const i=s/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;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return yi.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:ci.Float2},{name:"a_texCoord",type:ci.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,i=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);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 yi.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:ci.Float2},{name:"a_texCoord",type:ci.Float2}],indices:new Uint16Array(r)})}};let _i=1;const wi=new Map,xi=new Map;function bi(){return wi}function vi(){return xi}class Si{constructor(){this.passes_=[],this.destroyed_=!1,this.id=_i++,wi.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of xi)t===this&&xi.delete(e);wi.delete(this.id)}}}const Mi="#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";let Pi=null;function Ti(e){Pi=e}function Ci(){for(const e of bi().values())e.destroy();bi().clear(),vi().clear(),Pi&&Ai.isInitialized()&&Ai.shutdown(),Pi=null}function Ei(){if(!Pi)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Pi}const Ai={createStack:()=>new Si,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");vi().set(e,t)},unbind(e){vi().delete(e)},getStack:e=>vi().get(e)??null,init(e,t){try{return Ei().postprocess_init(e,t)}catch(n){return Pt(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ei().postprocess_shutdown()}catch(e){Pt(e,"PostProcess.shutdown")}},resize(e,t){try{Ei().postprocess_resize(e,t)}catch(n){Pt(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!Pi)return!1;try{return Pi.postprocess_isInitialized()}catch(e){return Pt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ei().postprocess_setBypass(e)}catch(e){Pt(e,"PostProcess.setBypass")}},setOutputViewport(e,t,n,s){try{Ei().postprocess_setOutputViewport(e,t,n,s)}catch(e){Pt(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=vi().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(Ai.isInitialized()||Ai.init(1,1),Ai.setBypass(!1),function(e){const t=Ei();try{t.postprocess_clearPasses()}catch(e){return void Pt(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){Pt(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){Pt(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Pt(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):Ai.setBypass(!0)},_resetAfterCamera(){try{Ei().postprocess_clearPasses(),Ei().postprocess_setBypass(!0)}catch(e){Pt(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of vi().keys())e(t)||vi().delete(t)},screenStack:null,setScreenStack(e){Ai.screenStack=e},_beginScreenCapture(){try{Ei().postprocess_beginScreenCapture()}catch(e){Pt(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{Ei().postprocess_endScreenCapture()}catch(e){Pt(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=Ai.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=Ei();try{t.postprocess_clearScreenPasses()}catch(e){return void Pt(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){Pt(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){Pt(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Pt(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{Ei().postprocess_executeScreenPasses()}catch(e){Pt(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Pn.createShader(Mi,"#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:()=>Pn.createShader(Mi,"#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:()=>Pn.createShader(Mi,"#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"),createBloom:()=>Pn.createShader(Mi,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>Pn.createShader(Mi,"#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")},Ri=new Map;function Ii(e){Ri.set(e.type,e)}function ki(e){return Ri.get(e)}function Fi(){return Array.from(Ri.keys())}function Bi(){return Array.from(Ri.values())}Ii({type:"blur",label:"Blur",factory:()=>Ai.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),Ii({type:"bloom",label:"Bloom",factory:()=>Ai.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),Ii({type:"vignette",label:"Vignette",factory:()=>Ai.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),Ii({type:"grayscale",label:"Grayscale",factory:()=>Ai.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),Ii({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>Ai.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const zi=new Map,Ui=new Map;function Wi(e,t){let n=zi.get(e),s=Ui.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=Ai.createStack(),zi.set(e,n)),s||(s=new Map,Ui.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=ki(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}Ai.bind(e,n)}else if(n&&(Ai.unbind(e),n.destroy(),zi.delete(e)),s){for(const e of s.values())Pn.releaseShader(e);Ui.delete(e)}}function $i(e){const t=zi.get(e);t&&(Ai.unbind(e),t.destroy(),zi.delete(e));const n=Ui.get(e);if(n){for(const e of n.values())Pn.releaseShader(e);Ui.delete(e)}}function Di(){for(const e of zi.keys())$i(e)}const Li=pt({enabled:!0},"PostProcessVolumeConfig"),Oi=new Map,Hi=new Map;function ji(e){const t=Hi.get(e);if(void 0!==t)return t;const n=ki(e);if(!n)return null;const s=n.factory();return Hi.set(e,s),s}function Vi(e,t){if(0===t.size){const t=Oi.get(e);return void(t&&(Ai.unbind(e),t.destroy(),Oi.delete(e)))}let n=Oi.get(e);for(n||(n=Ai.createStack(),Oi.set(e,n));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const[e,s]of t){if(!s.enabled)continue;const t=ji(e);if(null!==t){n.addPass(e,t);for(const[t,i]of s.uniforms)n.setUniform(e,t,i)}}n.enabledPassCount>0?Ai.bind(e,n):Ai.unbind(e)}const Xi=on([Ot(rt,je)],e=>{const t=[];for(const[n,s,i]of e)t.push({data:s,tx:{x:i.position.x,y:i.position.y}});if(0===t.length)return;const n=[];for(const{data:e,tx:s}of t)e.isGlobal&&n.push({data:e,factor:1});if(n.length>0){const e=function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,i]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(i-n)*s)}else{const e=new Map;for(const[t,i]of Object.entries(n.uniforms))e.set(t,i*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(n);for(const[t]of Oi)Vi(t,e)}},{name:"PostProcessVolumeSystem"});class Ni{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(Li,{enabled:!0}),e.addSystemToSchedule(tn.PostUpdate,Xi)}cleanup(){Di(),function(){for(const[e,t]of Oi)Ai.unbind(e),t.destroy();Oi.clear();for(const e of Hi.values())Pn.releaseShader(e);Hi.clear()}(),Ai.setScreenStack(null)}}const Yi=new Ni;var qi;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(qi||(qi={}));let Gi=null,Ki=0;function Ji(e){Gi=e,Ki=Gi._malloc(64)}function Qi(){Gi&&Ki&&(Gi._free(Ki),Ki=0),Gi=null}const Zi={init(e,t){Gi?.renderer_init(e,t)},resize(e,t){Gi?.renderer_resize(e,t)},begin(e,t){if(Gi&&Ki)try{Gi.HEAPF32.set(e,Ki/4),Gi.renderer_begin(Ki,t??0)}catch(e){Pt(e,"Renderer.begin")}},flush(){try{Gi?.renderer_flush()}catch(e){Pt(e,"Renderer.flush")}},end(){try{Gi?.renderer_end()}catch(e){Pt(e,"Renderer.end")}},submitSprites(e){if(Gi)try{Gi.renderer_submitSprites(e._cpp)}catch(e){Pt(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Gi)try{Gi.renderer_submitBitmapText(e._cpp)}catch(e){Pt(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Gi)try{Gi.renderer_submitSpine?.(e._cpp)}catch(e){Pt(e,"Renderer.submitSpine")}},submitParticles(e){if(Gi)try{Gi.renderer_submitParticles?.(e._cpp)}catch(e){Pt(e,"Renderer.submitParticles")}},setStage(e){Gi?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Gi?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Gi?.renderer_releaseTarget(e)},getTargetTexture:e=>Gi?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Gi?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Gi?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Gi?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Gi?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Gi?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Gi?Gi.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Gi?{drawCalls:Gi.renderer_getDrawCalls(),triangles:Gi.renderer_getTriangles(),sprites:Gi.renderer_getSprites(),text:Gi.renderer_getText(),spine:Gi.renderer_getSpine?.()??0,meshes:Gi.renderer_getMeshes(),culled:Gi.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let eo=null;function to(e){eo=e}function no(){eo=null}const so={enable(){eo?.gl_enableErrorCheck(!0)},disable(){eo?.gl_enableErrorCheck(!1)},check:e=>eo?.gl_checkErrors(e)??0,diagnose(){eo?.renderer_diagnose()}};class io{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}beginScreenCapture(){Ai.screenStack&&Ai.screenStack.enabledPassCount>0&&(Ai.isInitialized()||Ai.init(1,1),Ai._applyScreenStack(),Ai._beginScreenCapture())}endScreenCapture(){Ai.screenStack&&Ai.screenStack.enabledPassCount>0&&(Ai._endScreenCapture(),Ai._executeScreenPasses())}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(Zi.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Zi.setViewport(0,0,s,i),Zi.clearBuffers(3),Zi.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),this.tilemapRenderer_&&this.tilemapRenderer_(),Zi.submitSprites(t),Zi.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Zi.submitSpine(t),Zi.submitParticles(t),Zi.flush(),this.executeDrawCallbacks(n,o),Zi.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==Ai.getStack(r);a&&(Ai._applyForCamera(r),Ai.resize(s.w,s.h),Ai.setOutputViewport(s.x,s.y,s.w,s.h)),Zi.setViewport(s.x,s.y,s.w,s.h),Zi.setScissor(s.x,s.y,s.w,s.h,!0),Zi.clearBuffers(i),Zi.setScissor(0,0,0,0,!1),Zi.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),this.tilemapRenderer_&&this.tilemapRenderer_(),Zi.submitSprites(t),Zi.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Zi.submitSpine(t),Zi.submitParticles(t),Zi.flush(),this.executeDrawCallbacks(n,o),Zi.end(),a&&Ai._resetAfterCamera()}executeDrawCallbacks(e,t){const n=oi;if(n.size>0){ti.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}ti.end();for(const e of s)ai(e)}}}const oo="__scene_transition_overlay__";class ro{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class ao{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,ot,{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),ri(e,t,this.instance_.config.name)}bindPostProcess(e,t){Ai.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){Ai.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,ot)){const n=this.app_.world.get(e,ot);n.persistent=t,this.app_.world.insert(e,ot,n)}}}class lo{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}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())ai(t);for(const t of e.postProcessBindings.keys())Ai.unbind(t)}this.transition_&&(ai(oo),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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(n=>{const s=t.duration??he.sceneTransitionDuration,i=t.color??{...he.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},ri(oo,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;ti.setLayer(9999),ti.setDepth(9999),ti.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:n})})})}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_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,ai(oo),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,ai(oo),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 n=new ro(t);this.scenes_.set(e,n);const s=new ao(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ks)?this.app_.getResource(ks):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();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 n=new ro(t);this.scenes_.set(e,n);const s=new ao(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ks)?this.app_.getResource(ks):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,ot)){if(this.app_.world.get(e,ot).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())ai(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())Ai.unbind(e);n.postProcessBindings.clear(),this.releaseSceneAssets_(n),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,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(ks)&&(i.assetServer=this.app_.getResource(ks));const o=await Ts(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,ot,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=uo(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(ks)?this.app_.getResource(ks):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)Pn.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 n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,Ne)){const t=n.get(e,Ne);s.sprite=t.color.a,t.color.a=0,n.insert(e,Ne,t),i=!0}if(n.has(e,Ze)){const t=n.get(e,Ze);s.spine=t.color.a,t.color.a=0,n.insert(e,Ze,t),i=!0}if(n.has(e,Qe)){const t=n.get(e,Qe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Qe,t),i=!0}i&&t.savedAlphas.set(e,s)}}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 n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,Ne)){const t=n.get(e,Ne);t.color.a=s.sprite,n.insert(e,Ne,t)}if(void 0!==s.spine&&n.has(e,Ze)){const t=n.get(e,Ze);t.color.a=s.spine,n.insert(e,Ze,t)}if(void 0!==s.bitmapText&&n.has(e,Qe)){const t=n.get(e,Qe);t.color.a=s.bitmapText,n.insert(e,Qe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}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,n]of this.scenes_)"running"===n.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 co=pt(null,"SceneManager");function uo(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(co).getSceneStatus(t)&&n._fn(...s)}}}const ho=on([gt(co),mt(wt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),fo={name:"SceneManager",build(e){const t=new lo(e);e.insertResource(co,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(co),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(tn.Startup,n),e.addSystemToSchedule(tn.Last,ho)}};class po{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 Kt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,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 n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(tn.Last);else{this.runSchedule(tn.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(tn.FixedPreUpdate),this.runSchedule(tn.FixedUpdate),this.runSchedule(tn.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(tn.PreUpdate),this.runSchedule(tn.Update),this.runSchedule(tn.PostUpdate),this.runSchedule(tn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new kt,this.resources_=new _t;for(const e of Object.values(tn))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new po}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,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(tn.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(tn.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),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 Mt(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.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}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(co).register(e),this}setInitialScene(e){return this.getResource(co).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new un(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(wt)||this.resources_.insert(wt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(tn.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(tn.Last);else{this.runSchedule(tn.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(tn.FixedPreUpdate),this.runSchedule(tn.FixedUpdate),this.runSchedule(tn.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(tn.PreUpdate),this.runSchedule(tn.Update),this.runSchedule(tn.PostUpdate),this.runSchedule(tn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new un(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(wt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(tn.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,li();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=[no,Qi,Ci,mi,Sn,Qs];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 n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.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 n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const s=this.phaseTimings_?performance.now():0;for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(tn[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(wt);t.delta=e,t.elapsed+=e,t.frameCount++}}function mo(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const go=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function yo(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case He.FixedWidth:return o;case He.FixedHeight:return r;case He.Expand:return Math.max(o,r);case He.Shrink:return Math.min(o,r);case He.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const _o=[];function wo(e){if(e<_o.length)return _o[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 _o.push(t),t}function xo(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,ot);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*n/(i.viewportH*s);let a,u=0,d=0;if(i.projectionType===Le.Orthographic){if(d=i.orthoSize,l){d=yo(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=vo(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=Mo(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=To(o.position.x,o.position.y,o.position.z),f=wo(c.length);f.entity=e,f.viewProjection.set(Eo(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=u,f.halfH=d,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const bo=new Float32Array(16);function vo(e,t,n,s,i,o){const r=bo;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const So=new Float32Array(16);function Mo(e,t,n,s){const i=So;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const Po=new Float32Array(16);function To(e,t,n){const s=Po;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const Co=new Float32Array(16);function Eo(e,t){const n=Co;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const Ao={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Ro(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*r.x,m=f+i.x):(f=c+n.x,m=u+s.x),e.y===t.y?(p=d+n.y-i.y*r.y,g=p+i.y):(p=d+n.y,g=h+s.y);const y=Math.max(0,m-f),_=Math.max(0,g-p);return{originX:f+r.x*y,originY:p+r.y*_,width:y,height:_,rect:{left:f,bottom:p,right:m,top:g}}}const Io=De("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 ko=null,Fo=null;function Bo(e,t){e.has(t,Ne)||e.insert(t,Ne,{texture:ye,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 zo(e,t){switch(e){case Ao.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ao.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ao.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 Uo(e,t){switch(e){case Ao.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Ao.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Ao.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 Wo(e,t,n,s){switch(e){case Ao.BottomToTop:case Ao.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function $o(e,t,n,s){if(!e.has(t,Io))return;const i=e.get(t,Io),o=zo(n,s);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,Io,i)}function Do(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Lo(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Oo(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if(Lo(r.charCodeAt(0))&&s.length>0&&Lo(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Lo(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Ho(e){let t=1;for(;t<e;)t*=2;return t}function jo(e,t){let n=0,s=t;for(;e.has(s,Ke);){const t=e.get(s,Ke).entity;if(!e.valid(t))break;n++,s=t}return n}function Vo(e,t){if(ko&&Fo){const e=ko.getUIRectComputedWidth(Fo,t);if(e>0)return e}return e.size.x}function Xo(e,t){if(ko&&Fo){const e=ko.getUIRectComputedHeight(Fo,t);if(e>0)return e}return e.size.y}function No(e,t,n,s,i,o){if(!e.has(t,Ne))return;const r=e.get(t,Ne);let a,l;switch(n){case Ao.BottomToTop:case Ao.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,Ne,r))}function Yo(e,t,n){let s=t;for(;e.has(s,Ke);){const t=e.get(s,Ke).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function qo(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Go(e,t,n,s,i){if(!e.has(t,Io))return;const o=e.get(t,Io),r=Ro(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,n,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,Ne)){const n=e.get(t,Ne);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,Ne,n))}if(e.has(t,je)){const n=e.get(t,je);n.position.x=r.originX-s,n.position.y=r.originY-i,e.insert(t,je,n)}}function Ko(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const Jo=.1,Qo=30,Zo={r:.3,g:.5,b:.8,a:1},er={Left:0,Center:1,Right:2},tr={Top:0,Middle:1,Bottom:2},nr={Visible:0,Clip:1,Ellipsis:2},sr=Ae("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:er.Left,verticalAlign:tr.Top,wordWrap:!0,overflow:nr.Visible,lineHeight:1.2});class ir{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=d(he.textCanvasSize,he.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,Ho(this.frameMaxW_)),e.height=Math.max(e.height,Ho(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ho(this.frameMaxW_),e.height=Ho(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 n=this.ctx,s=this.canvas;n.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=Oo(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=i?Math.ceil(o):d+2*u,p=i?Math.ceil(r):h+2*u;if(i&&e.overflow===nr.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),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Ho(f)),s.height=Math.max(s.height,Ho(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===nr.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case tr.Top:x=u;break;case tr.Middle:x=u+(p-2*u-w)/2;break;case tr.Bottom:x=p-w-u;break;default:x=u}x<0&&(x=0)}else x=u;let b=x;for(const t of l){let s;switch(e.align){case er.Left:s=u;break;case er.Center:s=f/2;break;case er.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}i&&e.overflow===nr.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.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 n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const i=this.renderText(t,n);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[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}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 n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case er.Left:return"left";case er.Center:return"center";case er.Right:return"right"}}}const or=Ko({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?Vo(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Xo(e.uiRect,e.entity):0});class rr{build(e){We("Text",sr);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ir(t),s=e.world,i=new Map;e.addSystemToSchedule(tn.PreUpdate,on([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,sr));for(const e of i.keys())if(!s.valid(e)||!s.has(e,sr)){if(s.valid(e)&&s.has(e,Ne)){const t=s.get(e,Ne);s.insert(e,Ne,{texture:ye,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=s.getEntitiesWithComponents([sr]);for(const t of e){const e=s.get(t,sr),o=s.has(t,Io)?s.get(t,Io):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!or.changed(a,r)){if(s.has(t,Ne)&&s.get(t,Ne).texture!==ye)continue}Bo(s,t);const l=o?{size:{x:Vo(o,t),y:Xo(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Ne);s.insert(t,Ne,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,or.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const ar=new rr,lr=0,cr=1,ur=De("UIMask",{enabled:!0,mode:lr});function dr(e,t){const n=Math.max(e.x,t.x),s=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:n,y:s,w:Math.max(0,i-n),h:Math.max(0,o-s)}}function hr(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],w=s*l-i*a,x=s*c-o*a,b=s*u-r*a,v=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=d*g-h*m,T=d*y-f*m,C=d*_-p*m,E=h*y-f*g,A=h*_-p*g,R=f*_-p*y;let I=w*R-x*A+b*E+v*C-S*T+M*P;return 0===I||(I=1/I,n[0]=(l*R-c*A+u*E)*I,n[1]=(o*A-i*R-r*E)*I,n[2]=(g*M-y*S+_*v)*I,n[3]=(f*S-h*M-p*v)*I,n[4]=(c*C-a*R-u*T)*I,n[5]=(s*R-o*C+r*T)*I,n[6]=(y*b-m*M-_*x)*I,n[7]=(d*M-f*b+p*x)*I,n[8]=(a*A-l*C+u*P)*I,n[9]=(i*C-s*A-r*P)*I,n[10]=(m*S-g*b+_*w)*I,n[11]=(h*b-d*S-p*w)*I,n[12]=(l*T-a*E-c*P)*I,n[13]=(s*E-i*T+o*P)*I,n[14]=(g*x-m*v-y*w)*I,n[15]=(d*v-h*x+f*w)*I),n}function fr(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function pr(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function mr(e,t){return 2*Math.atan2(e,t)}function gr(e,t,n,s,i,o,r){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function yr(e,t,n,s,i,o,r,a,l,c){const u=mr(l,c),d=Math.sin(-u),h=Math.cos(-u),f=e-n,p=t-s,m=f*h-p*d+n,g=f*d+p*h+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}function _r(e,t,n,s,i,o,r){if(!e.has(t,Io)||!e.has(t,je))return null;const a=e.get(t,Io),l=e.get(t,je),c=Vo(a,t)*l.worldScale.x,u=Xo(a,t)*l.worldScale.y,d=l.worldPosition.x,h=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,g=c*(1-f),y=-u*p,_=u*(1-p),w=mr(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),b=Math.sin(w),v=[[d+m*x-y*b,h+m*b+y*x],[d+g*x-y*b,h+g*b+y*x],[d+g*x-_*b,h+g*b+_*x],[d+m*x-_*b,h+m*b+_*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of v){const[a,l]=gr(e,t,n,s,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 wr(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([ur]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const n=t.get(e,ur);n.enabled&&(d.add(e),n.mode===cr?(u.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,o,r,a,l,c){const u=[];for(const e of s){let n=!0;Yo(t,e,e=>{if(i.has(e)){if(t.get(e,ur).mode===lr)return n=!1,!0}return!1}),n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(i.has(n)){if(t.get(n,ur).mode===lr){const e=_r(t,n,o,r,a,l,c);e&&(s=dr(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=_r(t,e,o,r,a,l,c);n&&d(e,n)}}(e,t,n,c,d,s,i,o,r,a),u.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0;Yo(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&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,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,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,s),u(t,s)}function u(t,s){if(a)return;const o=e.getChildEntities(n,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,s),u(t,s)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,u,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class xr{build(e){if(We("UIMask",ur),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(wr(e.wasmModule,e.world))}}const br=new xr,vr=De("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Sr=De("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Mr={Normal:0,Hovered:1,Pressed:2,Disabled:3},Pr=Ae("Button",{state:Mr.Normal,transition:null});class Tr{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,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(n=>n.entity===e&&n.type===t)}}const Cr=pt(new Tr,"UIEvents");class Er{build(e){We("UIRect",Io);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){ko=e,Fo=t}(n,s);e.addSystemToSchedule(tn.PreUpdate,on([mt(mn)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s),n.transform_update(s))},{name:"UILayoutSystem"})),e.addSystemToSchedule(tn.PostUpdate,on([mt(mn)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(tn.PostUpdate,on([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ar=new Er;let Rr=!1,Ir=!1;function kr(e){Rr=e}function Fr(){return Rr}function Br(){return!Rr}function zr(e){Ir=e}function Ur(){return Ir}const Wr=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(hr(t,e),n=!1),e)}}();function $r(e,t,n,s){t.emit(n,s,n),Yo(e,n,i=>{if(!e.has(i,vr))return!1;const o=e.get(i,vr);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class Dr{build(e){We("Interactable",vr),We("Button",Pr);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new Tr;e.insertResource(Cr,i);let o=null,r=null;e.addSystemToSchedule(tn.PreUpdate,on([mt(hn),mt(mn)],(e,a)=>{if(i.drain(),Fr()&&!Ur())return;const l=t.getEntitiesWithComponents([Sr]);for(const e of l){const n=t.get(e,Sr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Sr,n))}if(!a.valid)return;const c=f(),u=e.mouseX*c,d=a.screenH-e.mouseY*c;Wr.update(a.viewProjection);const h=fr(u,d,Wr.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),g=e.isMouseButtonReleased(0);n.uiHitTest_update(s,h.x,h.y,p,m,g);const y=n.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,Sr)){const e=t.get(o,Sr);e.hovered=!1,t.insert(o,Sr,e),i.emit(o,"hover_exit")}if(null!==_){qo(t,_,Sr);const e=t.get(_,Sr);e.hovered=!0,t.insert(_,Sr,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,Sr);e.pressed=!0,e.justPressed=!0,t.insert(_,Sr,e),r=_,$r(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,Sr)){const e=t.get(r,Sr);e.pressed=!1,e.justReleased=!0,t.insert(r,Sr,e),$r(t,i,r,"release"),r===o&&$r(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(tn.Update,on([],()=>{const e=t.getEntitiesWithComponents([Pr]);for(const n of e){if(qo(t,n,vr,{enabled:!0}),!t.has(n,Sr))continue;const e=t.get(n,Sr),s=t.get(n,Pr),i=t.get(n,vr),o=!a.has(n),r=s.state;if(i.enabled?e.pressed?s.state=Mr.Pressed:e.hovered?s.state=Mr.Hovered:s.state=Mr.Normal:s.state=Mr.Disabled,o&&a.add(n),(o||r!==s.state)&&s.transition&&t.has(n,Ne)){const o=t.get(n,Ne);o.color=Do(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,Ne,o)}}},{name:"ButtonSystem"}))}}const Lr=new Dr,Or=Ae("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}),Hr=Ae("Focusable",{tabIndex:0,isFocused:!1});class jr{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 Vr=pt(new jr,"FocusManager");class Xr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(We("TextInput",Or),Fr()&&!Ur())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=d(he.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,u=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(Vr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Or)?s:null}const g=()=>{l||null===m()||b()},y=()=>{l=!0},_=()=>{l=!1,b()},w=t=>{const s=m();if(null===s)return;if("Escape"===t.key)return void v();const i=n.get(s,Or);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(Cr).emit(s,"submit"),void v()}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 s=n.get(t,Or);s.focused=!1,s.dirty=!0;e.getResource(Vr).blur()}};function b(){const t=m();if(null===t)return;const s=n.get(t,Or);if(s.readOnly)return;let i=p.value;if(s.maxLength>0&&i.length>s.maxLength&&(i=i.substring(0,s.maxLength),p.value=i),i!==s.value){s.value=i;e.getResource(Cr).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function v(){const t=m();if(null!==t){const e=n.get(t,Or);e.focused=!1,e.dirty=!0}e.getResource(Vr).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",g),p.addEventListener("compositionstart",y),p.addEventListener("compositionend",_),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",y),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,u,d){(i.width<u||i.height<d)&&(i.width=Ho(Math.max(i.width,u)),i.height=Ho(Math.max(i.height,d))),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,u,d),o.save(),o.beginPath(),o.rect(l.padding,0,u-2*l.padding,d),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 g=Math.ceil(1.2*l.fontSize),y=l.padding;if(l.multiline){const e=Oo(o,p,u-2*y);let t=y;for(const n of e)o.fillText(n,y,t),t+=g}else{const e=(d-l.fontSize)/2;o.fillText(p,y,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=Oo(o,l.value,u-2*y);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=n,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=y+o.measureText(c).width,n=y+r*g,s=g}else t=y+o.measureText(e).width,n=(d-l.fontSize)/2,s=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,n,2,s)}o.restore();const _=o.getImageData(0,0,u,d),w=new Uint8Array(_.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 b=s.get(e);void 0!==b&&x.releaseTexture(b);const v=x.createTexture(u,d,r,w.length,1,!0);s.set(e,v);const S=n.get(e,Ne);S.texture=v,S.size.x=u,S.size.y=d,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},n.insert(e,Ne,S)}e.addSystemToSchedule(tn.Update,on([mt(Vr)],e=>{const t=n.getEntitiesWithComponents([Or]);for(const e of t)qo(n,e,Hr,{tabIndex:0,isFocused:!1}),qo(n,e,vr,{enabled:!0,blockRaycast:!0});const s=m();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,Or)){const e=n.get(M,Or);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,Or);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(s),M=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(tn.PreUpdate,on([],()=>{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&&(u+=i,u>=.5)){u-=.5,c=!c;n.get(o,Or).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Or)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Or,Io]);for(const e of a){const t=n.get(e,Or);if(!t.dirty)continue;const s=n.get(e,Io),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(Bo(n,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Nr=new Xr,Yr={Simple:0,Sliced:1,Tiled:2,Filled:3},qr={Horizontal:0,Vertical:1},Gr={Left:0,Right:1,Bottom:2,Top:3},Kr=Ae("Image",{texture:ye,color:{r:1,g:1,b:1,a:1},imageType:Yr.Simple,fillMethod:qr.Horizontal,fillOrigin:Gr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Jr=Ko({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?Vo(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Xo(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Qr{build(e){We("Image",Kr);const t=e.world,n=new Map;e.addSystemToSchedule(tn.PreUpdate,on([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Kr)||n.delete(e);const e=t.getEntitiesWithComponents([Kr]);for(const s of e){const e=t.get(s,Kr),i=t.has(s,Io)?t.get(s,Io):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&!Jr.changed(r,o))continue;Bo(t,s);const a=t.get(s,Ne);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=Vo(i,s),a.size.y=Xo(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Yr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===qr.Horizontal?e.fillOrigin===Gr.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===Gr.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===Yr.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(s,Ne,a),n.set(s,Jr.take(o))}else a.color.a=0,t.insert(s,Ne,a),n.set(s,Jr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Zr=new Qr,ea=Ae("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),ta=Ae("ToggleGroup",{allowSwitchOff:!1});class na{build(e){We("Toggle",ea),We("ToggleGroup",ta);const t=e.world,n=new Set;e.addSystemToSchedule(tn.Update,on([mt(Cr)],e=>{const s=t.getEntitiesWithComponents([ea]);if(!Fr()||Ur()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,ea);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,ea,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,ea);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(qo(t,n,vr,{enabled:!0}),!t.has(n,Sr))continue;const s=t.get(n,Sr),i=t.get(n,ea),r=t.get(n,vr);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,ta);if(i.isOn&&r){if(!t.get(s,ta).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,ea,i),i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,ea);i.isOn&&(i.isOn=!1,t.insert(s,ea,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,Ne)){const e=t.get(n,Ne);e.color=Do(i.transition,r.enabled,s.pressed,s.hovered),t.insert(n,Ne,e)}}}for(const e of s){const n=t.get(e,ea);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,Ne)){const e=t.get(n.graphicEntity,Ne);e.enabled=n.isOn,t.insert(n.graphicEntity,Ne,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const sa=new na,ia=Ao,oa=Ae("ProgressBar",{value:0,fillEntity:0,direction:Ao.LeftToRight});function ra(e,t,n,s){if(!e.has(t,Io))return;const i=e.get(t,Io),o=n/2,r=s/2,a={left:-o,bottom:-r,right:o,top:r},l=Ro(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,Ne)){const n=e.get(t,Ne);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,Ne,n))}if(e.has(t,je)){const n=e.get(t,je),s=n.position;s.x===l.originX&&s.y===l.originY||(n.position={x:l.originX,y:l.originY,z:s.z},e.insert(t,je,n))}}class aa{build(e){We("ProgressBar",oa);const t=e.world;e.addSystemToSchedule(tn.PreUpdate,on([],()=>{const e=t.getEntitiesWithComponents([oa,Io]);for(const n of e){const e=t.get(n,oa);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Io),i=Math.max(0,Math.min(1,e.value));$o(t,e.fillEntity,e.direction,i);const o=Vo(s,n),r=Xo(s,n);ra(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const la=new aa,ca=Ae("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),ua=Ae("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}});class da{build(e){We("Draggable",ca),We("DragState",ua);const t=e.world,n=e.getResource(Cr);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(tn.PreUpdate,on([mt(hn),mt(mn)],(e,r)=>{if(Fr()&&!Ur())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([ca,Sr]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,ca).enabled)continue;if(t.get(s,Sr).hovered){let e=0;t.has(s,Ne)&&(e=t.get(s,Ne).layer);const i=jo(t,s);(e>o||e===o&&i>=r)&&(o=e,r=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,ua)||t.insert(n,ua);const e=t.get(n,ua),o=t.get(n,je);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!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,ua)){t.get(s,ua).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,ca);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,ua).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,ua))return void(o=null);const s=t.get(o,ua),i=t.get(o,ca),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const d=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;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,s,c,u);c=d.x,u=d.y;const h=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-h,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,je)){const e=function(e,t,n,s){if(!e.has(t,Ke))return{x:n,y:s};const i=e.get(t,Ke).entity;if(!e.valid(i)||!e.has(i,je))return{x:n,y:s};const o=e.get(i,je),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=mr(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,je);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,je,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const ha=new da,fa=Ae("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function pa(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function ma(e,t,n,s,i){const o=2/(s=Math.max(1e-4,s)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-o*c)*a}}class ga{build(e){We("ScrollView",fa);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(tn.PostUpdate,on([mt(hn),mt(mn),mt(wt)],(e,i,o)=>{const r=Fr()&&!Ur(),a=Math.min(o.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([fa,Io]);for(const o of l){qo(t,o,ur,{enabled:!0,mode:lr});const l=t.get(o,fa),c=t.get(o,Io);let u=n.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(o,u));const d=Vo(c,o),h=Xo(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,Je)){const e=t.get(l.contentEntity,Je).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,je))continue;const e=t.get(r,je);let a=0,l=0,c=.5,u=.5;if(t.has(r,Io)){const e=t.get(r,Io);a=Vo(e,r)||e.size.x,l=Xo(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,Ne)){const e=t.get(r,Ne);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);d<n&&(n=d),h>s&&(s=h),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-d),g=Math.max(0,p-h);if(!r&&i.valid){qo(t,o,vr,{enabled:!0,blockRaycast:!0});const n=t.has(o,Sr)?t.get(o,Sr):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=pa(l.scrollX,0,m,d);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=pa(l.scrollY,0,g,h);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*d,t=5*h;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=pa(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=pa(l.scrollX,0,m,d);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=ma(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Jo&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Jo?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=ma(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Jo&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Jo?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.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,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*d,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,je)){const e=t.get(l.contentEntity,je),n=e.position.x,s=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(n-u.lastAppliedX)>.01)&&(u.contentBaseX=n),(isNaN(u.lastAppliedY)||Math.abs(s-u.lastAppliedY)>.01)&&(u.contentBaseY=s),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,je,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const ya=new ga,_a=Ao,wa=Ae("Slider",{value:0,minValue:0,maxValue:1,direction:Ao.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function xa(e,t,n,s,i,o){const r=Vo(s,i)*n.worldScale.x,a=Xo(s,i)*n.worldScale.y,l=mr(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-n.worldPosition.x,h=t-n.worldPosition.y,f=d*u-h*c,p=d*c+h*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case Ao.LeftToRight:return r>0?(f-m)/r:0;case Ao.RightToLeft:return r>0?1-(f-m)/r:0;case Ao.BottomToTop:return a>0?(p-g)/a:0;case Ao.TopToBottom:return a>0?1-(p-g)/a:0}}function ba(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Ao.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case Ao.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case Ao.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case Ao.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class va{build(e){We("Slider",wa);const t=e.world;let n=null;e.addSystemToSchedule(tn.PreUpdate,on([mt(hn),mt(mn),mt(Cr)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=t.getEntitiesWithComponents([wa,Io]);for(const r of o){const o=t.get(r,wa),a=t.get(r,Io);if(!Fr()||Ur()){if(t.has(r,je)){qo(t,r,vr,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&qo(t,o.handleEntity,vr,{enabled:!0,blockRaycast:!1});const l=t.get(r,je),c=t.has(r,Sr)?t.get(r,Sr):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Sr)&&(u=t.get(o.handleEntity,Sr).justPressed),u&&(n=r),n===r&&e.isMouseButtonDown(0)){let e=xa(s.worldMouseX,s.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let n=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(n=Math.round(n));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,n)),t.insert(r,wa,o),o.value!==c&&i.emit(r,"change")}n===r&&e.isMouseButtonReleased(0)&&(n=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=Vo(a,r),d=Xo(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&($o(t,o.fillEntity,o.direction,c),Go(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Io)){const e=t.get(o.handleEntity,Io);ba(e,o.direction,c),t.insert(o.handleEntity,Io,e),Go(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Sa=new va;class Ma{build(e){We("Focusable",Hr);const t=e.world,n=new jr;e.insertResource(Vr,n),e.addSystemToSchedule(tn.Update,on([mt(hn),mt(Cr)],(e,s)=>{if(Fr()&&!Ur())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Hr]);for(const e of i){if(!t.has(e,Sr))continue;t.get(e,Sr).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,vr)){if(!t.get(n,vr).enabled)continue}const s=t.get(n,Hr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Hr)){t.get(i,Hr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Hr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Pa=new Ma,Ta=Ae("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Ca(){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:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.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")}}()}class Ea{build(e){We("SafeArea",Ta);const t=e.world;let n=Ca(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Ca(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Ca(),s=!0});e.addSystemToSchedule(tn.PreUpdate,on([mt(mn)],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,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([Ta,Io]);for(const e of u){const s=t.get(e,Ta),i=t.get(e,Io),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Io,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const Aa=new Ea,Ra=Ae("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Ia=null;function ka(e,t){if(!Ia)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Ia.get(e);n?n.renderer=t:Ia.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class Fa{build(e){We("ListView",Ra);const t=e.world,n=new Map;Ia=n,e.addSystemToSchedule(tn.PostUpdate,on([mt(hn)],e=>{const s=Fr()&&!Ur();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([Ra,Io]);for(const o of i){qo(t,o,vr,{enabled:!0,blockRaycast:!0}),qo(t,o,ur,{enabled:!0,mode:lr});let i=n.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,i));const r=t.get(o,Ra),a=t.get(o,Io),l=Xo(a,o),c=Vo(a,o);if(!s){const n=t.has(o,Sr)?t.get(o,Sr):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const d=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,n]of i.itemEntities)(e<d||e>=h)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=d;e<h;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,it,{value:`ListItem_${e}`}),t.insert(n,Io,{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(n,o),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,je)){const s=t.get(n,je);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,je,s)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ba=new Fa,za=Ae("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class Ua{build(e){We("Dropdown",za);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,je))return;const n=t.get(e,je);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,je,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,Ne)){const n=t.get(e,Ne);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,Ne,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},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:n.enabled})}}function o(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(s);const o=t.get(e,Ne),r=o.size.x,a=o.size.y;s.ddWidth=r;const l=n.options.length*Qo;t.insert(i,Io,{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,je,{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,Ne,{texture:ye,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<n.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*Qo;t.insert(o,it,{value:`Option_${e}`}),t.insert(o,Io,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Qo},offsetMax:{x:0,y:0},size:{x:r,y:Qo},pivot:{x:.5,y:.5}}),t.insert(o,je,{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,Ne,{texture:ye,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Qo},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,vr,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),s.optionEntities.push(o);const c=t.spawn();t.insert(c,je,{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,sr,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:er.Left,verticalAlign:tr.Middle,wordWrap:!1,overflow:nr.Clip,lineHeight:1.2}),t.insert(c,Io,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Qo},pivot:{x:.5,y:.5}}),t.setParent(c,o),s.textEntities.push(c)}d(s)}function r(e,t,n){t.isOpen=!1,c(n),u(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,r(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,sr))return;const s=t.get(n,sr);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},o=s.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(n,sr,{content:o,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function u(e,n){if(0!==e&&t.valid(e)&&(t.has(e,vr)&&t.insert(e,vr,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,Ne))){const s=t.get(e,Ne);t.insert(e,Ne,{texture:s.texture,color:{r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},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:n})}}function d(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,Ne))continue;const i=n===e.highlightIndex?{...Zo}:{r:.95,g:.95,b:.95,a:1};t.insert(s,Ne,{texture:ye,color:i,size:{x:e.ddWidth,y:Qo},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 n of e.optionEntities){if(!t.valid(n)||!t.has(n,Sr))continue;if(t.get(n,Sr).hovered)return!0}return!1}e.addSystemToSchedule(tn.Update,on([mt(hn),mt(Cr)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=Fr()&&!Ur(),p=t.getEntitiesWithComponents([za]);for(const m of p){const p=t.get(m,za);let g=n.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(m,g)),s(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;qo(t,m,vr,{enabled:!0,blockRaycast:!0});const y=t.has(m,Sr)?t.get(m,Sr):null;if(y?.justPressed&&(p.isOpen?r(m,p,g):o(m,p,g)),p.isOpen){for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,Sr))continue;if(t.get(n,Sr).justPressed){a(m,p,g,e,c);break}}let n=-1;for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,Sr))continue;if(t.get(s,Sr).hovered){n=e;break}}n>=0&&n!==g.highlightIndex&&(g.highlightIndex=n,d(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=p.options.length-1?g.highlightIndex=0:g.highlightIndex++,d(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=p.options.length-1:g.highlightIndex--,d(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,p,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,g),e.isMouseButtonPressed(0)&&(y?.hovered||h(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const Wa=new Ua,$a=0,Da=0,La=2,Oa=Ae("LayoutGroup",{direction:$a,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Da,reverseOrder:!1});class Ha{build(e){We("LayoutGroup",Oa);const t=e.world;e.addSystemToSchedule(tn.PreUpdate,on([],()=>{const e=t.getEntitiesWithComponents([Oa,Io,Je]);for(const n of e){const e=t.get(n,Oa),s=t.get(n,Io),i=t.get(n,Je);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Io)&&t.has(e,je)&&o.push({entity:e,rect:t.get(e,Io)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Vo(s,n),a=Xo(s,n),l=s.pivot.x,c=s.pivot.y,u=e.padding,d=e.direction===$a;let h=0;for(let n=0;n<o.length;n++){const s=o[n],i=Vo(s.rect,s.entity),f=Xo(s.rect,s.entity),p=s.rect.pivot.x,m=s.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+p*i,y=e.childAlignment===Da?(1-c)*a-u.top-(1-m)*f:e.childAlignment===La?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,h+=i,n<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===Da?-l*r+u.left+p*i:e.childAlignment===La?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,y=(1-c)*a-u.top-h-(1-m)*f,h+=f,n<o.length-1&&(h+=e.spacing));const _=t.get(s.entity,je);_.position.x=g,_.position.y=y,t.insert(s.entity,je,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const ja=new Ha;class Va{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(tn.PostUpdate,on([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Xa=new Va;async function Na(e,t,n){const s=e.getResource(co);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Ya(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 qa=pt({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),Ga={r:.2,g:.4,b:1,a:.7},Ka={r:.2,g:1,b:.2,a:.7},Ja={r:.2,g:1,b:1,a:.7},Qa={r:1,g:1,b:.2,a:.5},Za={r:1,g:.2,b:.2,a:.8},el={r:1,g:.2,b:.2,a:1},tl=1.5,nl=16;function sl(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function il(e){switch(e){case ht.Static:return Ga;case ht.Kinematic:return Ja;default:return Ka}}function ol(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*r-n.y*a,y:t+n.x*a+n.y*r}));for(let e=0;e<4;e++)ti.line(l[e],l[(e+1)%4],o,tl)}function rl(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=(n,s)=>({x:e+n*r-s*a,y:t+n*a+s*r}),c=l(-n,s),u=l(n,s),d=l(-n,-s),h=l(n,-s);ti.line(c,d,o,tl),ti.line(u,h,o,tl);for(let e=0;e<nl;e++){const t=e/nl*Math.PI,i=(e+1)/nl*Math.PI,r=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(i),s+n*Math.sin(i));ti.line(r,a,o,tl)}for(let e=0;e<nl;e++){const t=Math.PI+e/nl*Math.PI,i=Math.PI+(e+1)/nl*Math.PI,r=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(i),-s+n*Math.sin(i));ti.line(r,a,o,tl)}}function al(e,t,n,s){const i=e+.5*n,o=t+.5*s;ti.line({x:e,y:t},{x:i,y:o},Za,tl);const r=Math.sqrt(n*n+s*s);if(r<1)return;const a=Math.PI/6,l=n/r,c=s/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),d=o-6*(l*Math.sin(a)+c*Math.cos(a)),h=i-6*(l*Math.cos(a)+c*Math.sin(a)),f=o-6*(-l*Math.sin(a)+c*Math.cos(a));ti.line({x:i,y:o},{x:u,y:d},Za,tl),ti.line({x:i,y:o},{x:h,y:f},Za,tl)}function ll(e,t,n){const s=e.getResource(qa);if(!s||!s.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([qe]);for(const n of t){const t=e.world.get(n,qe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([lt,je]);let r=null;s.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const n=e.world.get(t,lt);if(!n.enabled)continue;const o=e.world.get(t,je),a=o.worldPosition.x,l=o.worldPosition.y,c=sl(o.worldRotation);if(s.showColliders){if(e.world.has(t,ct)){const s=e.world.get(t,ct),o=s.isSensor?Qa:il(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,d=Math.cos(c),h=Math.sin(c);ol(a+r*d-u*h,l+r*h+u*d,s.halfExtents.x*i,s.halfExtents.y*i,c,o)}if(e.world.has(t,ut)){const s=e.world.get(t,ut),o=s.isSensor?Qa:il(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,d=Math.cos(c),h=Math.sin(c),f=a+r*d-u*h,p=l+r*h+u*d;ti.circleOutline({x:f,y:p},s.radius*i,o,tl,32)}if(e.world.has(t,dt)){const s=e.world.get(t,dt),o=s.isSensor?Qa:il(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,d=Math.cos(c),h=Math.sin(c);rl(a+r*d-u*h,l+r*h+u*d,s.radius*i,s.halfHeight*i,c,o)}}if(s.showVelocity&&r&&n.bodyType===ht.Dynamic){const e=r.getLinearVelocity(t);al(a,l,e.x*i,e.y*i)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)ti.circle({x:e.contactX,y:e.contactY},3,el,!0,32)}}const cl=pt({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ul=pt(null,"PhysicsAPI");function dl(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function hl(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class fl{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(cl,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Ya(this.wasmUrl_,this.factory_).then(s=>{s._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([qe]);for(const n of t){const t=e.world.get(n,qe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(tn.PostUpdate,on([mt(wt)],a=>{const l=r.getEntitiesWithComponents([lt,je]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,lt),l=r.get(i,je);if(t.has(i)){const e=n.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||(s._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=dl(l.worldRotation);s._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),pl(e,s,i),t.add(i),n.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ht.Kinematic){const e=dl(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<s;i++){const s=o+4*i,r=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(r))continue;const u=e.world.get(r,je);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(r,Ke)){const t=e.world.get(r,Ke);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,je)){const n=e.world.get(t.entity,je),s=dl(n.worldRotation),i=a-n.worldPosition.x,o=l-n.worldPosition.y,r=Math.cos(-s),u=Math.sin(-s);d=(i*r-o*u)/(0!==n.worldScale.x?n.worldScale.x:1),h=(i*u+o*r)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=hl(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(r,je,u)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],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;s.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]*n,contactY:t.HEAPF32[i+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(cl,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(ul,ml._fromModule(s)),function(e,t,n){e.insertResource(qa,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),ri("physics-debug-draw",()=>{ll(e,t,n)})}(e,ul,cl),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function pl(e,t,n){const s=e.world;if(s.has(n,ct)){const e=s.get(n,ct);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,ut)){const e=s.get(n,ut);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,dt)){const e=s.get(n,dt);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class ml{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(ml.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)}static setDebugDraw(e,t){const n=e.getResource(qa);n&&(n.enabled=t,e.insertResource(qa,n))}static setDebugDrawConfig(e,t){const n=e.getResource(qa);n&&e.insertResource(qa,{...n,...t})}}const gl={nearest:0,linear:1},yl={repeat:0,clamp:1,mirror:2};function _l(e,t,n=!0,s){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=gl[s.filterMode??"linear"]??1,a=yl[s.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,n,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),r}function wl(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function xl(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),o=e.worldScale.y*t*(s?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,y=l*h,_=l*f,w=c*f,x=u*d,b=u*h,v=u*f;return new Float32Array([(1-(y+w))*i,(m+v)*i,(g-b)*i,0,(m-v)*o,(1-(p+w))*o,(_+x)*o,0,(g+b)*r,(_-x)*r,(1-(p+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function bl(e){const{app:t,module:n,sceneData:s,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=_s(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===s[o])try{const t=i?.[o];s[o]=_l(e,await n.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),s[o]=0}}}return s}(n,s,i);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(n,s,u);let d={},h=null;if(o&&(h=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"])}}(o),d=await async function(e,t,n,s,i){const o={};for(const r of s.entities)for(const s of r.components){const r=ws(s.type);if(!r||!s.data)continue;const a=s.data[r.skeletonField],l=s.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const s=await i.readText(l),r="binary"===T(c)?.contentType;let d,h;if(r){const e=await i.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,r);if(t._free(d),f<0)continue;o[a]=f;const p=wl(s),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),r=_l(e,o,!1),a=e.getResourceManager().getTextureGLId(r);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(n,o,h,s,i)),r){const e={gravity:a?.gravity??{...ce},fixedTimestep:a?.fixedTimestep??ue,subStepCount:a?.subStepCount??4};new fl("",e,()=>Promise.resolve(r)).build(t)}const f=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=_s(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=T(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=_l(e,c,!1),d=e.getResourceManager();s[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{s[o]=0}}return s}(n,s,i),p=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=_s(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=Pn.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=Pn.createFromAsset(e,r)}catch{n[o]=0}}return n}(s,i);await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=_s(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=JSON.parse(t),o=Un(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,_l(e,s))}catch{r.set(t,0)}Dn(Wn(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(n,s,i),await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=_s(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=cs(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=us(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=_l(e,t),qn(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}Jn(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=_s(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await Xn.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await Xn.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=_s(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,u,f,p);const m=Ps(t.world,s);if(c&&t.hasResource(co))for(const e of m.values())t.world.insert(e,ot,{scene:c,persistent:!1});if(o&&h){const e=function(e,t,n,s){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=ws(t.type);if(!r||!t.data)continue;const a=n[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.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}(h,s,d,m);!function(e,t,n,s,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=le);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,Ze)?c.get(o,Ze):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(r,l*d);let h=0;if(c.has(o,je)){const e=xl(c.get(o,je),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(r);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(r,e),o=s.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*i),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,i,w,o,p,m,h),t._free(_),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(t,n,o,h,e)}if(l){const e=t.getResource(ks);e&&e.setAddressableManifest(l)}}function vl(e,t,n){return{name:e,async setup(){await bl({...n,sceneData:t,sceneName:e})}}}async function Sl(e){const{app:t,firstScene:n,aspectRatio:s}=e;mo(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(co);for(const t of e.scenes)o.register(vl(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&As(t.world,s)}class Ml{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=ws(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===T(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=_s(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}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 n)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 s){const t=T(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,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),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),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 Pl="__preview__";class Tl{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(co);t.register({name:Pl,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Pl),this.loadPromise_=t.load(Pl).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(),n=new Ml(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await bl({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineModule:s,sceneName:Pl})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Ye]);for(const s of n){if(e.get(s,Ye).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([qe]);for(const i of s){const s=e.get(i,qe);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(co).getScene(Pl),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,je,r);const a={isActive:!0,projectionType:Le.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Oe.ColorAndDepth};e.insert(o,Ye,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(co);await e.switchTo(Pl),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 Cl={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=Zi.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:Zi.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){Zi.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Zi.releaseRenderTarget(e._handle),Cl.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){Zi.begin(t,e._handle)},end(){Zi.end()},getDepthTexture:e=>Zi.getTargetDepthTexture(e._handle)};var El;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(El||(El={}));class Al{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${El[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case El.Debug:console.debug(t,n);break;case El.Info:console.log(t,n);break;case El.Warn:console.warn(t,n);break;case El.Error:console.error(t,n)}}}class Rl{constructor(){this.handlers_=[],this.minLevel_=El.Info,this.addHandler(new Al)}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,n){this.log(El.Debug,e,t,n)}info(e,t,n){this.log(El.Info,e,t,n)}warn(e,t,n){this.log(El.Warn,e,t,n)}error(e,t,n){this.log(El.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Il=new Rl;function kl(){return Il}function Fl(e){Il.setMinLevel(e)}function Bl(e,t,n){Il.debug(e,t,n)}function zl(e,t,n){Il.info(e,t,n)}function Ul(e,t,n){Il.warn(e,t,n)}function Wl(e,t,n){Il.error(e,t,n)}const $l={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},Dl={Running:0,Paused:1,Completed:2,Cancelled:3},Ll={None:0,Restart:1,PingPong:2};const Ol=1.70158,Hl=2.70158,jl=2.5949095;const Vl=2*Math.PI/3,Xl=2*Math.PI/4.5;const Nl=7.5625,Yl=2.75;const ql=1e-6;function Gl(e,t,n){switch(e){case $l.Linear:return t;case $l.EaseInQuad:return function(e){return e*e}(t);case $l.EaseOutQuad:return function(e){return e*(2-e)}(t);case $l.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case $l.EaseInCubic:return function(e){return e*e*e}(t);case $l.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case $l.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case $l.EaseInBack:return function(e){return Hl*e*e*e-Ol*e*e}(t);case $l.EaseOutBack:return function(e){const t=e-1;return 1+Hl*t*t*t+Ol*t*t}(t);case $l.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-jl)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+jl)+2)/2}(t);case $l.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Vl)}(t);case $l.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Vl)+1}(t);case $l.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Xl)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Xl)/2+1}(t);case $l.EaseOutBounce:return function(e){return e<1/Yl?Nl*e*e:e<2/Yl?Nl*(e-=1.5/Yl)*e+.75:e<2.5/Yl?Nl*(e-=2.25/Yl)*e+.9375:Nl*(e-=2.625/Yl)*e+.984375}(t);case $l.CubicBezier:return n?function(e,t,n,s,i){let o=e;for(let n=0;n<8;n++){const n=1-o,i=3*t*n*n*o+3*s*n*o*o+o*o*o-e;if(Math.abs(i)<ql)break;const r=3*t*(1-2*o)*(1-o)+6*s*o*(1-o)-3*s*o*o+3*o*o;if(Math.abs(r)<ql)break;o-=i/r}const r=1-o;return 3*n*r*r*o+3*i*r*o*o+o*o*o}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case $l.Step:return function(e){return e<1?0:1}(t);default:return t}}const Kl=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:n,elapsed:0,delay:i?.delay??0,easing:i?.easing??$l.Linear,bezierPoints:null,state:Dl.Running,loop:i?.loop??Ll.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===Dl.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Dl.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=Gl(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Ll.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Ll.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Dl.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Dl.Running&&(t.state=Dl.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Dl.Paused&&(t.state=Dl.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Dl.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Dl.Cancelled}setBezier(e,t,n,s,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:i})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Jl{constructor(e){this.id=e}get state(){return Kl.getState(this.id)}bezier(e,t,n,s){return Kl.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof Jl?Kl.setSequenceNext(this.id,e.id):Kl.setSequenceNextExternal(this.id,e),this}pause(){Kl.pause(this.id)}resume(){Kl.resume(this.id)}cancel(){Kl.cancel(this.id)}}const Ql={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};class Zl{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof Jl?(Kl.registerCppSequence(this.entity,e.id),this):(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 ec=null,tc=null;function nc(e,t){ec=e,tc=t,Kl.init(e,t)}function sc(){Kl.shutdown(),ec=null,tc=null}function ic(){if(!ec)throw new Error("Tween API not initialized");return ec}function oc(){if(!tc)throw new Error("Tween API not initialized");return tc}const rc={to(e,t,n,s,i,o){const r=ic(),a=oc(),l=o?.easing??$l.Linear,c=o?.delay??0,u=o?.loop??Ll.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,n,s,i,l,c,u,d);return new Zl(r,a,h)},value(e,t,n,s,i){const o=Kl.create(e,t,n,s,i);return new Jl(o)},cancel(e){ic()._anim_cancelTween(oc(),e.entity)},cancelAll(e){ic()._anim_cancelAllTweens(oc(),e)},update(e){ic()._anim_updateTweens(oc(),e),Kl.update(e)}};class ac{constructor(){this.name="AnimationPlugin"}build(e){nc(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(tn.Update,on([mt(wt)],e=>{rc.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(tn.Update,on([mt(wt)],e=>{Vn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){sc()}}const lc=new ac;var cc;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(cc||(cc={}));const uc={model:cc.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function dc(e,t=uc){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case cc.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case cc.Inverse:a=s/Math.max(r,s);break;case cc.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function hc(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const fc=Ae("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:cc.Inverse,rolloff:1,priority:0,enabled:!0}),pc=Ae("AudioListener",{enabled:!0});class mc{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=n.mixer;Xn.init(n,i),i&&(void 0!==s.masterVolume&&(i.master.volume=s.masterVolume),void 0!==s.musicVolume&&(i.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(i.sfx.volume=s.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(tn.PreUpdate,on([mt(wt)],t=>{if(!(!Fr()||Ur()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let i=0,u=0,d=!1;const h=s.getEntitiesWithComponents([pc,Xe]);for(const e of h){if(s.get(e,pc).enabled){const t=s.get(e,Xe);i=t.position.x,u=t.position.y,d=!0;break}}const f=s.getEntitiesWithComponents([fc]);a.clear();for(const e of f){const t=s.get(e,fc);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&n.isReady){const e=Xn.getBufferHandle(t.clip);if(e){const s=n.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,s),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const n=o.get(c);if(!n.isPlaying){o.delete(c);continue}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,Xe),a=r?.position.x??0,h=r?.position.y??0,f=a-i,p=h-u,m=dc(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=hc(a,0,i,0,t.maxDistance);n.setVolume(t.volume*m),n.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),Xn.dispose()}}const gc=new mc;let yc=null,_c=null;function wc(e,t){yc=e,_c=t}function xc(){yc=null,_c=null}const bc={update(e){yc&&_c&&yc.particle_update?.(_c,e)},play(e){yc&&_c&&yc.particle_play?.(_c,e)},stop(e){yc&&_c&&yc.particle_stop?.(_c,e)},reset(e){yc&&_c&&yc.particle_reset?.(_c,e)},getAliveCount:e=>yc?yc.particle_getAliveCount?.(e)??0:0};class vc{constructor(){this.name="ParticlePlugin"}build(e){wc(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(tn.Update,on([mt(wt)],e=>{bc.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){xc()}}const Sc=new vc,Mc=1e6;class Pc{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){ts(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(mn),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:Mc,l=i?.valid?i.worldTop:Mc,c=t.getEntitiesWithComponents([os,je]);for(const e of c){const s=t.tryGet(e,os),i=t.tryGet(e,je);if(!s||!i)continue;if(!s.visible)continue;const c=s.texture;if(!c)continue;const u=Gn(c);if(!u)continue;if(!n.has(e)){if(ss.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];ss.setTiles(e,t)}n.add(e)}const d=s.tileWidth/u.width,h=s.tileHeight/u.height,f=s.tint,p=s.parallaxFactor;ss.submitLayer(e,c,s.layer,0,s.tilesetColumns,d,h,i.worldPosition.x,i.worldPosition.y,o,r,a,l,f.r,f.g,f.b,f.a,s.opacity,p.x,p.y)}const u=t.getEntitiesWithComponents([is,je]);for(const e of u){if(t.tryGet(e,os))continue;const i=t.tryGet(e,is),c=t.tryGet(e,je);if(!i?.source||!c)continue;const u=Qn(i.source);if(!u)continue;if(!s.has(e)){const t=[];for(let s=0;s<u.layers.length;s++){const i=1073741824+256*e+s,o=u.layers[s];ss.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&ss.setTiles(i,o.tiles),t.push(i),n.add(i)}s.set(e,t)}const d=s.get(e);for(let e=0;e<u.layers.length&&e<d.length;e++){const t=d[e],n=u.tilesets[0];if(!n)continue;const s=Gn(n.textureHandle);if(!s)continue;const i=u.tileWidth/s.width,h=u.tileHeight/s.height;ss.submitLayer(t,n.textureHandle,e,0,n.columns,i,h,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)ss.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),Kn(),ns()}}const Tc=new Pc;function Cc(e,t){return e.toFixed(t)}function Ec(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class Ac{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">${Cc(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Cc(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 n=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let s='<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 n){s+=`<div>${Ec(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Cc(t,1)}ms</span></div>`}t.push(s)}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 Rc(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const Ic=pt(Rc(),"Stats");class kc{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const Fc="StatsCollect";class Bc{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 zc{constructor(e){this.name="Stats",this.collector_=new Bc,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Ic,Rc());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Ac(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=on([mt(wt),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(Ic);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(Fc),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Zi.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,n?.update(o)},{name:Fc});e.addSystemToSchedule(tn.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Uc=new zc;class Wc{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.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]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(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 $c(e,t){try{const n=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function Dc(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(ks);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await $c(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 $c(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new Wc(s);await Sl({app:t,module:n,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Lc=[ar,br,Ar,Zr,la,Lr,ha,ya,Sa,sa,Nr,Pa,Aa,Ba,Wa,ja,Xa],Oc=[...Lc,lc,gc,Sc,Tc,Yi];function Hc(e,t){return function(e,t){const n=po.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Js(e),vn(e),pi(e),Ti(e),Ji(e),to(e);const i=new io;n.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=xo(e,s,t,i));const r=n.getResource(mn);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*i),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.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}n.insertResource(mn,{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(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Zi.setClearColor(e.x,e.y,e.z,e.w)}const u=(h()-o)/1e3;let d;if(Zi.resize(t,l),n.hasResource(co)){const e=n.getResource(co).getActiveScenes();e.length>0&&(d=new Set(e))}i.setActiveScenes(d??null);const f=xo(e,s,t,l,n.world,d);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:go,width:t,height:l,elapsed:u});else{i.beginScreenCapture();for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u,cameraEntity:e.entity})}i.endScreenCapture(),Zi.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(tn.First,l),n.addSystemToSchedule(tn.Last,c),n.addPlugin(Bs),n.addPlugin(Xs),n.addPlugin(pn),n.addPlugin(fo),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Oc,...t})}class jc{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return l(this.resolvePath_(e))}async readBinary(e){const t=await a(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function Vc(e){return(t,n)=>(u(e,t).then(e=>{n(e.instance,e.module)}),{})}async function Xc(e,t){try{return await e({instantiateWasm:Vc(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function Nc(e){const t=await l("asset-manifest.json"),n=JSON.parse(t),s=function(e){const t={},n={};for(const s in e.groups){const i=e.groups[s];for(const e in i.assets){const s=i.assets[e];t[e]=s,n[s.path]=s}}return{assetIndex:t,pathIndex:n}}(n),i=function(e){const{assetIndex:t,pathIndex:n}=e;return e=>{const s=W(e),i=t[e]||t[s]||n[s]||n[e];return i?i.path:s}}(s),o=wx.createCanvas(),r=wx.getSystemInfoSync();o.width=r.windowWidth*r.pixelRatio,o.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:o,instantiateWasm:Vc("esengine.wasm")}),c=o.getContext("webgl2")||o.getContext("webgl");if(!c)return void console.error("[ESEngine] Failed to create WebGL context");const u=a.GL.registerContext(c,{majorVersion:0===c.getParameter(c.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),d=Hc(a,{glContextHandle:u,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&me(d,e.runtimeConfig);let h=null;e.spineFactory&&(h=await Xc(e.spineFactory,"spine.wasm"));let f=null;e.physicsFactory&&(f=await Xc(e.physicsFactory,"physics.wasm"));const p=new jc(i),m=[];for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`);m.push({name:t,data:JSON.parse(e)})}await Sl({app:d,module:a,provider:p,scenes:m,firstScene:e.firstScene,spineModule:h,physicsModule:f,physicsConfig:e.physicsConfig,manifest:n,aspectRatio:o.width/o.height}),d.run()}J||(J=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},i=await w(n,s);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return x(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i<128?n[s++]=i:i<2048?(n[s++]=192|i>>6,n[s++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,n[s++]=240|i>>18,n[s++]=128|i>>12&63,n[s++]=128|i>>6&63,n[s++]=128|63&i):(n[s++]=224|i>>12,n[s++]=128|i>>6&63,n[s++]=128|63&i)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const i=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Q;export{zt as Added,ac as AnimationPlugin,po as App,Fs as AssetPlugin,zs as AssetRefCounter,Is as AssetServer,ks as Assets,Bn as AsyncCache,cc as AttenuationModel,Xn as Audio,p as AudioBus,pc as AudioListener,m as AudioMixer,mc as AudioPlugin,g as AudioPool,fc as AudioSource,Qe as BitmapText,gn as BlendMode,ht as BodyType,ct as BoxCollider,Pr as Button,Mr as ButtonState,Ye as Camera,qe as Canvas,dt as CapsuleCollider,Ut as Changed,Je as Children,ut as CircleCollider,Oe as ClearFlags,Xt as Commands,Yt as CommandsInstance,ee as DEFAULT_DESIGN_HEIGHT,Z as DEFAULT_DESIGN_WIDTH,le as DEFAULT_FALLBACK_DT,ue as DEFAULT_FIXED_TIMESTEP,ie as DEFAULT_FONT_FAMILY,oe as DEFAULT_FONT_SIZE,ce as DEFAULT_GRAVITY,re as DEFAULT_LINE_HEIGHT,ae as DEFAULT_MAX_DELTA_TIME,te as DEFAULT_PIXELS_PER_UNIT,de as DEFAULT_SPINE_SKIN,se as DEFAULT_SPRITE_SIZE,ne as DEFAULT_TEXT_CANVAS_SIZE,ci as DataType,da as DragPlugin,ua as DragState,ca as Draggable,ti as Draw,za as Dropdown,Ua as DropdownPlugin,$l as EasingType,et as EmitterShape,Nt as EntityCommands,Qt as EventReader,en as EventReaderInstance,Kt as EventRegistry,Jt as EventWriter,Zt as EventWriterInstance,Ao as FillDirection,qr as FillMethod,Gr as FillOrigin,Vr as FocusManager,jr as FocusManagerState,Ma as FocusPlugin,Hr as Focusable,kc as FrameHistory,so as GLDebug,yi as Geometry,nn as GetWorld,ge as INVALID_ENTITY,_e as INVALID_FONT,we as INVALID_MATERIAL,ye as INVALID_TEXTURE,Kr as Image,Qr as ImagePlugin,Yr as ImageType,hn as Input,fn as InputPlugin,dn as InputState,vr as Interactable,Ha as LayoutGroupPlugin,Ra as ListView,Fa as ListViewPlugin,Ve as LocalTransform,El as LogLevel,Rl as Logger,Ll as LoopMode,Pn as Material,zn as MaterialLoader,Ft as Mut,it as Name,Ke as Parent,bc as Particle,nt as ParticleEasing,st as ParticleEmitter,vc as ParticlePlugin,ml as Physics,cl as PhysicsEvents,fl as PhysicsPlugin,Ai as PostProcess,Ni as PostProcessPlugin,Si as PostProcessStack,rt as PostProcessVolume,Hs as PrefabServer,js as Prefabs,Vs as PrefabsPlugin,Tl as PreviewPlugin,oa as ProgressBar,ia as ProgressBarDirection,aa as ProgressBarPlugin,Le as ProjectionType,Ot as Query,Ht as QueryInstance,jt as Removed,Vt as RemovedQueryInstance,io as RenderPipeline,qi as RenderStage,Cl as RenderTexture,Zi as Renderer,mt as Res,gt as ResMut,lt as RigidBody,he as RuntimeConfig,Ta as SafeArea,Ea as SafeAreaPlugin,He as ScaleMode,co as SceneManager,lo as SceneManagerState,ot as SceneOwner,tn as Schedule,fa as ScrollView,ga as ScrollViewPlugin,Fn as ShaderSources,tt as SimulationSpace,wa as Slider,_a as SliderDirection,va as SliderPlugin,Ze as SpineAnimation,Ne as Sprite,jn as SpriteAnimator,Ic as Stats,Bc as StatsCollector,Ac as StatsOverlay,zc as StatsPlugin,un as SystemRunner,sr as Text,er as TextAlign,Or as TextInput,Xr as TextInputPlugin,nr as TextOverflow,rr as TextPlugin,ir as TextRenderer,tr as TextVerticalAlign,is as Tilemap,ss as TilemapAPI,os as TilemapLayer,Pc as TilemapPlugin,wt as Time,ea as Toggle,na as TogglePlugin,je as Transform,rc as Tween,Zl as TweenHandle,Dl as TweenState,Ql as TweenTarget,mn as UICameraInfo,Tr as UIEventQueue,Cr as UIEvents,Sr as UIInteraction,Dr as UIInteractionPlugin,Er as UILayoutPlugin,ur as UIMask,xr as UIMaskPlugin,Io as UIRect,Va as UIRenderOrderPlugin,Ge as Velocity,jc as WeChatAssetProvider,Ml as WebAssetProvider,kt as World,Xe as WorldTransform,ln as addStartupSystem,an as addSystem,cn as addSystemToSchedule,lc as animationPlugin,me as applyBuildRuntimeConfig,$o as applyDirectionalFill,fe as applyRuntimeConfig,Bs as assetPlugin,gc as audioPlugin,dc as calculateAttenuation,hc as calculatePanning,Di as cleanupAllPostProcessVolumes,$i as cleanupPostProcessVolume,Hn as clearAnimClips,li as clearDrawCallbacks,Kn as clearTextureDimensionsCache,Zn as clearTilemapSourceCache,ke as clearUserComponents,Se as color,zo as computeFillAnchors,Wo as computeFillSize,Uo as computeHandleAnchors,Ro as computeUIRectLayout,wr as createMaskProcessor,vl as createRuntimeSceneConfig,Hc as createWebApp,Bl as debug,Rc as defaultFrameStats,Ae as defineComponent,qt as defineEvent,pt as defineResource,on as defineSystem,Re as defineTag,ha as dragPlugin,Wa as dropdownPlugin,Wl as error,Un as extractAnimClipTexturePaths,Rs as findEntityByName,mo as flushPendingSystems,Pa as focusPlugin,E as getAddressableType,A as getAddressableTypeByEditorType,I as getAllAssetExtensions,Bi as getAllEffectDefs,On as getAnimClip,D as getAssetBuildTransform,z as getAssetMimeType,T as getAssetTypeEntry,$e as getComponent,_s as getComponentAssetFieldDescriptors,ys as getComponentAssetFields,at as getComponentDefaults,vs as getComponentEntityFields,ws as getComponentSpineFieldDescriptor,F as getCustomExtensions,C as getEditorType,ki as getEffectDef,Fi as getEffectTypes,kl as getLogger,t as getPlatform,s as getPlatformType,Gn as getTextureDimensions,Qn as getTilemapSource,Ie as getUserComponent,B as getWeChatPackOptions,Zr as imagePlugin,zl as info,Js as initDrawAPI,to as initGLDebugAPI,pi as initGeometryAPI,vn as initMaterialAPI,wc as initParticleAPI,Dc as initPlayableRuntime,Ti as initPostProcessAPI,Ji as initRendererAPI,Sl as initRuntime,ts as initTilemapAPI,nc as initTweenAPI,Nc as initWeChatRuntime,pn as inputPlugin,Ws as instantiatePrefab,dr as intersectRects,hr as invertMatrix4,ze as isBuiltinComponent,U as isCustomExtension,Fr as isEditor,R as isKnownAssetExtension,n as isPlatformInitialized,Ur as isPlayMode,Br as isRuntime,yn as isTextureRef,i as isWeChat,o as isWeb,ja as layoutGroupPlugin,Ba as listViewPlugin,Es as loadComponent,Ya as loadPhysicsModule,bl as loadRuntimeScene,Ps as loadSceneData,Ts as loadSceneWithAssets,ps as loadTiledMap,k as looksLikeAssetPath,Wn as parseAnimClipData,ds as parseTiledMap,cs as parseTmjJson,Sc as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,yr as pointInOBB,pr as pointInWorldRect,Yi as postProcessPlugin,Xs as prefabsPlugin,la as progressBarPlugin,Me as quat,Dn as registerAnimClip,$ as registerAssetBuildTransform,We as registerComponent,gs as registerComponentAssetFields,bs as registerComponentEntityFields,ri as registerDrawCallback,Us as registerEmbeddedAssets,kn as registerMaterialCallback,qn as registerTextureDimensions,Jn as registerTilemapSource,Ss as remapEntityFields,us as resolveRelativePath,Aa as safeAreaPlugin,fo as sceneManagerPlugin,fr as screenToWorld,ya as scrollViewPlugin,kr as setEditorMode,ka as setListViewRenderer,Fl as setLogLevel,zr as setPlayMode,Mt as setWasmErrorHandler,Qs as shutdownDrawAPI,no as shutdownGLDebugAPI,mi as shutdownGeometryAPI,Sn as shutdownMaterialAPI,xc as shutdownParticleAPI,Ci as shutdownPostProcessAPI,Qi as shutdownRendererAPI,ns as shutdownTilemapAPI,sc as shutdownTweenAPI,Sa as sliderPlugin,Vn as spriteAnimatorSystemUpdate,Uc as statsPlugin,No as syncFillSpriteSize,Wi as syncPostProcessVolume,Nr as textInputPlugin,ar as textPlugin,Tc as tilemapPlugin,W as toBuildPath,sa as togglePlugin,Na as transitionTo,Lr as uiInteractionPlugin,Ar as uiLayoutPlugin,br as uiMaskPlugin,Lc as uiPlugins,Xa as uiRenderOrderPlugin,Ln as unregisterAnimClip,Fe as unregisterComponent,ai as unregisterDrawCallback,As as updateCameraAspectRatio,xe as vec2,be as vec3,ve as vec4,Ul as warn,uo as wrapSceneSystem,X as wxFileExists,N as wxFileExistsSync,G as wxGetImagePixels,q as wxLoadImage,K as wxLoadImagePixels,j as wxReadFile,V as wxReadTextFile,Y as wxWriteFile};+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 n(){return null!==e}function s(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,n){return t().fetch(e,n)}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 u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){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),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class g{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 y{constructor(e,t,n){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=n}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class _{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}async loadBufferFromData(e,t){return this.loadBuffer(e)}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const n=this.urlCache_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=wx.createInnerAudioContext();s.loop=t.loop??!1,s.volume=t.volume??1,s.playbackRate=t.playbackRate??1,s.startTime=t.startOffset??0,s.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,s);const o=new y(i,s,this.contexts_);return s.onEnded(()=>{o.onEnd?.(),s.loop||(s.destroy(),this.contexts_.delete(i))}),s.onError(e=>{console.error(`[WeChatAudio] Playback error for "${n}":`,e.errMsg)}),s.src=n,s.play(),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function w(e,t){return new Promise((n,s)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function x(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const b=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],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},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],v={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",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",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"},S=new Map,M=new Set;for(const e of b)for(const t of e.extensions)S.set(t,e),M.add(t);function P(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function T(e){return S.get(P(e))}function C(e){return T(e)?.editorType??"unknown"}function E(e){return T(e)?.addressableType??null}function A(e){for(const t of b)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function R(e){return M.has(e.toLowerCase())}function I(){return M}function k(e){return"string"==typeof e&&(!!e.includes("/")&&R(P(e)))}function F(){const e=[];for(const t of b)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function B(){return F().map(e=>({type:"suffix",value:e}))}function z(e){return v[e.toLowerCase()]}function U(e){const t=T(e);return t?.wechatPackInclude??!1}function W(e){const t=T(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}function $(e,t){for(const n of b)n.editorType===e&&(n.buildTransform=t)}function D(e){return T(e)?.buildTransform}let O=null;function L(){return O||(O=wx.getFileSystemManager()),O}function H(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(U(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function j(e){return new Promise((t,n)=>{L().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(H(e,t.errMsg)))}})})}function V(e,t="utf-8"){return new Promise((n,s)=>{L().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(H(e,t.errMsg)))}})})}function N(e){return new Promise(t=>{L().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function X(e){const t=L();try{return t.accessSync(e),!0}catch{return!1}}function Y(e,t){return new Promise((n,s)=>{L().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function q(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function G(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const i=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(i.data.buffer)}}async function K(e){return G(await q(e))}let J=!1;const Q=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return w(e,t)}async readFile(e){return function(e){return L().readFileSync(e)}(W(e))}async readTextFile(e){return function(e,t="utf-8"){return L().readFileSync(e,t)}(W(e))}async fileExists(e){return X(W(e))}async loadImagePixels(e){return K(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return x(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t=>e.onKeyDown(t.code),s=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(n),wx.onKeyUp(s));const o=t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)},r=t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)},a=t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(n),wx.offKeyUp(s)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new _}getStorageItem(e){try{const t=wx.getStorageSync(e);return"string"==typeof t?t:null}catch{return null}}setStorageItem(e,t){try{wx.setStorageSync(e,t)}catch{}}removeStorageItem(e){try{wx.removeStorageSync(e)}catch{}}clearStorage(e){try{const{keys:t}=wx.getStorageInfoSync();for(const n of t)n.startsWith(e)&&wx.removeStorageSync(n)}catch{}}},Z=1920,ee=1080,te=100,ne=512,se={x:100,y:100},ie="Arial",oe=24,re=1.2,ae=.5,le=1/60,ce={x:0,y:-9.81},ue=1/60,he="default",de={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function fe(e){e.Text&&(e.Text._default.fontFamily=de.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=de.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=de.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=de.canvasMatchWidthOrHeight)}const pe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function me(e,t){if(void 0!==t.maxDeltaTime&&(de.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(de.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(de.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(de.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(de.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");de.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&&(de.canvasScaleMode=pe[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(de.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const ge=0,ye=4294967295,_e=4294967295,we=0,xe=(e=0,t=0)=>({x:e,y:t}),be=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),ve=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),Se=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),Me=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function Pe(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Pe);const t={};for(const n in e)t[n]=Pe(e[n]);return t}let Te=0;function Ce(e,t){const n=++Te,s=function(e){for(const t in e){const n=e[t];if(null!==n&&"object"==typeof n)return!0}return!1}(t);return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>s?e?{...Pe(t),...e}:Pe(t):e?{...t,...e}:{...t}}}function Ee(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Ae(e,t){const n=Ue.get(e)??Ee().get(e);if(n)return n;const s=Ce(e,t);return Ee().set(e,s),Ue.set(e,s),Be(e,t,!1),s}function Re(e){const t=Ue.get(e)??Ee().get(e);if(t)return t;const n=Ce(e,{});return Ee().set(e,n),Ue.set(e,n),Be(e,{},!0),n}function Ie(e){return Ee().get(e)}function ke(){const e=Ee();for(const t of e.keys())Ue.delete(t);e.clear()}function Fe(e){Ee().delete(e),Ue.delete(e)}function Be(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function ze(e){return!0===e._builtin}const Ue=new Map;function We(e,t){Ue.set(e,t)}function $e(e){return Ue.get(e)??Ie(e)}function De(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Ue.set(e,n),n}const Oe={Perspective:0,Orthographic:1},Le={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},He={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},je=De("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}}),Ve=je,Ne=je,Xe=De("Sprite",{texture:ye,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}),Ye=De("Camera",{projectionType:Oe.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}),qe=De("Canvas",{designResolution:{x:Z,y:ee},pixelsPerUnit:100,scaleMode:He.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Ge=De("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ke=De("Parent",{entity:0}),Je=De("Children",{entities:[]}),Qe=De("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:_e,enabled:!0}),Ze=De("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}),et={Point:0,Circle:1,Rectangle:2,Cone:3},tt={World:0,Local:1},nt={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},st=De("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:et.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:nt.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:nt.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:ye,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:tt.World,enabled:!0}),it=Ae("Name",{value:""}),ot=Ae("SceneOwner",{scene:"",persistent:!1}),rt=Ae("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function at(e){const t=$e(e);return t?Pe(t._default):null}const lt=De("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ct=De("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ut=De("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ht=De("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),dt={Static:0,Kinematic:1,Dynamic:2};let ft=0;function pt(e,t){const n=++ft;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function mt(e){return{_type:"res",_resource:e}}function gt(e){return{_type:"res_mut",_resource:e}}class yt{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 _t{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 yt(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const wt=pt({delta:0,elapsed:0,frameCount:0},"Time"),xt="esengine:",bt={getString(e,n){const s=t().getStorageItem(xt+e);return null!==s?s:n},setString(e,n){t().setStorageItem(xt+e,n)},getNumber(e,n){const s=t().getStorageItem(xt+e);if(null===s)return n;const i=Number(s);return Number.isNaN(i)?n:i},setNumber(e,n){t().setStorageItem(xt+e,String(n))},getBoolean(e,n){const s=t().getStorageItem(xt+e);return null===s?n:"true"===s},setBoolean(e,n){t().setStorageItem(xt+e,String(n))},getJSON(e,n){const s=t().getStorageItem(xt+e);if(null===s)return n;try{return JSON.parse(s)}catch{return n}},setJSON(e,n){t().setStorageItem(xt+e,JSON.stringify(n))},remove(e){t().removeStorageItem(xt+e)},has:e=>null!==t().getStorageItem(xt+e),clear(){t().clearStorage(xt)}};function vt(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=St(t[e]),o=St(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function St(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Mt(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let Pt=null;function Tt(e){Pt=e}function Ct(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Pt&&Pt(e,t)}function Et(e){let t=!1;for(const n of Object.keys(e)){const s=e[n];if(null!=s&&"object"==typeof s&&!Array.isArray(s)){if("r"in s&&"g"in s&&"b"in s&&"a"in s&&!("x"in s)){t=!0;break}}}if(!t)return e;const n={};for(const t of Object.keys(e)){const s=e[t];if(null==s||"object"!=typeof s||Array.isArray(s))n[t]=s;else{const e=s;n[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}:s}}return n}let At=1;const Rt=new WeakMap;function It(e){let t=Rt.get(e);return void 0===t&&(t=At++,Rt.set(e,t)),t}const kt=[];function Ft(e,t=[],n=[]){kt.length=0;for(const t of e)kt.push(It(t));kt.sort((e,t)=>e-t);let s=kt.join(",");if(t.length>0){kt.length=0;for(const e of t)kt.push(It(e));kt.sort((e,t)=>e-t),s+="|+"+kt.join(",")}if(n.length>0){kt.length=0;for(const e of n)kt.push(It(e));kt.sort((e,t)=>e-t),s+="|-"+kt.join(",")}return s}class Bt{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 Ct(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){Ct(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,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(n){Ct(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ct(t,`removeParent(entity=${e})`)}}insert(e,t,n){return ze(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(ze(t)){if(this.cppRegistry_)try{const s=t._default,i=n;let o=i;for(const e of Object.keys(i))e in s||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,Et(o))}catch(n){Ct(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return ze(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return ze(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(ze(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Ct(n,`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.");ze(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],o=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"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:s.bind(n),get:i.bind(n),has:o.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s=t._default,i={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(i[e]=t);const e=vt(t._name,s,i);if(e.length>0)throw new Error(Mt(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,Et(o))}catch(n){Ct(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],o=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))s[n]=i;else{const e=i,t=o;s[n]="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 s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return Ct(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return Ct(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Ct(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const i=vt(t._name,t._default,e);if(i.length>0)throw new Error(Mt(t._name,i));s=e}const i=t.create(s),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 n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.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[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of Ue)if(ze(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e=Ee();for(const s of n)for(const[n,i]of e)if(i._id===s){t.add(n);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const i=s??Ft(e,t,n),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(!ze(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,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 s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function zt(e){return{_type:"mut",_component:e}}function Ut(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Wt(e){return{_filterType:"added",_component:e}}function $t(e){return{_filterType:"changed",_component:e}}function Dt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Ot(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Lt(e){return Ut(e)||Dt(e)||Ot(e)?e._component:e}function Ht(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{Ut(e)&&s.push(t),Dt(e)?i.push({index:t,component:e._component}):Ot(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>Ht(e,[...t,...s],n),without:(...s)=>Ht(e,t,[...n,...s])}}function jt(...e){return Ht(e)}class Vt{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Lt),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_=Ft(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=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 u of n)if(!o||this.passesChangeFilters_(u)){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]=u;for(let e=0;e<s;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}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,...n]of this)e(t,...n)}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 Nt(e){return{_type:"removed",_component:e}}class Xt{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n}*[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 Yt(){return{_type:"commands"}}class qt{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 n;return n=ze(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),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 Gt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new qt(this,null);return this.spawned_.push(e),e}entity(e){return new qt(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,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,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 Kt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class Jt{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 Qt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Jt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Jt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function Zt(e){return{_type:"event_writer",_event:e}}function en(e){return{_type:"event_reader",_event:e}}class tn{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class nn{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var sn;function on(){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"}(sn||(sn={}));let rn=0;function an(e,t,n){const s=++rn;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function ln(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function cn(e){ln().push({schedule:sn.Update,system:e})}function un(e){ln().push({schedule:sn.Startup,system:e})}function hn(e,t){ln().push({schedule:e,system:t})}class dn{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??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 n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);const n=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Gt&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new Vt(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 Gt(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new tn(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new nn(n)}case"removed":{const t=e;return new Xt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class fn{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 pn=pt(new fn,"Input");class mn{constructor(e){this.target_=e??null}build(e){const n=new fn;e.insertResource(pn,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(sn.Last,an([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const gn=new mn,yn=pt({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 _n;function wn(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"}(_n||(_n={}));let xn=null,bn=null,vn=1;const Sn=new Map;function Mn(e){xn=e,bn=e.getResourceManager(),Bn()}function Pn(){0!==An&&xn&&(xn._free(An),An=0),Sn.clear(),vn=1,En=!1,In.clear(),kn=null,bn=null,xn=null}function Tn(){if(!bn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return bn}const Cn={createShader:(e,t)=>Tn().createShader(e,t),releaseShader(e){e>0&&Tn().releaseShader(e)},create(e){const t=vn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??_n.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Sn.set(t,n),t},get:e=>Sn.get(e),setUniform(e,t,n){const s=Sn.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,xn?.invalidateMaterialCache(e))},getUniform(e,t){const n=Sn.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Sn.get(e);n&&(n.blendMode=t,xn?.invalidateMaterialCache(e))},getBlendMode(e){const t=Sn.get(e);return t?.blendMode??_n.Normal},setDepthTest(e,t){const n=Sn.get(e);n&&(n.depthTest=t,xn?.invalidateMaterialCache(e))},getShader(e){const t=Sn.get(e);return t?.shader??0},release(e){Sn.delete(e),xn?.invalidateMaterialCache(e)},isValid:e=>Sn.has(e),releaseAll(){Sn.clear(),xn?.clearMaterialCache()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??_n.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Sn.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=vn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Sn.set(n,s),n},toAssetData(e,t){const n=Sn.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=Sn.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let En=!1,An=0;const Rn=16384,In=new Map;let kn=null;function Fn(e){const t=(0===An&&xn&&(An=xn._malloc(Rn)),An);if(0===t||!xn)return{ptr:0,count:0};let n=0,s=0;const i=xn.HEAPU8,o=xn.HEAPU32,r=xn.HEAPF32;for(const[a,l]of e){if(wn(l))continue;let e=In.get(a);e||(kn||(kn=new TextEncoder),e=kn.encode(a),In.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>Rn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Rn} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Bn(){if(!xn||En)return;xn.materialDataProvider=(e,t,n,s,i)=>{const o=Sn.get(e);if(!o)return xn.HEAPU32[t>>2]=0,xn.HEAPU32[n>>2]=0,xn.HEAPU32[s>>2]=0,void(xn.HEAPU32[i>>2]=0);xn.HEAPU32[t>>2]=o.shader,xn.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=Fn(o.uniforms);xn.HEAPU32[s>>2]=r,xn.HEAPU32[i>>2]=a},En=!0}const zn={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 Un{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+5e3}),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(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Wn{constructor(e,t=""){this.cache_=new Un,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&&(Cn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Cn.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 n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:Cn.createFromAsset(s,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 n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function $n(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Dn(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const On=new Map;function Ln(e){On.set(e.name,e)}function Hn(e){On.delete(e)}function jn(e){return On.get(e)}function Vn(){On.clear()}const Nn=Ae("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Xn(e,t){const n=e.getEntitiesWithComponents([Nn]);for(const s of n){const n=e.get(s,Nn);if(!n.enabled||!n.playing||!n.clip)continue;const i=On.get(n.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*n.speed),r=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let a=r;if(n.frameTimer>=o&&(n.frameTimer-=o,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),a=!0),a&&e.has(s,Xe)){const t=i.frames[n.currentFrame],o=e.get(s,Xe);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,Xe,o)}a&&e.insert(s,Nn,n)}}class Yn{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 async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:n,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}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 n=this.mixer_?.getBus(e);n&&(n.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,n){e.setVolume(0);const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(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}}}}Yn.mixer_=null,Yn.bufferCache_=new Map,Yn.bgmHandle_=null,Yn.bgmVolume_=1,Yn.fadeAnimId_=0,Yn.disposed_=!1;const qn=new Map,Gn=new Map;function Kn(e,t,n){qn.set(e,{width:t,height:n})}function Jn(e){return qn.get(e)}function Qn(){qn.clear()}function Zn(e,t){Gn.set(e,t)}function es(e){return Gn.get(e)}function ts(){Gn.clear()}let ns=null;function ss(e){ns=e}function is(){ns=null}const os={initLayer(e,t,n,s,i){ns?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){ns?.tilemap_destroyLayer(e)},setTile(e,t,n,s){ns?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>ns?ns.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){ns?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!ns)return;const n=t.byteLength,s=ns._malloc(n);new Uint16Array(ns.HEAPU8.buffer,s,t.length).set(t),ns.tilemap_setTiles(e,s,t.length),ns._free(s)},hasLayer:e=>!!ns&&ns.tilemap_hasLayer(e),submitLayer(e,t,n,s,i,o,r,a,l,c,u,h,d,f,p,m,g,y,_,w){ns?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,u,h,d,f,p,m,g,y,_,w)}},rs=Ae("Tilemap",{source:""}),as=Ae("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function ls(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function cs(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function us(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function hs(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=us(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,h=cs(e.tintcolor),d="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l,opacity:u,tintColor:h,parallaxX:d,parallaxY:f})}const u=[],h=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}n.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:n})}if(o)for(const e of o){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.properties;if(n)for(const s of n)"collision"===s.name&&!0===s.value&&h.push(e.id+t)}}return{width:t,height:n,tileWidth:s,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:h}}function ds(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function fs(e,t){const n=ns;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?ls(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch{return n.tiled_freeMap(r),null}}const ps=Math.PI/180;function ms(e,t,n,s,i,o){const r=function(e,t,n,s){const i=new Uint8Array(t*n),o=[],r=(o,r)=>{if(o>=t||r>=n)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let o=0;o<a;o++)i[(e+n)*t+(s+o)]=1;o.push({col:s,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,u=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=i+t.col*l+.5*n,h=o+(u-t.row*c)-.5*s,d=e.spawn();e.insert(d,je,{position:{x:r,y:h,z:0}}),e.insert(d,lt,{bodyType:dt.Static}),e.insert(d,ct,{halfExtents:{x:.5*n,y:.5*s}}),a.push(d)}return a}function gs(e,t,n,s={}){const i=[],o=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,je,{});const l=o?n.get(o.image)??0:0,c=o?.columns??1;e.insert(a,as,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),i.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,u=s+(o-l)-.5*t.height,h=-t.rotation*ps;if(e.insert(r,je,{position:{x:c,y:u,z:0}}),e.insert(r,lt,{bodyType:dt.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,ut,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>i&&(i=r),a<s&&(s=a),a>o&&(o=a)}const a=i-n,l=o-s,c=.5*(n+i),u=.5*(s+o);e.insert(r,ct,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,ct,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==h){const t=.5*h;e.insert(r,je,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=ms(e,n,t,a,0,0);i.push(...s)}return i}const ys=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"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function _s(e,t){ys.set(e,t)}function ws(e){const t=ys.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function xs(e){return ys.get(e)?.fields??[]}function bs(e){return ys.get(e)?.spine??null}const vs=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Ss(e,t){vs.set(e,t)}function Ms(e){return vs.get(e)}function Ps(e,t){const n=vs.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const o=t.get(n);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==o?o:0}}}function Ts(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,it,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const i of s.components)Ps(i,n),Rs(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function Cs(e,t){return Ts(e,t)}async function Es(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,o=new Map;s&&await async function(e,t,n,s,i){const o=new Map;for(const e of As.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=ys.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...As.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),i){for(const e of s.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=ys.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,o,n?.collectAssets);const r=Ts(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const As=new Map([["texture",{async load(e,t,n,s){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o),Kn(r.handle,r.width,r.height)}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,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=$n(i),r=new Map,a=o.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);Ln(Dn(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,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await Yn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=hs(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=ds(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),Kn(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}Zn(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Rs(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=$e(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function Is(e,t){const n=e.getEntitiesWithComponents([Ye]);for(const s of n){const n=e.get(s,Ye);n&&(n.aspectRatio=t,e.insert(s,Ye,n))}}function ks(e,t){const n=e.getEntitiesWithComponents([it]);for(const s of n){const n=e.get(s,it);if(n&&n.value===t)return s}return null}class Fs{constructor(e){this.textureCache_=new Un,this.shaderCache_=new Un,this.jsonCache_=new Un,this.textCache_=new Un,this.binaryCache_=new Un,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Un,this.prefabCache_=new Un,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_=h(de.textCanvasSize,de.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 Wn(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);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 n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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(),Cn.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 n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),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,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===T(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,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 n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=T(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}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),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const i=n?`${n}/${s}`:s;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,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 n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of ws(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=bs(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.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 n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Es(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.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},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"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 n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((n,s)=>{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 n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,n,s,t):this.createTextureFallback(e,n,s,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,n,s,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,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),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,n),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,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return Cn.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return Cn.createShader(i,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.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(W(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.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 n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let i="";for(const e of s){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 n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Bs=pt(null,"Assets");class zs{build(e){const t=e.wasmModule;t?e.insertResource(Bs,new Fs(t)):console.warn("AssetPlugin: No WASM module available")}}const Us=new zs;class Ws{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.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 n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.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 n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.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,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});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 $s(e,t){const n=e.getResource(Bs);n&&n.registerEmbeddedAssets(t)}async function Ds(e,t,n){const{entities:s,rootId:i}=await Ls(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},r=await Es(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=r.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:r}}const Os=10;async function Ls(e,t,n,s,i,o=0){if(o>Os)throw new Error(`Prefab nesting depth exceeded ${Os}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===s){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=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Ls(e,s.nestedPrefab.overrides,n,a,i,o+1);r.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?r.get(s.parent)??null:null),l.push(...t.entities);continue}const c=r.get(s.prefabEntityId),u=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:u?null:null!==s.parent?r.get(s.parent)??null:null,children:s.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Hs(h.components,r),js(h,t),l.push(h)}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 Hs(e,t){for(const n of e){const e=Ms(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function js(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Vs{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Ds(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Ns=pt(null,"Prefabs");class Xs{constructor(){this.name="PrefabsPlugin",this.dependencies=[Bs]}build(e){const t=e.getResource(Bs);e.insertResource(Ns,new Vs(e.world,t))}}const Ys=new Xs;let qs=null,Gs=0,Ks=0,Js=0;const Qs=new Float32Array(256);function Zs(e){qs=e,Gs=qs._malloc(64),Ks=qs._malloc(64),Js=qs._malloc(1024)}function ei(){qs&&(Gs&&(qs._free(Gs),Gs=0),Ks&&(qs._free(Ks),Ks=0),Js&&(qs._free(Js),Js=0)),qs=null}function ti(){if(!qs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return qs}const ni={r:1,g:1,b:1,a:1},si={begin(e){const t=ti();try{t.HEAPF32.set(e,Gs/4),t.draw_begin(Gs)}catch(e){Ct(e,"Draw.begin")}},end(){try{ti().draw_end()}catch(e){Ct(e,"Draw.end")}},line(e,t,n,s=1){try{ti().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ct(e,"Draw.line")}},rect(e,t,n,s=!0){try{ti().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ct(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{ti().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ct(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{ti().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Ct(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{ti().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Ct(e,"Draw.circleOutline")}},texture(e,t,n,s=ni){try{ti().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Ct(e,"Draw.texture")}},textureRotated(e,t,n,s,i=ni){try{ti().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){Ct(e,"Draw.textureRotated")}},setLayer(e){ti().draw_setLayer(e)},setDepth(e){ti().draw_setDepth(e)},getDrawCallCount:()=>qs?qs.draw_getDrawCallCount():0,getPrimitiveCount:()=>qs?qs.draw_getPrimitiveCount():0,setBlendMode(e){ti().draw_setBlendMode(e)},setDepthTest(e){ti().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=ti();s.HEAPF32.set(n,Ks/4),s.draw_mesh(e,t,Ks)}catch(n){Ct(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=ti(),i=Cn.get(t);if(!i)return;if(si.setBlendMode(i.blendMode),si.setDepthTest(i.depthTest),0===i.uniforms.size)return void si.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,Ks/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=ri(t);if(!(s<0)){if(wn(n))Qs[o++]=10,Qs[o++]=s,Qs[o++]=n.slot??e++,Qs[o++]=n.textureId;else if("number"==typeof n)Qs[o++]=1,Qs[o++]=s,Qs[o++]=n;else if(Array.isArray(n)){Qs[o++]=n.length,Qs[o++]=s;for(let e=0;e<n.length;e++)Qs[o++]=n[e]}else"w"in n?(Qs[o++]=4,Qs[o++]=s,Qs[o++]=n.x,Qs[o++]=n.y,Qs[o++]=n.z,Qs[o++]=n.w):"z"in n?(Qs[o++]=3,Qs[o++]=s,Qs[o++]=n.x,Qs[o++]=n.y,Qs[o++]=n.z):(Qs[o++]=2,Qs[o++]=s,Qs[o++]=n.x,Qs[o++]=n.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(Qs.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,Ks);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Js/4),s.draw_meshWithUniforms(e,i.shader,Ks,Js,o)}catch(n){Ct(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},ii={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},oi=new Set;function ri(e){const t=ii[e];return void 0!==t?t:(oi.has(e)||(oi.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(ii).join(", ")}`)),-1)}const ai=new Map;function li(e,t,n){ai.set(e,{fn:t,scene:n??""})}function ci(e){ai.delete(e)}function ui(){ai.clear()}var hi;!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"}(hi||(hi={}));let di=null,fi=0,pi=0,mi=0;function gi(e){di=e,fi=di._malloc(262144),pi=di._malloc(65536),mi=di._malloc(256)}function yi(){di&&(fi&&di._free(fi),pi&&di._free(pi),mi&&di._free(mi),fi=0,pi=0,mi=0),di=null}function _i(){if(!di)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return di}const wi={create(e){const t=_i(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,fi/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,mi,i).set(o),t.geometry_init(n,fi,s,mi,i,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,pi,s).set(e.indices),t.geometry_setIndices16(n,pi,s)}else{new Uint32Array(t.HEAPU8.buffer,pi,s).set(e.indices),t.geometry_setIndices32(n,pi,s)}}return n},updateVertices(e,t,n=0){const s=_i(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,fi/4),s.geometry_updateVertices(e,fi,i,n)},release(e){e>0&&_i().geometry_release(e)},isValid:e=>!(!di||e<=0)&&di.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return wi.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:hi.Float2},{name:"a_texCoord",type:hi.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const i=s/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;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return wi.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:hi.Float2},{name:"a_texCoord",type:hi.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,i=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);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 wi.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:hi.Float2},{name:"a_texCoord",type:hi.Float2}],indices:new Uint16Array(r)})}};let xi=1;const bi=new Map,vi=new Map;function Si(){return bi}function Mi(){return vi}class Pi{constructor(){this.passes_=[],this.destroyed_=!1,this.id=xi++,bi.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of vi)t===this&&vi.delete(e);bi.delete(this.id)}}}const Ti="#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";let Ci=null;function Ei(e){Ci=e}function Ai(){for(const e of Si().values())e.destroy();Si().clear(),Mi().clear(),Ci&&Ii.isInitialized()&&Ii.shutdown(),Ci=null}function Ri(){if(!Ci)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ci}const Ii={createStack:()=>new Pi,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");Mi().set(e,t)},unbind(e){Mi().delete(e)},getStack:e=>Mi().get(e)??null,init(e,t){try{return Ri().postprocess_init(e,t)}catch(n){return Ct(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ri().postprocess_shutdown()}catch(e){Ct(e,"PostProcess.shutdown")}},resize(e,t){try{Ri().postprocess_resize(e,t)}catch(n){Ct(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!Ci)return!1;try{return Ci.postprocess_isInitialized()}catch(e){return Ct(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ri().postprocess_setBypass(e)}catch(e){Ct(e,"PostProcess.setBypass")}},setOutputViewport(e,t,n,s){try{Ri().postprocess_setOutputViewport(e,t,n,s)}catch(e){Ct(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=Mi().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(Ii.isInitialized()||Ii.init(1,1),Ii.setBypass(!1),function(e){const t=Ri();try{t.postprocess_clearPasses()}catch(e){return void Ct(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){Ct(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){Ct(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Ct(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):Ii.setBypass(!0)},_resetAfterCamera(){try{Ri().postprocess_clearPasses(),Ri().postprocess_setBypass(!0)}catch(e){Ct(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of Mi().keys())e(t)||Mi().delete(t)},screenStack:null,setScreenStack(e){Ii.screenStack=e},_beginScreenCapture(){try{Ri().postprocess_beginScreenCapture()}catch(e){Ct(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{Ri().postprocess_endScreenCapture()}catch(e){Ct(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=Ii.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=Ri();try{t.postprocess_clearScreenPasses()}catch(e){return void Ct(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){Ct(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){Ct(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Ct(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{Ri().postprocess_executeScreenPasses()}catch(e){Ct(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Cn.createShader(Ti,"#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:()=>Cn.createShader(Ti,"#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:()=>Cn.createShader(Ti,"#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"),createBloom:()=>Cn.createShader(Ti,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>Cn.createShader(Ti,"#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")},ki=new Map;function Fi(e){ki.set(e.type,e)}function Bi(e){return ki.get(e)}function zi(){return Array.from(ki.keys())}function Ui(){return Array.from(ki.values())}Fi({type:"blur",label:"Blur",factory:()=>Ii.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),Fi({type:"bloom",label:"Bloom",factory:()=>Ii.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),Fi({type:"vignette",label:"Vignette",factory:()=>Ii.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),Fi({type:"grayscale",label:"Grayscale",factory:()=>Ii.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),Fi({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>Ii.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const Wi=new Map,$i=new Map;function Di(e,t){let n=Wi.get(e),s=$i.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=Ii.createStack(),Wi.set(e,n)),s||(s=new Map,$i.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=Bi(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}Ii.bind(e,n)}else if(n&&(Ii.unbind(e),n.destroy(),Wi.delete(e)),s){for(const e of s.values())Cn.releaseShader(e);$i.delete(e)}}function Oi(e){const t=Wi.get(e);t&&(Ii.unbind(e),t.destroy(),Wi.delete(e));const n=$i.get(e);if(n){for(const e of n.values())Cn.releaseShader(e);$i.delete(e)}}function Li(){for(const e of Wi.keys())Oi(e)}const Hi=pt({enabled:!0},"PostProcessVolumeConfig"),ji=new Map,Vi=new Map;function Ni(e){const t=Vi.get(e);if(void 0!==t)return t;const n=Bi(e);if(!n)return null;const s=n.factory();return Vi.set(e,s),s}function Xi(e,t){if(0===t.size){const t=ji.get(e);return void(t&&(Ii.unbind(e),t.destroy(),ji.delete(e)))}let n=ji.get(e);for(n||(n=Ii.createStack(),ji.set(e,n));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const[e,s]of t){if(!s.enabled)continue;const t=Ni(e);if(null!==t){n.addPass(e,t);for(const[t,i]of s.uniforms)n.setUniform(e,t,i)}}n.enabledPassCount>0?Ii.bind(e,n):Ii.unbind(e)}const Yi=an([jt(rt,je)],e=>{const t=[];for(const[n,s,i]of e)t.push({data:s,tx:{x:i.position.x,y:i.position.y}});if(0===t.length)return;const n=[];for(const{data:e,tx:s}of t)e.isGlobal&&n.push({data:e,factor:1});if(n.length>0){const e=function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,i]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(i-n)*s)}else{const e=new Map;for(const[t,i]of Object.entries(n.uniforms))e.set(t,i*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(n);for(const[t]of ji)Xi(t,e)}},{name:"PostProcessVolumeSystem"});class qi{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(Hi,{enabled:!0}),e.addSystemToSchedule(sn.PostUpdate,Yi)}cleanup(){Li(),function(){for(const[e,t]of ji)Ii.unbind(e),t.destroy();ji.clear();for(const e of Vi.values())Cn.releaseShader(e);Vi.clear()}(),Ii.setScreenStack(null)}}const Gi=new qi;var Ki;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ki||(Ki={}));let Ji=null,Qi=0;function Zi(e){Ji=e,Qi=Ji._malloc(64)}function eo(){Ji&&Qi&&(Ji._free(Qi),Qi=0),Ji=null}const to={init(e,t){Ji?.renderer_init(e,t)},resize(e,t){Ji?.renderer_resize(e,t)},begin(e,t){if(Ji&&Qi)try{Ji.HEAPF32.set(e,Qi/4),Ji.renderer_begin(Qi,t??0)}catch(e){Ct(e,"Renderer.begin")}},flush(){try{Ji?.renderer_flush()}catch(e){Ct(e,"Renderer.flush")}},end(){try{Ji?.renderer_end()}catch(e){Ct(e,"Renderer.end")}},submitSprites(e){if(Ji)try{Ji.renderer_submitSprites(e._cpp)}catch(e){Ct(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Ji)try{Ji.renderer_submitBitmapText(e._cpp)}catch(e){Ct(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Ji)try{Ji.renderer_submitSpine?.(e._cpp)}catch(e){Ct(e,"Renderer.submitSpine")}},submitParticles(e){if(Ji)try{Ji.renderer_submitParticles?.(e._cpp)}catch(e){Ct(e,"Renderer.submitParticles")}},setStage(e){Ji?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Ji?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Ji?.renderer_releaseTarget(e)},getTargetTexture:e=>Ji?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ji?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Ji?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Ji?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Ji?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Ji?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Ji?Ji.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Ji?{drawCalls:Ji.renderer_getDrawCalls(),triangles:Ji.renderer_getTriangles(),sprites:Ji.renderer_getSprites(),text:Ji.renderer_getText(),spine:Ji.renderer_getSpine?.()??0,meshes:Ji.renderer_getMeshes(),culled:Ji.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let no=null;function so(e){no=e}function io(){no=null}const oo={enable(){no?.gl_enableErrorCheck(!0)},disable(){no?.gl_enableErrorCheck(!1)},check:e=>no?.gl_checkErrors(e)??0,diagnose(){no?.renderer_diagnose()}};class ro{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}beginScreenCapture(){Ii.screenStack&&Ii.screenStack.enabledPassCount>0&&(Ii.isInitialized()||Ii.init(1,1),Ii._applyScreenStack(),Ii._beginScreenCapture())}endScreenCapture(){Ii.screenStack&&Ii.screenStack.enabledPassCount>0&&(Ii._endScreenCapture(),Ii._executeScreenPasses())}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(to.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),to.setViewport(0,0,s,i),to.clearBuffers(3),to.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),this.tilemapRenderer_&&this.tilemapRenderer_(),to.submitSprites(t),to.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):to.submitSpine(t),to.submitParticles(t),to.flush(),this.executeDrawCallbacks(n,o),to.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==Ii.getStack(r);a&&(Ii._applyForCamera(r),Ii.resize(s.w,s.h),Ii.setOutputViewport(s.x,s.y,s.w,s.h)),to.setViewport(s.x,s.y,s.w,s.h),to.setScissor(s.x,s.y,s.w,s.h,!0),to.clearBuffers(i),to.setScissor(0,0,0,0,!1),to.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),this.tilemapRenderer_&&this.tilemapRenderer_(),to.submitSprites(t),to.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):to.submitSpine(t),to.submitParticles(t),to.flush(),this.executeDrawCallbacks(n,o),to.end(),a&&Ii._resetAfterCamera()}executeDrawCallbacks(e,t){const n=ai;if(n.size>0){si.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}si.end();for(const e of s)ci(e)}}}const ao="__scene_transition_overlay__";class lo{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class co{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,ot,{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),li(e,t,this.instance_.config.name)}bindPostProcess(e,t){Ii.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){Ii.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,ot)){const n=this.app_.world.get(e,ot);n.persistent=t,this.app_.world.insert(e,ot,n)}}}class uo{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}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())ci(t);for(const t of e.postProcessBindings.keys())Ii.unbind(t)}this.transition_&&(ci(ao),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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(n=>{const s=t.duration??de.sceneTransitionDuration,i=t.color??{...de.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},li(ao,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;si.setLayer(9999),si.setDepth(9999),si.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:n})})})}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_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,ci(ao),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,ci(ao),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 n=new lo(t);this.scenes_.set(e,n);const s=new co(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Bs)?this.app_.getResource(Bs):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();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 n=new lo(t);this.scenes_.set(e,n);const s=new co(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Bs)?this.app_.getResource(Bs):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,ot)){if(this.app_.world.get(e,ot).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())ci(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())Ii.unbind(e);n.postProcessBindings.clear(),this.releaseSceneAssets_(n),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,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(Bs)&&(i.assetServer=this.app_.getResource(Bs));const o=await Es(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,ot,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=fo(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(Bs)?this.app_.getResource(Bs):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)Cn.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 n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,Xe)){const t=n.get(e,Xe);s.sprite=t.color.a,t.color.a=0,n.insert(e,Xe,t),i=!0}if(n.has(e,Ze)){const t=n.get(e,Ze);s.spine=t.color.a,t.color.a=0,n.insert(e,Ze,t),i=!0}if(n.has(e,Qe)){const t=n.get(e,Qe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Qe,t),i=!0}i&&t.savedAlphas.set(e,s)}}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 n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,Xe)){const t=n.get(e,Xe);t.color.a=s.sprite,n.insert(e,Xe,t)}if(void 0!==s.spine&&n.has(e,Ze)){const t=n.get(e,Ze);t.color.a=s.spine,n.insert(e,Ze,t)}if(void 0!==s.bitmapText&&n.has(e,Qe)){const t=n.get(e,Qe);t.color.a=s.bitmapText,n.insert(e,Qe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}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,n]of this.scenes_)"running"===n.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 ho=pt(null,"SceneManager");function fo(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(ho).getSceneStatus(t)&&n._fn(...s)}}}const po=an([gt(ho),mt(wt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),mo={name:"SceneManager",build(e){const t=new uo(e);e.insertResource(ho,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ho),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(sn.Startup,n),e.addSystemToSchedule(sn.Last,po)}};class go{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 Qt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(sn.Last);else{this.runSchedule(sn.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(sn.FixedPreUpdate),this.runSchedule(sn.FixedUpdate),this.runSchedule(sn.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(sn.PreUpdate),this.runSchedule(sn.Update),this.runSchedule(sn.PostUpdate),this.runSchedule(sn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Bt,this.resources_=new _t;for(const e of Object.values(sn))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new go}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,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(sn.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(sn.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),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 Tt(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.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}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(ho).register(e),this}setInitialScene(e){return this.getResource(ho).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new dn(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(wt)||this.resources_.insert(wt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(sn.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(sn.Last);else{this.runSchedule(sn.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(sn.FixedPreUpdate),this.runSchedule(sn.FixedUpdate),this.runSchedule(sn.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(sn.PreUpdate),this.runSchedule(sn.Update),this.runSchedule(sn.PostUpdate),this.runSchedule(sn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new dn(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(wt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(sn.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,ui();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=[io,eo,Ai,yi,Pn,ei];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 n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.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 n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const s=this.phaseTimings_?performance.now():0;for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(sn[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(wt);t.delta=e,t.elapsed+=e,t.frameCount++}}function yo(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const _o=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function wo(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case He.FixedWidth:return o;case He.FixedHeight:return r;case He.Expand:return Math.max(o,r);case He.Shrink:return Math.min(o,r);case He.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const xo=[];function bo(e){if(e<xo.length)return xo[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 xo.push(t),t}function vo(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,ot);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*n/(i.viewportH*s);let a,u=0,h=0;if(i.projectionType===Oe.Orthographic){if(h=i.orthoSize,l){h=wo(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=h*r,a=Mo(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=To(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const d=Eo(o.position.x,o.position.y,o.position.z),f=bo(c.length);f.entity=e,f.viewProjection.set(Ro(a,d)),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=u,f.halfH=h,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const So=new Float32Array(16);function Mo(e,t,n,s,i,o){const r=So;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const Po=new Float32Array(16);function To(e,t,n,s){const i=Po;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const Co=new Float32Array(16);function Eo(e,t,n){const s=Co;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const Ao=new Float32Array(16);function Ro(e,t){const n=Ao;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const Io={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function ko(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,h=o.bottom+e.y*l,d=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*r.x,m=f+i.x):(f=c+n.x,m=u+s.x),e.y===t.y?(p=h+n.y-i.y*r.y,g=p+i.y):(p=h+n.y,g=d+s.y);const y=Math.max(0,m-f),_=Math.max(0,g-p);return{originX:f+r.x*y,originY:p+r.y*_,width:y,height:_,rect:{left:f,bottom:p,right:m,top:g}}}const Fo=De("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 Bo=null,zo=null;function Uo(e,t){e.has(t,Xe)||e.insert(t,Xe,{texture:ye,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 Wo(e,t){switch(e){case Io.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Io.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Io.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 $o(e,t){switch(e){case Io.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Io.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Io.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 Do(e,t,n,s){switch(e){case Io.BottomToTop:case Io.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Oo(e,t,n,s){if(!e.has(t,Fo))return;const i=e.get(t,Fo),o=Wo(n,s);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,Fo,i)}function Lo(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Ho(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function jo(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if(Ho(r.charCodeAt(0))&&s.length>0&&Ho(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Ho(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Vo(e){let t=1;for(;t<e;)t*=2;return t}function No(e,t){let n=0,s=t;for(;e.has(s,Ke);){const t=e.get(s,Ke).entity;if(!e.valid(t))break;n++,s=t}return n}function Xo(e,t){if(Bo&&zo){const e=Bo.getUIRectComputedWidth(zo,t);if(e>0)return e}return e.size.x}function Yo(e,t){if(Bo&&zo){const e=Bo.getUIRectComputedHeight(zo,t);if(e>0)return e}return e.size.y}function qo(e,t,n,s,i,o){if(!e.has(t,Xe))return;const r=e.get(t,Xe);let a,l;switch(n){case Io.BottomToTop:case Io.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,Xe,r))}function Go(e,t,n){let s=t;for(;e.has(s,Ke);){const t=e.get(s,Ke).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Ko(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Jo(e,t,n,s,i){if(!e.has(t,Fo))return;const o=e.get(t,Fo),r=ko(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,n,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,Xe)){const n=e.get(t,Xe);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,Xe,n))}if(e.has(t,je)){const n=e.get(t,je);n.position.x=r.originX-s,n.position.y=r.originY-i,e.insert(t,je,n)}}function Qo(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const Zo=.1,er=30,tr={r:.3,g:.5,b:.8,a:1},nr={Left:0,Center:1,Right:2},sr={Top:0,Middle:1,Bottom:2},ir={Visible:0,Clip:1,Ellipsis:2},or=Ae("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:nr.Left,verticalAlign:sr.Top,wordWrap:!0,overflow:ir.Visible,lineHeight:1.2});class rr{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(de.textCanvasSize,de.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,Vo(this.frameMaxW_)),e.height=Math.max(e.height,Vo(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Vo(this.frameMaxW_),e.height=Vo(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 n=this.ctx,s=this.canvas;n.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=jo(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=i?Math.ceil(o):h+2*u,p=i?Math.ceil(r):d+2*u;if(i&&e.overflow===ir.Ellipsis&&d>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),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Vo(f)),s.height=Math.max(s.height,Vo(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===ir.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case sr.Top:x=u;break;case sr.Middle:x=u+(p-2*u-w)/2;break;case sr.Bottom:x=p-w-u;break;default:x=u}x<0&&(x=0)}else x=u;let b=x;for(const t of l){let s;switch(e.align){case nr.Left:s=u;break;case nr.Center:s=f/2;break;case nr.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}i&&e.overflow===ir.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.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 n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const i=this.renderText(t,n);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[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}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 n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case nr.Left:return"left";case nr.Center:return"center";case nr.Right:return"right"}}}const ar=Qo({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?Xo(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Yo(e.uiRect,e.entity):0});class lr{build(e){We("Text",or);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new rr(t),s=e.world,i=new Map;e.addSystemToSchedule(sn.PreUpdate,an([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,or));for(const e of i.keys())if(!s.valid(e)||!s.has(e,or)){if(s.valid(e)&&s.has(e,Xe)){const t=s.get(e,Xe);s.insert(e,Xe,{texture:ye,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=s.getEntitiesWithComponents([or]);for(const t of e){const e=s.get(t,or),o=s.has(t,Fo)?s.get(t,Fo):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!ar.changed(a,r)){if(s.has(t,Xe)&&s.get(t,Xe).texture!==ye)continue}Uo(s,t);const l=o?{size:{x:Xo(o,t),y:Yo(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Xe);s.insert(t,Xe,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,ar.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const cr=new lr,ur=0,hr=1,dr=De("UIMask",{enabled:!0,mode:ur});function fr(e,t){const n=Math.max(e.x,t.x),s=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:n,y:s,w:Math.max(0,i-n),h:Math.max(0,o-s)}}function pr(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],w=s*l-i*a,x=s*c-o*a,b=s*u-r*a,v=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=h*g-d*m,T=h*y-f*m,C=h*_-p*m,E=d*y-f*g,A=d*_-p*g,R=f*_-p*y;let I=w*R-x*A+b*E+v*C-S*T+M*P;return 0===I||(I=1/I,n[0]=(l*R-c*A+u*E)*I,n[1]=(o*A-i*R-r*E)*I,n[2]=(g*M-y*S+_*v)*I,n[3]=(f*S-d*M-p*v)*I,n[4]=(c*C-a*R-u*T)*I,n[5]=(s*R-o*C+r*T)*I,n[6]=(y*b-m*M-_*x)*I,n[7]=(h*M-f*b+p*x)*I,n[8]=(a*A-l*C+u*P)*I,n[9]=(i*C-s*A-r*P)*I,n[10]=(m*S-g*b+_*w)*I,n[11]=(d*b-h*S-p*w)*I,n[12]=(l*T-a*E-c*P)*I,n[13]=(s*E-i*T+o*P)*I,n[14]=(g*x-m*v-y*w)*I,n[15]=(h*v-d*x+f*w)*I),n}function mr(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function gr(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function yr(e,t){return 2*Math.atan2(e,t)}function _r(e,t,n,s,i,o,r){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function wr(e,t,n,s,i,o,r,a,l,c){const u=yr(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-n,p=t-s,m=f*d-p*h+n,g=f*h+p*d+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}function xr(e,t,n,s,i,o,r){if(!e.has(t,Fo)||!e.has(t,je))return null;const a=e.get(t,Fo),l=e.get(t,je),c=Xo(a,t)*l.worldScale.x,u=Yo(a,t)*l.worldScale.y,h=l.worldPosition.x,d=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,g=c*(1-f),y=-u*p,_=u*(1-p),w=yr(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),b=Math.sin(w),v=[[h+m*x-y*b,d+m*b+y*x],[h+g*x-y*b,d+g*b+y*x],[h+g*x-_*b,d+g*b+_*x],[h+m*x-_*b,d+m*b+_*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of v){const[a,l]=_r(e,t,n,s,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 br(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([dr]);if(0===l.length)return;const c=[],u=[],h=new Set,d=new Set;for(const e of l){const n=t.get(e,dr);n.enabled&&(h.add(e),n.mode===hr?(u.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,o,r,a,l,c){const u=[];for(const e of s){let n=!0;Go(t,e,e=>{if(i.has(e)){if(t.get(e,dr).mode===ur)return n=!1,!0}return!1}),n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(i.has(n)){if(t.get(n,dr).mode===ur){const e=xr(t,n,o,r,a,l,c);e&&(s=fr(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=xr(t,e,o,r,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,o,r,a),u.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0;Go(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&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,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,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,s),u(t,s)}function u(t,s){if(a)return;const o=e.getChildEntities(n,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,s),u(t,s)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,u,d)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class vr{build(e){if(We("UIMask",dr),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(br(e.wasmModule,e.world))}}const Sr=new vr,Mr=De("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Pr=De("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Tr={Normal:0,Hovered:1,Pressed:2,Disabled:3},Cr=Ae("Button",{state:Tr.Normal,transition:null});class Er{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,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(n=>n.entity===e&&n.type===t)}}const Ar=pt(new Er,"UIEvents");class Rr{build(e){We("UIRect",Fo);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){Bo=e,zo=t}(n,s);e.addSystemToSchedule(sn.PreUpdate,an([mt(yn)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s),n.transform_update(s))},{name:"UILayoutSystem"})),e.addSystemToSchedule(sn.PostUpdate,an([mt(yn)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(sn.PostUpdate,an([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ir=new Rr;let kr=!1,Fr=!1;function Br(e){kr=e}function zr(){return kr}function Ur(){return!kr}function Wr(e){Fr=e}function $r(){return Fr}const Dr=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(pr(t,e),n=!1),e)}}();function Or(e,t,n,s){t.emit(n,s,n),Go(e,n,i=>{if(!e.has(i,Mr))return!1;const o=e.get(i,Mr);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class Lr{build(e){We("Interactable",Mr),We("Button",Cr);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new Er;e.insertResource(Ar,i);let o=null,r=null;e.addSystemToSchedule(sn.PreUpdate,an([mt(pn),mt(yn)],(e,a)=>{if(i.drain(),zr()&&!$r())return;const l=t.getEntitiesWithComponents([Pr]);for(const e of l){const n=t.get(e,Pr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Pr,n))}if(!a.valid)return;const c=f(),u=e.mouseX*c,h=a.screenH-e.mouseY*c;Dr.update(a.viewProjection);const d=mr(u,h,Dr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=d.x,a.worldMouseY=d.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);n.uiHitTest_update(s,d.x,d.y,p,m,g);const y=n.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,Pr)){const e=t.get(o,Pr);e.hovered=!1,t.insert(o,Pr,e),i.emit(o,"hover_exit")}if(null!==_){Ko(t,_,Pr);const e=t.get(_,Pr);e.hovered=!0,t.insert(_,Pr,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,Pr);e.pressed=!0,e.justPressed=!0,t.insert(_,Pr,e),r=_,Or(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,Pr)){const e=t.get(r,Pr);e.pressed=!1,e.justReleased=!0,t.insert(r,Pr,e),Or(t,i,r,"release"),r===o&&Or(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(sn.Update,an([],()=>{const e=t.getEntitiesWithComponents([Cr]);for(const n of e){if(Ko(t,n,Mr,{enabled:!0}),!t.has(n,Pr))continue;const e=t.get(n,Pr),s=t.get(n,Cr),i=t.get(n,Mr),o=!a.has(n),r=s.state;if(i.enabled?e.pressed?s.state=Tr.Pressed:e.hovered?s.state=Tr.Hovered:s.state=Tr.Normal:s.state=Tr.Disabled,o&&a.add(n),(o||r!==s.state)&&s.transition&&t.has(n,Xe)){const o=t.get(n,Xe);o.color=Lo(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,Xe,o)}}},{name:"ButtonSystem"}))}}const Hr=new Lr,jr=Ae("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}),Vr=Ae("Focusable",{tabIndex:0,isFocused:!1});class Nr{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 Xr=pt(new Nr,"FocusManager");class Yr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(We("TextInput",jr),zr()&&!$r())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=h(de.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,u=0,d=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(Xr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,jr)?s:null}const g=()=>{l||null===m()||b()},y=()=>{l=!0},_=()=>{l=!1,b()},w=t=>{const s=m();if(null===s)return;if("Escape"===t.key)return void v();const i=n.get(s,jr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(Ar).emit(s,"submit"),void v()}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 s=n.get(t,jr);s.focused=!1,s.dirty=!0;e.getResource(Xr).blur()}};function b(){const t=m();if(null===t)return;const s=n.get(t,jr);if(s.readOnly)return;let i=p.value;if(s.maxLength>0&&i.length>s.maxLength&&(i=i.substring(0,s.maxLength),p.value=i),i!==s.value){s.value=i;e.getResource(Ar).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function v(){const t=m();if(null!==t){const e=n.get(t,jr);e.focused=!1,e.dirty=!0}e.getResource(Xr).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",g),p.addEventListener("compositionstart",y),p.addEventListener("compositionend",_),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",y),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,u,h){(i.width<u||i.height<h)&&(i.width=Vo(Math.max(i.width,u)),i.height=Vo(Math.max(i.height,h))),o.clearRect(0,0,i.width,i.height);const d=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,o.fillRect(0,0,u,h),o.save(),o.beginPath(),o.rect(l.padding,0,u-2*l.padding,h),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 g=Math.ceil(1.2*l.fontSize),y=l.padding;if(l.multiline){const e=jo(o,p,u-2*y);let t=y;for(const n of e)o.fillText(n,y,t),t+=g}else{const e=(h-l.fontSize)/2;o.fillText(p,y,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=jo(o,l.value,u-2*y);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=n,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=y+o.measureText(c).width,n=y+r*g,s=g}else t=y+o.measureText(e).width,n=(h-l.fontSize)/2,s=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,n,2,s)}o.restore();const _=o.getImageData(0,0,u,h),w=new Uint8Array(_.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 b=s.get(e);void 0!==b&&x.releaseTexture(b);const v=x.createTexture(u,h,r,w.length,1,!0);s.set(e,v);const S=n.get(e,Xe);S.texture=v,S.size.x=u,S.size.y=h,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},n.insert(e,Xe,S)}e.addSystemToSchedule(sn.Update,an([mt(Xr)],e=>{const t=n.getEntitiesWithComponents([jr]);for(const e of t)Ko(n,e,Vr,{tabIndex:0,isFocused:!1}),Ko(n,e,Mr,{enabled:!0,blockRaycast:!0});const s=m();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,jr)){const e=n.get(M,jr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,jr);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(s),M=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(sn.PreUpdate,an([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===d?0:(e-d)/1e3;d=e,i=Math.min(i,.1);const o=m();if(null!==o&&(u+=i,u>=.5)){u-=.5,c=!c;n.get(o,jr).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,jr)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([jr,Fo]);for(const e of a){const t=n.get(e,jr);if(!t.dirty)continue;const s=n.get(e,Fo),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(Uo(n,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const qr=new Yr,Gr={Simple:0,Sliced:1,Tiled:2,Filled:3},Kr={Horizontal:0,Vertical:1},Jr={Left:0,Right:1,Bottom:2,Top:3},Qr=Ae("Image",{texture:ye,color:{r:1,g:1,b:1,a:1},imageType:Gr.Simple,fillMethod:Kr.Horizontal,fillOrigin:Jr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Zr=Qo({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?Xo(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Yo(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class ea{build(e){We("Image",Qr);const t=e.world,n=new Map;e.addSystemToSchedule(sn.PreUpdate,an([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Qr)||n.delete(e);const e=t.getEntitiesWithComponents([Qr]);for(const s of e){const e=t.get(s,Qr),i=t.has(s,Fo)?t.get(s,Fo):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&!Zr.changed(r,o))continue;Uo(t,s);const a=t.get(s,Xe);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=Xo(i,s),a.size.y=Yo(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Gr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Kr.Horizontal?e.fillOrigin===Jr.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===Jr.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===Gr.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(s,Xe,a),n.set(s,Zr.take(o))}else a.color.a=0,t.insert(s,Xe,a),n.set(s,Zr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const ta=new ea,na=Ae("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),sa=Ae("ToggleGroup",{allowSwitchOff:!1});class ia{build(e){We("Toggle",na),We("ToggleGroup",sa);const t=e.world,n=new Set;e.addSystemToSchedule(sn.Update,an([mt(Ar)],e=>{const s=t.getEntitiesWithComponents([na]);if(!zr()||$r()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,na);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,na,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,na);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(Ko(t,n,Mr,{enabled:!0}),!t.has(n,Pr))continue;const s=t.get(n,Pr),i=t.get(n,na),r=t.get(n,Mr);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,sa);if(i.isOn&&r){if(!t.get(s,sa).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,na,i),i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,na);i.isOn&&(i.isOn=!1,t.insert(s,na,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,Xe)){const e=t.get(n,Xe);e.color=Lo(i.transition,r.enabled,s.pressed,s.hovered),t.insert(n,Xe,e)}}}for(const e of s){const n=t.get(e,na);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,Xe)){const e=t.get(n.graphicEntity,Xe);e.enabled=n.isOn,t.insert(n.graphicEntity,Xe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const oa=new ia,ra=Io,aa=Ae("ProgressBar",{value:0,fillEntity:0,direction:Io.LeftToRight});function la(e,t,n,s){if(!e.has(t,Fo))return;const i=e.get(t,Fo),o=n/2,r=s/2,a={left:-o,bottom:-r,right:o,top:r},l=ko(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,Xe)){const n=e.get(t,Xe);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,Xe,n))}if(e.has(t,je)){const n=e.get(t,je),s=n.position;s.x===l.originX&&s.y===l.originY||(n.position={x:l.originX,y:l.originY,z:s.z},e.insert(t,je,n))}}class ca{build(e){We("ProgressBar",aa);const t=e.world;e.addSystemToSchedule(sn.PreUpdate,an([],()=>{const e=t.getEntitiesWithComponents([aa,Fo]);for(const n of e){const e=t.get(n,aa);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Fo),i=Math.max(0,Math.min(1,e.value));Oo(t,e.fillEntity,e.direction,i);const o=Xo(s,n),r=Yo(s,n);la(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const ua=new ca,ha=Ae("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),da=Ae("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}});class fa{build(e){We("Draggable",ha),We("DragState",da);const t=e.world,n=e.getResource(Ar);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(sn.PreUpdate,an([mt(pn),mt(yn)],(e,r)=>{if(zr()&&!$r())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([ha,Pr]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,ha).enabled)continue;if(t.get(s,Pr).hovered){let e=0;t.has(s,Xe)&&(e=t.get(s,Xe).layer);const i=No(t,s);(e>o||e===o&&i>=r)&&(o=e,r=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,da)||t.insert(n,da);const e=t.get(n,da),o=t.get(n,je);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!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,da)){t.get(s,da).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,ha);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,da).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,da))return void(o=null);const s=t.get(o,da),i=t.get(o,ha),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;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,s,c,u);c=h.x,u=h.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,je)){const e=function(e,t,n,s){if(!e.has(t,Ke))return{x:n,y:s};const i=e.get(t,Ke).entity;if(!e.valid(i)||!e.has(i,je))return{x:n,y:s};const o=e.get(i,je),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=yr(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,je);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,je,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const pa=new fa,ma=Ae("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function ga(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function ya(e,t,n,s,i){const o=2/(s=Math.max(1e-4,s)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-o*c)*a}}class _a{build(e){We("ScrollView",ma);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(sn.PostUpdate,an([mt(pn),mt(yn),mt(wt)],(e,i,o)=>{const r=zr()&&!$r(),a=Math.min(o.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([ma,Fo]);for(const o of l){Ko(t,o,dr,{enabled:!0,mode:ur});const l=t.get(o,ma),c=t.get(o,Fo);let u=n.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(o,u));const h=Xo(c,o),d=Yo(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,Je)){const e=t.get(l.contentEntity,Je).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,je))continue;const e=t.get(r,je);let a=0,l=0,c=.5,u=.5;if(t.has(r,Fo)){const e=t.get(r,Fo);a=Xo(e,r)||e.size.x,l=Yo(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,Xe)){const e=t.get(r,Xe);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,d=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);h<n&&(n=h),d>s&&(s=d),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-h),g=Math.max(0,p-d);if(!r&&i.valid){Ko(t,o,Mr,{enabled:!0,blockRaycast:!0});const n=t.has(o,Pr)?t.get(o,Pr):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=ga(l.scrollX,0,m,h);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=ga(l.scrollY,0,g,d);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*h,t=5*d;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=ga(l.scrollY,0,g,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=ga(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=ya(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Zo&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Zo?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=ya(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Zo&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Zo?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.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,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*d;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,je)){const e=t.get(l.contentEntity,je),n=e.position.x,s=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(n-u.lastAppliedX)>.01)&&(u.contentBaseX=n),(isNaN(u.lastAppliedY)||Math.abs(s-u.lastAppliedY)>.01)&&(u.contentBaseY=s),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,je,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const wa=new _a,xa=Io,ba=Ae("Slider",{value:0,minValue:0,maxValue:1,direction:Io.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function va(e,t,n,s,i,o){const r=Xo(s,i)*n.worldScale.x,a=Yo(s,i)*n.worldScale.y,l=yr(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),h=e-n.worldPosition.x,d=t-n.worldPosition.y,f=h*u-d*c,p=h*c+d*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case Io.LeftToRight:return r>0?(f-m)/r:0;case Io.RightToLeft:return r>0?1-(f-m)/r:0;case Io.BottomToTop:return a>0?(p-g)/a:0;case Io.TopToBottom:return a>0?1-(p-g)/a:0}}function Sa(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Io.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case Io.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case Io.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case Io.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class Ma{build(e){We("Slider",ba);const t=e.world;let n=null;e.addSystemToSchedule(sn.PreUpdate,an([mt(pn),mt(yn),mt(Ar)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=t.getEntitiesWithComponents([ba,Fo]);for(const r of o){const o=t.get(r,ba),a=t.get(r,Fo);if(!zr()||$r()){if(t.has(r,je)){Ko(t,r,Mr,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Ko(t,o.handleEntity,Mr,{enabled:!0,blockRaycast:!1});const l=t.get(r,je),c=t.has(r,Pr)?t.get(r,Pr):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Pr)&&(u=t.get(o.handleEntity,Pr).justPressed),u&&(n=r),n===r&&e.isMouseButtonDown(0)){let e=va(s.worldMouseX,s.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let n=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(n=Math.round(n));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,n)),t.insert(r,ba,o),o.value!==c&&i.emit(r,"change")}n===r&&e.isMouseButtonReleased(0)&&(n=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=Xo(a,r),h=Yo(a,r),d={left:-u/2,bottom:-h/2,right:u/2,top:h/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Oo(t,o.fillEntity,o.direction,c),Jo(t,o.fillEntity,d,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Fo)){const e=t.get(o.handleEntity,Fo);Sa(e,o.direction,c),t.insert(o.handleEntity,Fo,e),Jo(t,o.handleEntity,d,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Pa=new Ma;class Ta{build(e){We("Focusable",Vr);const t=e.world,n=new Nr;e.insertResource(Xr,n),e.addSystemToSchedule(sn.Update,an([mt(pn),mt(Ar)],(e,s)=>{if(zr()&&!$r())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Vr]);for(const e of i){if(!t.has(e,Pr))continue;t.get(e,Pr).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,Mr)){if(!t.get(n,Mr).enabled)continue}const s=t.get(n,Vr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Vr)){t.get(i,Vr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Vr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Ca=new Ta,Ea=Ae("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Aa(){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:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.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")}}()}class Ra{build(e){We("SafeArea",Ea);const t=e.world;let n=Aa(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Aa(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Aa(),s=!0});e.addSystemToSchedule(sn.PreUpdate,an([mt(yn)],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,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([Ea,Fo]);for(const e of u){const s=t.get(e,Ea),i=t.get(e,Fo),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Fo,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const Ia=new Ra,ka=Ae("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Fa=null;function Ba(e,t){if(!Fa)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Fa.get(e);n?n.renderer=t:Fa.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class za{build(e){We("ListView",ka);const t=e.world,n=new Map;Fa=n,e.addSystemToSchedule(sn.PostUpdate,an([mt(pn)],e=>{const s=zr()&&!$r();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([ka,Fo]);for(const o of i){Ko(t,o,Mr,{enabled:!0,blockRaycast:!0}),Ko(t,o,dr,{enabled:!0,mode:ur});let i=n.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,i));const r=t.get(o,ka),a=t.get(o,Fo),l=Yo(a,o),c=Xo(a,o);if(!s){const n=t.has(o,Pr)?t.get(o,Pr):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=d)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<d;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,it,{value:`ListItem_${e}`}),t.insert(n,Fo,{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(n,o),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,je)){const s=t.get(n,je);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,je,s)}}i.visibleStart=h,i.visibleEnd=d}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ua=new za,Wa=Ae("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class $a{build(e){We("Dropdown",Wa);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,je))return;const n=t.get(e,je);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,je,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,Xe)){const n=t.get(e,Xe);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,Xe,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},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:n.enabled})}}function o(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(s);const o=t.get(e,Xe),r=o.size.x,a=o.size.y;s.ddWidth=r;const l=n.options.length*er;t.insert(i,Fo,{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,je,{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,Xe,{texture:ye,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<n.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*er;t.insert(o,it,{value:`Option_${e}`}),t.insert(o,Fo,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*er},offsetMax:{x:0,y:0},size:{x:r,y:er},pivot:{x:.5,y:.5}}),t.insert(o,je,{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,Xe,{texture:ye,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:er},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,Mr,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),s.optionEntities.push(o);const c=t.spawn();t.insert(c,je,{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,or,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:nr.Left,verticalAlign:sr.Middle,wordWrap:!1,overflow:ir.Clip,lineHeight:1.2}),t.insert(c,Fo,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:er},pivot:{x:.5,y:.5}}),t.setParent(c,o),s.textEntities.push(c)}h(s)}function r(e,t,n){t.isOpen=!1,c(n),u(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,r(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,or))return;const s=t.get(n,or);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},o=s.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(n,or,{content:o,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function u(e,n){if(0!==e&&t.valid(e)&&(t.has(e,Mr)&&t.insert(e,Mr,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,Xe))){const s=t.get(e,Xe);t.insert(e,Xe,{texture:s.texture,color:{r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},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:n})}}function h(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,Xe))continue;const i=n===e.highlightIndex?{...tr}:{r:.95,g:.95,b:.95,a:1};t.insert(s,Xe,{texture:ye,color:i,size:{x:e.ddWidth,y:er},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function d(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,Pr))continue;if(t.get(n,Pr).hovered)return!0}return!1}e.addSystemToSchedule(sn.Update,an([mt(pn),mt(Ar)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=zr()&&!$r(),p=t.getEntitiesWithComponents([Wa]);for(const m of p){const p=t.get(m,Wa);let g=n.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(m,g)),s(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;Ko(t,m,Mr,{enabled:!0,blockRaycast:!0});const y=t.has(m,Pr)?t.get(m,Pr):null;if(y?.justPressed&&(p.isOpen?r(m,p,g):o(m,p,g)),p.isOpen){for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,Pr))continue;if(t.get(n,Pr).justPressed){a(m,p,g,e,c);break}}let n=-1;for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,Pr))continue;if(t.get(s,Pr).hovered){n=e;break}}n>=0&&n!==g.highlightIndex&&(g.highlightIndex=n,h(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=p.options.length-1?g.highlightIndex=0:g.highlightIndex++,h(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=p.options.length-1:g.highlightIndex--,h(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,p,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,g),e.isMouseButtonPressed(0)&&(y?.hovered||d(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const Da=new $a,Oa=0,La=0,Ha=2,ja=Ae("LayoutGroup",{direction:Oa,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:La,reverseOrder:!1});class Va{build(e){We("LayoutGroup",ja);const t=e.world;e.addSystemToSchedule(sn.PreUpdate,an([],()=>{const e=t.getEntitiesWithComponents([ja,Fo,Je]);for(const n of e){const e=t.get(n,ja),s=t.get(n,Fo),i=t.get(n,Je);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Fo)&&t.has(e,je)&&o.push({entity:e,rect:t.get(e,Fo)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Xo(s,n),a=Yo(s,n),l=s.pivot.x,c=s.pivot.y,u=e.padding,h=e.direction===Oa;let d=0;for(let n=0;n<o.length;n++){const s=o[n],i=Xo(s.rect,s.entity),f=Yo(s.rect,s.entity),p=s.rect.pivot.x,m=s.rect.pivot.y;let g,y;h?(g=-l*r+u.left+d+p*i,y=e.childAlignment===La?(1-c)*a-u.top-(1-m)*f:e.childAlignment===Ha?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,d+=i,n<o.length-1&&(d+=e.spacing)):(g=e.childAlignment===La?-l*r+u.left+p*i:e.childAlignment===Ha?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,y=(1-c)*a-u.top-d-(1-m)*f,d+=f,n<o.length-1&&(d+=e.spacing));const _=t.get(s.entity,je);_.position.x=g,_.position.y=y,t.insert(s.entity,je,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Na=new Va;class Xa{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(sn.PostUpdate,an([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Ya=new Xa;async function qa(e,t,n){const s=e.getResource(ho);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Ga(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 Ka=pt({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),Ja={r:.2,g:.4,b:1,a:.7},Qa={r:.2,g:1,b:.2,a:.7},Za={r:.2,g:1,b:1,a:.7},el={r:1,g:1,b:.2,a:.5},tl={r:1,g:.2,b:.2,a:.8},nl={r:1,g:.2,b:.2,a:1},sl=1.5,il=16;function ol(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function rl(e){switch(e){case dt.Static:return Ja;case dt.Kinematic:return Za;default:return Qa}}function al(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*r-n.y*a,y:t+n.x*a+n.y*r}));for(let e=0;e<4;e++)si.line(l[e],l[(e+1)%4],o,sl)}function ll(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=(n,s)=>({x:e+n*r-s*a,y:t+n*a+s*r}),c=l(-n,s),u=l(n,s),h=l(-n,-s),d=l(n,-s);si.line(c,h,o,sl),si.line(u,d,o,sl);for(let e=0;e<il;e++){const t=e/il*Math.PI,i=(e+1)/il*Math.PI,r=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(i),s+n*Math.sin(i));si.line(r,a,o,sl)}for(let e=0;e<il;e++){const t=Math.PI+e/il*Math.PI,i=Math.PI+(e+1)/il*Math.PI,r=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(i),-s+n*Math.sin(i));si.line(r,a,o,sl)}}function cl(e,t,n,s){const i=e+.5*n,o=t+.5*s;si.line({x:e,y:t},{x:i,y:o},tl,sl);const r=Math.sqrt(n*n+s*s);if(r<1)return;const a=Math.PI/6,l=n/r,c=s/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),h=o-6*(l*Math.sin(a)+c*Math.cos(a)),d=i-6*(l*Math.cos(a)+c*Math.sin(a)),f=o-6*(-l*Math.sin(a)+c*Math.cos(a));si.line({x:i,y:o},{x:u,y:h},tl,sl),si.line({x:i,y:o},{x:d,y:f},tl,sl)}function ul(e,t,n){const s=e.getResource(Ka);if(!s||!s.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([qe]);for(const n of t){const t=e.world.get(n,qe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([lt,je]);let r=null;s.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const n=e.world.get(t,lt);if(!n.enabled)continue;const o=e.world.get(t,je),a=o.worldPosition.x,l=o.worldPosition.y,c=ol(o.worldRotation);if(s.showColliders){if(e.world.has(t,ct)){const s=e.world.get(t,ct),o=s.isSensor?el:rl(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c);al(a+r*h-u*d,l+r*d+u*h,s.halfExtents.x*i,s.halfExtents.y*i,c,o)}if(e.world.has(t,ut)){const s=e.world.get(t,ut),o=s.isSensor?el:rl(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c),f=a+r*h-u*d,p=l+r*d+u*h;si.circleOutline({x:f,y:p},s.radius*i,o,sl,32)}if(e.world.has(t,ht)){const s=e.world.get(t,ht),o=s.isSensor?el:rl(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c);ll(a+r*h-u*d,l+r*d+u*h,s.radius*i,s.halfHeight*i,c,o)}}if(s.showVelocity&&r&&n.bodyType===dt.Dynamic){const e=r.getLinearVelocity(t);cl(a,l,e.x*i,e.y*i)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)si.circle({x:e.contactX,y:e.contactY},3,nl,!0,32)}}const hl=pt({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),dl=pt(null,"PhysicsAPI");function fl(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function pl(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ml{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(hl,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Ga(this.wasmUrl_,this.factory_).then(s=>{s._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([qe]);for(const n of t){const t=e.world.get(n,qe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(sn.PostUpdate,an([mt(wt)],a=>{const l=r.getEntitiesWithComponents([lt,je]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,lt),l=r.get(i,je);if(t.has(i)){const e=n.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||(s._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=fl(l.worldRotation);s._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),gl(e,s,i),t.add(i),n.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===dt.Kinematic){const e=fl(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<s;i++){const s=o+4*i,r=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(r))continue;const u=e.world.get(r,je);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(r,Ke)){const t=e.world.get(r,Ke);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,je)){const n=e.world.get(t.entity,je),s=fl(n.worldRotation),i=a-n.worldPosition.x,o=l-n.worldPosition.y,r=Math.cos(-s),u=Math.sin(-s);h=(i*r-o*u)/(0!==n.worldScale.x?n.worldScale.x:1),d=(i*u+o*r)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=pl(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(r,je,u)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],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;s.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]*n,contactY:t.HEAPF32[i+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(hl,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(dl,yl._fromModule(s)),function(e,t,n){e.insertResource(Ka,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),li("physics-debug-draw",()=>{ul(e,t,n)})}(e,dl,hl),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function gl(e,t,n){const s=e.world;if(s.has(n,ct)){const e=s.get(n,ct);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,ut)){const e=s.get(n,ut);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,ht)){const e=s.get(n,ht);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class yl{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(yl.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)}static setDebugDraw(e,t){const n=e.getResource(Ka);n&&(n.enabled=t,e.insertResource(Ka,n))}static setDebugDrawConfig(e,t){const n=e.getResource(Ka);n&&e.insertResource(Ka,{...n,...t})}}const _l={nearest:0,linear:1},wl={repeat:0,clamp:1,mirror:2};function xl(e,t,n=!0,s){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=_l[s.filterMode??"linear"]??1,a=wl[s.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,n,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),r}function bl(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function vl(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),o=e.worldScale.y*t*(s?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.w,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,g=a*f,y=l*d,_=l*f,w=c*f,x=u*h,b=u*d,v=u*f;return new Float32Array([(1-(y+w))*i,(m+v)*i,(g-b)*i,0,(m-v)*o,(1-(p+w))*o,(_+x)*o,0,(g+b)*r,(_-x)*r,(1-(p+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Sl(e){const{app:t,module:n,sceneData:s,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=xs(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===s[o])try{const t=i?.[o];s[o]=xl(e,await n.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),s[o]=0}}}return s}(n,s,i);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(n,s,u);let h={},d=null;if(o&&(d=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"])}}(o),h=await async function(e,t,n,s,i){const o={};for(const r of s.entities)for(const s of r.components){const r=bs(s.type);if(!r||!s.data)continue;const a=s.data[r.skeletonField],l=s.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const s=await i.readText(l),r="binary"===T(c)?.contentType;let h,d;if(r){const e=await i.readBinary(a);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,r);if(t._free(h),f<0)continue;o[a]=f;const p=bl(s),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),r=xl(e,o,!1),a=e.getResourceManager().getTextureGLId(r);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(n,o,d,s,i)),r){const e={gravity:a?.gravity??{...ce},fixedTimestep:a?.fixedTimestep??ue,subStepCount:a?.subStepCount??4};new ml("",e,()=>Promise.resolve(r)).build(t)}const f=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=xs(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=T(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=xl(e,c,!1),h=e.getResourceManager();s[o]=h.loadBitmapFont(t,u,c.width,c.height)}catch{s[o]=0}}return s}(n,s,i),p=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=xs(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=Cn.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=Cn.createFromAsset(e,r)}catch{n[o]=0}}return n}(s,i);await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=xs(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=JSON.parse(t),o=$n(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,xl(e,s))}catch{r.set(t,0)}Ln(Dn(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(n,s,i),await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=xs(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=hs(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=ds(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=xl(e,t),Kn(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}Zn(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=xs(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await Yn.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await Yn.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=xs(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,u,f,p);const m=Cs(t.world,s);if(c&&t.hasResource(ho))for(const e of m.values())t.world.insert(e,ot,{scene:c,persistent:!1});if(o&&d){const e=function(e,t,n,s){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=bs(t.type);if(!r||!t.data)continue;const a=n[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.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}(d,s,h,m);!function(e,t,n,s,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=le);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,Ze)?c.get(o,Ze):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(r,l*h);let d=0;if(c.has(o,je)){const e=vl(c.get(o,je),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(r);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(r,e),o=s.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,u,h,f);const p=n.HEAPU32[h>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*i),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,i,w,o,p,m,d),t._free(_),t._free(w),n._free(c),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(t,n,o,d,e)}if(l){const e=t.getResource(Bs);e&&e.setAddressableManifest(l)}}function Ml(e,t,n){return{name:e,async setup(){await Sl({...n,sceneData:t,sceneName:e})}}}async function Pl(e){const{app:t,firstScene:n,aspectRatio:s}=e;yo(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(ho);for(const t of e.scenes)o.register(Ml(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&Is(t.world,s)}class Tl{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=bs(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===T(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=xs(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}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 n)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 s){const t=T(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,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),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),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 Cl="__preview__";class El{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(ho);t.register({name:Cl,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Cl),this.loadPromise_=t.load(Cl).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(),n=new Tl(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Sl({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineModule:s,sceneName:Cl})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Ye]);for(const s of n){if(e.get(s,Ye).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([qe]);for(const i of s){const s=e.get(i,qe);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(ho).getScene(Cl),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,je,r);const a={isActive:!0,projectionType:Oe.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Le.ColorAndDepth};e.insert(o,Ye,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(ho);await e.switchTo(Cl),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 Al={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=to.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:to.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){to.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(to.releaseRenderTarget(e._handle),Al.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){to.begin(t,e._handle)},end(){to.end()},getDepthTexture:e=>to.getTargetDepthTexture(e._handle)};var Rl;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Rl||(Rl={}));class Il{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Rl[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Rl.Debug:console.debug(t,n);break;case Rl.Info:console.log(t,n);break;case Rl.Warn:console.warn(t,n);break;case Rl.Error:console.error(t,n)}}}class kl{constructor(){this.handlers_=[],this.minLevel_=Rl.Info,this.addHandler(new Il)}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,n){this.log(Rl.Debug,e,t,n)}info(e,t,n){this.log(Rl.Info,e,t,n)}warn(e,t,n){this.log(Rl.Warn,e,t,n)}error(e,t,n){this.log(Rl.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Fl=new kl;function Bl(){return Fl}function zl(e){Fl.setMinLevel(e)}function Ul(e,t,n){Fl.debug(e,t,n)}function Wl(e,t,n){Fl.info(e,t,n)}function $l(e,t,n){Fl.warn(e,t,n)}function Dl(e,t,n){Fl.error(e,t,n)}const Ol={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},Ll={Running:0,Paused:1,Completed:2,Cancelled:3},Hl={None:0,Restart:1,PingPong:2};const jl=1.70158,Vl=2.70158,Nl=2.5949095;const Xl=2*Math.PI/3,Yl=2*Math.PI/4.5;const ql=7.5625,Gl=2.75;const Kl=1e-6;function Jl(e,t,n){switch(e){case Ol.Linear:return t;case Ol.EaseInQuad:return function(e){return e*e}(t);case Ol.EaseOutQuad:return function(e){return e*(2-e)}(t);case Ol.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Ol.EaseInCubic:return function(e){return e*e*e}(t);case Ol.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Ol.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Ol.EaseInBack:return function(e){return Vl*e*e*e-jl*e*e}(t);case Ol.EaseOutBack:return function(e){const t=e-1;return 1+Vl*t*t*t+jl*t*t}(t);case Ol.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Nl)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Nl)+2)/2}(t);case Ol.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Xl)}(t);case Ol.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Xl)+1}(t);case Ol.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Yl)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Yl)/2+1}(t);case Ol.EaseOutBounce:return function(e){return e<1/Gl?ql*e*e:e<2/Gl?ql*(e-=1.5/Gl)*e+.75:e<2.5/Gl?ql*(e-=2.25/Gl)*e+.9375:ql*(e-=2.625/Gl)*e+.984375}(t);case Ol.CubicBezier:return n?function(e,t,n,s,i){let o=e;for(let n=0;n<8;n++){const n=1-o,i=3*t*n*n*o+3*s*n*o*o+o*o*o-e;if(Math.abs(i)<Kl)break;const r=3*t*(1-2*o)*(1-o)+6*s*o*(1-o)-3*s*o*o+3*o*o;if(Math.abs(r)<Kl)break;o-=i/r}const r=1-o;return 3*n*r*r*o+3*i*r*o*o+o*o*o}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case Ol.Step:return function(e){return e<1?0:1}(t);default:return t}}const Ql=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:n,elapsed:0,delay:i?.delay??0,easing:i?.easing??Ol.Linear,bezierPoints:null,state:Ll.Running,loop:i?.loop??Hl.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===Ll.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Ll.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=Jl(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Hl.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Hl.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Ll.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Ll.Running&&(t.state=Ll.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Ll.Paused&&(t.state=Ll.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Ll.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Ll.Cancelled}setBezier(e,t,n,s,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:i})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Zl{constructor(e){this.id=e}get state(){return Ql.getState(this.id)}bezier(e,t,n,s){return Ql.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof Zl?Ql.setSequenceNext(this.id,e.id):Ql.setSequenceNextExternal(this.id,e),this}pause(){Ql.pause(this.id)}resume(){Ql.resume(this.id)}cancel(){Ql.cancel(this.id)}}const ec={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};class tc{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof Zl?(Ql.registerCppSequence(this.entity,e.id),this):(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 nc=null,sc=null;function ic(e,t){nc=e,sc=t,Ql.init(e,t)}function oc(){Ql.shutdown(),nc=null,sc=null}function rc(){if(!nc)throw new Error("Tween API not initialized");return nc}function ac(){if(!sc)throw new Error("Tween API not initialized");return sc}const lc={to(e,t,n,s,i,o){const r=rc(),a=ac(),l=o?.easing??Ol.Linear,c=o?.delay??0,u=o?.loop??Hl.None,h=o?.loopCount??0,d=r._anim_createTween(a,e,t,n,s,i,l,c,u,h);return new tc(r,a,d)},value(e,t,n,s,i){const o=Ql.create(e,t,n,s,i);return new Zl(o)},cancel(e){rc()._anim_cancelTween(ac(),e.entity)},cancelAll(e){rc()._anim_cancelAllTweens(ac(),e)},update(e){rc()._anim_updateTweens(ac(),e),Ql.update(e)}};class cc{constructor(){this.name="AnimationPlugin"}build(e){ic(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(sn.Update,an([mt(wt)],e=>{lc.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(sn.Update,an([mt(wt)],e=>{Xn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){oc()}}const uc=new cc;var hc;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(hc||(hc={}));const dc={model:hc.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function fc(e,t=dc){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case hc.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case hc.Inverse:a=s/Math.max(r,s);break;case hc.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function pc(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const mc=Ae("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:hc.Inverse,rolloff:1,priority:0,enabled:!0}),gc=Ae("AudioListener",{enabled:!0});class yc{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=n.mixer;Yn.init(n,i),i&&(void 0!==s.masterVolume&&(i.master.volume=s.masterVolume),void 0!==s.musicVolume&&(i.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(i.sfx.volume=s.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(sn.PreUpdate,an([mt(wt)],t=>{if(!(!zr()||$r()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let i=0,u=0,h=!1;const d=s.getEntitiesWithComponents([gc,Ne]);for(const e of d){if(s.get(e,gc).enabled){const t=s.get(e,Ne);i=t.position.x,u=t.position.y,h=!0;break}}const f=s.getEntitiesWithComponents([mc]);a.clear();for(const e of f){const t=s.get(e,mc);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&n.isReady){const e=Yn.getBufferHandle(t.clip);if(e){const s=n.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,s),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const n=o.get(c);if(!n.isPlaying){o.delete(c);continue}h||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,Ne),a=r?.position.x??0,d=r?.position.y??0,f=a-i,p=d-u,m=fc(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=pc(a,0,i,0,t.maxDistance);n.setVolume(t.volume*m),n.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),Yn.dispose()}}const _c=new yc;let wc=null,xc=null;function bc(e,t){wc=e,xc=t}function vc(){wc=null,xc=null}const Sc={update(e){wc&&xc&&wc.particle_update?.(xc,e)},play(e){wc&&xc&&wc.particle_play?.(xc,e)},stop(e){wc&&xc&&wc.particle_stop?.(xc,e)},reset(e){wc&&xc&&wc.particle_reset?.(xc,e)},getAliveCount:e=>wc?wc.particle_getAliveCount?.(e)??0:0};class Mc{constructor(){this.name="ParticlePlugin"}build(e){bc(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(sn.Update,an([mt(wt)],e=>{Sc.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){vc()}}const Pc=new Mc,Tc=1e6;class Cc{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){ss(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(yn),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:Tc,l=i?.valid?i.worldTop:Tc,c=t.getEntitiesWithComponents([as,je]);for(const e of c){const s=t.tryGet(e,as),i=t.tryGet(e,je);if(!s||!i)continue;if(!s.visible)continue;const c=s.texture;if(!c)continue;const u=Jn(c);if(!u)continue;if(!n.has(e)){if(os.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];os.setTiles(e,t)}n.add(e)}const h=s.tileWidth/u.width,d=s.tileHeight/u.height,f=s.tint,p=s.parallaxFactor;os.submitLayer(e,c,s.layer,0,s.tilesetColumns,h,d,i.worldPosition.x,i.worldPosition.y,o,r,a,l,f.r,f.g,f.b,f.a,s.opacity,p.x,p.y)}const u=t.getEntitiesWithComponents([rs,je]);for(const e of u){if(t.tryGet(e,as))continue;const i=t.tryGet(e,rs),c=t.tryGet(e,je);if(!i?.source||!c)continue;const u=es(i.source);if(!u)continue;if(!s.has(e)){const t=[];for(let s=0;s<u.layers.length;s++){const i=1073741824+256*e+s,o=u.layers[s];os.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&os.setTiles(i,o.tiles),t.push(i),n.add(i)}s.set(e,t)}const h=s.get(e);for(let e=0;e<u.layers.length&&e<h.length;e++){const t=h[e],n=u.tilesets[0];if(!n)continue;const s=Jn(n.textureHandle);if(!s)continue;const i=u.tileWidth/s.width,d=u.tileHeight/s.height;os.submitLayer(t,n.textureHandle,e,0,n.columns,i,d,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)os.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),Qn(),is()}}const Ec=new Cc;function Ac(e,t){return e.toFixed(t)}function Rc(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class Ic{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">${Ac(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Ac(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 n=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let s='<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 n){s+=`<div>${Rc(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Ac(t,1)}ms</span></div>`}t.push(s)}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 kc(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const Fc=pt(kc(),"Stats");class Bc{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const zc="StatsCollect";class Uc{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 Wc{constructor(e){this.name="Stats",this.collector_=new Uc,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Fc,kc());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Ic(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=an([mt(wt),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(Fc);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(zc),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=to.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,n?.update(o)},{name:zc});e.addSystemToSchedule(sn.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const $c=new Wc;class Dc{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.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]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(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 Oc(e,t){try{const n=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function Lc(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(Bs);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Oc(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 Oc(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new Dc(s);await Pl({app:t,module:n,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Hc=[cr,Sr,Ir,ta,ua,Hr,pa,wa,Pa,oa,qr,Ca,Ia,Ua,Da,Na,Ya],jc=[...Hc,uc,_c,Pc,Ec,Gi];function Vc(e,t){return function(e,t){const n=go.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Zs(e),Mn(e),gi(e),Ei(e),Zi(e),so(e);const i=new ro;n.setPipeline(i);let o=d();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=vo(e,s,t,i));const r=n.getResource(yn);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*i),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.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}n.insertResource(yn,{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(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;to.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(to.resize(t,l),n.hasResource(ho)){const e=n.getResource(ho).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=vo(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:_o,width:t,height:l,elapsed:u});else{i.beginScreenCapture();for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u,cameraEntity:e.entity})}i.endScreenCapture(),to.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(sn.First,l),n.addSystemToSchedule(sn.Last,c),n.addPlugin(Us),n.addPlugin(Ys),n.addPlugin(gn),n.addPlugin(mo),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:jc,...t})}class Nc{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return l(this.resolvePath_(e))}async readBinary(e){const t=await a(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function Xc(e){return(t,n)=>(u(e,t).then(e=>{n(e.instance,e.module)}),{})}async function Yc(e,t){try{return await e({instantiateWasm:Xc(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function qc(e){const t=await l("asset-manifest.json"),n=JSON.parse(t),s=function(e){const t={},n={};for(const s in e.groups){const i=e.groups[s];for(const e in i.assets){const s=i.assets[e];t[e]=s,n[s.path]=s}}return{assetIndex:t,pathIndex:n}}(n),i=function(e){const{assetIndex:t,pathIndex:n}=e;return e=>{const s=W(e),i=t[e]||t[s]||n[s]||n[e];return i?i.path:s}}(s),o=wx.createCanvas(),r=wx.getSystemInfoSync();o.width=r.windowWidth*r.pixelRatio,o.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:o,instantiateWasm:Xc("esengine.wasm")}),c=o.getContext("webgl2")||o.getContext("webgl");if(!c)return void console.error("[ESEngine] Failed to create WebGL context");const u=a.GL.registerContext(c,{majorVersion:0===c.getParameter(c.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),h=Vc(a,{glContextHandle:u,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&me(h,e.runtimeConfig);let d=null;e.spineFactory&&(d=await Yc(e.spineFactory,"spine.wasm"));let f=null;e.physicsFactory&&(f=await Yc(e.physicsFactory,"physics.wasm"));const p=new Nc(i),m=[];for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`);m.push({name:t,data:JSON.parse(e)})}await Pl({app:h,module:a,provider:p,scenes:m,firstScene:e.firstScene,spineModule:d,physicsModule:f,physicsConfig:e.physicsConfig,manifest:n,aspectRatio:o.width/o.height}),h.run()}J||(J=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},i=await w(n,s);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return x(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i<128?n[s++]=i:i<2048?(n[s++]=192|i>>6,n[s++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,n[s++]=240|i>>18,n[s++]=128|i>>12&63,n[s++]=128|i>>6&63,n[s++]=128|63&i):(n[s++]=224|i>>12,n[s++]=128|i>>6&63,n[s++]=128|63&i)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const i=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Q;export{Wt as Added,cc as AnimationPlugin,go as App,zs as AssetPlugin,Ws as AssetRefCounter,Fs as AssetServer,Bs as Assets,Un as AsyncCache,hc as AttenuationModel,Yn as Audio,p as AudioBus,gc as AudioListener,m as AudioMixer,yc as AudioPlugin,g as AudioPool,mc as AudioSource,Qe as BitmapText,_n as BlendMode,dt as BodyType,ct as BoxCollider,Cr as Button,Tr as ButtonState,Ye as Camera,qe as Canvas,ht as CapsuleCollider,$t as Changed,Je as Children,ut as CircleCollider,Le as ClearFlags,Yt as Commands,Gt as CommandsInstance,ee as DEFAULT_DESIGN_HEIGHT,Z as DEFAULT_DESIGN_WIDTH,le as DEFAULT_FALLBACK_DT,ue as DEFAULT_FIXED_TIMESTEP,ie as DEFAULT_FONT_FAMILY,oe as DEFAULT_FONT_SIZE,ce as DEFAULT_GRAVITY,re as DEFAULT_LINE_HEIGHT,ae as DEFAULT_MAX_DELTA_TIME,te as DEFAULT_PIXELS_PER_UNIT,he as DEFAULT_SPINE_SKIN,se as DEFAULT_SPRITE_SIZE,ne as DEFAULT_TEXT_CANVAS_SIZE,hi as DataType,fa as DragPlugin,da as DragState,ha as Draggable,si as Draw,Wa as Dropdown,$a as DropdownPlugin,Ol as EasingType,et as EmitterShape,qt as EntityCommands,en as EventReader,nn as EventReaderInstance,Qt as EventRegistry,Zt as EventWriter,tn as EventWriterInstance,Io as FillDirection,Kr as FillMethod,Jr as FillOrigin,Xr as FocusManager,Nr as FocusManagerState,Ta as FocusPlugin,Vr as Focusable,Bc as FrameHistory,oo as GLDebug,wi as Geometry,on as GetWorld,ge as INVALID_ENTITY,_e as INVALID_FONT,we as INVALID_MATERIAL,ye as INVALID_TEXTURE,Qr as Image,ea as ImagePlugin,Gr as ImageType,pn as Input,mn as InputPlugin,fn as InputState,Mr as Interactable,Va as LayoutGroupPlugin,ka as ListView,za as ListViewPlugin,Ve as LocalTransform,Rl as LogLevel,kl as Logger,Hl as LoopMode,Cn as Material,Wn as MaterialLoader,zt as Mut,it as Name,Ke as Parent,Sc as Particle,nt as ParticleEasing,st as ParticleEmitter,Mc as ParticlePlugin,yl as Physics,hl as PhysicsEvents,ml as PhysicsPlugin,Ii as PostProcess,qi as PostProcessPlugin,Pi as PostProcessStack,rt as PostProcessVolume,Vs as PrefabServer,Ns as Prefabs,Xs as PrefabsPlugin,El as PreviewPlugin,aa as ProgressBar,ra as ProgressBarDirection,ca as ProgressBarPlugin,Oe as ProjectionType,jt as Query,Vt as QueryInstance,Nt as Removed,Xt as RemovedQueryInstance,ro as RenderPipeline,Ki as RenderStage,Al as RenderTexture,to as Renderer,mt as Res,gt as ResMut,lt as RigidBody,de as RuntimeConfig,Ea as SafeArea,Ra as SafeAreaPlugin,He as ScaleMode,ho as SceneManager,uo as SceneManagerState,ot as SceneOwner,sn as Schedule,ma as ScrollView,_a as ScrollViewPlugin,zn as ShaderSources,tt as SimulationSpace,ba as Slider,xa as SliderDirection,Ma as SliderPlugin,Ze as SpineAnimation,Xe as Sprite,Nn as SpriteAnimator,Fc as Stats,Uc as StatsCollector,Ic as StatsOverlay,Wc as StatsPlugin,bt as Storage,dn as SystemRunner,or as Text,nr as TextAlign,jr as TextInput,Yr as TextInputPlugin,ir as TextOverflow,lr as TextPlugin,rr as TextRenderer,sr as TextVerticalAlign,rs as Tilemap,os as TilemapAPI,as as TilemapLayer,Cc as TilemapPlugin,wt as Time,na as Toggle,ia as TogglePlugin,je as Transform,lc as Tween,tc as TweenHandle,Ll as TweenState,ec as TweenTarget,yn as UICameraInfo,Er as UIEventQueue,Ar as UIEvents,Pr as UIInteraction,Lr as UIInteractionPlugin,Rr as UILayoutPlugin,dr as UIMask,vr as UIMaskPlugin,Fo as UIRect,Xa as UIRenderOrderPlugin,Ge as Velocity,Nc as WeChatAssetProvider,Tl as WebAssetProvider,Bt as World,Ne as WorldTransform,un as addStartupSystem,cn as addSystem,hn as addSystemToSchedule,uc as animationPlugin,me as applyBuildRuntimeConfig,Oo as applyDirectionalFill,fe as applyRuntimeConfig,Us as assetPlugin,_c as audioPlugin,fc as calculateAttenuation,pc as calculatePanning,Li as cleanupAllPostProcessVolumes,Oi as cleanupPostProcessVolume,Vn as clearAnimClips,ui as clearDrawCallbacks,Qn as clearTextureDimensionsCache,ts as clearTilemapSourceCache,ke as clearUserComponents,Se as color,Wo as computeFillAnchors,Do as computeFillSize,$o as computeHandleAnchors,ko as computeUIRectLayout,br as createMaskProcessor,Ml as createRuntimeSceneConfig,Vc as createWebApp,Ul as debug,kc as defaultFrameStats,Ae as defineComponent,Kt as defineEvent,pt as defineResource,an as defineSystem,Re as defineTag,pa as dragPlugin,Da as dropdownPlugin,Dl as error,$n as extractAnimClipTexturePaths,ks as findEntityByName,yo as flushPendingSystems,Ca as focusPlugin,E as getAddressableType,A as getAddressableTypeByEditorType,I as getAllAssetExtensions,Ui as getAllEffectDefs,jn as getAnimClip,D as getAssetBuildTransform,z as getAssetMimeType,T as getAssetTypeEntry,$e as getComponent,xs as getComponentAssetFieldDescriptors,ws as getComponentAssetFields,at as getComponentDefaults,Ms as getComponentEntityFields,bs as getComponentSpineFieldDescriptor,F as getCustomExtensions,C as getEditorType,Bi as getEffectDef,zi as getEffectTypes,Bl as getLogger,t as getPlatform,s as getPlatformType,Jn as getTextureDimensions,es as getTilemapSource,Ie as getUserComponent,B as getWeChatPackOptions,ta as imagePlugin,Wl as info,Zs as initDrawAPI,so as initGLDebugAPI,gi as initGeometryAPI,Mn as initMaterialAPI,bc as initParticleAPI,Lc as initPlayableRuntime,Ei as initPostProcessAPI,Zi as initRendererAPI,Pl as initRuntime,ss as initTilemapAPI,ic as initTweenAPI,qc as initWeChatRuntime,gn as inputPlugin,Ds as instantiatePrefab,fr as intersectRects,pr as invertMatrix4,ze as isBuiltinComponent,U as isCustomExtension,zr as isEditor,R as isKnownAssetExtension,n as isPlatformInitialized,$r as isPlayMode,Ur as isRuntime,wn as isTextureRef,i as isWeChat,o as isWeb,Na as layoutGroupPlugin,Ua as listViewPlugin,Rs as loadComponent,Ga as loadPhysicsModule,Sl as loadRuntimeScene,Cs as loadSceneData,Es as loadSceneWithAssets,gs as loadTiledMap,k as looksLikeAssetPath,Dn as parseAnimClipData,fs as parseTiledMap,hs as parseTmjJson,Pc as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,wr as pointInOBB,gr as pointInWorldRect,Gi as postProcessPlugin,Ys as prefabsPlugin,ua as progressBarPlugin,Me as quat,Ln as registerAnimClip,$ as registerAssetBuildTransform,We as registerComponent,_s as registerComponentAssetFields,Ss as registerComponentEntityFields,li as registerDrawCallback,$s as registerEmbeddedAssets,Bn as registerMaterialCallback,Kn as registerTextureDimensions,Zn as registerTilemapSource,Ps as remapEntityFields,ds as resolveRelativePath,Ia as safeAreaPlugin,mo as sceneManagerPlugin,mr as screenToWorld,wa as scrollViewPlugin,Br as setEditorMode,Ba as setListViewRenderer,zl as setLogLevel,Wr as setPlayMode,Tt as setWasmErrorHandler,ei as shutdownDrawAPI,io as shutdownGLDebugAPI,yi as shutdownGeometryAPI,Pn as shutdownMaterialAPI,vc as shutdownParticleAPI,Ai as shutdownPostProcessAPI,eo as shutdownRendererAPI,is as shutdownTilemapAPI,oc as shutdownTweenAPI,Pa as sliderPlugin,Xn as spriteAnimatorSystemUpdate,$c as statsPlugin,qo as syncFillSpriteSize,Di as syncPostProcessVolume,qr as textInputPlugin,cr as textPlugin,Ec as tilemapPlugin,W as toBuildPath,oa as togglePlugin,qa as transitionTo,Hr as uiInteractionPlugin,Ir as uiLayoutPlugin,Sr as uiMaskPlugin,Hc as uiPlugins,Ya as uiRenderOrderPlugin,Hn as unregisterAnimClip,Fe as unregisterComponent,ci as unregisterDrawCallback,Is as updateCameraAspectRatio,xe as vec2,be as vec3,ve as vec4,$l as warn,fo as wrapSceneSystem,N as wxFileExists,X as wxFileExistsSync,G as wxGetImagePixels,q as wxLoadImage,K as wxLoadImagePixels,j as wxReadFile,V as wxReadTextFile,Y as wxWriteFile};//# sourceMappingURL=index.wechat.js.mapdiff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex ba654b380..0e2c392e5 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -431,6 +431,20 @@ interface TimeData {}declare const Time: ResourceDef<TimeData>;+declare const Storage: {+ getString(key: string, defaultValue?: string): string | undefined;+ setString(key: string, value: string): void;+ getNumber(key: string, defaultValue?: number): number | undefined;+ setNumber(key: string, value: number): void;+ getBoolean(key: string, defaultValue?: boolean): boolean | undefined;+ setBoolean(key: string, value: boolean): void;+ getJSON<T>(key: string, defaultValue?: T): T | undefined;+ setJSON<T>(key: string, value: T): void;+ remove(key: string): void;+ has(key: string): boolean;+ clear(): void;+};+/*** @file wasm.generated.ts* @brief ESEngine WASM Bindings TypeScript Definitions@@ -3192,6 +3206,10 @@ interface PlatformAdapter {createImage(): HTMLImageElement;bindInputEvents(callbacks: InputEventCallbacks, target?: unknown): void;createAudioBackend(): PlatformAudioBackend;+ getStorageItem(key: string): string | null;+ setStorageItem(key: string, value: string): void;+ removeStorageItem(key: string): void;+ clearStorage(prefix: string): void;}type PlatformType = 'web' | 'wechat';@@ -4169,5 +4187,5 @@ declare const uiPlugins: Plugin[];declare function createWebApp(module: ESEngineModule, options?: WebAppOptions): App;-export { Added, AnimationPlugin, App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, AttenuationModel, Audio, AudioBus, AudioListener, AudioMixer, AudioPlugin, AudioPool, AudioSource, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Changed, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_FALLBACK_DT, DEFAULT_FIXED_TIMESTEP, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, DEFAULT_GRAVITY, DEFAULT_LINE_HEIGHT, DEFAULT_MAX_DELTA_TIME, DEFAULT_PIXELS_PER_UNIT, DEFAULT_SPINE_SKIN, DEFAULT_SPRITE_SIZE, DEFAULT_TEXT_CANVAS_SIZE, DataType, DragPlugin, DragState, Draggable, Draw, Dropdown, DropdownPlugin, EasingType, EmitterShape, EntityCommands, EventReader, EventReaderInstance, EventRegistry, EventWriter, EventWriterInstance, FillDirection, FillMethod, FillOrigin, FocusManager, FocusManagerState, FocusPlugin, Focusable, FrameHistory, GLDebug, Geometry, GetWorld, INVALID_ENTITY, INVALID_FONT, INVALID_MATERIAL, INVALID_TEXTURE, Image, ImagePlugin, ImageType, Input, InputPlugin, InputState, Interactable, LayoutGroupPlugin, ListView, ListViewPlugin, LocalTransform, LogLevel, Logger, LoopMode, MaskMode, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Particle, ParticleEasing, ParticleEmitter$1 as ParticleEmitter, ParticlePlugin, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PostProcessPlugin, PostProcessStack, PostProcessVolume, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProgressBar, ProgressBarDirection, ProgressBarPlugin, ProjectionType, Query, QueryInstance, Removed, RemovedQueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, RuntimeConfig, SafeArea, SafeAreaPlugin, ScaleMode, SceneManager, SceneManagerState, SceneOwner, Schedule, ScrollView, ScrollViewPlugin, ShaderSources, SimulationSpace, Slider, SliderDirection, SliderPlugin, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SpriteAnimator, Stats, StatsCollector, StatsOverlay, StatsPlugin, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Tilemap, TilemapAPI, TilemapLayer, TilemapPlugin, Time, Toggle, TogglePlugin, Transform$1 as Transform, Tween, TweenHandle, TweenState, TweenTarget, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, UIRenderOrderPlugin, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, animationPlugin, applyBuildRuntimeConfig, applyDirectionalFill, applyRuntimeConfig, assetPlugin, audioPlugin, calculateAttenuation, calculatePanning, cleanupAllPostProcessVolumes, cleanupPostProcessVolume, clearAnimClips, clearDrawCallbacks, clearTextureDimensionsCache, clearTilemapSourceCache, clearUserComponents, color, computeFillAnchors, computeFillSize, computeHandleAnchors, computeUIRectLayout, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defaultFrameStats, defineComponent, defineEvent, defineResource, defineSystem, defineTag, dragPlugin, dropdownPlugin, error, extractAnimClipTexturePaths, findEntityByName, flushPendingSystems, focusPlugin, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAllEffectDefs, getAnimClip, getAssetBuildTransform, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFieldDescriptors, getComponentAssetFields, getComponentDefaults, getComponentEntityFields, getComponentSpineFieldDescriptor, getCustomExtensions, getEditorType, getEffectDef, getEffectTypes, getLogger, getPlatform, getPlatformType, getTextureDimensions, getTilemapSource, getUserComponent, getWeChatPackOptions, imagePlugin, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initParticleAPI, initPlayableRuntime, initPostProcessAPI, initRendererAPI, initRuntime, initTilemapAPI, initTweenAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isPlayMode, isRuntime, isTextureRef, isWeChat, isWeb, layoutGroupPlugin, listViewPlugin, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, loadTiledMap, looksLikeAssetPath, parseAnimClipData, parseTiledMap, parseTmjJson, particlePlugin, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInOBB, pointInWorldRect, postProcessPlugin, prefabsPlugin, progressBarPlugin, quat, registerAnimClip, registerAssetBuildTransform, registerComponent, registerComponentAssetFields, registerComponentEntityFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, registerTextureDimensions, registerTilemapSource, remapEntityFields, resolveRelativePath, safeAreaPlugin, sceneManagerPlugin, screenToWorld, scrollViewPlugin, setEditorMode, setListViewRenderer, setLogLevel, setPlayMode, setWasmErrorHandler, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownParticleAPI, shutdownPostProcessAPI, shutdownRendererAPI, shutdownTilemapAPI, shutdownTweenAPI, sliderPlugin, spriteAnimatorSystemUpdate, statsPlugin, syncFillSpriteSize, syncPostProcessVolume, textInputPlugin, textPlugin, tilemapPlugin, toBuildPath, togglePlugin, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, uiRenderOrderPlugin, unregisterAnimClip, unregisterComponent, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, wrapSceneSystem };+export { Added, AnimationPlugin, App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, AttenuationModel, Audio, AudioBus, AudioListener, AudioMixer, AudioPlugin, AudioPool, AudioSource, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Changed, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_FALLBACK_DT, DEFAULT_FIXED_TIMESTEP, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, DEFAULT_GRAVITY, DEFAULT_LINE_HEIGHT, DEFAULT_MAX_DELTA_TIME, DEFAULT_PIXELS_PER_UNIT, DEFAULT_SPINE_SKIN, DEFAULT_SPRITE_SIZE, DEFAULT_TEXT_CANVAS_SIZE, DataType, DragPlugin, DragState, Draggable, Draw, Dropdown, DropdownPlugin, EasingType, EmitterShape, EntityCommands, EventReader, EventReaderInstance, EventRegistry, EventWriter, EventWriterInstance, FillDirection, FillMethod, FillOrigin, FocusManager, FocusManagerState, FocusPlugin, Focusable, FrameHistory, GLDebug, Geometry, GetWorld, INVALID_ENTITY, INVALID_FONT, INVALID_MATERIAL, INVALID_TEXTURE, Image, ImagePlugin, ImageType, Input, InputPlugin, InputState, Interactable, LayoutGroupPlugin, ListView, ListViewPlugin, LocalTransform, LogLevel, Logger, LoopMode, MaskMode, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Particle, ParticleEasing, ParticleEmitter$1 as ParticleEmitter, ParticlePlugin, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PostProcessPlugin, PostProcessStack, PostProcessVolume, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProgressBar, ProgressBarDirection, ProgressBarPlugin, ProjectionType, Query, QueryInstance, Removed, RemovedQueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, RuntimeConfig, SafeArea, SafeAreaPlugin, ScaleMode, SceneManager, SceneManagerState, SceneOwner, Schedule, ScrollView, ScrollViewPlugin, ShaderSources, SimulationSpace, Slider, SliderDirection, SliderPlugin, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SpriteAnimator, Stats, StatsCollector, StatsOverlay, StatsPlugin, Storage, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Tilemap, TilemapAPI, TilemapLayer, TilemapPlugin, Time, Toggle, TogglePlugin, Transform$1 as Transform, Tween, TweenHandle, TweenState, TweenTarget, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, UIRenderOrderPlugin, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, animationPlugin, applyBuildRuntimeConfig, applyDirectionalFill, applyRuntimeConfig, assetPlugin, audioPlugin, calculateAttenuation, calculatePanning, cleanupAllPostProcessVolumes, cleanupPostProcessVolume, clearAnimClips, clearDrawCallbacks, clearTextureDimensionsCache, clearTilemapSourceCache, clearUserComponents, color, computeFillAnchors, computeFillSize, computeHandleAnchors, computeUIRectLayout, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defaultFrameStats, defineComponent, defineEvent, defineResource, defineSystem, defineTag, dragPlugin, dropdownPlugin, error, extractAnimClipTexturePaths, findEntityByName, flushPendingSystems, focusPlugin, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAllEffectDefs, getAnimClip, getAssetBuildTransform, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFieldDescriptors, getComponentAssetFields, getComponentDefaults, getComponentEntityFields, getComponentSpineFieldDescriptor, getCustomExtensions, getEditorType, getEffectDef, getEffectTypes, getLogger, getPlatform, getPlatformType, getTextureDimensions, getTilemapSource, getUserComponent, getWeChatPackOptions, imagePlugin, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initParticleAPI, initPlayableRuntime, initPostProcessAPI, initRendererAPI, initRuntime, initTilemapAPI, initTweenAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isPlayMode, isRuntime, isTextureRef, isWeChat, isWeb, layoutGroupPlugin, listViewPlugin, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, loadTiledMap, looksLikeAssetPath, parseAnimClipData, parseTiledMap, parseTmjJson, particlePlugin, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInOBB, pointInWorldRect, postProcessPlugin, prefabsPlugin, progressBarPlugin, quat, registerAnimClip, registerAssetBuildTransform, registerComponent, registerComponentAssetFields, registerComponentEntityFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, registerTextureDimensions, registerTilemapSource, remapEntityFields, resolveRelativePath, safeAreaPlugin, sceneManagerPlugin, screenToWorld, scrollViewPlugin, setEditorMode, setListViewRenderer, setLogLevel, setPlayMode, setWasmErrorHandler, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownParticleAPI, shutdownPostProcessAPI, shutdownRendererAPI, shutdownTilemapAPI, shutdownTweenAPI, sliderPlugin, spriteAnimatorSystemUpdate, statsPlugin, syncFillSpriteSize, syncPostProcessVolume, textInputPlugin, textPlugin, tilemapPlugin, toBuildPath, togglePlugin, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, uiRenderOrderPlugin, unregisterAnimClip, unregisterComponent, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, wrapSceneSystem };export type { AddedWrapper, AddressableAssetType, AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AddressableResultMap, AnimClipAssetData, AnyComponentDef, AssetBuildTransform, AssetBundle, AssetContentType, AssetFieldType, AssetRefInfo, AssetTypeEntry, AssetsData, AudioBackendInitOptions, AudioBufferHandle, AudioBusConfig, AudioHandle, AudioListenerData, AudioMixerConfig, AudioPluginConfig, AudioSourceData, BezierPoints, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChangedWrapper, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DragStateData, DraggableData, DrawAPI, DrawCallback, DropdownData, ESEngineModule, EditorAssetType, EffectDef, EffectUniformDef, Entity, EventDef, EventReaderDescriptor, EventWriterDescriptor, FileLoadOptions, FocusableData, FontHandle, FrameSnapshot, FrameStats, GeometryHandle, GeometryOptions, GetWorldDescriptor, ImageData, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, ListViewData, ListViewItemRenderer, LoadRuntimeSceneOptions, LoadedMaterial, LoadedTilemapLayer, LoadedTilemapSource, LoadedTilemapTileset, LocalTransformData, LogEntry, LogHandler, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, ParticleEmitterData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformAudioBackend, PlatformRequestOptions, PlatformResponse, PlatformType, PlayConfig, PlayableRuntimeConfig, Plugin, PluginDependency, PooledAudioNode, PostProcessEffectData, PostProcessVolumeData$1 as PostProcessVolumeData, PrefabData, PrefabEntityData, PrefabOverride, ProgressBarData, Quat, QueryBuilder, QueryDescriptor, QueryResult, RemovedQueryDescriptor, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, RuntimeBuildConfig, RuntimeInitConfig, SafeAreaData, SceneComponentData, SceneConfig, SceneContext, SceneData, SceneEntityData, SceneLoadOptions, SceneOwnerData, SceneStatus, ScreenRect, ScrollViewData, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder$1 as SliceBorder, SliderData, SpatialAudioConfig, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteAnimClip, SpriteAnimFrame, SpriteAnimatorData, SpriteData, StatsPluginOptions, StatsPosition, SystemDef, SystemOptions, SystemParam, TextData, TextInputData, TextRenderResult, TextureDimensions, TextureHandle, TextureInfo, TextureRef, TiledLayerData, TiledMapData, TiledTilesetData, TilemapData, TilemapLayerData, TimeData, ToggleData, ToggleTransition, TransformData, TransitionConfig, TransitionOptions, TweenOptions, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.jsindex 013d707e1..fcf38f402 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 u(e,s){return t().instantiateWasm(e,s)}function h(e,s){return t().createCanvas(e,s)}function d(){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 g{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 _{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_}get isReady(){return"running"===this.context_?.state}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new m(this.context_,e.mixerConfig),this.pool_=new g(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 loadBufferFromData(e,t){if(!this.context_)throw new Error("AudioContext not initialized");const s=this.urlToId_.get(e);if(void 0!==s&&this.buffers_.has(s)){return{id:s,duration:this.buffers_.get(s).duration}}let n;try{n=await this.context_.decodeAudioData(t)}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}}async doLoadBuffer_(e){const s=await t().readFile(e);return this.loadBufferFromData(e,s)}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 _(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)}},u=()=>{e.onPointerUp(0)},h=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",u),s.addEventListener("wheel",h),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",u),s.removeEventListener("wheel",h)}}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 L=0,$=4294967295,D=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}),V=(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}),X=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function N(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(N);const t={};for(const s in e)t[s]=N(e[s]);return t}let Y=0;function q(e,t){const s=++Y,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?{...N(t),...e}:N(t):e?{...t,...e}:{...t}}}function G(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function K(e,t){const s=ne.get(e)??G().get(e);if(s)return s;const n=q(e,t);return G().set(e,n),ne.set(e,n),te(e,t,!1),n}function J(e){const t=ne.get(e)??G().get(e);if(t)return t;const s=q(e,{});return G().set(e,s),ne.set(e,s),te(e,{},!0),s}function Q(e){return G().get(e)}function Z(){const e=G();for(const t of e.keys())ne.delete(t);e.clear()}function ee(e){G().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},ue=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}}),he=ue,de=ue,fe=re("Sprite",{texture:$,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}}),ge=re("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),_e=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:D,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={Point:0,Circle:1,Rectangle:2,Cone:3},be={World:0,Local:1},Se={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},Me=re("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:ve.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:Se.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:Se.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:$,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:be.World,enabled:!0}),Pe=K("Name",{value:""}),Te=K("SceneOwner",{scene:"",persistent:!1}),Ee=K("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function Ce(e){const t=oe(e);return t?N(t._default):null}const Re=re("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Ae=re("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ie=re("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ke=re("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Fe={Static:0,Kinematic:1,Dynamic:2};let Be=0;function ze(e,t){const s=++Be;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Ue(e){return{_type:"res",_resource:e}}function Le(e){return{_type:"res_mut",_resource:e}}class $e{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 De{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 $e(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Oe=ze({delta:0,elapsed:0,frameCount:0},"Time");function We(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=He(t[e]),o=He(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function He(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ve(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 je=null;function Xe(e){je=e}function Ne(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),je&&je(e,t)}function Ye(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 qe=1;const Ge=new WeakMap;function Ke(e){let t=Ge.get(e);return void 0===t&&(t=qe++,Ge.set(e,t)),t}const Je=[];function Qe(e,t=[],s=[]){Je.length=0;for(const t of e)Je.push(Ke(t));Je.sort((e,t)=>e-t);let n=Je.join(",");if(t.length>0){Je.length=0;for(const e of t)Je.push(Ke(e));Je.sort((e,t)=>e-t),n+="|+"+Je.join(",")}if(s.length>0){Je.length=0;for(const e of s)Je.push(Ke(e));Je.sort((e,t)=>e-t),n+="|-"+Je.join(",")}return n}class Ze{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 Ne(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){Ne(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){Ne(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ne(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{const n=t._default,i=s;let o=i;for(const e of Object.keys(i))e in n||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,Ye(o))}catch(s){Ne(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 Ne(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=t._default,i={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&e in n&&(i[e]=t);const e=We(t._name,n,i);if(e.length>0)throw new Error(Ve(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);r=!s.has(e),s.add(e,Ye(o))}catch(s){Ne(s,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}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 Ne(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 Ne(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ne(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=We(t._name,t._default,e);if(i.length>0)throw new Error(Ve(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=G();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??Qe(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 et(e){return{_type:"mut",_component:e}}function tt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function st(e){return{_filterType:"added",_component:e}}function nt(e){return{_filterType:"changed",_component:e}}function it(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function ot(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function rt(e){return tt(e)||it(e)||ot(e)?e._component:e}function at(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{tt(e)&&n.push(t),it(e)?i.push({index:t,component:e._component}):ot(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>at(e,[...t,...n],s),without:(...n)=>at(e,t,[...s,...n])}}function lt(...e){return at(e)}class ct{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(rt),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_=Qe(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 u of s)if(!o||this.passesChangeFilters_(u)){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]=u;for(let e=0;e<n;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}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 ut(e){return{_type:"removed",_component:e}}class ht{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 dt(){return{_type:"commands"}}class ft{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 pt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ft(this,null);return this.spawned_.push(e),e}entity(e){return new ft(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 mt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class gt{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 _t{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new gt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new gt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function yt(e){return{_type:"event_writer",_event:e}}function wt(e){return{_type:"event_reader",_event:e}}class xt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class vt{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var bt;function St(){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"}(bt||(bt={}));let Mt=0;function Pt(e,t,s){const n=++Mt;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Tt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function Et(e){Tt().push({schedule:bt.Update,system:e})}function Ct(e){Tt().push({schedule:bt.Startup,system:e})}function Rt(e,t){Tt().push({schedule:e,system:t})}class At{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 pt&&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 ct(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 pt(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 xt(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new vt(s)}case"removed":{const t=e;return new ht(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class It{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 kt=ze(new It,"Input");class Ft{constructor(e){this.target_=e??null}build(e){const s=new It;e.insertResource(kt,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(bt.Last,Pt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Bt=new Ft,zt=ze({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 Ut;function Lt(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"}(Ut||(Ut={}));let $t=null,Dt=null,Ot=1;const Wt=new Map;function Ht(e){$t=e,Dt=e.getResourceManager(),Qt()}function Vt(){0!==Yt&&$t&&($t._free(Yt),Yt=0),Wt.clear(),Ot=1,Nt=!1,Gt.clear(),Kt=null,Dt=null,$t=null}function jt(){if(!Dt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Dt}const Xt={createShader:(e,t)=>jt().createShader(e,t),releaseShader(e){e>0&&jt().releaseShader(e)},create(e){const t=Ot++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ut.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 Wt.set(t,s),t},get:e=>Wt.get(e),setUniform(e,t,s){const n=Wt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,$t?.invalidateMaterialCache(e))},getUniform(e,t){const s=Wt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Wt.get(e);s&&(s.blendMode=t,$t?.invalidateMaterialCache(e))},getBlendMode(e){const t=Wt.get(e);return t?.blendMode??Ut.Normal},setDepthTest(e,t){const s=Wt.get(e);s&&(s.depthTest=t,$t?.invalidateMaterialCache(e))},getShader(e){const t=Wt.get(e);return t?.shader??0},release(e){Wt.delete(e),$t?.invalidateMaterialCache(e)},isValid:e=>Wt.has(e),releaseAll(){Wt.clear(),$t?.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??Ut.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Wt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Ot++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Wt.set(s,n),s},toAssetData(e,t){const s=Wt.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=Wt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Nt=!1,Yt=0;const qt=16384,Gt=new Map;let Kt=null;function Jt(e){const t=(0===Yt&&$t&&(Yt=$t._malloc(qt)),Yt);if(0===t||!$t)return{ptr:0,count:0};let s=0,n=0;const i=$t.HEAPU8,o=$t.HEAPU32,r=$t.HEAPF32;for(const[a,l]of e){if(Lt(l))continue;let e=Gt.get(a);e||(Kt||(Kt=new TextEncoder),e=Kt.encode(a),Gt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>qt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${qt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)r[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function Qt(){if(!$t||Nt)return;$t.materialDataProvider=(e,t,s,n,i)=>{const o=Wt.get(e);if(!o)return $t.HEAPU32[t>>2]=0,$t.HEAPU32[s>>2]=0,$t.HEAPU32[n>>2]=0,void($t.HEAPU32[i>>2]=0);$t.HEAPU32[t>>2]=o.shader,$t.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Jt(o.uniforms);$t.HEAPU32[n>>2]=r,$t.HEAPU32[i>>2]=a},Nt=!0}const Zt={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 es{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const n=t(),i=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{r.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+5e3}),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(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class ts{constructor(e,t=""){this.cache_=new es,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&&(Xt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Xt.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:Xt.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 ss(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function ns(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:s.get(e.texture)??0};if(e.atlasFrame){const s=e.atlasFrame;t.uvOffset={x:s.x/s.pageWidth,y:1-(s.y+s.height)/s.pageHeight},t.uvScale={x:s.width/s.pageWidth,y:s.height/s.pageHeight}}return t})}}const is=new Map;function os(e){is.set(e.name,e)}function rs(e){is.delete(e)}function as(e){return is.get(e)}function ls(){is.clear()}const cs=K("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function us(e,t){const s=e.getEntitiesWithComponents([cs]);for(const n of s){const s=e.get(n,cs);if(!s.enabled||!s.playing||!s.clip)continue;const i=is.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,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(n,fe,o)}a&&e.insert(n,cs,s)}}class hs{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 async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const s=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,s)}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 stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}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}}}}hs.mixer_=null,hs.bufferCache_=new Map,hs.bgmHandle_=null,hs.bgmVolume_=1,hs.fadeAnimId_=0,hs.disposed_=!1;const ds=new Map,fs=new Map;function ps(e,t,s){ds.set(e,{width:t,height:s})}function ms(e){return ds.get(e)}function gs(){ds.clear()}function _s(e,t){fs.set(e,t)}function ys(e){return fs.get(e)}function ws(){fs.clear()}let xs=null;function vs(e){xs=e}function bs(){xs=null}const Ss={initLayer(e,t,s,n,i){xs?.tilemap_initLayer(e,t,s,n,i)},destroyLayer(e){xs?.tilemap_destroyLayer(e)},setTile(e,t,s,n){xs?.tilemap_setTile(e,t,s,n)},getTile:(e,t,s)=>xs?xs.tilemap_getTile(e,t,s):0,fillRect(e,t,s,n,i,o){xs?.tilemap_fillRect(e,t,s,n,i,o)},setTiles(e,t){if(!xs)return;const s=t.byteLength,n=xs._malloc(s);new Uint16Array(xs.HEAPU8.buffer,n,t.length).set(t),xs.tilemap_setTiles(e,n,t.length),xs._free(n)},hasLayer:e=>!!xs&&xs.tilemap_hasLayer(e),submitLayer(e,t,s,n,i,o,r,a,l,c,u,h,d,f,p,m,g,_,y,w){xs?.tilemap_submitLayer(e,t,s,n,i,o,r,a,l,c,u,h,d,f,p,m,g,_,y,w)}},Ms=K("Tilemap",{source:""}),Ps=K("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function Ts(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function Es(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function Cs(e,t){if(0===e)return 0;let s=0;2147483648&e&&(s|=8192),1073741824&e&&(s|=16384),536870912&e&&(s|=32768);return(536870911&e)-t+1|s}function Rs(e){const t=e.width,s=e.height,n=e.tilewidth??0,i=e.tileheight??0;if(!(t&&s&&n&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??n,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const n=e.width??t,i=e.height??s,o=!1!==e.visible,r=e.data,l=new Uint16Array(n*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=Cs(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,h=Es(e.tintcolor),d="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:n,height:i,visible:o,tiles:l,opacity:u,tintColor:h,parallaxX:d,parallaxY:f})}const u=[],h=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const s=[];for(const e of t){const t=new Map,n=e.properties;if(n)for(const e of n)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}s.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:s})}if(o)for(const e of o){const t=e.firstgid??1,s=e.tiles;if(s)for(const e of s){const s=e.properties;if(s)for(const n of s)"collision"===n.name&&!0===n.value&&h.push(e.id+t)}}return{width:t,height:s,tileWidth:n,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:h}}function As(e,t){const s=e.lastIndexOf("/"),n=((s>=0?e.substring(0,s+1):"")+t).split("/"),i=[];for(const e of n)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function Is(e,t){const s=xs;if(!s)return null;const n=new TextEncoder,i=n.encode(e),o=s._malloc(i.byteLength);s.HEAPU8.set(i,o);const r=s.tiled_loadMap(o,i.byteLength);if(s._free(o),0===r)return null;try{const e=s.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=s.tiled_getExternalTilesetSource(r,i);if(!t)return s.tiled_freeMap(r),null;const o=await t(e),a=n.encode(o),l=s._malloc(a.byteLength);s.HEAPU8.set(a,l);const c=s.tiled_loadExternalTileset(r,i,l,a.byteLength);if(s._free(l),!c)return s.tiled_freeMap(r),null}if(!s.tiled_finalize(r))return s.tiled_freeMap(r),null;const i={width:s.tiled_getMapWidth(r),height:s.tiled_getMapHeight(r),tileWidth:s.tiled_getMapTileWidth(r),tileHeight:s.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},o=s.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=s.tiled_getLayerWidth(r,e),n=s.tiled_getLayerHeight(r,e),o=t*n,a=2*o,l=s._malloc(a);s.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(s.HEAPU8.buffer,l,o)),s._free(l),i.layers.push({name:s.tiled_getLayerName(r,e),width:t,height:n,visible:s.tiled_getLayerVisible(r,e),tiles:c,opacity:s.tiled_getLayerOpacity(r,e),tintColor:s.tiled_getLayerTintColor?Ts(s.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:s.tiled_getLayerParallaxX(r,e),parallaxY:s.tiled_getLayerParallaxY(r,e)})}const a=s.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:s.tiled_getTilesetName(r,e),image:s.tiled_getTilesetImage(r,e),tileWidth:s.tiled_getTilesetTileWidth(r,e),tileHeight:s.tiled_getTilesetTileHeight(r,e),columns:s.tiled_getTilesetColumns(r,e),tileCount:s.tiled_getTilesetTileCount(r,e)});return s.tiled_freeMap(r),i}catch{return s.tiled_freeMap(r),null}}const ks=Math.PI/180;function Fs(e,t,s,n,i,o){const r=function(e,t,s,n){const i=new Uint8Array(t*s),o=[],r=(o,r)=>{if(o>=t||r>=s)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&n.has(l)};for(let e=0;e<s;e++)for(let n=0;n<t;n++){if(!r(n,e))continue;let a=1;for(;r(n+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=s)break;for(let e=0;e<a;e++)if(!r(n+e,t)){c=!1;break}c&&l++}for(let s=0;s<l;s++)for(let o=0;o<a;o++)i[(e+s)*t+(n+o)]=1;o.push({col:n,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,n),a=[],l=s.tileWidth,c=s.tileHeight,u=s.height*c;for(const t of r){const s=t.width*l,n=t.height*c,r=i+t.col*l+.5*s,h=o+(u-t.row*c)-.5*n,d=e.spawn();e.insert(d,ue,{position:{x:r,y:h,z:0}}),e.insert(d,Re,{bodyType:Fe.Static}),e.insert(d,Ae,{halfExtents:{x:.5*s,y:.5*n}}),a.push(d)}return a}function Bs(e,t,s,n={}){const i=[],o=t.tilesets[0];let r=0;for(const n of t.layers){if(!n.visible)continue;const a=e.spawn();e.insert(a,ue,{});const l=o?s.get(o.image)??0:0,c=o?.columns??1;e.insert(a,Ps,{width:n.width,height:n.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(n.tiles),tint:{...n.tintColor},opacity:n.opacity,visible:n.visible,parallaxFactor:{x:n.parallaxX,y:n.parallaxY}}),i.push(a),r++}if(!1!==n.generateObjectCollision&&t.objectGroups.length>0){const s=function(e,t,s,n){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=s+a+.5*t.width,u=n+(o-l)-.5*t.height,h=-t.rotation*ks;if(e.insert(r,ue,{position:{x:c,y:u,z:0}}),e.insert(r,Re,{bodyType:Fe.Static}),"ellipse"===t.shape){const s=.5*Math.max(t.width,t.height);e.insert(r,Ie,{radius:s})}else if("polygon"===t.shape&&t.vertices){let s=1/0,n=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<s&&(s=r),r>i&&(i=r),a<n&&(n=a),a>o&&(o=a)}const a=i-s,l=o-n,c=.5*(s+i),u=.5*(n+o);e.insert(r,Ae,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,Ae,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==h){const t=.5*h;e.insert(r,ue,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...s)}const a=new Set(n.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const s of t.layers){if(!s.visible)continue;const n=Fs(e,s,t,a,0,0);i.push(...n)}return i}const zs=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"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function Us(e,t){zs.set(e,t)}function Ls(e){const t=zs.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 $s(e){return zs.get(e)?.fields??[]}function Ds(e){return zs.get(e)?.spine??null}const Os=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Ws(e,t){Os.set(e,t)}function Hs(e){return Os.get(e)}function Vs(e,t){const s=Os.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 js(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,Pe,{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)Vs(i,s),qs(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 Xs(e,t){return js(e,t)}async function Ns(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 Ys.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=zs.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=[...Ys.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),u=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,...u]),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=zs.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=js(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 Ys=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),ps(r.handle,r.width,r.height)}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=ss(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);os(ns(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 hs.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=Rs(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=As(e,r.image);let a=0;try{const e=s?`${s}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,n.set(i,e),ps(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}_s(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function qs(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 Gs(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 Ks(e,t){const s=e.getEntitiesWithComponents([Pe]);for(const n of s){const s=e.get(n,Pe);if(s&&s.value===t)return n}return null}const Js=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],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},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],Qs={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",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",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"},Zs=new Map,en=new Set;for(const e of Js)for(const t of e.extensions)Zs.set(t,e),en.add(t);function tn(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function sn(e){return Zs.get(tn(e))}function nn(e){return sn(e)?.editorType??"unknown"}function on(e){return sn(e)?.addressableType??null}function rn(e){for(const t of Js)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function an(e){return en.has(e.toLowerCase())}function ln(){return en}function cn(e){return"string"==typeof e&&(!!e.includes("/")&&an(tn(e)))}function un(){const e=[];for(const t of Js)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function hn(){return un().map(e=>({type:"suffix",value:e}))}function dn(e){return Qs[e.toLowerCase()]}function fn(e){const t=sn(e);return t?.wechatPackInclude??!1}function pn(e){const t=sn(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}function mn(e,t){for(const s of Js)s.editorType===e&&(s.buildTransform=t)}function gn(e){return sn(e)?.buildTransform}class _n{constructor(e){this.textureCache_=new es,this.shaderCache_=new es,this.jsonCache_=new es,this.textCache_=new es,this.binaryCache_=new es,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new es,this.prefabCache_=new es,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_=h(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 ts(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(),Xt.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),u="binary"===sn(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(h,o,u);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=sn(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 Ls(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=Ds(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 Ns(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 Xt.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 Xt.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(pn(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 yn=ze(null,"Assets");class wn{build(e){const t=e.wasmModule;t?e.insertResource(yn,new _n(t)):console.warn("AssetPlugin: No WASM module available")}}const xn=new wn;class vn{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 bn(e,t){const s=e.getResource(yn);s&&s.registerEmbeddedAssets(t)}async function Sn(e,t,s){const{entities:n,rootId:i}=await Pn(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 Ns(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 Mn=10;async function Pn(e,t,s,n,i,o=0){if(o>Mn)throw new Error(`Prefab nesting depth exceeded ${Mn}. 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 Pn(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),u=n.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?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};Tn(h.components,r),En(h,t),l.push(h)}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 Tn(e,t){for(const s of e){const e=Hs(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 En(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 Cn{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 Sn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Rn=ze(null,"Prefabs");class An{constructor(){this.name="PrefabsPlugin",this.dependencies=[yn]}build(e){const t=e.getResource(yn);e.insertResource(Rn,new Cn(e.world,t))}}const In=new An;let kn=null,Fn=0,Bn=0,zn=0;const Un=new Float32Array(256);function Ln(e){kn=e,Fn=kn._malloc(64),Bn=kn._malloc(64),zn=kn._malloc(1024)}function $n(){kn&&(Fn&&(kn._free(Fn),Fn=0),Bn&&(kn._free(Bn),Bn=0),zn&&(kn._free(zn),zn=0)),kn=null}function Dn(){if(!kn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return kn}const On={r:1,g:1,b:1,a:1},Wn={begin(e){const t=Dn();try{t.HEAPF32.set(e,Fn/4),t.draw_begin(Fn)}catch(e){Ne(e,"Draw.begin")}},end(){try{Dn().draw_end()}catch(e){Ne(e,"Draw.end")}},line(e,t,s,n=1){try{Dn().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ne(e,"Draw.line")}},rect(e,t,s,n=!0){try{Dn().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ne(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Dn().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ne(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{Dn().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ne(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{Dn().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ne(e,"Draw.circleOutline")}},texture(e,t,s,n=On){try{Dn().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ne(e,"Draw.texture")}},textureRotated(e,t,s,n,i=On){try{Dn().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){Ne(e,"Draw.textureRotated")}},setLayer(e){Dn().draw_setLayer(e)},setDepth(e){Dn().draw_setDepth(e)},getDrawCallCount:()=>kn?kn.draw_getDrawCallCount():0,getPrimitiveCount:()=>kn?kn.draw_getPrimitiveCount():0,setBlendMode(e){Dn().draw_setBlendMode(e)},setDepthTest(e){Dn().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Dn();n.HEAPF32.set(s,Bn/4),n.draw_mesh(e,t,Bn)}catch(s){Ne(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Dn(),i=Xt.get(t);if(!i)return;if(Wn.setBlendMode(i.blendMode),Wn.setDepthTest(i.depthTest),0===i.uniforms.size)return void Wn.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,Bn/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=jn(t);if(!(n<0)){if(Lt(s))Un[o++]=10,Un[o++]=n,Un[o++]=s.slot??e++,Un[o++]=s.textureId;else if("number"==typeof s)Un[o++]=1,Un[o++]=n,Un[o++]=s;else if(Array.isArray(s)){Un[o++]=s.length,Un[o++]=n;for(let e=0;e<s.length;e++)Un[o++]=s[e]}else"w"in s?(Un[o++]=4,Un[o++]=n,Un[o++]=s.x,Un[o++]=s.y,Un[o++]=s.z,Un[o++]=s.w):"z"in s?(Un[o++]=3,Un[o++]=n,Un[o++]=s.x,Un[o++]=s.y,Un[o++]=s.z):(Un[o++]=2,Un[o++]=n,Un[o++]=s.x,Un[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(Un.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,Bn);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),zn/4),n.draw_meshWithUniforms(e,i.shader,Bn,zn,o)}catch(s){Ne(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},Vn=new Set;function jn(e){const t=Hn[e];return void 0!==t?t:(Vn.has(e)||(Vn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Hn).join(", ")}`)),-1)}const Xn=new Map;function Nn(e,t,s){Xn.set(e,{fn:t,scene:s??""})}function Yn(e){Xn.delete(e)}function qn(){Xn.clear()}var Gn;!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"}(Gn||(Gn={}));let Kn=null,Jn=0,Qn=0,Zn=0;function ei(e){Kn=e,Jn=Kn._malloc(262144),Qn=Kn._malloc(65536),Zn=Kn._malloc(256)}function ti(){Kn&&(Jn&&Kn._free(Jn),Qn&&Kn._free(Qn),Zn&&Kn._free(Zn),Jn=0,Qn=0,Zn=0),Kn=null}function si(){if(!Kn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Kn}const ni={create(e){const t=si(),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,Jn/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,Zn,i).set(o),t.geometry_init(s,Jn,n,Zn,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,Qn,n).set(e.indices),t.geometry_setIndices16(s,Qn,n)}else{new Uint32Array(t.HEAPU8.buffer,Qn,n).set(e.indices),t.geometry_setIndices32(s,Qn,n)}}return s},updateVertices(e,t,s=0){const n=si(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,Jn/4),n.geometry_updateVertices(e,Jn,i,s)},release(e){e>0&&si().geometry_release(e)},isValid:e=>!(!Kn||e<=0)&&Kn.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return ni.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:Gn.Float2},{name:"a_texCoord",type:Gn.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 ni.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:Gn.Float2},{name:"a_texCoord",type:Gn.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 ni.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Gn.Float2},{name:"a_texCoord",type:Gn.Float2}],indices:new Uint16Array(r)})}};let ii=1;const oi=new Map,ri=new Map;function ai(){return oi}function li(){return ri}class ci{constructor(){this.passes_=[],this.destroyed_=!1,this.id=ii++,oi.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const s=this.passes_.find(t=>t.name===e);return s&&(s.enabled=t),this}setUniform(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.floatUniforms.set(t,s),this}setUniformVec4(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.vec4Uniforms.set(t,{...s}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of ri)t===this&&ri.delete(e);oi.delete(this.id)}}}const ui="#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";let hi=null;function di(e){hi=e}function fi(){for(const e of ai().values())e.destroy();ai().clear(),li().clear(),hi&&mi.isInitialized()&&mi.shutdown(),hi=null}function pi(){if(!hi)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return hi}const mi={createStack:()=>new ci,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");li().set(e,t)},unbind(e){li().delete(e)},getStack:e=>li().get(e)??null,init(e,t){try{return pi().postprocess_init(e,t)}catch(s){return Ne(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{pi().postprocess_shutdown()}catch(e){Ne(e,"PostProcess.shutdown")}},resize(e,t){try{pi().postprocess_resize(e,t)}catch(s){Ne(s,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!hi)return!1;try{return hi.postprocess_isInitialized()}catch(e){return Ne(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{pi().postprocess_setBypass(e)}catch(e){Ne(e,"PostProcess.setBypass")}},setOutputViewport(e,t,s,n){try{pi().postprocess_setOutputViewport(e,t,s,n)}catch(e){Ne(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=li().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(mi.isInitialized()||mi.init(1,1),mi.setBypass(!1),function(e){const t=pi();try{t.postprocess_clearPasses()}catch(e){return void Ne(e,"PostProcess._applyForCamera:clearPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addPass(s.name,s.shader)}catch(e){Ne(e,`PostProcess._applyForCamera:addPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setUniformFloat(s.name,e,n)}catch(t){Ne(t,`PostProcess._applyForCamera:setUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Ne(t,`PostProcess._applyForCamera:setUniformVec4("${s.name}", "${e}")`)}}}(t)):mi.setBypass(!0)},_resetAfterCamera(){try{pi().postprocess_clearPasses(),pi().postprocess_setBypass(!0)}catch(e){Ne(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of li().keys())e(t)||li().delete(t)},screenStack:null,setScreenStack(e){mi.screenStack=e},_beginScreenCapture(){try{pi().postprocess_beginScreenCapture()}catch(e){Ne(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{pi().postprocess_endScreenCapture()}catch(e){Ne(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=mi.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=pi();try{t.postprocess_clearScreenPasses()}catch(e){return void Ne(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addScreenPass(s.name,s.shader)}catch(e){Ne(e,`PostProcess._applyScreenStack:addScreenPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setScreenUniformFloat(s.name,e,n)}catch(t){Ne(t,`PostProcess._applyScreenStack:setScreenUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Ne(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${s.name}", "${e}")`)}}},_executeScreenPasses(){try{pi().postprocess_executeScreenPasses()}catch(e){Ne(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Xt.createShader(ui,"#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:()=>Xt.createShader(ui,"#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:()=>Xt.createShader(ui,"#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"),createBloom:()=>Xt.createShader(ui,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>Xt.createShader(ui,"#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")},gi=new Map;function _i(e){gi.set(e.type,e)}function yi(e){return gi.get(e)}function wi(){return Array.from(gi.keys())}function xi(){return Array.from(gi.values())}_i({type:"blur",label:"Blur",factory:()=>mi.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),_i({type:"bloom",label:"Bloom",factory:()=>mi.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),_i({type:"vignette",label:"Vignette",factory:()=>mi.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),_i({type:"grayscale",label:"Grayscale",factory:()=>mi.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),_i({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>mi.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const vi=new Map,bi=new Map;function Si(e,t){let s=vi.get(e),n=bi.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(s||(s=mi.createStack(),vi.set(e,s)),n||(n=new Map,bi.set(e,n));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const e of i){const t=yi(e.type);if(!t)continue;let i=n.get(e.type);void 0===i&&(i=t.factory(),n.set(e.type,i)),s.addPass(e.type,i);for(const n of t.uniforms){const t=e.uniforms[n.name]??n.defaultValue;s.setUniform(e.type,n.name,t)}}mi.bind(e,s)}else if(s&&(mi.unbind(e),s.destroy(),vi.delete(e)),n){for(const e of n.values())Xt.releaseShader(e);bi.delete(e)}}function Mi(e){const t=vi.get(e);t&&(mi.unbind(e),t.destroy(),vi.delete(e));const s=bi.get(e);if(s){for(const e of s.values())Xt.releaseShader(e);bi.delete(e)}}function Pi(){for(const e of vi.keys())Mi(e)}const Ti=ze({enabled:!0},"PostProcessVolumeConfig"),Ei=new Map,Ci=new Map;function Ri(e){const t=Ci.get(e);if(void 0!==t)return t;const s=yi(e);if(!s)return null;const n=s.factory();return Ci.set(e,n),n}function Ai(e,t){if(0===t.size){const t=Ei.get(e);return void(t&&(mi.unbind(e),t.destroy(),Ei.delete(e)))}let s=Ei.get(e);for(s||(s=mi.createStack(),Ei.set(e,s));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const[e,n]of t){if(!n.enabled)continue;const t=Ri(e);if(null!==t){s.addPass(e,t);for(const[t,i]of n.uniforms)s.setUniform(e,t,i)}}s.enabledPassCount>0?mi.bind(e,s):mi.unbind(e)}const Ii=Pt([lt(Ee,ue)],e=>{const t=[];for(const[s,n,i]of e)t.push({data:n,tx:{x:i.position.x,y:i.position.y}});if(0===t.length)return;const s=[];for(const{data:e,tx:n}of t)e.isGlobal&&s.push({data:e,factor:1});if(s.length>0){const e=function(e){const t=new Map,s=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:n}of s)if(!(n<=0))for(const s of e.effects){if(!s.enabled)continue;const e=t.get(s.type);if(e)for(const[t,i]of Object.entries(s.uniforms)){const s=e.uniforms.get(t)??0;e.uniforms.set(t,s+(i-s)*n)}else{const e=new Map;for(const[t,i]of Object.entries(s.uniforms))e.set(t,i*n);t.set(s.type,{enabled:!0,uniforms:e})}}return t}(s);for(const[t]of Ei)Ai(t,e)}},{name:"PostProcessVolumeSystem"});class ki{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(Ti,{enabled:!0}),e.addSystemToSchedule(bt.PostUpdate,Ii)}cleanup(){Pi(),function(){for(const[e,t]of Ei)mi.unbind(e),t.destroy();Ei.clear();for(const e of Ci.values())Xt.releaseShader(e);Ci.clear()}(),mi.setScreenStack(null)}}const Fi=new ki;var Bi;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Bi||(Bi={}));let zi=null,Ui=0;function Li(e){zi=e,Ui=zi._malloc(64)}function $i(){zi&&Ui&&(zi._free(Ui),Ui=0),zi=null}const Di={init(e,t){zi?.renderer_init(e,t)},resize(e,t){zi?.renderer_resize(e,t)},begin(e,t){if(zi&&Ui)try{zi.HEAPF32.set(e,Ui/4),zi.renderer_begin(Ui,t??0)}catch(e){Ne(e,"Renderer.begin")}},flush(){try{zi?.renderer_flush()}catch(e){Ne(e,"Renderer.flush")}},end(){try{zi?.renderer_end()}catch(e){Ne(e,"Renderer.end")}},submitSprites(e){if(zi)try{zi.renderer_submitSprites(e._cpp)}catch(e){Ne(e,"Renderer.submitSprites")}},submitBitmapText(e){if(zi)try{zi.renderer_submitBitmapText(e._cpp)}catch(e){Ne(e,"Renderer.submitBitmapText")}},submitSpine(e){if(zi)try{zi.renderer_submitSpine?.(e._cpp)}catch(e){Ne(e,"Renderer.submitSpine")}},submitParticles(e){if(zi)try{zi.renderer_submitParticles?.(e._cpp)}catch(e){Ne(e,"Renderer.submitParticles")}},setStage(e){zi?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>zi?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){zi?.renderer_releaseTarget(e)},getTargetTexture:e=>zi?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>zi?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){zi?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){zi?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){zi?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){zi?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>zi?zi.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>zi?{drawCalls:zi.renderer_getDrawCalls(),triangles:zi.renderer_getTriangles(),sprites:zi.renderer_getSprites(),text:zi.renderer_getText(),spine:zi.renderer_getSpine?.()??0,meshes:zi.renderer_getMeshes(),culled:zi.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Oi=null;function Wi(e){Oi=e}function Hi(){Oi=null}const Vi={enable(){Oi?.gl_enableErrorCheck(!0)},disable(){Oi?.gl_enableErrorCheck(!1)},check:e=>Oi?.gl_checkErrors(e)??0,diagnose(){Oi?.renderer_diagnose()}};class ji{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}beginScreenCapture(){mi.screenStack&&mi.screenStack.enabledPassCount>0&&(mi.isInitialized()||mi.init(1,1),mi._applyScreenStack(),mi._beginScreenCapture())}endScreenCapture(){mi.screenStack&&mi.screenStack.enabledPassCount>0&&(mi._endScreenCapture(),mi._executeScreenPasses())}render(e){const{registry:t,viewProjection:s,width:n,height:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Di.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Di.setViewport(0,0,n,i),Di.clearBuffers(3),Di.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),this.tilemapRenderer_&&this.tilemapRenderer_(),Di.submitSprites(t),Di.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Di.submitSpine(t),Di.submitParticles(t),Di.flush(),this.executeDrawCallbacks(s,o),Di.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==mi.getStack(r);a&&(mi._applyForCamera(r),mi.resize(n.w,n.h),mi.setOutputViewport(n.x,n.y,n.w,n.h)),Di.setViewport(n.x,n.y,n.w,n.h),Di.setScissor(n.x,n.y,n.w,n.h,!0),Di.clearBuffers(i),Di.setScissor(0,0,0,0,!1),Di.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),this.tilemapRenderer_&&this.tilemapRenderer_(),Di.submitSprites(t),Di.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Di.submitSpine(t),Di.submitParticles(t),Di.flush(),this.executeDrawCallbacks(s,o),Di.end(),a&&mi._resetAfterCamera()}executeDrawCallbacks(e,t){const s=Xn;if(s.size>0){Wn.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)}Wn.end();for(const e of n)Yn(e)}}}const Xi="__scene_transition_overlay__";class Ni{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Yi{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,Te,{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),Nn(e,t,this.instance_.config.name)}bindPostProcess(e,t){mi.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){mi.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,Te)){const s=this.app_.world.get(e,Te);s.persistent=t,this.app_.world.insert(e,Te,s)}}}class qi{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}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())Yn(t);for(const t of e.postProcessBindings.keys())mi.unbind(t)}this.transition_&&(Yn(Xi),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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},Nn(Xi,()=>{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;Wn.setLayer(9999),Wn.setDepth(9999),Wn.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,Yn(Xi),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Yn(Xi),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 Ni(t);this.scenes_.set(e,s);const n=new Yi(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(yn)?this.app_.getResource(yn):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 Ni(t);this.scenes_.set(e,s);const n=new Yi(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(yn)?this.app_.getResource(yn):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,Te)){if(this.app_.world.get(e,Te).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Yn(e);s.drawCallbacks.clear();for(const e of s.postProcessBindings.keys())mi.unbind(e);s.postProcessBindings.clear(),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(yn)&&(i.assetServer=this.app_.getResource(yn));const o=await Ns(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,Te,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=Ki(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(yn)?this.app_.getResource(yn):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)Xt.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.postProcessBindings.values())s.setAllPassesEnabled(t)}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 Gi=ze(null,"SceneManager");function Ki(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Gi).getSceneStatus(t)&&s._fn(...n)}}}const Ji=Pt([Le(Gi),Ue(Oe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Qi={name:"SceneManager",build(e){const t=new qi(e);e.insertResource(Gi,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Gi),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(bt.Startup,s),e.addSystemToSchedule(bt.Last,Ji)}};class Zi{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 _t,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),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(bt.Last);else{this.runSchedule(bt.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(bt.FixedPreUpdate),this.runSchedule(bt.FixedUpdate),this.runSchedule(bt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(bt.PreUpdate),this.runSchedule(bt.Update),this.runSchedule(bt.PostUpdate),this.runSchedule(bt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Ze,this.resources_=new De;for(const e of Object.values(bt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Zi}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(bt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(bt.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 Xe(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.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}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(Gi).register(e),this}setInitialScene(e){return this.getResource(Gi).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new At(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(Oe)||this.resources_.insert(Oe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(bt.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(bt.Last);else{this.runSchedule(bt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(bt.FixedPreUpdate),this.runSchedule(bt.FixedUpdate),this.runSchedule(bt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(bt.PreUpdate),this.runSchedule(bt.Update),this.runSchedule(bt.PostUpdate),this.runSchedule(bt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new At(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(Oe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(bt.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,qn();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=[Hi,$i,fi,ti,Vt,$n];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));const n=this.phaseTimings_?performance.now():0;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)}}this.phaseTimings_&&this.phaseTimings_.set(bt[e],performance.now()-n)}updateTime(e){const t=this.resources_.get(Oe);t.delta=e,t.elapsed+=e,t.frameCount++}}function eo(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 to=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function so(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 no=[];function io(e){if(e<no.length)return no[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 no.push(t),t}function oo(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,Te);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,u=0,h=0;if(i.projectionType===ae.Orthographic){if(h=i.orthoSize,l){h=so(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=h*r,a=ao(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=co(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const d=ho(o.position.x,o.position.y,o.position.z),f=io(c.length);f.entity=e,f.viewProjection.set(po(a,d)),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=u,f.halfH=h,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const ro=new Float32Array(16);function ao(e,t,s,n,i,o){const r=ro;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 lo=new Float32Array(16);function co(e,t,s,n){const i=lo;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 uo=new Float32Array(16);function ho(e,t,s){const n=uo;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 fo=new Float32Array(16);function po(e,t){const s=fo;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 mo={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function go(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,u=o.left+t.x*a,h=o.bottom+e.y*l,d=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+s.x-i.x*r.x,m=f+i.x):(f=c+s.x,m=u+n.x),e.y===t.y?(p=h+s.y-i.y*r.y,g=p+i.y):(p=h+s.y,g=d+n.y);const _=Math.max(0,m-f),y=Math.max(0,g-p);return{originX:f+r.x*_,originY:p+r.y*y,width:_,height:y,rect:{left:f,bottom:p,right:m,top:g}}}const _o=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 yo=null,wo=null;function xo(e,t){e.has(t,fe)||e.insert(t,fe,{texture:$,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 vo(e,t){switch(e){case mo.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case mo.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case mo.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 bo(e,t){switch(e){case mo.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case mo.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case mo.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 So(e,t,s,n){switch(e){case mo.BottomToTop:case mo.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}}function Mo(e,t,s,n){if(!e.has(t,_o))return;const i=e.get(t,_o),o=vo(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,_o,i)}function Po(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function To(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Eo(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(To(r.charCodeAt(0))&&n.length>0&&To(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!To(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 Co(e){let t=1;for(;t<e;)t*=2;return t}function Ro(e,t){let s=0,n=t;for(;e.has(n,_e);){const t=e.get(n,_e).entity;if(!e.valid(t))break;s++,n=t}return s}function Ao(e,t){if(yo&&wo){const e=yo.getUIRectComputedWidth(wo,t);if(e>0)return e}return e.size.x}function Io(e,t){if(yo&&wo){const e=yo.getUIRectComputedHeight(wo,t);if(e>0)return e}return e.size.y}function ko(e,t,s,n,i,o){if(!e.has(t,fe))return;const r=e.get(t,fe);let a,l;switch(s){case mo.BottomToTop:case mo.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 Fo(e,t,s){let n=t;for(;e.has(n,_e);){const t=e.get(n,_e).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Bo(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function zo(e,t,s,n,i){if(!e.has(t,_o))return;const o=e.get(t,_o),r=go(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,ue)){const s=e.get(t,ue);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,ue,s)}}function Uo(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 Lo=.1,$o=30,Do={r:.3,g:.5,b:.8,a:1},Oo={Left:0,Center:1,Right:2},Wo={Top:0,Middle:1,Bottom:2},Ho={Visible:0,Clip:1,Ellipsis:2},Vo=K("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Oo.Left,verticalAlign:Wo.Top,wordWrap:!0,overflow:Ho.Visible,lineHeight:1.2});class jo{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(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,Co(this.frameMaxW_)),e.height=Math.max(e.height,Co(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Co(this.frameMaxW_),e.height=Co(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=Eo(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=i?Math.ceil(o):h+2*u,p=i?Math.ceil(r):d+2*u;if(i&&e.overflow===Ho.Ellipsis&&d>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,Co(f)),n.height=Math.max(n.height,Co(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.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===Ho.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 Wo.Top:x=u;break;case Wo.Middle:x=u+(p-2*u-w)/2;break;case Wo.Bottom:x=p-w-u;break;default:x=u}x<0&&(x=0)}else x=u;let v=x;for(const t of l){let n;switch(e.align){case Oo.Left:n=u;break;case Oo.Center:n=f/2;break;case Oo.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=c}i&&e.overflow===Ho.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 Oo.Left:return"left";case Oo.Center:return"center";case Oo.Right:return"right"}}}const Xo=Uo({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?Ao(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Io(e.uiRect,e.entity):0});class No{build(e){ie("Text",Vo);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new jo(t),n=e.world,i=new Map;e.addSystemToSchedule(bt.PreUpdate,Pt([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Vo));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Vo)){if(n.valid(e)&&n.has(e,fe)){const t=n.get(e,fe);n.insert(e,fe,{texture:$,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([Vo]);for(const t of e){const e=n.get(t,Vo),o=n.has(t,_o)?n.get(t,_o):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Xo.changed(a,r)){if(n.has(t,fe)&&n.get(t,fe).texture!==$)continue}xo(n,t);const l=o?{size:{x:Ao(o,t),y:Io(o,t)}}:null,c=s.renderForEntity(t,e,l),u=n.get(t,fe);n.insert(t,fe,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,Xo.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Yo=new No,qo=0,Go=1,Ko=re("UIMask",{enabled:!0,mode:qo});function Jo(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 Qo(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],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],g=e[13],_=e[14],y=e[15],w=n*l-i*a,x=n*c-o*a,v=n*u-r*a,b=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=h*g-d*m,T=h*_-f*m,E=h*y-p*m,C=d*_-f*g,R=d*y-p*g,A=f*y-p*_;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+u*C)*I,s[1]=(o*R-i*A-r*C)*I,s[2]=(g*M-_*S+y*b)*I,s[3]=(f*S-d*M-p*b)*I,s[4]=(c*E-a*A-u*T)*I,s[5]=(n*A-o*E+r*T)*I,s[6]=(_*v-m*M-y*x)*I,s[7]=(h*M-f*v+p*x)*I,s[8]=(a*R-l*E+u*P)*I,s[9]=(i*E-n*R-r*P)*I,s[10]=(m*S-g*v+y*w)*I,s[11]=(d*v-h*S-p*w)*I,s[12]=(l*T-a*C-c*P)*I,s[13]=(n*C-i*T+o*P)*I,s[14]=(g*x-m*b-_*w)*I,s[15]=(h*b-d*x+f*w)*I),s}function Zo(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],u=s[1]*a+s[5]*l+s[13],h=s[3]*a+s[7]*l+s[15];return{x:c/h,y:u/h}}function er(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 tr(e,t){return 2*Math.atan2(e,t)}function sr(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 nr(e,t,s,n,i,o,r,a,l,c){const u=tr(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-s,p=t-n,m=f*d-p*h+s,g=f*h+p*d+n;return m>=s-i*r&&m<=s+i*(1-r)&&g>=n-o*a&&g<=n+o*(1-a)}function ir(e,t,s,n,i,o,r){if(!e.has(t,_o)||!e.has(t,ue))return null;const a=e.get(t,_o),l=e.get(t,ue),c=Ao(a,t)*l.worldScale.x,u=Io(a,t)*l.worldScale.y,h=l.worldPosition.x,d=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,g=c*(1-f),_=-u*p,y=u*(1-p),w=tr(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+m*x-_*v,d+m*v+_*x],[h+g*x-_*v,d+g*v+_*x],[h+g*x-y*v,d+g*v+y*x],[h+m*x-y*v,d+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]=sr(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 or(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ko]);if(0===l.length)return;const c=[],u=[],h=new Set,d=new Set;for(const e of l){const s=t.get(e,Ko);s.enabled&&(h.add(e),s.mode===Go?(u.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,i,o,r,a,l,c){const u=[];for(const e of n){let s=!0;Fo(t,e,e=>{if(i.has(e)){if(t.get(e,Ko).mode===qo)return s=!1,!0}return!1}),s&&u.push(e)}function h(n,u){const d=e.getChildEntities(s,n);for(const s of d){let n=u;if(i.has(s)){if(t.get(s,Ko).mode===qo){const e=ir(t,s,o,r,a,l,c);e&&(n=Jo(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of u){const s=ir(t,e,o,r,a,l,c);s&&h(e,s)}}(e,t,s,c,h,n,i,o,r,a),u.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Fo(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),u(t,n)}function u(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),u(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,u,d)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class rr{build(e){if(ie("UIMask",Ko),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(or(e.wasmModule,e.world))}}const ar=new rr,lr=re("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),cr=re("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),ur={Normal:0,Hovered:1,Pressed:2,Disabled:3},hr=K("Button",{state:ur.Normal,transition:null});class dr{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 fr=ze(new dr,"UIEvents");class pr{build(e){ie("UIRect",_o);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){yo=e,wo=t}(s,n);e.addSystemToSchedule(bt.PreUpdate,Pt([Ue(zt)],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(bt.PostUpdate,Pt([Ue(zt)],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(bt.PostUpdate,Pt([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const mr=new pr;let gr=!1,_r=!1;function yr(e){gr=e}function wr(){return gr}function xr(){return!gr}function vr(e){_r=e}function br(){return _r}const Sr=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&&(Qo(t,e),s=!1),e)}}();function Mr(e,t,s,n){t.emit(s,n,s),Fo(e,s,i=>{if(!e.has(i,lr))return!1;const o=e.get(i,lr);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Pr{build(e){ie("Interactable",lr),ie("Button",hr);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new dr;e.insertResource(fr,i);let o=null,r=null;e.addSystemToSchedule(bt.PreUpdate,Pt([Ue(kt),Ue(zt)],(e,a)=>{if(i.drain(),wr()&&!br())return;const l=t.getEntitiesWithComponents([cr]);for(const e of l){const s=t.get(e,cr);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,cr,s))}if(!a.valid)return;const c=f(),u=e.mouseX*c,h=a.screenH-e.mouseY*c;Sr.update(a.viewProjection);const d=Zo(u,h,Sr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=d.x,a.worldMouseY=d.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);s.uiHitTest_update(n,d.x,d.y,p,m,g);const _=s.uiHitTest_getHitEntity(),y=4294967295===_?null:_;if(null===o||t.valid(o)||(o=null),o!==y){if(null!==o&&t.valid(o)&&t.has(o,cr)){const e=t.get(o,cr);e.hovered=!1,t.insert(o,cr,e),i.emit(o,"hover_exit")}if(null!==y){Bo(t,y,cr);const e=t.get(y,cr);e.hovered=!0,t.insert(y,cr,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,cr);e.pressed=!0,e.justPressed=!0,t.insert(y,cr,e),r=y,Mr(t,i,y,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,cr)){const e=t.get(r,cr);e.pressed=!1,e.justReleased=!0,t.insert(r,cr,e),Mr(t,i,r,"release"),r===o&&Mr(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(bt.Update,Pt([],()=>{const e=t.getEntitiesWithComponents([hr]);for(const s of e){if(Bo(t,s,lr,{enabled:!0}),!t.has(s,cr))continue;const e=t.get(s,cr),n=t.get(s,hr),i=t.get(s,lr),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=ur.Pressed:e.hovered?n.state=ur.Hovered:n.state=ur.Normal:n.state=ur.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,fe)){const o=t.get(s,fe);o.color=Po(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,fe,o)}}},{name:"ButtonSystem"}))}}const Tr=new Pr,Er=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}),Cr=K("Focusable",{tabIndex:0,isFocused:!1});class Rr{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 Ar=ze(new Rr,"FocusManager");class Ir{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ie("TextInput",Er),wr()&&!br())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=h(F.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,u=0,d=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(Ar);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Er)?n:null}const g=()=>{l||null===m()||v()},_=()=>{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,Er);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(fr).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,Er);n.focused=!1,n.dirty=!0;e.getResource(Ar).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,Er);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(fr).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,Er);e.focused=!1,e.dirty=!0}e.getResource(Ar).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",g),p.addEventListener("compositionstart",_),p.addEventListener("compositionend",y),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",_),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,u,h){(i.width<u||i.height<h)&&(i.width=Co(Math.max(i.width,u)),i.height=Co(Math.max(i.height,h))),o.clearRect(0,0,i.width,i.height);const d=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,o.fillRect(0,0,u,h),o.save(),o.beginPath(),o.rect(l.padding,0,u-2*l.padding,h),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 g=Math.ceil(1.2*l.fontSize),_=l.padding;if(l.multiline){const e=Eo(o,p,u-2*_);let t=_;for(const s of e)o.fillText(s,_,t),t+=g}else{const e=(h-l.fontSize)/2;o.fillText(p,_,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=Eo(o,l.value,u-2*_);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=_+o.measureText(c).width,s=_+r*g,n=g}else t=_+o.measureText(e).width,s=(h-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,u,h),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(u,h,r,w.length,1,!0);n.set(e,b);const S=s.get(e,fe);S.texture=b,S.size.x=u,S.size.y=h,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(bt.Update,Pt([Ue(Ar)],e=>{const t=s.getEntitiesWithComponents([Er]);for(const e of t)Bo(s,e,Cr,{tabIndex:0,isFocused:!1}),Bo(s,e,lr,{enabled:!0,blockRaycast:!0});const n=m();if(n!==M){if(null!==M&&s.valid(M)&&s.has(M,Er)){const e=s.get(M,Er);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,Er);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(bt.PreUpdate,Pt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===d?0:(e-d)/1e3;d=e,i=Math.min(i,.1);const o=m();if(null!==o&&(u+=i,u>=.5)){u-=.5,c=!c;s.get(o,Er).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Er)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Er,_o]);for(const e of a){const t=s.get(e,Er);if(!t.dirty)continue;const n=s.get(e,_o),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(xo(s,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const kr=new Ir,Fr={Simple:0,Sliced:1,Tiled:2,Filled:3},Br={Horizontal:0,Vertical:1},zr={Left:0,Right:1,Bottom:2,Top:3},Ur=K("Image",{texture:$,color:{r:1,g:1,b:1,a:1},imageType:Fr.Simple,fillMethod:Br.Horizontal,fillOrigin:zr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Lr=Uo({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?Ao(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Io(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class $r{build(e){ie("Image",Ur);const t=e.world,s=new Map;e.addSystemToSchedule(bt.PreUpdate,Pt([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Ur)||s.delete(e);const e=t.getEntitiesWithComponents([Ur]);for(const n of e){const e=t.get(n,Ur),i=t.has(n,_o)?t.get(n,_o):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!Lr.changed(r,o))continue;xo(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=Ao(i,n),a.size.y=Io(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Fr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Br.Horizontal?e.fillOrigin===zr.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===zr.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===Fr.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,Lr.take(o))}else a.color.a=0,t.insert(n,fe,a),s.set(n,Lr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Dr=new $r,Or=K("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Wr=K("ToggleGroup",{allowSwitchOff:!1});class Hr{build(e){ie("Toggle",Or),ie("ToggleGroup",Wr);const t=e.world,s=new Set;e.addSystemToSchedule(bt.Update,Pt([Ue(fr)],e=>{const n=t.getEntitiesWithComponents([Or]);if(!wr()||br()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Or);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,Or,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Or);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(Bo(t,s,lr,{enabled:!0}),!t.has(s,cr))continue;const n=t.get(s,cr),i=t.get(s,Or),r=t.get(s,lr);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,Wr);if(i.isOn&&r){if(!t.get(n,Wr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,Or,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,Or);i.isOn&&(i.isOn=!1,t.insert(n,Or,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,fe)){const e=t.get(s,fe);e.color=Po(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,fe,e)}}}for(const e of n){const s=t.get(e,Or);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"]})}}const Vr=new Hr,jr=mo,Xr=K("ProgressBar",{value:0,fillEntity:0,direction:mo.LeftToRight});function Nr(e,t,s,n){if(!e.has(t,_o))return;const i=e.get(t,_o),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=go(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,ue)){const s=e.get(t,ue),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,ue,s))}}class Yr{build(e){ie("ProgressBar",Xr);const t=e.world;e.addSystemToSchedule(bt.PreUpdate,Pt([],()=>{const e=t.getEntitiesWithComponents([Xr,_o]);for(const s of e){const e=t.get(s,Xr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,_o),i=Math.max(0,Math.min(1,e.value));Mo(t,e.fillEntity,e.direction,i);const o=Ao(n,s),r=Io(n,s);Nr(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const qr=new Yr,Gr=K("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Kr=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}});class Jr{build(e){ie("Draggable",Gr),ie("DragState",Kr);const t=e.world,s=e.getResource(fr);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(bt.PreUpdate,Pt([Ue(kt),Ue(zt)],(e,r)=>{if(wr()&&!br())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Gr,cr]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Gr).enabled)continue;if(t.get(n,cr).hovered){let e=0;t.has(n,fe)&&(e=t.get(n,fe).layer);const i=Ro(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,Kr)||t.insert(s,Kr);const e=t.get(s,Kr),o=t.get(s,ue);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,Kr)){t.get(n,Kr).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),u=t.get(n,Gr);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Kr).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Kr))return void(o=null);const n=t.get(o,Kr),i=t.get(o,Gr),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,u=n.startWorldPos.y+l;const h=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,u);c=h.x,u=h.y;const d=n.currentWorldPos.x,f=n.currentWorldPos.y;if(n.deltaWorld={x:c-d,y:u-f},n.currentWorldPos={x:c,y:u},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:u-n.startWorldPos.y},t.has(o,ue)){const e=function(e,t,s,n){if(!e.has(t,_e))return{x:s,y:n};const i=e.get(t,_e).entity;if(!e.valid(i)||!e.has(i,ue))return{x:s,y:n};const o=e.get(i,ue),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=tr(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(s*u-n*c)/r,y:(s*c+n*u)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,ue);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,ue,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const Qr=new Jr,Zr=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 ea(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 ta(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,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(s-o*c)*a}}class sa{build(e){ie("ScrollView",Zr);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(bt.PostUpdate,Pt([Ue(kt),Ue(zt),Ue(Oe)],(e,i,o)=>{const r=wr()&&!br(),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([Zr,_o]);for(const o of l){Bo(t,o,Ko,{enabled:!0,mode:qo});const l=t.get(o,Zr),c=t.get(o,_o);let u=s.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,u));const h=Ao(c,o),d=Io(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,ue))continue;const e=t.get(r,ue);let a=0,l=0,c=.5,u=.5;if(t.has(r,_o)){const e=t.get(r,_o);a=Ao(e,r)||e.size.x,l=Io(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,fe)){const e=t.get(r,fe);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,d=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);h<s&&(s=h),d>n&&(n=d),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=n-s),0===p&&(p=o-i)}const m=Math.max(0,f-h),g=Math.max(0,p-d);if(!r&&i.valid){Bo(t,o,lr,{enabled:!0,blockRaycast:!0});const s=t.has(o,cr)?t.get(o,cr):null;if(s?.justPressed&&(u.isDragging=!0,u.lastWorldX=n.x,u.lastWorldY=n.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=n.x-u.lastWorldX,t=n.y-u.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=ea(l.scrollX,0,m,h);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const n=a>0?-e*t/a:0;u.velocityX+=(n-u.velocityX)*s}}if(l.verticalEnabled){const e=ea(l.scrollY,0,g,d);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const n=a>0?t*e/a:0;u.velocityY+=(n-u.velocityY)*s}}u.lastWorldX=n.x,u.lastWorldY=n.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*h,t=5*d;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=ea(l.scrollY,0,g,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=ea(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=ta(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Lo&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Lo?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=ta(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Lo&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Lo?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.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,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*d;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ue)){const e=t.get(l.contentEntity,ue),s=e.position.x,n=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(n-u.lastAppliedY)>.01)&&(u.contentBaseY=n),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,ue,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const na=new sa,ia=mo,oa=K("Slider",{value:0,minValue:0,maxValue:1,direction:mo.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function ra(e,t,s,n,i,o){const r=Ao(n,i)*s.worldScale.x,a=Io(n,i)*s.worldScale.y,l=tr(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),h=e-s.worldPosition.x,d=t-s.worldPosition.y,f=h*u-d*c,p=h*c+d*u,m=-n.pivot.x*r,g=-n.pivot.y*a;switch(o){case mo.LeftToRight:return r>0?(f-m)/r:0;case mo.RightToLeft:return r>0?1-(f-m)/r:0;case mo.BottomToTop:return a>0?(p-g)/a:0;case mo.TopToBottom:return a>0?1-(p-g)/a:0}}function aa(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case mo.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case mo.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case mo.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case mo.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class la{build(e){ie("Slider",oa);const t=e.world;let s=null;e.addSystemToSchedule(bt.PreUpdate,Pt([Ue(kt),Ue(zt),Ue(fr)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([oa,_o]);for(const r of o){const o=t.get(r,oa),a=t.get(r,_o);if(!wr()||br()){if(t.has(r,ue)){Bo(t,r,lr,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Bo(t,o.handleEntity,lr,{enabled:!0,blockRaycast:!1});const l=t.get(r,ue),c=t.has(r,cr)?t.get(r,cr):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,cr)&&(u=t.get(o.handleEntity,cr).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=ra(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,oa,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,u=Ao(a,r),h=Io(a,r),d={left:-u/2,bottom:-h/2,right:u/2,top:h/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Mo(t,o.fillEntity,o.direction,c),zo(t,o.fillEntity,d,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,_o)){const e=t.get(o.handleEntity,_o);aa(e,o.direction,c),t.insert(o.handleEntity,_o,e),zo(t,o.handleEntity,d,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const ca=new la;class ua{build(e){ie("Focusable",Cr);const t=e.world,s=new Rr;e.insertResource(Ar,s),e.addSystemToSchedule(bt.Update,Pt([Ue(kt),Ue(fr)],(e,n)=>{if(wr()&&!br())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Cr]);for(const e of i){if(!t.has(e,cr))continue;t.get(e,cr).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,lr)){if(!t.get(s,lr).enabled)continue}const n=t.get(s,Cr);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,Cr)){t.get(i,Cr).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Cr).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const ha=new ua,da=K("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function fa(){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")}}()}class pa{build(e){ie("SafeArea",da);const t=e.world;let s=fa(),n=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{s=fa(),n=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{s=fa(),n=!0});e.addSystemToSchedule(bt.PreUpdate,Pt([Ue(zt)],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,u=t.getEntitiesWithComponents([da,_o]);for(const e of u){const n=t.get(e,da),i=t.get(e,_o),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 u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,_o,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const ma=new pa,ga=K("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let _a=null;function ya(e,t){if(!_a)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=_a.get(e);s?s.renderer=t:_a.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class wa{build(e){ie("ListView",ga);const t=e.world,s=new Map;_a=s,e.addSystemToSchedule(bt.PostUpdate,Pt([Ue(kt)],e=>{const n=wr()&&!br();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([ga,_o]);for(const o of i){Bo(t,o,lr,{enabled:!0,blockRaycast:!0}),Bo(t,o,Ko,{enabled:!0,mode:qo});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,ga),a=t.get(o,_o),l=Io(a,o),c=Ao(a,o);if(!n){const s=t.has(o,cr)?t.get(o,cr):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,s]of i.itemEntities)(e<h||e>=d)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=h;e<d;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,Pe,{value:`ListItem_${e}`}),t.insert(s,_o,{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,ue)){const n=t.get(s,ue);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,ue,n)}}i.visibleStart=h,i.visibleEnd=d}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const xa=new wa,va=K("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class ba{build(e){ie("Dropdown",va);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,ue))return;const s=t.get(e,ue);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,ue,{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;u(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*$o;t.insert(i,_o,{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,ue,{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:$,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)*$o;t.insert(o,Pe,{value:`Option_${e}`}),t.insert(o,_o,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*$o},offsetMax:{x:0,y:0},size:{x:r,y:$o},pivot:{x:.5,y:.5}}),t.insert(o,ue,{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:$,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:$o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,lr,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);const c=t.spawn();t.insert(c,ue,{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,Vo,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Oo.Left,verticalAlign:Wo.Middle,wordWrap:!1,overflow:Ho.Clip,lineHeight:1.2}),t.insert(c,_o,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:$o},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}h(n)}function r(e,t,s){t.isOpen=!1,c(s),u(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,Vo))return;const n=t.get(s,Vo);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,Vo,{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 u(e,s){if(0!==e&&t.valid(e)&&(t.has(e,lr)&&t.insert(e,lr,{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 h(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?{...Do}:{r:.95,g:.95,b:.95,a:1};t.insert(n,fe,{texture:$,color:i,size:{x:e.ddWidth,y:$o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function d(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,cr))continue;if(t.get(s,cr).hovered)return!0}return!1}e.addSystemToSchedule(bt.Update,Pt([Ue(kt),Ue(fr)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=wr()&&!br(),p=t.getEntitiesWithComponents([va]);for(const m of p){const p=t.get(m,va);let g=s.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,g)),n(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;Bo(t,m,lr,{enabled:!0,blockRaycast:!0});const _=t.has(m,cr)?t.get(m,cr):null;if(_?.justPressed&&(p.isOpen?r(m,p,g):o(m,p,g)),p.isOpen){for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,cr))continue;if(t.get(s,cr).justPressed){a(m,p,g,e,c);break}}let s=-1;for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,cr))continue;if(t.get(n,cr).hovered){s=e;break}}s>=0&&s!==g.highlightIndex&&(g.highlightIndex=s,h(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=p.options.length-1?g.highlightIndex=0:g.highlightIndex++,h(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=p.options.length-1:g.highlightIndex--,h(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,p,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,g),e.isMouseButtonPressed(0)&&(_?.hovered||d(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const Sa=new ba,Ma=0,Pa=0,Ta=2,Ea=K("LayoutGroup",{direction:Ma,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Pa,reverseOrder:!1});class Ca{build(e){ie("LayoutGroup",Ea);const t=e.world;e.addSystemToSchedule(bt.PreUpdate,Pt([],()=>{const e=t.getEntitiesWithComponents([Ea,_o,ye]);for(const s of e){const e=t.get(s,Ea),n=t.get(s,_o),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,_o)&&t.has(e,ue)&&o.push({entity:e,rect:t.get(e,_o)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Ao(n,s),a=Io(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,h=e.direction===Ma;let d=0;for(let s=0;s<o.length;s++){const n=o[s],i=Ao(n.rect,n.entity),f=Io(n.rect,n.entity),p=n.rect.pivot.x,m=n.rect.pivot.y;let g,_;h?(g=-l*r+u.left+d+p*i,_=e.childAlignment===Pa?(1-c)*a-u.top-(1-m)*f:e.childAlignment===Ta?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,d+=i,s<o.length-1&&(d+=e.spacing)):(g=e.childAlignment===Pa?-l*r+u.left+p*i:e.childAlignment===Ta?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,_=(1-c)*a-u.top-d-(1-m)*f,d+=f,s<o.length-1&&(d+=e.spacing));const y=t.get(n.entity,ue);y.position.x=g,y.position.y=_,t.insert(n.entity,ue,y)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Ra=new Ca;class Aa{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(bt.PostUpdate,Pt([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Ia=new Aa;async function ka(e,t,s){const n=e.getResource(Gi);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Fa(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 Ba=ze({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),za={r:.2,g:.4,b:1,a:.7},Ua={r:.2,g:1,b:.2,a:.7},La={r:.2,g:1,b:1,a:.7},$a={r:1,g:1,b:.2,a:.5},Da={r:1,g:.2,b:.2,a:.8},Oa={r:1,g:.2,b:.2,a:1},Wa=1.5,Ha=16;function Va(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ja(e){switch(e){case Fe.Static:return za;case Fe.Kinematic:return La;default:return Ua}}function Xa(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-s,y:-n},{x:s,y:-n},{x:s,y:n},{x:-s,y:n}].map(s=>({x:e+s.x*r-s.y*a,y:t+s.x*a+s.y*r}));for(let e=0;e<4;e++)Wn.line(l[e],l[(e+1)%4],o,Wa)}function Na(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=(s,n)=>({x:e+s*r-n*a,y:t+s*a+n*r}),c=l(-s,n),u=l(s,n),h=l(-s,-n),d=l(s,-n);Wn.line(c,h,o,Wa),Wn.line(u,d,o,Wa);for(let e=0;e<Ha;e++){const t=e/Ha*Math.PI,i=(e+1)/Ha*Math.PI,r=l(-s*Math.cos(t),n+s*Math.sin(t)),a=l(-s*Math.cos(i),n+s*Math.sin(i));Wn.line(r,a,o,Wa)}for(let e=0;e<Ha;e++){const t=Math.PI+e/Ha*Math.PI,i=Math.PI+(e+1)/Ha*Math.PI,r=l(-s*Math.cos(t),-n+s*Math.sin(t)),a=l(-s*Math.cos(i),-n+s*Math.sin(i));Wn.line(r,a,o,Wa)}}function Ya(e,t,s,n){const i=e+.5*s,o=t+.5*n;Wn.line({x:e,y:t},{x:i,y:o},Da,Wa);const r=Math.sqrt(s*s+n*n);if(r<1)return;const a=Math.PI/6,l=s/r,c=n/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),h=o-6*(l*Math.sin(a)+c*Math.cos(a)),d=i-6*(l*Math.cos(a)+c*Math.sin(a)),f=o-6*(-l*Math.sin(a)+c*Math.cos(a));Wn.line({x:i,y:o},{x:u,y:h},Da,Wa),Wn.line({x:i,y:o},{x:d,y:f},Da,Wa)}function qa(e,t,s){const n=e.getResource(Ba);if(!n||!n.enabled)return;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=e.world.getEntitiesWithComponents([Re,ue]);let r=null;n.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const s=e.world.get(t,Re);if(!s.enabled)continue;const o=e.world.get(t,ue),a=o.worldPosition.x,l=o.worldPosition.y,c=Va(o.worldRotation);if(n.showColliders){if(e.world.has(t,Ae)){const n=e.world.get(t,Ae),o=n.isSensor?$a:ja(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,h=Math.cos(c),d=Math.sin(c);Xa(a+r*h-u*d,l+r*d+u*h,n.halfExtents.x*i,n.halfExtents.y*i,c,o)}if(e.world.has(t,Ie)){const n=e.world.get(t,Ie),o=n.isSensor?$a:ja(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,h=Math.cos(c),d=Math.sin(c),f=a+r*h-u*d,p=l+r*d+u*h;Wn.circleOutline({x:f,y:p},n.radius*i,o,Wa,32)}if(e.world.has(t,ke)){const n=e.world.get(t,ke),o=n.isSensor?$a:ja(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,h=Math.cos(c),d=Math.sin(c);Na(a+r*h-u*d,l+r*d+u*h,n.radius*i,n.halfHeight*i,c,o)}}if(n.showVelocity&&r&&s.bodyType===Fe.Dynamic){const e=r.getLinearVelocity(t);Ya(a,l,e.x*i,e.y*i)}}if(n.showContacts&&e.hasResource(s)){const t=e.getResource(s);for(const e of t.collisionEnters)Wn.circle({x:e.contactX,y:e.contactY},3,Oa,!0,32)}}const Ga=ze({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Ka=ze(null,"PhysicsAPI");function Ja(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Qa(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Za{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(Ga,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Fa(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(bt.PostUpdate,Pt([Ue(Oe)],a=>{const l=r.getEntitiesWithComponents([Re,ue]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Re),l=r.get(i,ue);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=Ja(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),el(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===Fe.Kinematic){const e=Ja(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 u=e.world.get(r,ue);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(r,_e)){const t=e.world.get(r,_e);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ue)){const s=e.world.get(t.entity,ue),n=Ja(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),u=Math.sin(-n);h=(i*r-o*u)/(0!==s.worldScale.x?s.worldScale.x:1),d=(i*u+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),f=c-n}}u.position.x=h,u.position.y=d;const p=Qa(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(r,ue,u)}}(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=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Ga,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Ka,tl._fromModule(n)),function(e,t,s){e.insertResource(Ba,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),Nn("physics-debug-draw",()=>{qa(e,t,s)})}(e,Ka,Ga),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function el(e,t,s){const n=e.world;if(n.has(s,Ae)){const e=n.get(s,Ae);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,Ie)){const e=n.get(s,Ie);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,ke)){const e=n.get(s,ke);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 tl{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(tl.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)}static setDebugDraw(e,t){const s=e.getResource(Ba);s&&(s.enabled=t,e.insertResource(Ba,s))}static setDebugDrawConfig(e,t){const s=e.getResource(Ba);s&&e.insertResource(Ba,{...s,...t})}}const sl={nearest:0,linear:1},nl={repeat:0,clamp:1,mirror:2};function il(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=sl[n.filterMode??"linear"]??1,a=nl[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 ol(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 rl(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,u=e.worldRotation.w,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,g=a*f,_=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(_+w))*i,(m+b)*i,(g-v)*i,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(g+v)*r,(y-x)*r,(1-(p+_))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function al(e){const{app:t,module:s,sceneData:n,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=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=$s(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]=il(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(s,n,i);!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)}}}}(s,n,u);let h={},d=null;if(o&&(d=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"])}}(o),h=await async function(e,t,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=Ds(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),u=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===sn(c)?.contentType;let h,d;if(r){const e=await i.readBinary(a);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const f=s.loadSkeleton(h,d,n,n.length,r);if(t._free(h),f<0)continue;o[a]=f;const p=ol(n),m=u.substring(0,u.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=il(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(s,o,d,n,i)),r){const e={gravity:a?.gravity??{...A},fixedTimestep:a?.fixedTimestep??I,subStepCount:a?.subStepCount??4};new Za("",e,()=>Promise.resolve(r)).build(t)}const f=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=$s(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=sn(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),u=il(e,c,!1),h=e.getResourceManager();n[o]=h.loadBitmapFont(t,u,c.width,c.height)}catch{n[o]=0}}return n}(s,n,i),p=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=$s(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=Xt.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=Xt.createFromAsset(e,r)}catch{s[o]=0}}return s}(n,i);await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=$s(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=JSON.parse(t),o=ss(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,il(e,n))}catch{r.set(t,0)}os(ns(i,n,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(s,n,i),await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=$s(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=Rs(JSON.parse(t));if(!n)continue;const o=[];for(const t of n.tilesets){const n=As(i,t.image);let r=0;try{const t=await s.loadPixels(n);r=il(e,t),ps(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}_s(i,{tileWidth:n.tileWidth,tileHeight:n.tileHeight,layers:n.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(s,n,i),await async function(e,t){const s=[],n=new Set;for(const t of e.entities)for(const e of t.components){const t=$s(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!n.has(t)&&(n.add(t),s.push(t))}}0!==s.length&&(t?await Promise.all(s.map(async e=>{try{const s=await t.readBinary(e);await hs.preloadFromData(e,s.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await hs.preloadAll(s).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(n,i),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=$s(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)}}}(n,u,f,p);const m=Xs(t.world,n);if(c&&t.hasResource(Gi))for(const e of m.values())t.world.insert(e,Te,{scene:c,persistent:!1});if(o&&d){const e=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=Ds(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}(d,n,h,m);!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,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(r,l*h);let d=0;if(c.has(o,ue)){const e=rl(c.get(o,ue),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>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),u=s._malloc(l),h=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(r,e,c,u,h,f);const p=s.HEAPU32[h>>2],m=s.HEAPU32[f>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*i),_=new Uint16Array(s.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(_),t.renderer_submitTriangles(y,i,w,o,p,m,d),t._free(y),t._free(w),s._free(c),s._free(u),s._free(h),s._free(f)}d&&t._free(d)}})}(t,s,o,d,e)}if(l){const e=t.getResource(yn);e&&e.setAddressableManifest(l)}}function ll(e,t,s){return{name:e,async setup(){await al({...s,sceneData:t,sceneName:e})}}}async function cl(e){const{app:t,firstScene:s,aspectRatio:n}=e;eo(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(Gi);for(const t of e.scenes)o.register(ll(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&Gs(t.world,n)}class ul{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=Ds(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===sn(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=$s(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(n.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&s.add(o))}}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=sn(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 hl="__preview__";class dl{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(Gi);t.register({name:hl,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(hl),this.loadPromise_=t.load(hl).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 ul(this.baseUrl_);await s.prefetch(t);let n=null;const i=this.app_.spineInitPromise;if(i){n=(await i).controller.raw}await al({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:n,sceneName:hl})}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(Gi).getScene(hl),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,ue,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(Gi);await e.switchTo(hl),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 fl={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=Di.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:Di.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){Di.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Di.releaseRenderTarget(e._handle),fl.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){Di.begin(t,e._handle)},end(){Di.end()},getDepthTexture:e=>Di.getTargetDepthTexture(e._handle)};var pl;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(pl||(pl={}));class ml{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${pl[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case pl.Debug:console.debug(t,s);break;case pl.Info:console.log(t,s);break;case pl.Warn:console.warn(t,s);break;case pl.Error:console.error(t,s)}}}class gl{constructor(){this.handlers_=[],this.minLevel_=pl.Info,this.addHandler(new ml)}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(pl.Debug,e,t,s)}info(e,t,s){this.log(pl.Info,e,t,s)}warn(e,t,s){this.log(pl.Warn,e,t,s)}error(e,t,s){this.log(pl.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 _l=new gl;function yl(){return _l}function wl(e){_l.setMinLevel(e)}function xl(e,t,s){_l.debug(e,t,s)}function vl(e,t,s){_l.info(e,t,s)}function bl(e,t,s){_l.warn(e,t,s)}function Sl(e,t,s){_l.error(e,t,s)}const Ml={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},Pl={Running:0,Paused:1,Completed:2,Cancelled:3},Tl={None:0,Restart:1,PingPong:2};const El=1.70158,Cl=2.70158,Rl=2.5949095;const Al=2*Math.PI/3,Il=2*Math.PI/4.5;const kl=7.5625,Fl=2.75;const Bl=1e-6;function zl(e,t,s){switch(e){case Ml.Linear:return t;case Ml.EaseInQuad:return function(e){return e*e}(t);case Ml.EaseOutQuad:return function(e){return e*(2-e)}(t);case Ml.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Ml.EaseInCubic:return function(e){return e*e*e}(t);case Ml.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Ml.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Ml.EaseInBack:return function(e){return Cl*e*e*e-El*e*e}(t);case Ml.EaseOutBack:return function(e){const t=e-1;return 1+Cl*t*t*t+El*t*t}(t);case Ml.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Rl)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Rl)+2)/2}(t);case Ml.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Al)}(t);case Ml.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Al)+1}(t);case Ml.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Il)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Il)/2+1}(t);case Ml.EaseOutBounce:return function(e){return e<1/Fl?kl*e*e:e<2/Fl?kl*(e-=1.5/Fl)*e+.75:e<2.5/Fl?kl*(e-=2.25/Fl)*e+.9375:kl*(e-=2.625/Fl)*e+.984375}(t);case Ml.CubicBezier:return s?function(e,t,s,n,i){let o=e;for(let s=0;s<8;s++){const s=1-o,i=3*t*s*s*o+3*n*s*o*o+o*o*o-e;if(Math.abs(i)<Bl)break;const r=3*t*(1-2*o)*(1-o)+6*n*o*(1-o)-3*n*o*o+3*o*o;if(Math.abs(r)<Bl)break;o-=i/r}const r=1-o;return 3*s*r*r*o+3*i*r*o*o+o*o*o}(t,s.p1x,s.p1y,s.p2x,s.p2y):t;case Ml.Step:return function(e){return e<1?0:1}(t);default:return t}}const Ul=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,s,n,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:s,elapsed:0,delay:i?.delay??0,easing:i?.easing??Ml.Linear,bezierPoints:null,state:Pl.Running,loop:i?.loop??Tl.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:n,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===Pl.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Pl.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const s=Math.min(t.elapsed/t.duration,1),n=zl(t.easing,s,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*n),s>=1){if(t.loop!==Tl.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Tl.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Pl.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Pl.Running&&(t.state=Pl.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Pl.Paused&&(t.state=Pl.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Pl.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Pl.Cancelled}setBezier(e,t,s,n,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:s,p2x:n,p2y:i})}setSequenceNext(e,t){const s=this.entries_.get(e);s&&(s.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const s=this.entries_.get(e);s&&(s.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Ll{constructor(e){this.id=e}get state(){return Ul.getState(this.id)}bezier(e,t,s,n){return Ul.setBezier(this.id,e,t,s,n),this}then(e){return e instanceof Ll?Ul.setSequenceNext(this.id,e.id):Ul.setSequenceNextExternal(this.id,e),this}pause(){Ul.pause(this.id)}resume(){Ul.resume(this.id)}cancel(){Ul.cancel(this.id)}}const $l={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};class Dl{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 e instanceof Ll?(Ul.registerCppSequence(this.entity,e.id),this):(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 Ol=null,Wl=null;function Hl(e,t){Ol=e,Wl=t,Ul.init(e,t)}function Vl(){Ul.shutdown(),Ol=null,Wl=null}function jl(){if(!Ol)throw new Error("Tween API not initialized");return Ol}function Xl(){if(!Wl)throw new Error("Tween API not initialized");return Wl}const Nl={to(e,t,s,n,i,o){const r=jl(),a=Xl(),l=o?.easing??Ml.Linear,c=o?.delay??0,u=o?.loop??Tl.None,h=o?.loopCount??0,d=r._anim_createTween(a,e,t,s,n,i,l,c,u,h);return new Dl(r,a,d)},value(e,t,s,n,i){const o=Ul.create(e,t,s,n,i);return new Ll(o)},cancel(e){jl()._anim_cancelTween(Xl(),e.entity)},cancelAll(e){jl()._anim_cancelAllTweens(Xl(),e)},update(e){jl()._anim_updateTweens(Xl(),e),Ul.update(e)}};class Yl{constructor(){this.name="AnimationPlugin"}build(e){Hl(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(bt.Update,Pt([Ue(Oe)],e=>{Nl.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(bt.Update,Pt([Ue(Oe)],e=>{us(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Vl()}}const ql=new Yl;var Gl;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Gl||(Gl={}));const Kl={model:Gl.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Jl(e,t=Kl){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case Gl.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case Gl.Inverse:a=n/Math.max(r,n);break;case Gl.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Ql(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const Zl=K("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Gl.Inverse,rolloff:1,priority:0,enabled:!0}),ec=K("AudioListener",{enabled:!0});class tc{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const s=t().createAudioBackend(),n=this.config_;s.initialize({initialPoolSize:n.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=s.mixer;hs.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;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(bt.PreUpdate,Pt([Ue(Oe)],t=>{if(!(!wr()||br()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,h=!1;const d=n.getEntitiesWithComponents([ec,de]);for(const e of d){if(n.get(e,ec).enabled){const t=n.get(e,de);i=t.position.x,u=t.position.y,h=!0;break}}const f=n.getEntitiesWithComponents([Zl]);a.clear();for(const e of f){const t=n.get(e,Zl);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&s.isReady){const e=hs.getBufferHandle(t.clip);if(e){const n=s.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,n),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const s=o.get(c);if(!s.isPlaying){o.delete(c);continue}h||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=n.tryGet?.(e,de),a=r?.position.x??0,d=r?.position.y??0,f=a-i,p=d-u,m=Jl(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Ql(a,0,i,0,t.maxDistance);s.setVolume(t.volume*m),s.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),hs.dispose()}}const sc=new tc;let nc=null,ic=null;function oc(e,t){nc=e,ic=t}function rc(){nc=null,ic=null}const ac={update(e){nc&&ic&&nc.particle_update?.(ic,e)},play(e){nc&&ic&&nc.particle_play?.(ic,e)},stop(e){nc&&ic&&nc.particle_stop?.(ic,e)},reset(e){nc&&ic&&nc.particle_reset?.(ic,e)},getAliveCount:e=>nc?nc.particle_getAliveCount?.(e)??0:0};class lc{constructor(){this.name="ParticlePlugin"}build(e){oc(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(bt.Update,Pt([Ue(Oe)],e=>{ac.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){rc()}}const cc=new lc,uc=1e6;class hc{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){vs(e.wasmModule);const t=e.world,s=this.initializedLayers_,n=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(zt),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:uc,l=i?.valid?i.worldTop:uc,c=t.getEntitiesWithComponents([Ps,ue]);for(const e of c){const n=t.tryGet(e,Ps),i=t.tryGet(e,ue);if(!n||!i)continue;if(!n.visible)continue;const c=n.texture;if(!c)continue;const u=ms(c);if(!u)continue;if(!s.has(e)){if(Ss.initLayer(e,n.width,n.height,n.tileWidth,n.tileHeight),n.tiles.length>0){const t=new Uint16Array(n.tiles.length);for(let e=0;e<n.tiles.length;e++)t[e]=n.tiles[e];Ss.setTiles(e,t)}s.add(e)}const h=n.tileWidth/u.width,d=n.tileHeight/u.height,f=n.tint,p=n.parallaxFactor;Ss.submitLayer(e,c,n.layer,0,n.tilesetColumns,h,d,i.worldPosition.x,i.worldPosition.y,o,r,a,l,f.r,f.g,f.b,f.a,n.opacity,p.x,p.y)}const u=t.getEntitiesWithComponents([Ms,ue]);for(const e of u){if(t.tryGet(e,Ps))continue;const i=t.tryGet(e,Ms),c=t.tryGet(e,ue);if(!i?.source||!c)continue;const u=ys(i.source);if(!u)continue;if(!n.has(e)){const t=[];for(let n=0;n<u.layers.length;n++){const i=1073741824+256*e+n,o=u.layers[n];Ss.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&Ss.setTiles(i,o.tiles),t.push(i),s.add(i)}n.set(e,t)}const h=n.get(e);for(let e=0;e<u.layers.length&&e<h.length;e++){const t=h[e],s=u.tilesets[0];if(!s)continue;const n=ms(s.textureHandle);if(!n)continue;const i=u.tileWidth/n.width,d=u.tileHeight/n.height;Ss.submitLayer(t,s.textureHandle,e,0,s.columns,i,d,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)Ss.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),gs(),bs()}}const dc=new hc;function fc(e,t){return e.toFixed(t)}function pc(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class mc{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">${fc(e.fps,1)}</span> Frame: <span style="color:#d19a66">${fc(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>${pc(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${fc(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 gc(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const _c=ze(gc(),"Stats");class yc{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,s){const n={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:s?new Map(s):new Map};this.count_<this.capacity_?(this.buffer_.push(n),this.count_++):this.buffer_[this.cursor_]=n,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const wc="StatsCollect";class xc{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 vc{constructor(e){this.name="Stats",this.collector_=new xc,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(_c,gc());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new mc(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=Pt([Ue(Oe),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(_c);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(wc),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Di.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,s?.update(o)},{name:wc});e.addSystemToSchedule(bt.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const bc=new vc;class Sc{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 Mc(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 Pc(e){const{app:t,module:s,assets:n,scenes:i,firstScene:o}=e,r=t.getResource(yn);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Mc(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 Mc(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new Sc(n);await cl({app:t,module:s,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Tc=[Yo,ar,mr,Dr,qr,Tr,Qr,na,ca,Vr,kr,ha,ma,xa,Sa,Ra,Ia],Ec=[...Tc,ql,sc,cc,dc,Fi];function Cc(e,t){return function(e,t){const s=Zi.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ln(e),Ht(e),ei(e),di(e),Li(e),Wi(e);const i=new ji;s.setPipeline(i);let o=d();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=oo(e,n,t,i));const r=s.getResource(zt);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(zt,{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;Di.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(Di.resize(t,l),s.hasResource(Gi)){const e=s.getResource(Gi).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=oo(e,n,t,l,s.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:n},viewProjection:to,width:t,height:l,elapsed:u});else{i.beginScreenCapture();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:u,cameraEntity:e.entity})}i.endScreenCapture(),Di.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(bt.First,l),s.addSystemToSchedule(bt.Last,c),s.addPlugin(xn),s.addPlugin(In),s.addPlugin(Bt),s.addPlugin(Qi),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Ec,...t})}e=w;export{st as Added,Yl as AnimationPlugin,Zi as App,wn as AssetPlugin,vn as AssetRefCounter,_n as AssetServer,yn as Assets,es as AsyncCache,Gl as AttenuationModel,hs as Audio,p as AudioBus,ec as AudioListener,m as AudioMixer,tc as AudioPlugin,g as AudioPool,Zl as AudioSource,we as BitmapText,Ut as BlendMode,Fe as BodyType,Ae as BoxCollider,hr as Button,ur as ButtonState,pe as Camera,me as Canvas,ke as CapsuleCollider,nt as Changed,ye as Children,Ie as CircleCollider,le as ClearFlags,dt as Commands,pt 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,Gn as DataType,Jr as DragPlugin,Kr as DragState,Gr as Draggable,Wn as Draw,va as Dropdown,ba as DropdownPlugin,Ml as EasingType,ve as EmitterShape,ft as EntityCommands,wt as EventReader,vt as EventReaderInstance,_t as EventRegistry,yt as EventWriter,xt as EventWriterInstance,mo as FillDirection,Br as FillMethod,zr as FillOrigin,Ar as FocusManager,Rr as FocusManagerState,ua as FocusPlugin,Cr as Focusable,yc as FrameHistory,Vi as GLDebug,ni as Geometry,St as GetWorld,L as INVALID_ENTITY,D as INVALID_FONT,O as INVALID_MATERIAL,$ as INVALID_TEXTURE,Ur as Image,$r as ImagePlugin,Fr as ImageType,kt as Input,Ft as InputPlugin,It as InputState,lr as Interactable,Ca as LayoutGroupPlugin,ga as ListView,wa as ListViewPlugin,he as LocalTransform,pl as LogLevel,gl as Logger,Tl as LoopMode,Xt as Material,ts as MaterialLoader,et as Mut,Pe as Name,_e as Parent,ac as Particle,Se as ParticleEasing,Me as ParticleEmitter,lc as ParticlePlugin,tl as Physics,Ga as PhysicsEvents,Za as PhysicsPlugin,mi as PostProcess,ki as PostProcessPlugin,ci as PostProcessStack,Ee as PostProcessVolume,Cn as PrefabServer,Rn as Prefabs,An as PrefabsPlugin,dl as PreviewPlugin,Xr as ProgressBar,jr as ProgressBarDirection,Yr as ProgressBarPlugin,ae as ProjectionType,lt as Query,ct as QueryInstance,ut as Removed,ht as RemovedQueryInstance,ji as RenderPipeline,Bi as RenderStage,fl as RenderTexture,Di as Renderer,Ue as Res,Le as ResMut,Re as RigidBody,F as RuntimeConfig,da as SafeArea,pa as SafeAreaPlugin,ce as ScaleMode,Gi as SceneManager,qi as SceneManagerState,Te as SceneOwner,bt as Schedule,Zr as ScrollView,sa as ScrollViewPlugin,Zt as ShaderSources,be as SimulationSpace,oa as Slider,ia as SliderDirection,la as SliderPlugin,xe as SpineAnimation,fe as Sprite,cs as SpriteAnimator,_c as Stats,xc as StatsCollector,mc as StatsOverlay,vc as StatsPlugin,At as SystemRunner,Vo as Text,Oo as TextAlign,Er as TextInput,Ir as TextInputPlugin,Ho as TextOverflow,No as TextPlugin,jo as TextRenderer,Wo as TextVerticalAlign,Ms as Tilemap,Ss as TilemapAPI,Ps as TilemapLayer,hc as TilemapPlugin,Oe as Time,Or as Toggle,Hr as TogglePlugin,ue as Transform,Nl as Tween,Dl as TweenHandle,Pl as TweenState,$l as TweenTarget,zt as UICameraInfo,dr as UIEventQueue,fr as UIEvents,cr as UIInteraction,Pr as UIInteractionPlugin,pr as UILayoutPlugin,Ko as UIMask,rr as UIMaskPlugin,_o as UIRect,Aa as UIRenderOrderPlugin,ge as Velocity,ul as WebAssetProvider,Ze as World,de as WorldTransform,Ct as addStartupSystem,Et as addSystem,Rt as addSystemToSchedule,ql as animationPlugin,U as applyBuildRuntimeConfig,Mo as applyDirectionalFill,B as applyRuntimeConfig,xn as assetPlugin,sc as audioPlugin,Jl as calculateAttenuation,Ql as calculatePanning,Pi as cleanupAllPostProcessVolumes,Mi as cleanupPostProcessVolume,ls as clearAnimClips,qn as clearDrawCallbacks,gs as clearTextureDimensionsCache,ws as clearTilemapSourceCache,Z as clearUserComponents,j as color,vo as computeFillAnchors,So as computeFillSize,bo as computeHandleAnchors,go as computeUIRectLayout,or as createMaskProcessor,ll as createRuntimeSceneConfig,Cc as createWebApp,xl as debug,gc as defaultFrameStats,K as defineComponent,mt as defineEvent,ze as defineResource,Pt as defineSystem,J as defineTag,Qr as dragPlugin,Sa as dropdownPlugin,Sl as error,ss as extractAnimClipTexturePaths,Ks as findEntityByName,eo as flushPendingSystems,ha as focusPlugin,on as getAddressableType,rn as getAddressableTypeByEditorType,ln as getAllAssetExtensions,xi as getAllEffectDefs,as as getAnimClip,gn as getAssetBuildTransform,dn as getAssetMimeType,sn as getAssetTypeEntry,oe as getComponent,$s as getComponentAssetFieldDescriptors,Ls as getComponentAssetFields,Ce as getComponentDefaults,Hs as getComponentEntityFields,Ds as getComponentSpineFieldDescriptor,un as getCustomExtensions,nn as getEditorType,yi as getEffectDef,wi as getEffectTypes,yl as getLogger,t as getPlatform,n as getPlatformType,ms as getTextureDimensions,ys as getTilemapSource,Q as getUserComponent,hn as getWeChatPackOptions,Dr as imagePlugin,vl as info,Ln as initDrawAPI,Wi as initGLDebugAPI,ei as initGeometryAPI,Ht as initMaterialAPI,oc as initParticleAPI,Pc as initPlayableRuntime,di as initPostProcessAPI,Li as initRendererAPI,cl as initRuntime,vs as initTilemapAPI,Hl as initTweenAPI,Bt as inputPlugin,Sn as instantiatePrefab,Jo as intersectRects,Qo as invertMatrix4,se as isBuiltinComponent,fn as isCustomExtension,wr as isEditor,an as isKnownAssetExtension,s as isPlatformInitialized,br as isPlayMode,xr as isRuntime,Lt as isTextureRef,i as isWeChat,o as isWeb,Ra as layoutGroupPlugin,xa as listViewPlugin,qs as loadComponent,Fa as loadPhysicsModule,al as loadRuntimeScene,Xs as loadSceneData,Ns as loadSceneWithAssets,Bs as loadTiledMap,cn as looksLikeAssetPath,ns as parseAnimClipData,Is as parseTiledMap,Rs as parseTmjJson,cc as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,nr as pointInOBB,er as pointInWorldRect,Fi as postProcessPlugin,In as prefabsPlugin,qr as progressBarPlugin,X as quat,os as registerAnimClip,mn as registerAssetBuildTransform,ie as registerComponent,Us as registerComponentAssetFields,Ws as registerComponentEntityFields,Nn as registerDrawCallback,bn as registerEmbeddedAssets,Qt as registerMaterialCallback,ps as registerTextureDimensions,_s as registerTilemapSource,Vs as remapEntityFields,As as resolveRelativePath,ma as safeAreaPlugin,Qi as sceneManagerPlugin,Zo as screenToWorld,na as scrollViewPlugin,yr as setEditorMode,ya as setListViewRenderer,wl as setLogLevel,vr as setPlayMode,Xe as setWasmErrorHandler,$n as shutdownDrawAPI,Hi as shutdownGLDebugAPI,ti as shutdownGeometryAPI,Vt as shutdownMaterialAPI,rc as shutdownParticleAPI,fi as shutdownPostProcessAPI,$i as shutdownRendererAPI,bs as shutdownTilemapAPI,Vl as shutdownTweenAPI,ca as sliderPlugin,us as spriteAnimatorSystemUpdate,bc as statsPlugin,ko as syncFillSpriteSize,Si as syncPostProcessVolume,kr as textInputPlugin,Yo as textPlugin,dc as tilemapPlugin,pn as toBuildPath,Vr as togglePlugin,ka as transitionTo,Tr as uiInteractionPlugin,mr as uiLayoutPlugin,ar as uiMaskPlugin,Tc as uiPlugins,Ia as uiRenderOrderPlugin,rs as unregisterAnimClip,ee as unregisterComponent,Yn as unregisterDrawCallback,Gs as updateCameraAspectRatio,W as vec2,H as vec3,V as vec4,bl as warn,Ki 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 n(){return null!==e}function s(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,n){return t().fetch(e,n)}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 u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){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),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class g{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 _{constructor(e,t,n,s,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=n,this.poolNode_=s,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_}get isReady(){return"running"===this.context_?.state}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new m(this.context_,e.mixerConfig),this.pool_=new g(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 n=this.loadingUrls_.get(e);if(n)return n;const s=this.doLoadBuffer_(e);this.loadingUrls_.set(e,s);try{return await s}finally{this.loadingUrls_.delete(e)}}async loadBufferFromData(e,t){if(!this.context_)throw new Error("AudioContext not initialized");const n=this.urlToId_.get(e);if(void 0!==n&&this.buffers_.has(n)){return{id:n,duration:this.buffers_.get(n).duration}}let s;try{s=await this.context_.decodeAudioData(t)}catch(t){throw new Error(`Failed to decode audio ${e}: ${t.message}`)}const i=++this.nextBufferId_;return this.buffers_.set(i,s),this.urlToId_.set(e,i),{id:i,duration:s.duration}}async doLoadBuffer_(e){const n=await t().readFile(e);return this.loadBufferFromData(e,n)}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 n=this.buffers_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=this.pool_.acquire(),i=this.context_.createBufferSource();i.buffer=n,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(s.gain),s.source=i,s.gain.gain.value=t.volume??1,s.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;s.panner.connect(r.node);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new _(l,i,n,s,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 n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.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((n,s)=>{t.crossOrigin="anonymous",t.onload=()=>n(),t.onerror=()=>s(new Error(`Failed to load image: ${e}`)),t.src=e});const n=this.createCanvas(t.width,t.height).getContext("2d");n.drawImage(t,0,0);const s=n.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(s.data.buffer)}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},r=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},h=t=>{const n=t;let s=n.deltaX,i=n.deltaY;1===n.deltaMode?(s*=16,i*=16):2===n.deltaMode&&(s*=window.innerWidth,i*=window.innerHeight),e.onWheel(s,i)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",o),n.addEventListener("mousedown",r),document.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",u),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",i),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new y}getStorageItem(e){return localStorage.getItem(e)}setStorageItem(e,t){localStorage.setItem(e,t)}removeStorageItem(e){localStorage.removeItem(e)}clearStorage(e){const t=[];for(let n=0;n<localStorage.length;n++){const s=localStorage.key(n);null!==s&&s.startsWith(e)&&t.push(s)}for(const e of t)localStorage.removeItem(e)}},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 L=0,$=4294967295,D=4294967295,O=0,W=(e=0,t=0)=>({x:e,y:t}),H=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),V=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),j=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),N=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function X(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(X);const t={};for(const n in e)t[n]=X(e[n]);return t}let Y=0;function q(e,t){const n=++Y,s=function(e){for(const t in e){const n=e[t];if(null!==n&&"object"==typeof n)return!0}return!1}(t);return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>s?e?{...X(t),...e}:X(t):e?{...t,...e}:{...t}}}function G(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function K(e,t){const n=se.get(e)??G().get(e);if(n)return n;const s=q(e,t);return G().set(e,s),se.set(e,s),te(e,t,!1),s}function J(e){const t=se.get(e)??G().get(e);if(t)return t;const n=q(e,{});return G().set(e,n),se.set(e,n),te(e,{},!0),n}function Q(e){return G().get(e)}function Z(){const e=G();for(const t of e.keys())se.delete(t);e.clear()}function ee(e){G().delete(e),se.delete(e)}function te(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function ne(e){return!0===e._builtin}const se=new Map;function ie(e,t){se.set(e,t)}function oe(e){return se.get(e)??Q(e)}function re(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return se.set(e,n),n}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},ue=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}}),he=ue,de=ue,fe=re("Sprite",{texture:$,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}}),ge=re("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),_e=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:D,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={Point:0,Circle:1,Rectangle:2,Cone:3},be={World:0,Local:1},Se={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},Me=re("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:ve.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:Se.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:Se.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:$,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:be.World,enabled:!0}),Pe=K("Name",{value:""}),Te=K("SceneOwner",{scene:"",persistent:!1}),Ee=K("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function Ce(e){const t=oe(e);return t?X(t._default):null}const Re=re("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Ae=re("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ie=re("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ke=re("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Fe={Static:0,Kinematic:1,Dynamic:2};let Be=0;function ze(e,t){const n=++Be;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Ue(e){return{_type:"res",_resource:e}}function Le(e){return{_type:"res_mut",_resource:e}}class $e{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 De{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 $e(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Oe=ze({delta:0,elapsed:0,frameCount:0},"Time"),We="esengine:",He={getString(e,n){const s=t().getStorageItem(We+e);return null!==s?s:n},setString(e,n){t().setStorageItem(We+e,n)},getNumber(e,n){const s=t().getStorageItem(We+e);if(null===s)return n;const i=Number(s);return Number.isNaN(i)?n:i},setNumber(e,n){t().setStorageItem(We+e,String(n))},getBoolean(e,n){const s=t().getStorageItem(We+e);return null===s?n:"true"===s},setBoolean(e,n){t().setStorageItem(We+e,String(n))},getJSON(e,n){const s=t().getStorageItem(We+e);if(null===s)return n;try{return JSON.parse(s)}catch{return n}},setJSON(e,n){t().setStorageItem(We+e,JSON.stringify(n))},remove(e){t().removeStorageItem(We+e)},has:e=>null!==t().getStorageItem(We+e),clear(){t().clearStorage(We)}};function Ve(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=je(t[e]),o=je(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function je(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ne(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let Xe=null;function Ye(e){Xe=e}function qe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Xe&&Xe(e,t)}function Ge(e){let t=!1;for(const n of Object.keys(e)){const s=e[n];if(null!=s&&"object"==typeof s&&!Array.isArray(s)){if("r"in s&&"g"in s&&"b"in s&&"a"in s&&!("x"in s)){t=!0;break}}}if(!t)return e;const n={};for(const t of Object.keys(e)){const s=e[t];if(null==s||"object"!=typeof s||Array.isArray(s))n[t]=s;else{const e=s;n[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}:s}}return n}let Ke=1;const Je=new WeakMap;function Qe(e){let t=Je.get(e);return void 0===t&&(t=Ke++,Je.set(e,t)),t}const Ze=[];function et(e,t=[],n=[]){Ze.length=0;for(const t of e)Ze.push(Qe(t));Ze.sort((e,t)=>e-t);let s=Ze.join(",");if(t.length>0){Ze.length=0;for(const e of t)Ze.push(Qe(e));Ze.sort((e,t)=>e-t),s+="|+"+Ze.join(",")}if(n.length>0){Ze.length=0;for(const e of n)Ze.push(Qe(e));Ze.sort((e,t)=>e-t),s+="|-"+Ze.join(",")}return s}class tt{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 qe(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){qe(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,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(n){qe(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){qe(t,`removeParent(entity=${e})`)}}insert(e,t,n){return ne(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(ne(t)){if(this.cppRegistry_)try{const s=t._default,i=n;let o=i;for(const e of Object.keys(i))e in s||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,Ge(o))}catch(n){qe(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return ne(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return ne(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(ne(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return qe(n,`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.");ne(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],o=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"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:s.bind(n),get:i.bind(n),has:o.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s=t._default,i={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(i[e]=t);const e=Ve(t._name,s,i);if(e.length>0)throw new Error(Ne(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,Ge(o))}catch(n){qe(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],o=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))s[n]=i;else{const e=i,t=o;s[n]="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 s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return qe(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return qe(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){qe(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const i=Ve(t._name,t._default,e);if(i.length>0)throw new Error(Ne(t._name,i));s=e}const i=t.create(s),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 n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.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[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of se)if(ne(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e=G();for(const s of n)for(const[n,i]of e)if(i._id===s){t.add(n);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const i=s??et(e,t,n),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(!ne(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,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 s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function nt(e){return{_type:"mut",_component:e}}function st(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function it(e){return{_filterType:"added",_component:e}}function ot(e){return{_filterType:"changed",_component:e}}function rt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function at(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function lt(e){return st(e)||rt(e)||at(e)?e._component:e}function ct(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{st(e)&&s.push(t),rt(e)?i.push({index:t,component:e._component}):at(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>ct(e,[...t,...s],n),without:(...s)=>ct(e,t,[...n,...s])}}function ut(...e){return ct(e)}class ht{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(lt),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_=et(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=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 u of n)if(!o||this.passesChangeFilters_(u)){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]=u;for(let e=0;e<s;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}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,...n]of this)e(t,...n)}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 dt(e){return{_type:"removed",_component:e}}class ft{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n}*[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 pt(){return{_type:"commands"}}class mt{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 n;return n=ne(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),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 gt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new mt(this,null);return this.spawned_.push(e),e}entity(e){return new mt(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,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,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 _t(e){return{_id:Symbol(`Event_${e}`),_name:e}}class yt{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 wt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new yt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new yt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function xt(e){return{_type:"event_writer",_event:e}}function vt(e){return{_type:"event_reader",_event:e}}class bt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class St{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Mt;function Pt(){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"}(Mt||(Mt={}));let Tt=0;function Et(e,t,n){const s=++Tt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Ct(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function Rt(e){Ct().push({schedule:Mt.Update,system:e})}function At(e){Ct().push({schedule:Mt.Startup,system:e})}function It(e,t){Ct().push({schedule:e,system:t})}class kt{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??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 n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);const n=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof gt&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new ht(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 gt(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new bt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new St(n)}case"removed":{const t=e;return new ft(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Ft{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 Bt=ze(new Ft,"Input");class zt{constructor(e){this.target_=e??null}build(e){const n=new Ft;e.insertResource(Bt,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Mt.Last,Et([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ut=new zt,Lt=ze({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 $t;function Dt(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"}($t||($t={}));let Ot=null,Wt=null,Ht=1;const Vt=new Map;function jt(e){Ot=e,Wt=e.getResourceManager(),en()}function Nt(){0!==Gt&&Ot&&(Ot._free(Gt),Gt=0),Vt.clear(),Ht=1,qt=!1,Jt.clear(),Qt=null,Wt=null,Ot=null}function Xt(){if(!Wt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Wt}const Yt={createShader:(e,t)=>Xt().createShader(e,t),releaseShader(e){e>0&&Xt().releaseShader(e)},create(e){const t=Ht++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??$t.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Vt.set(t,n),t},get:e=>Vt.get(e),setUniform(e,t,n){const s=Vt.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,Ot?.invalidateMaterialCache(e))},getUniform(e,t){const n=Vt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Vt.get(e);n&&(n.blendMode=t,Ot?.invalidateMaterialCache(e))},getBlendMode(e){const t=Vt.get(e);return t?.blendMode??$t.Normal},setDepthTest(e,t){const n=Vt.get(e);n&&(n.depthTest=t,Ot?.invalidateMaterialCache(e))},getShader(e){const t=Vt.get(e);return t?.shader??0},release(e){Vt.delete(e),Ot?.invalidateMaterialCache(e)},isValid:e=>Vt.has(e),releaseAll(){Vt.clear(),Ot?.clearMaterialCache()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??$t.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Vt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ht++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Vt.set(n,s),n},toAssetData(e,t){const n=Vt.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=Vt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let qt=!1,Gt=0;const Kt=16384,Jt=new Map;let Qt=null;function Zt(e){const t=(0===Gt&&Ot&&(Gt=Ot._malloc(Kt)),Gt);if(0===t||!Ot)return{ptr:0,count:0};let n=0,s=0;const i=Ot.HEAPU8,o=Ot.HEAPU32,r=Ot.HEAPF32;for(const[a,l]of e){if(Dt(l))continue;let e=Jt.get(a);e||(Qt||(Qt=new TextEncoder),e=Qt.encode(a),Jt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>Kt){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Kt} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function en(){if(!Ot||qt)return;Ot.materialDataProvider=(e,t,n,s,i)=>{const o=Vt.get(e);if(!o)return Ot.HEAPU32[t>>2]=0,Ot.HEAPU32[n>>2]=0,Ot.HEAPU32[s>>2]=0,void(Ot.HEAPU32[i>>2]=0);Ot.HEAPU32[t>>2]=o.shader,Ot.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=Zt(o.uniforms);Ot.HEAPU32[s>>2]=r,Ot.HEAPU32[i>>2]=a},qt=!0}const tn={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 nn{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&(this.failed_.set(e,{error:t,expiry:Date.now()+5e3}),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(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class sn{constructor(e,t=""){this.cache_=new nn,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&&(Yt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Yt.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 n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:Yt.createFromAsset(s,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 n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function on(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function rn(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const an=new Map;function ln(e){an.set(e.name,e)}function cn(e){an.delete(e)}function un(e){return an.get(e)}function hn(){an.clear()}const dn=K("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function fn(e,t){const n=e.getEntitiesWithComponents([dn]);for(const s of n){const n=e.get(s,dn);if(!n.enabled||!n.playing||!n.clip)continue;const i=an.get(n.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*n.speed),r=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let a=r;if(n.frameTimer>=o&&(n.frameTimer-=o,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),a=!0),a&&e.has(s,fe)){const t=i.frames[n.currentFrame],o=e.get(s,fe);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,fe,o)}a&&e.insert(s,dn,n)}}class pn{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 async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:n,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}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 n=this.mixer_?.getBus(e);n&&(n.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,n){e.setVolume(0);const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(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}}}}pn.mixer_=null,pn.bufferCache_=new Map,pn.bgmHandle_=null,pn.bgmVolume_=1,pn.fadeAnimId_=0,pn.disposed_=!1;const mn=new Map,gn=new Map;function _n(e,t,n){mn.set(e,{width:t,height:n})}function yn(e){return mn.get(e)}function wn(){mn.clear()}function xn(e,t){gn.set(e,t)}function vn(e){return gn.get(e)}function bn(){gn.clear()}let Sn=null;function Mn(e){Sn=e}function Pn(){Sn=null}const Tn={initLayer(e,t,n,s,i){Sn?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){Sn?.tilemap_destroyLayer(e)},setTile(e,t,n,s){Sn?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>Sn?Sn.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){Sn?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!Sn)return;const n=t.byteLength,s=Sn._malloc(n);new Uint16Array(Sn.HEAPU8.buffer,s,t.length).set(t),Sn.tilemap_setTiles(e,s,t.length),Sn._free(s)},hasLayer:e=>!!Sn&&Sn.tilemap_hasLayer(e),submitLayer(e,t,n,s,i,o,r,a,l,c,u,h,d,f,p,m,g,_,y,w){Sn?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,u,h,d,f,p,m,g,_,y,w)}},En=K("Tilemap",{source:""}),Cn=K("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function Rn(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function An(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function In(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function kn(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=In(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,h=An(e.tintcolor),d="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l,opacity:u,tintColor:h,parallaxX:d,parallaxY:f})}const u=[],h=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}n.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:n})}if(o)for(const e of o){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.properties;if(n)for(const s of n)"collision"===s.name&&!0===s.value&&h.push(e.id+t)}}return{width:t,height:n,tileWidth:s,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:h}}function Fn(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function Bn(e,t){const n=Sn;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?Rn(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch{return n.tiled_freeMap(r),null}}const zn=Math.PI/180;function Un(e,t,n,s,i,o){const r=function(e,t,n,s){const i=new Uint8Array(t*n),o=[],r=(o,r)=>{if(o>=t||r>=n)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let o=0;o<a;o++)i[(e+n)*t+(s+o)]=1;o.push({col:s,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,u=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=i+t.col*l+.5*n,h=o+(u-t.row*c)-.5*s,d=e.spawn();e.insert(d,ue,{position:{x:r,y:h,z:0}}),e.insert(d,Re,{bodyType:Fe.Static}),e.insert(d,Ae,{halfExtents:{x:.5*n,y:.5*s}}),a.push(d)}return a}function Ln(e,t,n,s={}){const i=[],o=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,ue,{});const l=o?n.get(o.image)??0:0,c=o?.columns??1;e.insert(a,Cn,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),i.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,u=s+(o-l)-.5*t.height,h=-t.rotation*zn;if(e.insert(r,ue,{position:{x:c,y:u,z:0}}),e.insert(r,Re,{bodyType:Fe.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,Ie,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>i&&(i=r),a<s&&(s=a),a>o&&(o=a)}const a=i-n,l=o-s,c=.5*(n+i),u=.5*(s+o);e.insert(r,Ae,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,Ae,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==h){const t=.5*h;e.insert(r,ue,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=Un(e,n,t,a,0,0);i.push(...s)}return i}const $n=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"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function Dn(e,t){$n.set(e,t)}function On(e){const t=$n.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function Wn(e){return $n.get(e)?.fields??[]}function Hn(e){return $n.get(e)?.spine??null}const Vn=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function jn(e,t){Vn.set(e,t)}function Nn(e){return Vn.get(e)}function Xn(e,t){const n=Vn.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const o=t.get(n);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==o?o:0}}}function Yn(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,Pe,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const i of s.components)Xn(i,n),Jn(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function qn(e,t){return Yn(e,t)}async function Gn(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,o=new Map;s&&await async function(e,t,n,s,i){const o=new Map;for(const e of Kn.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=$n.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Kn.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),i){for(const e of s.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=$n.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,o,n?.collectAssets);const r=Yn(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const Kn=new Map([["texture",{async load(e,t,n,s){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o),_n(r.handle,r.width,r.height)}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,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=on(i),r=new Map,a=o.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);ln(rn(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,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await pn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=kn(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=Fn(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),_n(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}xn(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Jn(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=oe(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function Qn(e,t){const n=e.getEntitiesWithComponents([pe]);for(const s of n){const n=e.get(s,pe);n&&(n.aspectRatio=t,e.insert(s,pe,n))}}function Zn(e,t){const n=e.getEntitiesWithComponents([Pe]);for(const s of n){const n=e.get(s,Pe);if(n&&n.value===t)return s}return null}const es=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],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},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],ts={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",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",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"},ns=new Map,ss=new Set;for(const e of es)for(const t of e.extensions)ns.set(t,e),ss.add(t);function is(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function os(e){return ns.get(is(e))}function rs(e){return os(e)?.editorType??"unknown"}function as(e){return os(e)?.addressableType??null}function ls(e){for(const t of es)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function cs(e){return ss.has(e.toLowerCase())}function us(){return ss}function hs(e){return"string"==typeof e&&(!!e.includes("/")&&cs(is(e)))}function ds(){const e=[];for(const t of es)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function fs(){return ds().map(e=>({type:"suffix",value:e}))}function ps(e){return ts[e.toLowerCase()]}function ms(e){const t=os(e);return t?.wechatPackInclude??!1}function gs(e){const t=os(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}function _s(e,t){for(const n of es)n.editorType===e&&(n.buildTransform=t)}function ys(e){return os(e)?.buildTransform}class ws{constructor(e){this.textureCache_=new nn,this.shaderCache_=new nn,this.jsonCache_=new nn,this.textCache_=new nn,this.binaryCache_=new nn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new nn,this.prefabCache_=new nn,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_=h(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 sn(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);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 n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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(),Yt.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 n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),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,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===os(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,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 n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=os(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}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),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const i=n?`${n}/${s}`:s;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,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 n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of On(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=Hn(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.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 n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Gn(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.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},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"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 n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((n,s)=>{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 n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,n,s,t):this.createTextureFallback(e,n,s,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,n,s,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,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),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,n),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,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return Yt.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return Yt.createShader(i,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.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(gs(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.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 n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let i="";for(const e of s){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 n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const xs=ze(null,"Assets");class vs{build(e){const t=e.wasmModule;t?e.insertResource(xs,new ws(t)):console.warn("AssetPlugin: No WASM module available")}}const bs=new vs;class Ss{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.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 n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.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 n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.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,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});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 Ms(e,t){const n=e.getResource(xs);n&&n.registerEmbeddedAssets(t)}async function Ps(e,t,n){const{entities:s,rootId:i}=await Es(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},r=await Gn(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=r.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:r}}const Ts=10;async function Es(e,t,n,s,i,o=0){if(o>Ts)throw new Error(`Prefab nesting depth exceeded ${Ts}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===s){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=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Es(e,s.nestedPrefab.overrides,n,a,i,o+1);r.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?r.get(s.parent)??null:null),l.push(...t.entities);continue}const c=r.get(s.prefabEntityId),u=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:u?null:null!==s.parent?r.get(s.parent)??null:null,children:s.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Cs(h.components,r),Rs(h,t),l.push(h)}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 Cs(e,t){for(const n of e){const e=Nn(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function Rs(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class As{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Ps(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Is=ze(null,"Prefabs");class ks{constructor(){this.name="PrefabsPlugin",this.dependencies=[xs]}build(e){const t=e.getResource(xs);e.insertResource(Is,new As(e.world,t))}}const Fs=new ks;let Bs=null,zs=0,Us=0,Ls=0;const $s=new Float32Array(256);function Ds(e){Bs=e,zs=Bs._malloc(64),Us=Bs._malloc(64),Ls=Bs._malloc(1024)}function Os(){Bs&&(zs&&(Bs._free(zs),zs=0),Us&&(Bs._free(Us),Us=0),Ls&&(Bs._free(Ls),Ls=0)),Bs=null}function Ws(){if(!Bs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Bs}const Hs={r:1,g:1,b:1,a:1},Vs={begin(e){const t=Ws();try{t.HEAPF32.set(e,zs/4),t.draw_begin(zs)}catch(e){qe(e,"Draw.begin")}},end(){try{Ws().draw_end()}catch(e){qe(e,"Draw.end")}},line(e,t,n,s=1){try{Ws().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){qe(e,"Draw.line")}},rect(e,t,n,s=!0){try{Ws().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){qe(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{Ws().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){qe(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{Ws().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){qe(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{Ws().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){qe(e,"Draw.circleOutline")}},texture(e,t,n,s=Hs){try{Ws().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){qe(e,"Draw.texture")}},textureRotated(e,t,n,s,i=Hs){try{Ws().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){qe(e,"Draw.textureRotated")}},setLayer(e){Ws().draw_setLayer(e)},setDepth(e){Ws().draw_setDepth(e)},getDrawCallCount:()=>Bs?Bs.draw_getDrawCallCount():0,getPrimitiveCount:()=>Bs?Bs.draw_getPrimitiveCount():0,setBlendMode(e){Ws().draw_setBlendMode(e)},setDepthTest(e){Ws().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=Ws();s.HEAPF32.set(n,Us/4),s.draw_mesh(e,t,Us)}catch(n){qe(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Ws(),i=Yt.get(t);if(!i)return;if(Vs.setBlendMode(i.blendMode),Vs.setDepthTest(i.depthTest),0===i.uniforms.size)return void Vs.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,Us/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=Xs(t);if(!(s<0)){if(Dt(n))$s[o++]=10,$s[o++]=s,$s[o++]=n.slot??e++,$s[o++]=n.textureId;else if("number"==typeof n)$s[o++]=1,$s[o++]=s,$s[o++]=n;else if(Array.isArray(n)){$s[o++]=n.length,$s[o++]=s;for(let e=0;e<n.length;e++)$s[o++]=n[e]}else"w"in n?($s[o++]=4,$s[o++]=s,$s[o++]=n.x,$s[o++]=n.y,$s[o++]=n.z,$s[o++]=n.w):"z"in n?($s[o++]=3,$s[o++]=s,$s[o++]=n.x,$s[o++]=n.y,$s[o++]=n.z):($s[o++]=2,$s[o++]=s,$s[o++]=n.x,$s[o++]=n.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($s.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,Us);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Ls/4),s.draw_meshWithUniforms(e,i.shader,Us,Ls,o)}catch(n){qe(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},js={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},Ns=new Set;function Xs(e){const t=js[e];return void 0!==t?t:(Ns.has(e)||(Ns.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(js).join(", ")}`)),-1)}const Ys=new Map;function qs(e,t,n){Ys.set(e,{fn:t,scene:n??""})}function Gs(e){Ys.delete(e)}function Ks(){Ys.clear()}var Js;!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"}(Js||(Js={}));let Qs=null,Zs=0,ei=0,ti=0;function ni(e){Qs=e,Zs=Qs._malloc(262144),ei=Qs._malloc(65536),ti=Qs._malloc(256)}function si(){Qs&&(Zs&&Qs._free(Zs),ei&&Qs._free(ei),ti&&Qs._free(ti),Zs=0,ei=0,ti=0),Qs=null}function ii(){if(!Qs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Qs}const oi={create(e){const t=ii(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Zs/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,ti,i).set(o),t.geometry_init(n,Zs,s,ti,i,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,ei,s).set(e.indices),t.geometry_setIndices16(n,ei,s)}else{new Uint32Array(t.HEAPU8.buffer,ei,s).set(e.indices),t.geometry_setIndices32(n,ei,s)}}return n},updateVertices(e,t,n=0){const s=ii(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,Zs/4),s.geometry_updateVertices(e,Zs,i,n)},release(e){e>0&&ii().geometry_release(e)},isValid:e=>!(!Qs||e<=0)&&Qs.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return oi.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:Js.Float2},{name:"a_texCoord",type:Js.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const i=s/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;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return oi.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Js.Float2},{name:"a_texCoord",type:Js.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,i=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);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 oi.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Js.Float2},{name:"a_texCoord",type:Js.Float2}],indices:new Uint16Array(r)})}};let ri=1;const ai=new Map,li=new Map;function ci(){return ai}function ui(){return li}class hi{constructor(){this.passes_=[],this.destroyed_=!1,this.id=ri++,ai.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of li)t===this&&li.delete(e);ai.delete(this.id)}}}const di="#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";let fi=null;function pi(e){fi=e}function mi(){for(const e of ci().values())e.destroy();ci().clear(),ui().clear(),fi&&_i.isInitialized()&&_i.shutdown(),fi=null}function gi(){if(!fi)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return fi}const _i={createStack:()=>new hi,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");ui().set(e,t)},unbind(e){ui().delete(e)},getStack:e=>ui().get(e)??null,init(e,t){try{return gi().postprocess_init(e,t)}catch(n){return qe(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{gi().postprocess_shutdown()}catch(e){qe(e,"PostProcess.shutdown")}},resize(e,t){try{gi().postprocess_resize(e,t)}catch(n){qe(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!fi)return!1;try{return fi.postprocess_isInitialized()}catch(e){return qe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{gi().postprocess_setBypass(e)}catch(e){qe(e,"PostProcess.setBypass")}},setOutputViewport(e,t,n,s){try{gi().postprocess_setOutputViewport(e,t,n,s)}catch(e){qe(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=ui().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(_i.isInitialized()||_i.init(1,1),_i.setBypass(!1),function(e){const t=gi();try{t.postprocess_clearPasses()}catch(e){return void qe(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){qe(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){qe(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){qe(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):_i.setBypass(!0)},_resetAfterCamera(){try{gi().postprocess_clearPasses(),gi().postprocess_setBypass(!0)}catch(e){qe(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of ui().keys())e(t)||ui().delete(t)},screenStack:null,setScreenStack(e){_i.screenStack=e},_beginScreenCapture(){try{gi().postprocess_beginScreenCapture()}catch(e){qe(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{gi().postprocess_endScreenCapture()}catch(e){qe(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=_i.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=gi();try{t.postprocess_clearScreenPasses()}catch(e){return void qe(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){qe(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){qe(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){qe(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{gi().postprocess_executeScreenPasses()}catch(e){qe(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Yt.createShader(di,"#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:()=>Yt.createShader(di,"#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:()=>Yt.createShader(di,"#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"),createBloom:()=>Yt.createShader(di,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>Yt.createShader(di,"#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")},yi=new Map;function wi(e){yi.set(e.type,e)}function xi(e){return yi.get(e)}function vi(){return Array.from(yi.keys())}function bi(){return Array.from(yi.values())}wi({type:"blur",label:"Blur",factory:()=>_i.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),wi({type:"bloom",label:"Bloom",factory:()=>_i.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),wi({type:"vignette",label:"Vignette",factory:()=>_i.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),wi({type:"grayscale",label:"Grayscale",factory:()=>_i.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),wi({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>_i.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const Si=new Map,Mi=new Map;function Pi(e,t){let n=Si.get(e),s=Mi.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=_i.createStack(),Si.set(e,n)),s||(s=new Map,Mi.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=xi(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}_i.bind(e,n)}else if(n&&(_i.unbind(e),n.destroy(),Si.delete(e)),s){for(const e of s.values())Yt.releaseShader(e);Mi.delete(e)}}function Ti(e){const t=Si.get(e);t&&(_i.unbind(e),t.destroy(),Si.delete(e));const n=Mi.get(e);if(n){for(const e of n.values())Yt.releaseShader(e);Mi.delete(e)}}function Ei(){for(const e of Si.keys())Ti(e)}const Ci=ze({enabled:!0},"PostProcessVolumeConfig"),Ri=new Map,Ai=new Map;function Ii(e){const t=Ai.get(e);if(void 0!==t)return t;const n=xi(e);if(!n)return null;const s=n.factory();return Ai.set(e,s),s}function ki(e,t){if(0===t.size){const t=Ri.get(e);return void(t&&(_i.unbind(e),t.destroy(),Ri.delete(e)))}let n=Ri.get(e);for(n||(n=_i.createStack(),Ri.set(e,n));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const[e,s]of t){if(!s.enabled)continue;const t=Ii(e);if(null!==t){n.addPass(e,t);for(const[t,i]of s.uniforms)n.setUniform(e,t,i)}}n.enabledPassCount>0?_i.bind(e,n):_i.unbind(e)}const Fi=Et([ut(Ee,ue)],e=>{const t=[];for(const[n,s,i]of e)t.push({data:s,tx:{x:i.position.x,y:i.position.y}});if(0===t.length)return;const n=[];for(const{data:e,tx:s}of t)e.isGlobal&&n.push({data:e,factor:1});if(n.length>0){const e=function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,i]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(i-n)*s)}else{const e=new Map;for(const[t,i]of Object.entries(n.uniforms))e.set(t,i*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(n);for(const[t]of Ri)ki(t,e)}},{name:"PostProcessVolumeSystem"});class Bi{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(Ci,{enabled:!0}),e.addSystemToSchedule(Mt.PostUpdate,Fi)}cleanup(){Ei(),function(){for(const[e,t]of Ri)_i.unbind(e),t.destroy();Ri.clear();for(const e of Ai.values())Yt.releaseShader(e);Ai.clear()}(),_i.setScreenStack(null)}}const zi=new Bi;var Ui;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ui||(Ui={}));let Li=null,$i=0;function Di(e){Li=e,$i=Li._malloc(64)}function Oi(){Li&&$i&&(Li._free($i),$i=0),Li=null}const Wi={init(e,t){Li?.renderer_init(e,t)},resize(e,t){Li?.renderer_resize(e,t)},begin(e,t){if(Li&&$i)try{Li.HEAPF32.set(e,$i/4),Li.renderer_begin($i,t??0)}catch(e){qe(e,"Renderer.begin")}},flush(){try{Li?.renderer_flush()}catch(e){qe(e,"Renderer.flush")}},end(){try{Li?.renderer_end()}catch(e){qe(e,"Renderer.end")}},submitSprites(e){if(Li)try{Li.renderer_submitSprites(e._cpp)}catch(e){qe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Li)try{Li.renderer_submitBitmapText(e._cpp)}catch(e){qe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Li)try{Li.renderer_submitSpine?.(e._cpp)}catch(e){qe(e,"Renderer.submitSpine")}},submitParticles(e){if(Li)try{Li.renderer_submitParticles?.(e._cpp)}catch(e){qe(e,"Renderer.submitParticles")}},setStage(e){Li?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Li?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Li?.renderer_releaseTarget(e)},getTargetTexture:e=>Li?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Li?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Li?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Li?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Li?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Li?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Li?Li.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Li?{drawCalls:Li.renderer_getDrawCalls(),triangles:Li.renderer_getTriangles(),sprites:Li.renderer_getSprites(),text:Li.renderer_getText(),spine:Li.renderer_getSpine?.()??0,meshes:Li.renderer_getMeshes(),culled:Li.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Hi=null;function Vi(e){Hi=e}function ji(){Hi=null}const Ni={enable(){Hi?.gl_enableErrorCheck(!0)},disable(){Hi?.gl_enableErrorCheck(!1)},check:e=>Hi?.gl_checkErrors(e)??0,diagnose(){Hi?.renderer_diagnose()}};class Xi{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}beginScreenCapture(){_i.screenStack&&_i.screenStack.enabledPassCount>0&&(_i.isInitialized()||_i.init(1,1),_i._applyScreenStack(),_i._beginScreenCapture())}endScreenCapture(){_i.screenStack&&_i.screenStack.enabledPassCount>0&&(_i._endScreenCapture(),_i._executeScreenPasses())}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(Wi.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Wi.setViewport(0,0,s,i),Wi.clearBuffers(3),Wi.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),this.tilemapRenderer_&&this.tilemapRenderer_(),Wi.submitSprites(t),Wi.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Wi.submitSpine(t),Wi.submitParticles(t),Wi.flush(),this.executeDrawCallbacks(n,o),Wi.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==_i.getStack(r);a&&(_i._applyForCamera(r),_i.resize(s.w,s.h),_i.setOutputViewport(s.x,s.y,s.w,s.h)),Wi.setViewport(s.x,s.y,s.w,s.h),Wi.setScissor(s.x,s.y,s.w,s.h,!0),Wi.clearBuffers(i),Wi.setScissor(0,0,0,0,!1),Wi.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),this.tilemapRenderer_&&this.tilemapRenderer_(),Wi.submitSprites(t),Wi.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Wi.submitSpine(t),Wi.submitParticles(t),Wi.flush(),this.executeDrawCallbacks(n,o),Wi.end(),a&&_i._resetAfterCamera()}executeDrawCallbacks(e,t){const n=Ys;if(n.size>0){Vs.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Vs.end();for(const e of s)Gs(e)}}}const Yi="__scene_transition_overlay__";class qi{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Gi{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,Te,{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),qs(e,t,this.instance_.config.name)}bindPostProcess(e,t){_i.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){_i.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,Te)){const n=this.app_.world.get(e,Te);n.persistent=t,this.app_.world.insert(e,Te,n)}}}class Ki{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}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())Gs(t);for(const t of e.postProcessBindings.keys())_i.unbind(t)}this.transition_&&(Gs(Yi),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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(n=>{const s=t.duration??F.sceneTransitionDuration,i=t.color??{...F.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},qs(Yi,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;Vs.setLayer(9999),Vs.setDepth(9999),Vs.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:n})})})}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_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,Gs(Yi),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Gs(Yi),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 n=new qi(t);this.scenes_.set(e,n);const s=new Gi(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(xs)?this.app_.getResource(xs):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();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 n=new qi(t);this.scenes_.set(e,n);const s=new Gi(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(xs)?this.app_.getResource(xs):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,Te)){if(this.app_.world.get(e,Te).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Gs(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())_i.unbind(e);n.postProcessBindings.clear(),this.releaseSceneAssets_(n),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,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(xs)&&(i.assetServer=this.app_.getResource(xs));const o=await Gn(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,Te,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Qi(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(xs)?this.app_.getResource(xs):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)Yt.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 n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,fe)){const t=n.get(e,fe);s.sprite=t.color.a,t.color.a=0,n.insert(e,fe,t),i=!0}if(n.has(e,xe)){const t=n.get(e,xe);s.spine=t.color.a,t.color.a=0,n.insert(e,xe,t),i=!0}if(n.has(e,we)){const t=n.get(e,we);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,we,t),i=!0}i&&t.savedAlphas.set(e,s)}}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 n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,fe)){const t=n.get(e,fe);t.color.a=s.sprite,n.insert(e,fe,t)}if(void 0!==s.spine&&n.has(e,xe)){const t=n.get(e,xe);t.color.a=s.spine,n.insert(e,xe,t)}if(void 0!==s.bitmapText&&n.has(e,we)){const t=n.get(e,we);t.color.a=s.bitmapText,n.insert(e,we,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}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,n]of this.scenes_)"running"===n.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 Ji=ze(null,"SceneManager");function Qi(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Ji).getSceneStatus(t)&&n._fn(...s)}}}const Zi=Et([Le(Ji),Ue(Oe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),eo={name:"SceneManager",build(e){const t=new Ki(e);e.insertResource(Ji,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ji),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Mt.Startup,n),e.addSystemToSchedule(Mt.Last,Zi)}};class to{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 wt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Mt.Last);else{this.runSchedule(Mt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Mt.FixedPreUpdate),this.runSchedule(Mt.FixedUpdate),this.runSchedule(Mt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Mt.PreUpdate),this.runSchedule(Mt.Update),this.runSchedule(Mt.PostUpdate),this.runSchedule(Mt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new tt,this.resources_=new De;for(const e of Object.values(Mt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new to}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,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Mt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Mt.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),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 Ye(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.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}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(Ji).register(e),this}setInitialScene(e){return this.getResource(Ji).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new kt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(Oe)||this.resources_.insert(Oe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Mt.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(Mt.Last);else{this.runSchedule(Mt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Mt.FixedPreUpdate),this.runSchedule(Mt.FixedUpdate),this.runSchedule(Mt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Mt.PreUpdate),this.runSchedule(Mt.Update),this.runSchedule(Mt.PostUpdate),this.runSchedule(Mt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new kt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(Oe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Mt.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Ks();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=[ji,Oi,mi,si,Nt,Os];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 n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.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 n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const s=this.phaseTimings_?performance.now():0;for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}this.phaseTimings_&&this.phaseTimings_.set(Mt[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(Oe);t.delta=e,t.elapsed+=e,t.frameCount++}}function no(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const so=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function io(e,t,n,s,i){const o=e*t/n,r=e;switch(s){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 oo=[];function ro(e){if(e<oo.length)return oo[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 oo.push(t),t}function ao(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,Te);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*n/(i.viewportH*s);let a,u=0,h=0;if(i.projectionType===ae.Orthographic){if(h=i.orthoSize,l){h=io(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=h*r,a=co(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=ho(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const d=po(o.position.x,o.position.y,o.position.z),f=ro(c.length);f.entity=e,f.viewProjection.set(go(a,d)),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=u,f.halfH=h,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const lo=new Float32Array(16);function co(e,t,n,s,i,o){const r=lo;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const uo=new Float32Array(16);function ho(e,t,n,s){const i=uo;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const fo=new Float32Array(16);function po(e,t,n){const s=fo;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const mo=new Float32Array(16);function go(e,t){const n=mo;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const _o={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function yo(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,h=o.bottom+e.y*l,d=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*r.x,m=f+i.x):(f=c+n.x,m=u+s.x),e.y===t.y?(p=h+n.y-i.y*r.y,g=p+i.y):(p=h+n.y,g=d+s.y);const _=Math.max(0,m-f),y=Math.max(0,g-p);return{originX:f+r.x*_,originY:p+r.y*y,width:_,height:y,rect:{left:f,bottom:p,right:m,top:g}}}const wo=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 xo=null,vo=null;function bo(e,t){e.has(t,fe)||e.insert(t,fe,{texture:$,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 So(e,t){switch(e){case _o.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case _o.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case _o.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 Mo(e,t){switch(e){case _o.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case _o.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case _o.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 Po(e,t,n,s){switch(e){case _o.BottomToTop:case _o.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function To(e,t,n,s){if(!e.has(t,wo))return;const i=e.get(t,wo),o=So(n,s);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,wo,i)}function Eo(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Co(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Ro(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if(Co(r.charCodeAt(0))&&s.length>0&&Co(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Co(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Ao(e){let t=1;for(;t<e;)t*=2;return t}function Io(e,t){let n=0,s=t;for(;e.has(s,_e);){const t=e.get(s,_e).entity;if(!e.valid(t))break;n++,s=t}return n}function ko(e,t){if(xo&&vo){const e=xo.getUIRectComputedWidth(vo,t);if(e>0)return e}return e.size.x}function Fo(e,t){if(xo&&vo){const e=xo.getUIRectComputedHeight(vo,t);if(e>0)return e}return e.size.y}function Bo(e,t,n,s,i,o){if(!e.has(t,fe))return;const r=e.get(t,fe);let a,l;switch(n){case _o.BottomToTop:case _o.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,fe,r))}function zo(e,t,n){let s=t;for(;e.has(s,_e);){const t=e.get(s,_e).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Uo(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Lo(e,t,n,s,i){if(!e.has(t,wo))return;const o=e.get(t,wo),r=yo(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,n,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,fe)){const n=e.get(t,fe);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,fe,n))}if(e.has(t,ue)){const n=e.get(t,ue);n.position.x=r.originX-s,n.position.y=r.originY-i,e.insert(t,ue,n)}}function $o(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const Do=.1,Oo=30,Wo={r:.3,g:.5,b:.8,a:1},Ho={Left:0,Center:1,Right:2},Vo={Top:0,Middle:1,Bottom:2},jo={Visible:0,Clip:1,Ellipsis:2},No=K("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ho.Left,verticalAlign:Vo.Top,wordWrap:!0,overflow:jo.Visible,lineHeight:1.2});class Xo{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(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,Ao(this.frameMaxW_)),e.height=Math.max(e.height,Ao(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ao(this.frameMaxW_),e.height=Ao(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 n=this.ctx,s=this.canvas;n.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=Ro(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=i?Math.ceil(o):h+2*u,p=i?Math.ceil(r):d+2*u;if(i&&e.overflow===jo.Ellipsis&&d>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),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Ao(f)),s.height=Math.max(s.height,Ao(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),_=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${_}, ${y})`,i&&e.overflow===jo.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case Vo.Top:x=u;break;case Vo.Middle:x=u+(p-2*u-w)/2;break;case Vo.Bottom:x=p-w-u;break;default:x=u}x<0&&(x=0)}else x=u;let v=x;for(const t of l){let s;switch(e.align){case Ho.Left:s=u;break;case Ho.Center:s=f/2;break;case Ho.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}i&&e.overflow===jo.Clip&&n.restore();const b=n.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 n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const i=this.renderText(t,n);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[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}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 n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case Ho.Left:return"left";case Ho.Center:return"center";case Ho.Right:return"right"}}}const Yo=$o({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?ko(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Fo(e.uiRect,e.entity):0});class qo{build(e){ie("Text",No);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Xo(t),s=e.world,i=new Map;e.addSystemToSchedule(Mt.PreUpdate,Et([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,No));for(const e of i.keys())if(!s.valid(e)||!s.has(e,No)){if(s.valid(e)&&s.has(e,fe)){const t=s.get(e,fe);s.insert(e,fe,{texture:$,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=s.getEntitiesWithComponents([No]);for(const t of e){const e=s.get(t,No),o=s.has(t,wo)?s.get(t,wo):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Yo.changed(a,r)){if(s.has(t,fe)&&s.get(t,fe).texture!==$)continue}bo(s,t);const l=o?{size:{x:ko(o,t),y:Fo(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,fe);s.insert(t,fe,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,Yo.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Go=new qo,Ko=0,Jo=1,Qo=re("UIMask",{enabled:!0,mode:Ko});function Zo(e,t){const n=Math.max(e.x,t.x),s=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:n,y:s,w:Math.max(0,i-n),h:Math.max(0,o-s)}}function er(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],g=e[13],_=e[14],y=e[15],w=s*l-i*a,x=s*c-o*a,v=s*u-r*a,b=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=h*g-d*m,T=h*_-f*m,E=h*y-p*m,C=d*_-f*g,R=d*y-p*g,A=f*y-p*_;let I=w*A-x*R+v*C+b*E-S*T+M*P;return 0===I||(I=1/I,n[0]=(l*A-c*R+u*C)*I,n[1]=(o*R-i*A-r*C)*I,n[2]=(g*M-_*S+y*b)*I,n[3]=(f*S-d*M-p*b)*I,n[4]=(c*E-a*A-u*T)*I,n[5]=(s*A-o*E+r*T)*I,n[6]=(_*v-m*M-y*x)*I,n[7]=(h*M-f*v+p*x)*I,n[8]=(a*R-l*E+u*P)*I,n[9]=(i*E-s*R-r*P)*I,n[10]=(m*S-g*v+y*w)*I,n[11]=(d*v-h*S-p*w)*I,n[12]=(l*T-a*C-c*P)*I,n[13]=(s*C-i*T+o*P)*I,n[14]=(g*x-m*b-_*w)*I,n[15]=(h*b-d*x+f*w)*I),n}function tr(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function nr(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function sr(e,t){return 2*Math.atan2(e,t)}function ir(e,t,n,s,i,o,r){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function or(e,t,n,s,i,o,r,a,l,c){const u=sr(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-n,p=t-s,m=f*d-p*h+n,g=f*h+p*d+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}function rr(e,t,n,s,i,o,r){if(!e.has(t,wo)||!e.has(t,ue))return null;const a=e.get(t,wo),l=e.get(t,ue),c=ko(a,t)*l.worldScale.x,u=Fo(a,t)*l.worldScale.y,h=l.worldPosition.x,d=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,g=c*(1-f),_=-u*p,y=u*(1-p),w=sr(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+m*x-_*v,d+m*v+_*x],[h+g*x-_*v,d+g*v+_*x],[h+g*x-y*v,d+g*v+y*x],[h+m*x-y*v,d+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]=ir(e,t,n,s,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 ar(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Qo]);if(0===l.length)return;const c=[],u=[],h=new Set,d=new Set;for(const e of l){const n=t.get(e,Qo);n.enabled&&(h.add(e),n.mode===Jo?(u.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,o,r,a,l,c){const u=[];for(const e of s){let n=!0;zo(t,e,e=>{if(i.has(e)){if(t.get(e,Qo).mode===Ko)return n=!1,!0}return!1}),n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(i.has(n)){if(t.get(n,Qo).mode===Ko){const e=rr(t,n,o,r,a,l,c);e&&(s=Zo(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=rr(t,e,o,r,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,o,r,a),u.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0;zo(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&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,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,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,s),u(t,s)}function u(t,s){if(a)return;const o=e.getChildEntities(n,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,s),u(t,s)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,u,d)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class lr{build(e){if(ie("UIMask",Qo),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ar(e.wasmModule,e.world))}}const cr=new lr,ur=re("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),hr=re("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),dr={Normal:0,Hovered:1,Pressed:2,Disabled:3},fr=K("Button",{state:dr.Normal,transition:null});class pr{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,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(n=>n.entity===e&&n.type===t)}}const mr=ze(new pr,"UIEvents");class gr{build(e){ie("UIRect",wo);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){xo=e,vo=t}(n,s);e.addSystemToSchedule(Mt.PreUpdate,Et([Ue(Lt)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s),n.transform_update(s))},{name:"UILayoutSystem"})),e.addSystemToSchedule(Mt.PostUpdate,Et([Ue(Lt)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(Mt.PostUpdate,Et([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const _r=new gr;let yr=!1,wr=!1;function xr(e){yr=e}function vr(){return yr}function br(){return!yr}function Sr(e){wr=e}function Mr(){return wr}const Pr=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(er(t,e),n=!1),e)}}();function Tr(e,t,n,s){t.emit(n,s,n),zo(e,n,i=>{if(!e.has(i,ur))return!1;const o=e.get(i,ur);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class Er{build(e){ie("Interactable",ur),ie("Button",fr);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new pr;e.insertResource(mr,i);let o=null,r=null;e.addSystemToSchedule(Mt.PreUpdate,Et([Ue(Bt),Ue(Lt)],(e,a)=>{if(i.drain(),vr()&&!Mr())return;const l=t.getEntitiesWithComponents([hr]);for(const e of l){const n=t.get(e,hr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,hr,n))}if(!a.valid)return;const c=f(),u=e.mouseX*c,h=a.screenH-e.mouseY*c;Pr.update(a.viewProjection);const d=tr(u,h,Pr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=d.x,a.worldMouseY=d.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);n.uiHitTest_update(s,d.x,d.y,p,m,g);const _=n.uiHitTest_getHitEntity(),y=4294967295===_?null:_;if(null===o||t.valid(o)||(o=null),o!==y){if(null!==o&&t.valid(o)&&t.has(o,hr)){const e=t.get(o,hr);e.hovered=!1,t.insert(o,hr,e),i.emit(o,"hover_exit")}if(null!==y){Uo(t,y,hr);const e=t.get(y,hr);e.hovered=!0,t.insert(y,hr,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,hr);e.pressed=!0,e.justPressed=!0,t.insert(y,hr,e),r=y,Tr(t,i,y,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,hr)){const e=t.get(r,hr);e.pressed=!1,e.justReleased=!0,t.insert(r,hr,e),Tr(t,i,r,"release"),r===o&&Tr(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(Mt.Update,Et([],()=>{const e=t.getEntitiesWithComponents([fr]);for(const n of e){if(Uo(t,n,ur,{enabled:!0}),!t.has(n,hr))continue;const e=t.get(n,hr),s=t.get(n,fr),i=t.get(n,ur),o=!a.has(n),r=s.state;if(i.enabled?e.pressed?s.state=dr.Pressed:e.hovered?s.state=dr.Hovered:s.state=dr.Normal:s.state=dr.Disabled,o&&a.add(n),(o||r!==s.state)&&s.transition&&t.has(n,fe)){const o=t.get(n,fe);o.color=Eo(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,fe,o)}}},{name:"ButtonSystem"}))}}const Cr=new Er,Rr=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}),Ar=K("Focusable",{tabIndex:0,isFocused:!1});class Ir{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 kr=ze(new Ir,"FocusManager");class Fr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ie("TextInput",Rr),vr()&&!Mr())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=h(F.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,u=0,d=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(kr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Rr)?s:null}const g=()=>{l||null===m()||v()},_=()=>{l=!0},y=()=>{l=!1,v()},w=t=>{const s=m();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,Rr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(mr).emit(s,"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 s=n.get(t,Rr);s.focused=!1,s.dirty=!0;e.getResource(kr).blur()}};function v(){const t=m();if(null===t)return;const s=n.get(t,Rr);if(s.readOnly)return;let i=p.value;if(s.maxLength>0&&i.length>s.maxLength&&(i=i.substring(0,s.maxLength),p.value=i),i!==s.value){s.value=i;e.getResource(mr).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=n.get(t,Rr);e.focused=!1,e.dirty=!0}e.getResource(kr).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",g),p.addEventListener("compositionstart",_),p.addEventListener("compositionend",y),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",_),p.removeEventListener("compositionend",y),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,u,h){(i.width<u||i.height<h)&&(i.width=Ao(Math.max(i.width,u)),i.height=Ao(Math.max(i.height,h))),o.clearRect(0,0,i.width,i.height);const d=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,o.fillRect(0,0,u,h),o.save(),o.beginPath(),o.rect(l.padding,0,u-2*l.padding,h),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 g=Math.ceil(1.2*l.fontSize),_=l.padding;if(l.multiline){const e=Ro(o,p,u-2*_);let t=_;for(const n of e)o.fillText(n,_,t),t+=g}else{const e=(h-l.fontSize)/2;o.fillText(p,_,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=Ro(o,l.value,u-2*_);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=n,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=_+o.measureText(c).width,n=_+r*g,s=g}else t=_+o.measureText(e).width,n=(h-l.fontSize)/2,s=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,n,2,s)}o.restore();const y=o.getImageData(0,0,u,h),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=s.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(u,h,r,w.length,1,!0);s.set(e,b);const S=n.get(e,fe);S.texture=b,S.size.x=u,S.size.y=h,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},n.insert(e,fe,S)}e.addSystemToSchedule(Mt.Update,Et([Ue(kr)],e=>{const t=n.getEntitiesWithComponents([Rr]);for(const e of t)Uo(n,e,Ar,{tabIndex:0,isFocused:!1}),Uo(n,e,ur,{enabled:!0,blockRaycast:!0});const s=m();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,Rr)){const e=n.get(M,Rr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,Rr);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(s),M=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(Mt.PreUpdate,Et([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===d?0:(e-d)/1e3;d=e,i=Math.min(i,.1);const o=m();if(null!==o&&(u+=i,u>=.5)){u-=.5,c=!c;n.get(o,Rr).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Rr)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Rr,wo]);for(const e of a){const t=n.get(e,Rr);if(!t.dirty)continue;const s=n.get(e,wo),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(bo(n,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Br=new Fr,zr={Simple:0,Sliced:1,Tiled:2,Filled:3},Ur={Horizontal:0,Vertical:1},Lr={Left:0,Right:1,Bottom:2,Top:3},$r=K("Image",{texture:$,color:{r:1,g:1,b:1,a:1},imageType:zr.Simple,fillMethod:Ur.Horizontal,fillOrigin:Lr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Dr=$o({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?ko(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Fo(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Or{build(e){ie("Image",$r);const t=e.world,n=new Map;e.addSystemToSchedule(Mt.PreUpdate,Et([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,$r)||n.delete(e);const e=t.getEntitiesWithComponents([$r]);for(const s of e){const e=t.get(s,$r),i=t.has(s,wo)?t.get(s,wo):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&!Dr.changed(r,o))continue;bo(t,s);const a=t.get(s,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=ko(i,s),a.size.y=Fo(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===zr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Ur.Horizontal?e.fillOrigin===Lr.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===Lr.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===zr.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(s,fe,a),n.set(s,Dr.take(o))}else a.color.a=0,t.insert(s,fe,a),n.set(s,Dr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Wr=new Or,Hr=K("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Vr=K("ToggleGroup",{allowSwitchOff:!1});class jr{build(e){ie("Toggle",Hr),ie("ToggleGroup",Vr);const t=e.world,n=new Set;e.addSystemToSchedule(Mt.Update,Et([Ue(mr)],e=>{const s=t.getEntitiesWithComponents([Hr]);if(!vr()||Mr()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Hr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Hr,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Hr);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(Uo(t,n,ur,{enabled:!0}),!t.has(n,hr))continue;const s=t.get(n,hr),i=t.get(n,Hr),r=t.get(n,ur);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,Vr);if(i.isOn&&r){if(!t.get(s,Vr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Hr,i),i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,Hr);i.isOn&&(i.isOn=!1,t.insert(s,Hr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,fe)){const e=t.get(n,fe);e.color=Eo(i.transition,r.enabled,s.pressed,s.hovered),t.insert(n,fe,e)}}}for(const e of s){const n=t.get(e,Hr);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,fe)){const e=t.get(n.graphicEntity,fe);e.enabled=n.isOn,t.insert(n.graphicEntity,fe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const Nr=new jr,Xr=_o,Yr=K("ProgressBar",{value:0,fillEntity:0,direction:_o.LeftToRight});function qr(e,t,n,s){if(!e.has(t,wo))return;const i=e.get(t,wo),o=n/2,r=s/2,a={left:-o,bottom:-r,right:o,top:r},l=yo(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,fe)){const n=e.get(t,fe);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,fe,n))}if(e.has(t,ue)){const n=e.get(t,ue),s=n.position;s.x===l.originX&&s.y===l.originY||(n.position={x:l.originX,y:l.originY,z:s.z},e.insert(t,ue,n))}}class Gr{build(e){ie("ProgressBar",Yr);const t=e.world;e.addSystemToSchedule(Mt.PreUpdate,Et([],()=>{const e=t.getEntitiesWithComponents([Yr,wo]);for(const n of e){const e=t.get(n,Yr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,wo),i=Math.max(0,Math.min(1,e.value));To(t,e.fillEntity,e.direction,i);const o=ko(s,n),r=Fo(s,n);qr(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Kr=new Gr,Jr=K("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Qr=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}});class Zr{build(e){ie("Draggable",Jr),ie("DragState",Qr);const t=e.world,n=e.getResource(mr);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(Mt.PreUpdate,Et([Ue(Bt),Ue(Lt)],(e,r)=>{if(vr()&&!Mr())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Jr,hr]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,Jr).enabled)continue;if(t.get(s,hr).hovered){let e=0;t.has(s,fe)&&(e=t.get(s,fe).layer);const i=Io(t,s);(e>o||e===o&&i>=r)&&(o=e,r=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,Qr)||t.insert(n,Qr);const e=t.get(n,Qr),o=t.get(n,ue);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!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Qr)){t.get(s,Qr).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,Jr);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,Qr).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Qr))return void(o=null);const s=t.get(o,Qr),i=t.get(o,Jr),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;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,s,c,u);c=h.x,u=h.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,ue)){const e=function(e,t,n,s){if(!e.has(t,_e))return{x:n,y:s};const i=e.get(t,_e).entity;if(!e.valid(i)||!e.has(i,ue))return{x:n,y:s};const o=e.get(i,ue),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=sr(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,ue);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,ue,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const ea=new Zr,ta=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 na(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function sa(e,t,n,s,i){const o=2/(s=Math.max(1e-4,s)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-o*c)*a}}class ia{build(e){ie("ScrollView",ta);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(Mt.PostUpdate,Et([Ue(Bt),Ue(Lt),Ue(Oe)],(e,i,o)=>{const r=vr()&&!Mr(),a=Math.min(o.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([ta,wo]);for(const o of l){Uo(t,o,Qo,{enabled:!0,mode:Ko});const l=t.get(o,ta),c=t.get(o,wo);let u=n.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(o,u));const h=ko(c,o),d=Fo(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 n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,ue))continue;const e=t.get(r,ue);let a=0,l=0,c=.5,u=.5;if(t.has(r,wo)){const e=t.get(r,wo);a=ko(e,r)||e.size.x,l=Fo(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,fe)){const e=t.get(r,fe);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,d=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);h<n&&(n=h),d>s&&(s=d),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-h),g=Math.max(0,p-d);if(!r&&i.valid){Uo(t,o,ur,{enabled:!0,blockRaycast:!0});const n=t.has(o,hr)?t.get(o,hr):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=na(l.scrollX,0,m,h);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=na(l.scrollY,0,g,d);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*h,t=5*d;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=na(l.scrollY,0,g,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=na(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=sa(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Do&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Do?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=sa(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Do&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Do?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.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,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*d;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ue)){const e=t.get(l.contentEntity,ue),n=e.position.x,s=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(n-u.lastAppliedX)>.01)&&(u.contentBaseX=n),(isNaN(u.lastAppliedY)||Math.abs(s-u.lastAppliedY)>.01)&&(u.contentBaseY=s),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,ue,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const oa=new ia,ra=_o,aa=K("Slider",{value:0,minValue:0,maxValue:1,direction:_o.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function la(e,t,n,s,i,o){const r=ko(s,i)*n.worldScale.x,a=Fo(s,i)*n.worldScale.y,l=sr(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),h=e-n.worldPosition.x,d=t-n.worldPosition.y,f=h*u-d*c,p=h*c+d*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case _o.LeftToRight:return r>0?(f-m)/r:0;case _o.RightToLeft:return r>0?1-(f-m)/r:0;case _o.BottomToTop:return a>0?(p-g)/a:0;case _o.TopToBottom:return a>0?1-(p-g)/a:0}}function ca(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case _o.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case _o.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case _o.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case _o.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class ua{build(e){ie("Slider",aa);const t=e.world;let n=null;e.addSystemToSchedule(Mt.PreUpdate,Et([Ue(Bt),Ue(Lt),Ue(mr)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=t.getEntitiesWithComponents([aa,wo]);for(const r of o){const o=t.get(r,aa),a=t.get(r,wo);if(!vr()||Mr()){if(t.has(r,ue)){Uo(t,r,ur,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Uo(t,o.handleEntity,ur,{enabled:!0,blockRaycast:!1});const l=t.get(r,ue),c=t.has(r,hr)?t.get(r,hr):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,hr)&&(u=t.get(o.handleEntity,hr).justPressed),u&&(n=r),n===r&&e.isMouseButtonDown(0)){let e=la(s.worldMouseX,s.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let n=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(n=Math.round(n));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,n)),t.insert(r,aa,o),o.value!==c&&i.emit(r,"change")}n===r&&e.isMouseButtonReleased(0)&&(n=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=ko(a,r),h=Fo(a,r),d={left:-u/2,bottom:-h/2,right:u/2,top:h/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(To(t,o.fillEntity,o.direction,c),Lo(t,o.fillEntity,d,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,wo)){const e=t.get(o.handleEntity,wo);ca(e,o.direction,c),t.insert(o.handleEntity,wo,e),Lo(t,o.handleEntity,d,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const ha=new ua;class da{build(e){ie("Focusable",Ar);const t=e.world,n=new Ir;e.insertResource(kr,n),e.addSystemToSchedule(Mt.Update,Et([Ue(Bt),Ue(mr)],(e,s)=>{if(vr()&&!Mr())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Ar]);for(const e of i){if(!t.has(e,hr))continue;t.get(e,hr).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,ur)){if(!t.get(n,ur).enabled)continue}const s=t.get(n,Ar);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Ar)){t.get(i,Ar).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Ar).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const fa=new da,pa=K("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function ma(){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:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.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")}}()}class ga{build(e){ie("SafeArea",pa);const t=e.world;let n=ma(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=ma(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=ma(),s=!0});e.addSystemToSchedule(Mt.PreUpdate,Et([Ue(Lt)],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,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([pa,wo]);for(const e of u){const s=t.get(e,pa),i=t.get(e,wo),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,wo,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const _a=new ga,ya=K("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let wa=null;function xa(e,t){if(!wa)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=wa.get(e);n?n.renderer=t:wa.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class va{build(e){ie("ListView",ya);const t=e.world,n=new Map;wa=n,e.addSystemToSchedule(Mt.PostUpdate,Et([Ue(Bt)],e=>{const s=vr()&&!Mr();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([ya,wo]);for(const o of i){Uo(t,o,ur,{enabled:!0,blockRaycast:!0}),Uo(t,o,Qo,{enabled:!0,mode:Ko});let i=n.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,i));const r=t.get(o,ya),a=t.get(o,wo),l=Fo(a,o),c=ko(a,o);if(!s){const n=t.has(o,hr)?t.get(o,hr):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=d)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<d;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Pe,{value:`ListItem_${e}`}),t.insert(n,wo,{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(n,o),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,ue)){const s=t.get(n,ue);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,ue,s)}}i.visibleStart=h,i.visibleEnd=d}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const ba=new va,Sa=K("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class Ma{build(e){ie("Dropdown",Sa);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,ue))return;const n=t.get(e,ue);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,ue,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,fe)){const n=t.get(e,fe);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,fe,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},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:n.enabled})}}function o(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(s);const o=t.get(e,fe),r=o.size.x,a=o.size.y;s.ddWidth=r;const l=n.options.length*Oo;t.insert(i,wo,{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,ue,{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:$,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<n.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*Oo;t.insert(o,Pe,{value:`Option_${e}`}),t.insert(o,wo,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Oo},offsetMax:{x:0,y:0},size:{x:r,y:Oo},pivot:{x:.5,y:.5}}),t.insert(o,ue,{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:$,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Oo},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,ur,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),s.optionEntities.push(o);const c=t.spawn();t.insert(c,ue,{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,No,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Ho.Left,verticalAlign:Vo.Middle,wordWrap:!1,overflow:jo.Clip,lineHeight:1.2}),t.insert(c,wo,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Oo},pivot:{x:.5,y:.5}}),t.setParent(c,o),s.textEntities.push(c)}h(s)}function r(e,t,n){t.isOpen=!1,c(n),u(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,r(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,No))return;const s=t.get(n,No);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},o=s.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(n,No,{content:o,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function u(e,n){if(0!==e&&t.valid(e)&&(t.has(e,ur)&&t.insert(e,ur,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,fe))){const s=t.get(e,fe);t.insert(e,fe,{texture:s.texture,color:{r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},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:n})}}function h(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,fe))continue;const i=n===e.highlightIndex?{...Wo}:{r:.95,g:.95,b:.95,a:1};t.insert(s,fe,{texture:$,color:i,size:{x:e.ddWidth,y:Oo},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function d(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,hr))continue;if(t.get(n,hr).hovered)return!0}return!1}e.addSystemToSchedule(Mt.Update,Et([Ue(Bt),Ue(mr)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=vr()&&!Mr(),p=t.getEntitiesWithComponents([Sa]);for(const m of p){const p=t.get(m,Sa);let g=n.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(m,g)),s(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;Uo(t,m,ur,{enabled:!0,blockRaycast:!0});const _=t.has(m,hr)?t.get(m,hr):null;if(_?.justPressed&&(p.isOpen?r(m,p,g):o(m,p,g)),p.isOpen){for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,hr))continue;if(t.get(n,hr).justPressed){a(m,p,g,e,c);break}}let n=-1;for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,hr))continue;if(t.get(s,hr).hovered){n=e;break}}n>=0&&n!==g.highlightIndex&&(g.highlightIndex=n,h(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=p.options.length-1?g.highlightIndex=0:g.highlightIndex++,h(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=p.options.length-1:g.highlightIndex--,h(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,p,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,g),e.isMouseButtonPressed(0)&&(_?.hovered||d(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const Pa=new Ma,Ta=0,Ea=0,Ca=2,Ra=K("LayoutGroup",{direction:Ta,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Ea,reverseOrder:!1});class Aa{build(e){ie("LayoutGroup",Ra);const t=e.world;e.addSystemToSchedule(Mt.PreUpdate,Et([],()=>{const e=t.getEntitiesWithComponents([Ra,wo,ye]);for(const n of e){const e=t.get(n,Ra),s=t.get(n,wo),i=t.get(n,ye);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,wo)&&t.has(e,ue)&&o.push({entity:e,rect:t.get(e,wo)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=ko(s,n),a=Fo(s,n),l=s.pivot.x,c=s.pivot.y,u=e.padding,h=e.direction===Ta;let d=0;for(let n=0;n<o.length;n++){const s=o[n],i=ko(s.rect,s.entity),f=Fo(s.rect,s.entity),p=s.rect.pivot.x,m=s.rect.pivot.y;let g,_;h?(g=-l*r+u.left+d+p*i,_=e.childAlignment===Ea?(1-c)*a-u.top-(1-m)*f:e.childAlignment===Ca?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,d+=i,n<o.length-1&&(d+=e.spacing)):(g=e.childAlignment===Ea?-l*r+u.left+p*i:e.childAlignment===Ca?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,_=(1-c)*a-u.top-d-(1-m)*f,d+=f,n<o.length-1&&(d+=e.spacing));const y=t.get(s.entity,ue);y.position.x=g,y.position.y=_,t.insert(s.entity,ue,y)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Ia=new Aa;class ka{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(Mt.PostUpdate,Et([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Fa=new ka;async function Ba(e,t,n){const s=e.getResource(Ji);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function za(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 Ua=ze({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),La={r:.2,g:.4,b:1,a:.7},$a={r:.2,g:1,b:.2,a:.7},Da={r:.2,g:1,b:1,a:.7},Oa={r:1,g:1,b:.2,a:.5},Wa={r:1,g:.2,b:.2,a:.8},Ha={r:1,g:.2,b:.2,a:1},Va=1.5,ja=16;function Na(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Xa(e){switch(e){case Fe.Static:return La;case Fe.Kinematic:return Da;default:return $a}}function Ya(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*r-n.y*a,y:t+n.x*a+n.y*r}));for(let e=0;e<4;e++)Vs.line(l[e],l[(e+1)%4],o,Va)}function qa(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=(n,s)=>({x:e+n*r-s*a,y:t+n*a+s*r}),c=l(-n,s),u=l(n,s),h=l(-n,-s),d=l(n,-s);Vs.line(c,h,o,Va),Vs.line(u,d,o,Va);for(let e=0;e<ja;e++){const t=e/ja*Math.PI,i=(e+1)/ja*Math.PI,r=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(i),s+n*Math.sin(i));Vs.line(r,a,o,Va)}for(let e=0;e<ja;e++){const t=Math.PI+e/ja*Math.PI,i=Math.PI+(e+1)/ja*Math.PI,r=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(i),-s+n*Math.sin(i));Vs.line(r,a,o,Va)}}function Ga(e,t,n,s){const i=e+.5*n,o=t+.5*s;Vs.line({x:e,y:t},{x:i,y:o},Wa,Va);const r=Math.sqrt(n*n+s*s);if(r<1)return;const a=Math.PI/6,l=n/r,c=s/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),h=o-6*(l*Math.sin(a)+c*Math.cos(a)),d=i-6*(l*Math.cos(a)+c*Math.sin(a)),f=o-6*(-l*Math.sin(a)+c*Math.cos(a));Vs.line({x:i,y:o},{x:u,y:h},Wa,Va),Vs.line({x:i,y:o},{x:d,y:f},Wa,Va)}function Ka(e,t,n){const s=e.getResource(Ua);if(!s||!s.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([me]);for(const n of t){const t=e.world.get(n,me);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([Re,ue]);let r=null;s.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const n=e.world.get(t,Re);if(!n.enabled)continue;const o=e.world.get(t,ue),a=o.worldPosition.x,l=o.worldPosition.y,c=Na(o.worldRotation);if(s.showColliders){if(e.world.has(t,Ae)){const s=e.world.get(t,Ae),o=s.isSensor?Oa:Xa(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c);Ya(a+r*h-u*d,l+r*d+u*h,s.halfExtents.x*i,s.halfExtents.y*i,c,o)}if(e.world.has(t,Ie)){const s=e.world.get(t,Ie),o=s.isSensor?Oa:Xa(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c),f=a+r*h-u*d,p=l+r*d+u*h;Vs.circleOutline({x:f,y:p},s.radius*i,o,Va,32)}if(e.world.has(t,ke)){const s=e.world.get(t,ke),o=s.isSensor?Oa:Xa(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,h=Math.cos(c),d=Math.sin(c);qa(a+r*h-u*d,l+r*d+u*h,s.radius*i,s.halfHeight*i,c,o)}}if(s.showVelocity&&r&&n.bodyType===Fe.Dynamic){const e=r.getLinearVelocity(t);Ga(a,l,e.x*i,e.y*i)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)Vs.circle({x:e.contactX,y:e.contactY},3,Ha,!0,32)}}const Ja=ze({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Qa=ze(null,"PhysicsAPI");function Za(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function el(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class tl{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Ja,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=za(this.wasmUrl_,this.factory_).then(s=>{s._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 n of t){const t=e.world.get(n,me);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(Mt.PostUpdate,Et([Ue(Oe)],a=>{const l=r.getEntitiesWithComponents([Re,ue]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Re),l=r.get(i,ue);if(t.has(i)){const e=n.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||(s._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=Za(l.worldRotation);s._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),nl(e,s,i),t.add(i),n.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===Fe.Kinematic){const e=Za(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<s;i++){const s=o+4*i,r=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(r))continue;const u=e.world.get(r,ue);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(r,_e)){const t=e.world.get(r,_e);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ue)){const n=e.world.get(t.entity,ue),s=Za(n.worldRotation),i=a-n.worldPosition.x,o=l-n.worldPosition.y,r=Math.cos(-s),u=Math.sin(-s);h=(i*r-o*u)/(0!==n.worldScale.x?n.worldScale.x:1),d=(i*u+o*r)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=el(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(r,ue,u)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],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;s.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]*n,contactY:t.HEAPF32[i+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Ja,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Qa,sl._fromModule(s)),function(e,t,n){e.insertResource(Ua,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),qs("physics-debug-draw",()=>{Ka(e,t,n)})}(e,Qa,Ja),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function nl(e,t,n){const s=e.world;if(s.has(n,Ae)){const e=s.get(n,Ae);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,Ie)){const e=s.get(n,Ie);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,ke)){const e=s.get(n,ke);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class sl{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(sl.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)}static setDebugDraw(e,t){const n=e.getResource(Ua);n&&(n.enabled=t,e.insertResource(Ua,n))}static setDebugDrawConfig(e,t){const n=e.getResource(Ua);n&&e.insertResource(Ua,{...n,...t})}}const il={nearest:0,linear:1},ol={repeat:0,clamp:1,mirror:2};function rl(e,t,n=!0,s){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=il[s.filterMode??"linear"]??1,a=ol[s.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,n,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),r}function al(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function ll(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),o=e.worldScale.y*t*(s?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.w,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,g=a*f,_=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(_+w))*i,(m+b)*i,(g-v)*i,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(g+v)*r,(y-x)*r,(1-(p+_))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function cl(e){const{app:t,module:n,sceneData:s,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=Wn(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===s[o])try{const t=i?.[o];s[o]=rl(e,await n.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),s[o]=0}}}return s}(n,s,i);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(n,s,u);let h={},d=null;if(o&&(d=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"])}}(o),h=await async function(e,t,n,s,i){const o={};for(const r of s.entities)for(const s of r.components){const r=Hn(s.type);if(!r||!s.data)continue;const a=s.data[r.skeletonField],l=s.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const s=await i.readText(l),r="binary"===os(c)?.contentType;let h,d;if(r){const e=await i.readBinary(a);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,r);if(t._free(h),f<0)continue;o[a]=f;const p=al(s),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),r=rl(e,o,!1),a=e.getResourceManager().getTextureGLId(r);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(n,o,d,s,i)),r){const e={gravity:a?.gravity??{...A},fixedTimestep:a?.fixedTimestep??I,subStepCount:a?.subStepCount??4};new tl("",e,()=>Promise.resolve(r)).build(t)}const f=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=Wn(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=os(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=rl(e,c,!1),h=e.getResourceManager();s[o]=h.loadBitmapFont(t,u,c.width,c.height)}catch{s[o]=0}}return s}(n,s,i),p=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Wn(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=Yt.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=Yt.createFromAsset(e,r)}catch{n[o]=0}}return n}(s,i);await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=Wn(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=JSON.parse(t),o=on(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,rl(e,s))}catch{r.set(t,0)}ln(rn(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(n,s,i),await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=Wn(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=kn(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=Fn(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=rl(e,t),_n(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}xn(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=Wn(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await pn.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await pn.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Wn(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,u,f,p);const m=qn(t.world,s);if(c&&t.hasResource(Ji))for(const e of m.values())t.world.insert(e,Te,{scene:c,persistent:!1});if(o&&d){const e=function(e,t,n,s){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=Hn(t.type);if(!r||!t.data)continue;const a=n[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.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}(d,s,h,m);!function(e,t,n,s,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,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(r,l*h);let d=0;if(c.has(o,ue)){const e=ll(c.get(o,ue),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(r);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(r,e),o=s.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,u,h,f);const p=n.HEAPU32[h>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*i),_=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(_),t.renderer_submitTriangles(y,i,w,o,p,m,d),t._free(y),t._free(w),n._free(c),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(t,n,o,d,e)}if(l){const e=t.getResource(xs);e&&e.setAddressableManifest(l)}}function ul(e,t,n){return{name:e,async setup(){await cl({...n,sceneData:t,sceneName:e})}}}async function hl(e){const{app:t,firstScene:n,aspectRatio:s}=e;no(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(Ji);for(const t of e.scenes)o.register(ul(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&Qn(t.world,s)}class dl{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Hn(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===os(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=Wn(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}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 n)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 s){const t=os(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,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),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),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 fl="__preview__";class pl{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(Ji);t.register({name:fl,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(fl),this.loadPromise_=t.load(fl).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(),n=new dl(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await cl({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineModule:s,sceneName:fl})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([pe]);for(const s of n){if(e.get(s,pe).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([me]);for(const i of s){const s=e.get(i,me);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(Ji).getScene(fl),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,ue,r);const a={isActive:!0,projectionType:ae.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,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(Ji);await e.switchTo(fl),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 ml={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=Wi.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:Wi.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){Wi.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Wi.releaseRenderTarget(e._handle),ml.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){Wi.begin(t,e._handle)},end(){Wi.end()},getDepthTexture:e=>Wi.getTargetDepthTexture(e._handle)};var gl;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(gl||(gl={}));class _l{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${gl[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case gl.Debug:console.debug(t,n);break;case gl.Info:console.log(t,n);break;case gl.Warn:console.warn(t,n);break;case gl.Error:console.error(t,n)}}}class yl{constructor(){this.handlers_=[],this.minLevel_=gl.Info,this.addHandler(new _l)}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,n){this.log(gl.Debug,e,t,n)}info(e,t,n){this.log(gl.Info,e,t,n)}warn(e,t,n){this.log(gl.Warn,e,t,n)}error(e,t,n){this.log(gl.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const wl=new yl;function xl(){return wl}function vl(e){wl.setMinLevel(e)}function bl(e,t,n){wl.debug(e,t,n)}function Sl(e,t,n){wl.info(e,t,n)}function Ml(e,t,n){wl.warn(e,t,n)}function Pl(e,t,n){wl.error(e,t,n)}const Tl={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},El={Running:0,Paused:1,Completed:2,Cancelled:3},Cl={None:0,Restart:1,PingPong:2};const Rl=1.70158,Al=2.70158,Il=2.5949095;const kl=2*Math.PI/3,Fl=2*Math.PI/4.5;const Bl=7.5625,zl=2.75;const Ul=1e-6;function Ll(e,t,n){switch(e){case Tl.Linear:return t;case Tl.EaseInQuad:return function(e){return e*e}(t);case Tl.EaseOutQuad:return function(e){return e*(2-e)}(t);case Tl.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Tl.EaseInCubic:return function(e){return e*e*e}(t);case Tl.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Tl.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Tl.EaseInBack:return function(e){return Al*e*e*e-Rl*e*e}(t);case Tl.EaseOutBack:return function(e){const t=e-1;return 1+Al*t*t*t+Rl*t*t}(t);case Tl.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Il)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Il)+2)/2}(t);case Tl.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*kl)}(t);case Tl.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*kl)+1}(t);case Tl.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Fl)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Fl)/2+1}(t);case Tl.EaseOutBounce:return function(e){return e<1/zl?Bl*e*e:e<2/zl?Bl*(e-=1.5/zl)*e+.75:e<2.5/zl?Bl*(e-=2.25/zl)*e+.9375:Bl*(e-=2.625/zl)*e+.984375}(t);case Tl.CubicBezier:return n?function(e,t,n,s,i){let o=e;for(let n=0;n<8;n++){const n=1-o,i=3*t*n*n*o+3*s*n*o*o+o*o*o-e;if(Math.abs(i)<Ul)break;const r=3*t*(1-2*o)*(1-o)+6*s*o*(1-o)-3*s*o*o+3*o*o;if(Math.abs(r)<Ul)break;o-=i/r}const r=1-o;return 3*n*r*r*o+3*i*r*o*o+o*o*o}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case Tl.Step:return function(e){return e<1?0:1}(t);default:return t}}const $l=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:n,elapsed:0,delay:i?.delay??0,easing:i?.easing??Tl.Linear,bezierPoints:null,state:El.Running,loop:i?.loop??Cl.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===El.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==El.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=Ll(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Cl.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Cl.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=El.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===El.Running&&(t.state=El.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===El.Paused&&(t.state=El.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=El.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:El.Cancelled}setBezier(e,t,n,s,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:i})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Dl{constructor(e){this.id=e}get state(){return $l.getState(this.id)}bezier(e,t,n,s){return $l.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof Dl?$l.setSequenceNext(this.id,e.id):$l.setSequenceNextExternal(this.id,e),this}pause(){$l.pause(this.id)}resume(){$l.resume(this.id)}cancel(){$l.cancel(this.id)}}const Ol={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};class Wl{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof Dl?($l.registerCppSequence(this.entity,e.id),this):(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 Hl=null,Vl=null;function jl(e,t){Hl=e,Vl=t,$l.init(e,t)}function Nl(){$l.shutdown(),Hl=null,Vl=null}function Xl(){if(!Hl)throw new Error("Tween API not initialized");return Hl}function Yl(){if(!Vl)throw new Error("Tween API not initialized");return Vl}const ql={to(e,t,n,s,i,o){const r=Xl(),a=Yl(),l=o?.easing??Tl.Linear,c=o?.delay??0,u=o?.loop??Cl.None,h=o?.loopCount??0,d=r._anim_createTween(a,e,t,n,s,i,l,c,u,h);return new Wl(r,a,d)},value(e,t,n,s,i){const o=$l.create(e,t,n,s,i);return new Dl(o)},cancel(e){Xl()._anim_cancelTween(Yl(),e.entity)},cancelAll(e){Xl()._anim_cancelAllTweens(Yl(),e)},update(e){Xl()._anim_updateTweens(Yl(),e),$l.update(e)}};class Gl{constructor(){this.name="AnimationPlugin"}build(e){jl(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(Mt.Update,Et([Ue(Oe)],e=>{ql.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(Mt.Update,Et([Ue(Oe)],e=>{fn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Nl()}}const Kl=new Gl;var Jl;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Jl||(Jl={}));const Ql={model:Jl.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Zl(e,t=Ql){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case Jl.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case Jl.Inverse:a=s/Math.max(r,s);break;case Jl.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function ec(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const tc=K("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Jl.Inverse,rolloff:1,priority:0,enabled:!0}),nc=K("AudioListener",{enabled:!0});class sc{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=n.mixer;pn.init(n,i),i&&(void 0!==s.masterVolume&&(i.master.volume=s.masterVolume),void 0!==s.musicVolume&&(i.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(i.sfx.volume=s.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(Mt.PreUpdate,Et([Ue(Oe)],t=>{if(!(!vr()||Mr()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let i=0,u=0,h=!1;const d=s.getEntitiesWithComponents([nc,de]);for(const e of d){if(s.get(e,nc).enabled){const t=s.get(e,de);i=t.position.x,u=t.position.y,h=!0;break}}const f=s.getEntitiesWithComponents([tc]);a.clear();for(const e of f){const t=s.get(e,tc);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&n.isReady){const e=pn.getBufferHandle(t.clip);if(e){const s=n.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,s),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const n=o.get(c);if(!n.isPlaying){o.delete(c);continue}h||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,de),a=r?.position.x??0,d=r?.position.y??0,f=a-i,p=d-u,m=Zl(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=ec(a,0,i,0,t.maxDistance);n.setVolume(t.volume*m),n.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),pn.dispose()}}const ic=new sc;let oc=null,rc=null;function ac(e,t){oc=e,rc=t}function lc(){oc=null,rc=null}const cc={update(e){oc&&rc&&oc.particle_update?.(rc,e)},play(e){oc&&rc&&oc.particle_play?.(rc,e)},stop(e){oc&&rc&&oc.particle_stop?.(rc,e)},reset(e){oc&&rc&&oc.particle_reset?.(rc,e)},getAliveCount:e=>oc?oc.particle_getAliveCount?.(e)??0:0};class uc{constructor(){this.name="ParticlePlugin"}build(e){ac(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(Mt.Update,Et([Ue(Oe)],e=>{cc.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){lc()}}const hc=new uc,dc=1e6;class fc{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){Mn(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(Lt),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:dc,l=i?.valid?i.worldTop:dc,c=t.getEntitiesWithComponents([Cn,ue]);for(const e of c){const s=t.tryGet(e,Cn),i=t.tryGet(e,ue);if(!s||!i)continue;if(!s.visible)continue;const c=s.texture;if(!c)continue;const u=yn(c);if(!u)continue;if(!n.has(e)){if(Tn.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];Tn.setTiles(e,t)}n.add(e)}const h=s.tileWidth/u.width,d=s.tileHeight/u.height,f=s.tint,p=s.parallaxFactor;Tn.submitLayer(e,c,s.layer,0,s.tilesetColumns,h,d,i.worldPosition.x,i.worldPosition.y,o,r,a,l,f.r,f.g,f.b,f.a,s.opacity,p.x,p.y)}const u=t.getEntitiesWithComponents([En,ue]);for(const e of u){if(t.tryGet(e,Cn))continue;const i=t.tryGet(e,En),c=t.tryGet(e,ue);if(!i?.source||!c)continue;const u=vn(i.source);if(!u)continue;if(!s.has(e)){const t=[];for(let s=0;s<u.layers.length;s++){const i=1073741824+256*e+s,o=u.layers[s];Tn.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&Tn.setTiles(i,o.tiles),t.push(i),n.add(i)}s.set(e,t)}const h=s.get(e);for(let e=0;e<u.layers.length&&e<h.length;e++){const t=h[e],n=u.tilesets[0];if(!n)continue;const s=yn(n.textureHandle);if(!s)continue;const i=u.tileWidth/s.width,d=u.tileHeight/s.height;Tn.submitLayer(t,n.textureHandle,e,0,n.columns,i,d,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)Tn.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),wn(),Pn()}}const pc=new fc;function mc(e,t){return e.toFixed(t)}function gc(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}class _c{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">${mc(e.fps,1)}</span> Frame: <span style="color:#d19a66">${mc(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 n=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let s='<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 n){s+=`<div>${gc(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${mc(t,1)}ms</span></div>`}t.push(s)}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 yc(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const wc=ze(yc(),"Stats");class xc{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const vc="StatsCollect";class bc{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 Sc{constructor(e){this.name="Stats",this.collector_=new bc,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(wc,yc());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new _c(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=Et([Ue(Oe),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(wc);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(vc),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Wi.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,n?.update(o)},{name:vc});e.addSystemToSchedule(Mt.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Mc=new Sc;class Pc{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.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]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(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 Tc(e,t){try{const n=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function Ec(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(xs);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Tc(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 Tc(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new Pc(s);await hl({app:t,module:n,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Cc=[Go,cr,_r,Wr,Kr,Cr,ea,oa,ha,Nr,Br,fa,_a,ba,Pa,Ia,Fa],Rc=[...Cc,Kl,ic,hc,pc,zi];function Ac(e,t){return function(e,t){const n=to.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ds(e),jt(e),ni(e),pi(e),Di(e),Vi(e);const i=new Xi;n.setPipeline(i);let o=d();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=ao(e,s,t,i));const r=n.getResource(Lt);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*i),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.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}n.insertResource(Lt,{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(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Wi.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(Wi.resize(t,l),n.hasResource(Ji)){const e=n.getResource(Ji).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=ao(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:so,width:t,height:l,elapsed:u});else{i.beginScreenCapture();for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u,cameraEntity:e.entity})}i.endScreenCapture(),Wi.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Mt.First,l),n.addSystemToSchedule(Mt.Last,c),n.addPlugin(bs),n.addPlugin(Fs),n.addPlugin(Ut),n.addPlugin(eo),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Rc,...t})}e=w;export{it as Added,Gl as AnimationPlugin,to as App,vs as AssetPlugin,Ss as AssetRefCounter,ws as AssetServer,xs as Assets,nn as AsyncCache,Jl as AttenuationModel,pn as Audio,p as AudioBus,nc as AudioListener,m as AudioMixer,sc as AudioPlugin,g as AudioPool,tc as AudioSource,we as BitmapText,$t as BlendMode,Fe as BodyType,Ae as BoxCollider,fr as Button,dr as ButtonState,pe as Camera,me as Canvas,ke as CapsuleCollider,ot as Changed,ye as Children,Ie as CircleCollider,le as ClearFlags,pt as Commands,gt 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,Js as DataType,Zr as DragPlugin,Qr as DragState,Jr as Draggable,Vs as Draw,Sa as Dropdown,Ma as DropdownPlugin,Tl as EasingType,ve as EmitterShape,mt as EntityCommands,vt as EventReader,St as EventReaderInstance,wt as EventRegistry,xt as EventWriter,bt as EventWriterInstance,_o as FillDirection,Ur as FillMethod,Lr as FillOrigin,kr as FocusManager,Ir as FocusManagerState,da as FocusPlugin,Ar as Focusable,xc as FrameHistory,Ni as GLDebug,oi as Geometry,Pt as GetWorld,L as INVALID_ENTITY,D as INVALID_FONT,O as INVALID_MATERIAL,$ as INVALID_TEXTURE,$r as Image,Or as ImagePlugin,zr as ImageType,Bt as Input,zt as InputPlugin,Ft as InputState,ur as Interactable,Aa as LayoutGroupPlugin,ya as ListView,va as ListViewPlugin,he as LocalTransform,gl as LogLevel,yl as Logger,Cl as LoopMode,Yt as Material,sn as MaterialLoader,nt as Mut,Pe as Name,_e as Parent,cc as Particle,Se as ParticleEasing,Me as ParticleEmitter,uc as ParticlePlugin,sl as Physics,Ja as PhysicsEvents,tl as PhysicsPlugin,_i as PostProcess,Bi as PostProcessPlugin,hi as PostProcessStack,Ee as PostProcessVolume,As as PrefabServer,Is as Prefabs,ks as PrefabsPlugin,pl as PreviewPlugin,Yr as ProgressBar,Xr as ProgressBarDirection,Gr as ProgressBarPlugin,ae as ProjectionType,ut as Query,ht as QueryInstance,dt as Removed,ft as RemovedQueryInstance,Xi as RenderPipeline,Ui as RenderStage,ml as RenderTexture,Wi as Renderer,Ue as Res,Le as ResMut,Re as RigidBody,F as RuntimeConfig,pa as SafeArea,ga as SafeAreaPlugin,ce as ScaleMode,Ji as SceneManager,Ki as SceneManagerState,Te as SceneOwner,Mt as Schedule,ta as ScrollView,ia as ScrollViewPlugin,tn as ShaderSources,be as SimulationSpace,aa as Slider,ra as SliderDirection,ua as SliderPlugin,xe as SpineAnimation,fe as Sprite,dn as SpriteAnimator,wc as Stats,bc as StatsCollector,_c as StatsOverlay,Sc as StatsPlugin,He as Storage,kt as SystemRunner,No as Text,Ho as TextAlign,Rr as TextInput,Fr as TextInputPlugin,jo as TextOverflow,qo as TextPlugin,Xo as TextRenderer,Vo as TextVerticalAlign,En as Tilemap,Tn as TilemapAPI,Cn as TilemapLayer,fc as TilemapPlugin,Oe as Time,Hr as Toggle,jr as TogglePlugin,ue as Transform,ql as Tween,Wl as TweenHandle,El as TweenState,Ol as TweenTarget,Lt as UICameraInfo,pr as UIEventQueue,mr as UIEvents,hr as UIInteraction,Er as UIInteractionPlugin,gr as UILayoutPlugin,Qo as UIMask,lr as UIMaskPlugin,wo as UIRect,ka as UIRenderOrderPlugin,ge as Velocity,dl as WebAssetProvider,tt as World,de as WorldTransform,At as addStartupSystem,Rt as addSystem,It as addSystemToSchedule,Kl as animationPlugin,U as applyBuildRuntimeConfig,To as applyDirectionalFill,B as applyRuntimeConfig,bs as assetPlugin,ic as audioPlugin,Zl as calculateAttenuation,ec as calculatePanning,Ei as cleanupAllPostProcessVolumes,Ti as cleanupPostProcessVolume,hn as clearAnimClips,Ks as clearDrawCallbacks,wn as clearTextureDimensionsCache,bn as clearTilemapSourceCache,Z as clearUserComponents,j as color,So as computeFillAnchors,Po as computeFillSize,Mo as computeHandleAnchors,yo as computeUIRectLayout,ar as createMaskProcessor,ul as createRuntimeSceneConfig,Ac as createWebApp,bl as debug,yc as defaultFrameStats,K as defineComponent,_t as defineEvent,ze as defineResource,Et as defineSystem,J as defineTag,ea as dragPlugin,Pa as dropdownPlugin,Pl as error,on as extractAnimClipTexturePaths,Zn as findEntityByName,no as flushPendingSystems,fa as focusPlugin,as as getAddressableType,ls as getAddressableTypeByEditorType,us as getAllAssetExtensions,bi as getAllEffectDefs,un as getAnimClip,ys as getAssetBuildTransform,ps as getAssetMimeType,os as getAssetTypeEntry,oe as getComponent,Wn as getComponentAssetFieldDescriptors,On as getComponentAssetFields,Ce as getComponentDefaults,Nn as getComponentEntityFields,Hn as getComponentSpineFieldDescriptor,ds as getCustomExtensions,rs as getEditorType,xi as getEffectDef,vi as getEffectTypes,xl as getLogger,t as getPlatform,s as getPlatformType,yn as getTextureDimensions,vn as getTilemapSource,Q as getUserComponent,fs as getWeChatPackOptions,Wr as imagePlugin,Sl as info,Ds as initDrawAPI,Vi as initGLDebugAPI,ni as initGeometryAPI,jt as initMaterialAPI,ac as initParticleAPI,Ec as initPlayableRuntime,pi as initPostProcessAPI,Di as initRendererAPI,hl as initRuntime,Mn as initTilemapAPI,jl as initTweenAPI,Ut as inputPlugin,Ps as instantiatePrefab,Zo as intersectRects,er as invertMatrix4,ne as isBuiltinComponent,ms as isCustomExtension,vr as isEditor,cs as isKnownAssetExtension,n as isPlatformInitialized,Mr as isPlayMode,br as isRuntime,Dt as isTextureRef,i as isWeChat,o as isWeb,Ia as layoutGroupPlugin,ba as listViewPlugin,Jn as loadComponent,za as loadPhysicsModule,cl as loadRuntimeScene,qn as loadSceneData,Gn as loadSceneWithAssets,Ln as loadTiledMap,hs as looksLikeAssetPath,rn as parseAnimClipData,Bn as parseTiledMap,kn as parseTmjJson,hc as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,or as pointInOBB,nr as pointInWorldRect,zi as postProcessPlugin,Fs as prefabsPlugin,Kr as progressBarPlugin,N as quat,ln as registerAnimClip,_s as registerAssetBuildTransform,ie as registerComponent,Dn as registerComponentAssetFields,jn as registerComponentEntityFields,qs as registerDrawCallback,Ms as registerEmbeddedAssets,en as registerMaterialCallback,_n as registerTextureDimensions,xn as registerTilemapSource,Xn as remapEntityFields,Fn as resolveRelativePath,_a as safeAreaPlugin,eo as sceneManagerPlugin,tr as screenToWorld,oa as scrollViewPlugin,xr as setEditorMode,xa as setListViewRenderer,vl as setLogLevel,Sr as setPlayMode,Ye as setWasmErrorHandler,Os as shutdownDrawAPI,ji as shutdownGLDebugAPI,si as shutdownGeometryAPI,Nt as shutdownMaterialAPI,lc as shutdownParticleAPI,mi as shutdownPostProcessAPI,Oi as shutdownRendererAPI,Pn as shutdownTilemapAPI,Nl as shutdownTweenAPI,ha as sliderPlugin,fn as spriteAnimatorSystemUpdate,Mc as statsPlugin,Bo as syncFillSpriteSize,Pi as syncPostProcessVolume,Br as textInputPlugin,Go as textPlugin,pc as tilemapPlugin,gs as toBuildPath,Nr as togglePlugin,Ba as transitionTo,Cr as uiInteractionPlugin,_r as uiLayoutPlugin,cr as uiMaskPlugin,Cc as uiPlugins,Fa as uiRenderOrderPlugin,cn as unregisterAnimClip,ee as unregisterComponent,Gs as unregisterDrawCallback,Qn as updateCameraAspectRatio,W as vec2,H as vec3,V as vec4,Ml as warn,Qi as wrapSceneSystem};//# sourceMappingURL=index.js.mapdiff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjsindex c23deadfb..ed8847145 100644--- a/docs/astro/astro.config.mjs+++ b/docs/astro/astro.config.mjs@@ -81,6 +81,7 @@ export default defineConfig({},{ label: 'Scenes', translations: { 'zh-CN': '场景' }, slug: 'guides/scenes' },{ label: 'Prefabs', translations: { 'zh-CN': '预制体' }, slug: 'guides/prefabs' },+ { label: 'Storage', translations: { 'zh-CN': '数据存储' }, slug: 'guides/storage' },{ label: 'Input Handling', translations: { 'zh-CN': '输入处理' }, slug: 'guides/input' },{label: 'UI',diff --git a/docs/astro/src/content/docs/guides/storage.mdx b/docs/astro/src/content/docs/guides/storage.mdxnew file mode 100644index 000000000..49820732c--- /dev/null+++ b/docs/astro/src/content/docs/guides/storage.mdx@@ -0,0 +1,136 @@+---+title: Storage+description: Save and load persistent data in ESEngine+---++import { Aside } from '@astrojs/starlight/components';++ESEngine provides a `Storage` API for persisting data locally. It works across Web (localStorage) and WeChat MiniGame (wx storage) platforms with a unified interface.++## Basic Usage++```typescript+import { Storage } from 'esengine';++// String+Storage.setString('playerName', 'Alice');+const name = Storage.getString('playerName'); // 'Alice'++// Number+Storage.setNumber('highScore', 9999);+const score = Storage.getNumber('highScore', 0); // 9999++// Boolean+Storage.setBoolean('musicEnabled', true);+const music = Storage.getBoolean('musicEnabled', false); // true++// JSON (objects, arrays, etc.)+Storage.setJSON('settings', { volume: 0.8, language: 'en' });+const settings = Storage.getJSON<{ volume: number; language: string }>('settings');+```++## Default Values++All getter methods accept an optional second parameter as the default value. It is returned when the key does not exist or when the stored value is corrupted:++```typescript+const score = Storage.getNumber('score', 0); // 0 if missing+const name = Storage.getString('name', 'Player'); // 'Player' if missing+const items = Storage.getJSON<string[]>('items', []); // [] if missing or invalid JSON+```++## Checking and Removing Keys++```typescript+if (Storage.has('highScore')) {+ console.log('Save data found');+}++Storage.remove('highScore');++// Remove all ESEngine storage data+Storage.clear();+```++## Game Save Example++```typescript+import { defineSystem, addSystem, Res, Input, Storage } from 'esengine';++interface SaveData {+ level: number;+ hp: number;+ position: { x: number; y: number };+ inventory: string[];+}++function saveGame(data: SaveData): void {+ Storage.setJSON('save:slot1', data);+}++function loadGame(): SaveData {+ return Storage.getJSON<SaveData>('save:slot1', {+ level: 1,+ hp: 100,+ position: { x: 0, y: 0 },+ inventory: [],+ })!;+}+```++<Aside type="tip">+ Use key naming conventions like `save:slot1`, `save:slot2` to implement multiple save slots without needing a built-in slot system.+</Aside>++## Player Settings Example++```typescript+function loadSettings() {+ return {+ musicVolume: Storage.getNumber('settings:musicVolume', 1.0),+ sfxVolume: Storage.getNumber('settings:sfxVolume', 1.0),+ language: Storage.getString('settings:language', 'en'),+ };+}++function saveMusicVolume(volume: number) {+ Storage.setNumber('settings:musicVolume', volume);+}+```++## API Reference++| Method | Description |+|--------|-------------|+| `getString(key, default?)` | Get a string value |+| `setString(key, value)` | Store a string value |+| `getNumber(key, default?)` | Get a number value |+| `setNumber(key, value)` | Store a number value |+| `getBoolean(key, default?)` | Get a boolean value |+| `setBoolean(key, value)` | Store a boolean value |+| `getJSON<T>(key, default?)` | Get a parsed JSON value |+| `setJSON<T>(key, value)` | Store a JSON-serializable value |+| `has(key)` | Check if a key exists |+| `remove(key)` | Remove a key |+| `clear()` | Remove all ESEngine storage data |++<Aside type="note">+ All keys are automatically prefixed with `esengine:` to avoid conflicts with other libraries. You don't need to add this prefix yourself.+</Aside>++## Platform Details++| Platform | Backend | Limit |+|----------|---------|-------|+| Web | `localStorage` | ~5 MB |+| WeChat MiniGame | `wx.getStorageSync` | 10 MB |++<Aside type="caution">+ Storage is synchronous on both platforms. Keep stored data small (settings, save states) to avoid frame drops. For large binary data, consider using platform-specific APIs directly.+</Aside>++## Next Steps++- [Scenes](/microes/guides/scenes/) — scene loading and management+- [Resources](/microes/core-concepts/resources/) — runtime global state with the Resource system+- [WeChat MiniGame](/microes/guides/wechat/) — WeChat platform specificsdiff --git a/docs/astro/src/content/docs/zh/guides/storage.mdx b/docs/astro/src/content/docs/zh/guides/storage.mdxnew file mode 100644index 000000000..63c017e0c--- /dev/null+++ b/docs/astro/src/content/docs/zh/guides/storage.mdx@@ -0,0 +1,136 @@+---+title: 数据存储+description: 在 ESEngine 中保存和读取本地持久化数据+---++import { Aside } from '@astrojs/starlight/components';++ESEngine 提供了 `Storage` API 用于本地数据持久化,在 Web(localStorage)和微信小游戏(wx storage)平台上使用统一的接口。++## 基本用法++```typescript+import { Storage } from 'esengine';++// 字符串+Storage.setString('playerName', 'Alice');+const name = Storage.getString('playerName'); // 'Alice'++// 数字+Storage.setNumber('highScore', 9999);+const score = Storage.getNumber('highScore', 0); // 9999++// 布尔值+Storage.setBoolean('musicEnabled', true);+const music = Storage.getBoolean('musicEnabled', false); // true++// JSON(对象、数组等)+Storage.setJSON('settings', { volume: 0.8, language: 'zh' });+const settings = Storage.getJSON<{ volume: number; language: string }>('settings');+```++## 默认值++所有 getter 方法接受可选的第二个参数作为默认值。当 key 不存在或存储的值损坏时返回默认值:++```typescript+const score = Storage.getNumber('score', 0); // 不存在时返回 0+const name = Storage.getString('name', 'Player'); // 不存在时返回 'Player'+const items = Storage.getJSON<string[]>('items', []); // 不存在或 JSON 无效时返回 []+```++## 检查与删除++```typescript+if (Storage.has('highScore')) {+ console.log('找到存档数据');+}++Storage.remove('highScore');++// 清除所有 ESEngine 存储的数据+Storage.clear();+```++## 游戏存档示例++```typescript+import { Storage } from 'esengine';++interface SaveData {+ level: number;+ hp: number;+ position: { x: number; y: number };+ inventory: string[];+}++function saveGame(data: SaveData): void {+ Storage.setJSON('save:slot1', data);+}++function loadGame(): SaveData {+ return Storage.getJSON<SaveData>('save:slot1', {+ level: 1,+ hp: 100,+ position: { x: 0, y: 0 },+ inventory: [],+ })!;+}+```++<Aside type="tip">+ 使用 key 命名约定如 `save:slot1`、`save:slot2` 来实现多存档槽,无需内置的存档槽系统。+</Aside>++## 玩家设置示例++```typescript+function loadSettings() {+ return {+ musicVolume: Storage.getNumber('settings:musicVolume', 1.0),+ sfxVolume: Storage.getNumber('settings:sfxVolume', 1.0),+ language: Storage.getString('settings:language', 'zh'),+ };+}++function saveMusicVolume(volume: number) {+ Storage.setNumber('settings:musicVolume', volume);+}+```++## API 参考++| 方法 | 说明 |+|------|------|+| `getString(key, default?)` | 获取字符串 |+| `setString(key, value)` | 存储字符串 |+| `getNumber(key, default?)` | 获取数字 |+| `setNumber(key, value)` | 存储数字 |+| `getBoolean(key, default?)` | 获取布尔值 |+| `setBoolean(key, value)` | 存储布尔值 |+| `getJSON<T>(key, default?)` | 获取 JSON 解析后的值 |+| `setJSON<T>(key, value)` | 存储可序列化为 JSON 的值 |+| `has(key)` | 检查 key 是否存在 |+| `remove(key)` | 删除指定 key |+| `clear()` | 清除所有 ESEngine 存储的数据 |++<Aside type="note">+ 所有 key 会自动添加 `esengine:` 前缀,避免与其他库冲突。使用时无需手动添加此前缀。+</Aside>++## 平台说明++| 平台 | 底层实现 | 容量限制 |+|------|---------|---------|+| Web | `localStorage` | ~5 MB |+| 微信小游戏 | `wx.getStorageSync` | 10 MB |++<Aside type="caution">+ 两个平台的存储操作都是同步的。请保持存储数据量较小(设置、存档状态),避免造成卡帧。如需存储大体积二进制数据,建议直接使用平台原生 API。+</Aside>++## 下一步++- [场景](/microes/zh/guides/scenes/) — 场景加载与管理+- [资源](/microes/zh/core-concepts/resources/) — Resource 系统的运行时全局状态+- [微信小游戏](/microes/zh/guides/wechat/) — 微信平台相关diff --git a/sdk/src/core.ts b/sdk/src/core.tsindex b3b5e4486..3ad3245f5 100644--- a/sdk/src/core.ts+++ b/sdk/src/core.ts@@ -133,6 +133,8 @@ export {type TimeData,} from './resource';+export { Storage } from './storage';+export {Input,InputState,diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex e341b231d..40a3d3e23 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -92,6 +92,11 @@ export interface PlatformAdapter {bindInputEvents(callbacks: InputEventCallbacks, target?: unknown): void;createAudioBackend(): import('../audio/PlatformAudioBackend').PlatformAudioBackend;++ getStorageItem(key: string): string | null;+ setStorageItem(key: string, value: string): void;+ removeStorageItem(key: string): void;+ clearStorage(prefix: string): void;}// =============================================================================diff --git a/sdk/src/platform/web.ts b/sdk/src/platform/web.tsindex 0d89903a3..19d97aa01 100644--- a/sdk/src/platform/web.ts+++ b/sdk/src/platform/web.ts@@ -211,6 +211,31 @@ class WebPlatformAdapter implements PlatformAdapter {createAudioBackend(): PlatformAudioBackend {return new WebAudioBackend();}++ getStorageItem(key: string): string | null {+ return localStorage.getItem(key);+ }++ setStorageItem(key: string, value: string): void {+ localStorage.setItem(key, value);+ }++ removeStorageItem(key: string): void {+ localStorage.removeItem(key);+ }++ clearStorage(prefix: string): void {+ const toRemove: string[] = [];+ for (let i = 0; i < localStorage.length; i++) {+ const k = localStorage.key(i);+ if (k !== null && k.startsWith(prefix)) {+ toRemove.push(k);+ }+ }+ for (const k of toRemove) {+ localStorage.removeItem(k);+ }+ }}// =============================================================================diff --git a/sdk/src/platform/wechat/index.ts b/sdk/src/platform/wechat/index.tsindex 9935bbcc0..84afbbbee 100644--- a/sdk/src/platform/wechat/index.ts+++ b/sdk/src/platform/wechat/index.ts@@ -136,6 +136,44 @@ class WeChatPlatformAdapter implements PlatformAdapter {createAudioBackend(): PlatformAudioBackend {return new WeChatAudioBackend();}++ getStorageItem(key: string): string | null {+ try {+ const value = wx.getStorageSync(key);+ return typeof value === 'string' ? value : null;+ } catch {+ return null;+ }+ }++ setStorageItem(key: string, value: string): void {+ try {+ wx.setStorageSync(key, value);+ } catch {+ // silent fail+ }+ }++ removeStorageItem(key: string): void {+ try {+ wx.removeStorageSync(key);+ } catch {+ // silent fail+ }+ }++ clearStorage(prefix: string): void {+ try {+ const { keys } = wx.getStorageInfoSync();+ for (const k of keys) {+ if (k.startsWith(prefix)) {+ wx.removeStorageSync(k);+ }+ }+ } catch {+ // silent fail+ }+ }}// =============================================================================diff --git a/sdk/src/storage.ts b/sdk/src/storage.tsnew file mode 100644index 000000000..fb1c051ba--- /dev/null+++ b/sdk/src/storage.ts@@ -0,0 +1,61 @@+import { getPlatform } from './platform/base';++const KEY_PREFIX = 'esengine:';++export const Storage = {+ getString(key: string, defaultValue?: string): string | undefined {+ const raw = getPlatform().getStorageItem(KEY_PREFIX + key);+ return raw !== null ? raw : defaultValue;+ },++ setString(key: string, value: string): void {+ getPlatform().setStorageItem(KEY_PREFIX + key, value);+ },++ getNumber(key: string, defaultValue?: number): number | undefined {+ const raw = getPlatform().getStorageItem(KEY_PREFIX + key);+ if (raw === null) return defaultValue;+ const num = Number(raw);+ return Number.isNaN(num) ? defaultValue : num;+ },++ setNumber(key: string, value: number): void {+ getPlatform().setStorageItem(KEY_PREFIX + key, String(value));+ },++ getBoolean(key: string, defaultValue?: boolean): boolean | undefined {+ const raw = getPlatform().getStorageItem(KEY_PREFIX + key);+ if (raw === null) return defaultValue;+ return raw === 'true';+ },++ setBoolean(key: string, value: boolean): void {+ getPlatform().setStorageItem(KEY_PREFIX + key, String(value));+ },++ getJSON<T>(key: string, defaultValue?: T): T | undefined {+ const raw = getPlatform().getStorageItem(KEY_PREFIX + key);+ if (raw === null) return defaultValue;+ try {+ return JSON.parse(raw) as T;+ } catch {+ return defaultValue;+ }+ },++ setJSON<T>(key: string, value: T): void {+ getPlatform().setStorageItem(KEY_PREFIX + key, JSON.stringify(value));+ },++ remove(key: string): void {+ getPlatform().removeStorageItem(KEY_PREFIX + key);+ },++ has(key: string): boolean {+ return getPlatform().getStorageItem(KEY_PREFIX + key) !== null;+ },++ clear(): void {+ getPlatform().clearStorage(KEY_PREFIX);+ },+};diff --git a/sdk/tests/storage.test.ts b/sdk/tests/storage.test.tsnew file mode 100644index 000000000..e17fbadd9--- /dev/null+++ b/sdk/tests/storage.test.ts@@ -0,0 +1,177 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Storage } from '../src/storage';+import { setPlatform } from '../src/platform/base';+import type { PlatformAdapter } from '../src/platform/types';++function createMockPlatform(): PlatformAdapter & { store: Map<string, string> } {+ const store = new Map<string, string>();+ return {+ store,+ name: 'web',+ getStorageItem: (key: string) => store.get(key) ?? null,+ setStorageItem: (key: string, value: string) => { store.set(key, value); },+ removeStorageItem: (key: string) => { store.delete(key); },+ clearStorage: (prefix: string) => {+ for (const k of [...store.keys()]) {+ if (k.startsWith(prefix)) store.delete(k);+ }+ },+ fetch: vi.fn() as any,+ readFile: vi.fn() as any,+ readTextFile: vi.fn() as any,+ fileExists: vi.fn() as any,+ loadImagePixels: vi.fn() as any,+ instantiateWasm: vi.fn() as any,+ createCanvas: vi.fn() as any,+ now: vi.fn(() => 0),+ createImage: vi.fn() as any,+ bindInputEvents: vi.fn(),+ createAudioBackend: vi.fn() as any,+ };+}++describe('Storage', () => {+ let mock: ReturnType<typeof createMockPlatform>;++ beforeEach(() => {+ mock = createMockPlatform();+ setPlatform(mock);+ });++ describe('getString / setString', () => {+ it('should return undefined for missing key', () => {+ expect(Storage.getString('missing')).toBeUndefined();+ });++ it('should return defaultValue for missing key', () => {+ expect(Storage.getString('missing', 'fallback')).toBe('fallback');+ });++ it('should store and retrieve a string', () => {+ Storage.setString('name', 'Alice');+ expect(Storage.getString('name')).toBe('Alice');+ });++ it('should store empty string', () => {+ Storage.setString('empty', '');+ expect(Storage.getString('empty')).toBe('');+ });+ });++ describe('getNumber / setNumber', () => {+ it('should return undefined for missing key', () => {+ expect(Storage.getNumber('missing')).toBeUndefined();+ });++ it('should return defaultValue for missing key', () => {+ expect(Storage.getNumber('missing', 42)).toBe(42);+ });++ it('should store and retrieve a number', () => {+ Storage.setNumber('score', 100);+ expect(Storage.getNumber('score')).toBe(100);+ });++ it('should handle float numbers', () => {+ Storage.setNumber('pi', 3.14);+ expect(Storage.getNumber('pi')).toBeCloseTo(3.14);+ });++ it('should handle negative numbers', () => {+ Storage.setNumber('neg', -5);+ expect(Storage.getNumber('neg')).toBe(-5);+ });++ it('should return defaultValue for corrupted number', () => {+ mock.store.set('esengine:bad', 'not_a_number');+ expect(Storage.getNumber('bad', 0)).toBe(0);+ });+ });++ describe('getBoolean / setBoolean', () => {+ it('should return undefined for missing key', () => {+ expect(Storage.getBoolean('missing')).toBeUndefined();+ });++ it('should return defaultValue for missing key', () => {+ expect(Storage.getBoolean('missing', true)).toBe(true);+ });++ it('should store and retrieve true', () => {+ Storage.setBoolean('flag', true);+ expect(Storage.getBoolean('flag')).toBe(true);+ });++ it('should store and retrieve false', () => {+ Storage.setBoolean('flag', false);+ expect(Storage.getBoolean('flag')).toBe(false);+ });+ });++ describe('getJSON / setJSON', () => {+ it('should return undefined for missing key', () => {+ expect(Storage.getJSON('missing')).toBeUndefined();+ });++ it('should return defaultValue for missing key', () => {+ expect(Storage.getJSON('missing', { x: 1 })).toEqual({ x: 1 });+ });++ it('should store and retrieve an object', () => {+ const data = { health: 100, position: { x: 10, y: 20 } };+ Storage.setJSON('player', data);+ expect(Storage.getJSON('player')).toEqual(data);+ });++ it('should store and retrieve an array', () => {+ Storage.setJSON('items', [1, 2, 3]);+ expect(Storage.getJSON('items')).toEqual([1, 2, 3]);+ });++ it('should return defaultValue for corrupted JSON', () => {+ mock.store.set('esengine:bad', '{invalid json}');+ expect(Storage.getJSON('bad', [])).toEqual([]);+ });+ });++ describe('remove', () => {+ it('should remove a stored key', () => {+ Storage.setString('key', 'value');+ Storage.remove('key');+ expect(Storage.getString('key')).toBeUndefined();+ });++ it('should not throw when removing non-existent key', () => {+ expect(() => Storage.remove('nope')).not.toThrow();+ });+ });++ describe('has', () => {+ it('should return false for missing key', () => {+ expect(Storage.has('missing')).toBe(false);+ });++ it('should return true for existing key', () => {+ Storage.setString('key', 'val');+ expect(Storage.has('key')).toBe(true);+ });+ });++ describe('clear', () => {+ it('should remove all esengine keys', () => {+ Storage.setString('a', '1');+ Storage.setNumber('b', 2);+ Storage.clear();+ expect(Storage.has('a')).toBe(false);+ expect(Storage.has('b')).toBe(false);+ });+ });++ describe('key prefix isolation', () => {+ it('should prefix keys with esengine:', () => {+ Storage.setString('mykey', 'val');+ expect(mock.store.has('esengine:mykey')).toBe(true);+ expect(mock.store.has('mykey')).toBe(false);+ });+ });+});