Skip to content

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.

feat: add user script injection for shared play mode

esengine0636e400520c
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index b4e6ae6e3..5cc789d09 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 r(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function i(e){return t().fileExists(e)}function a(e,s){return t().createCanvas(e,s)}function l(){return t().now()}function c(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}function d(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"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 u(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 h=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],f={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},p=new Map,g=new Set;for(const e of h)for(const t of e.extensions)p.set(t,e),g.add(t);function y(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function m(e){return p.get(y(e))}function _(e){return g.has(e.toLowerCase())}function x(){const e=[];for(const t of h)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function w(e){const t=m(e);return t?.wechatPackInclude??!1}let v=null;function b(){return v||(v=wx.getFileSystemManager()),v}function S(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(w(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 P(e){return new Promise((t,s)=>{b().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(S(e,t.errMsg)))}})})}function M(e,t="utf-8"){return new Promise((s,n)=>{b().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(S(e,t.errMsg)))}})})}function T(e){return new Promise(t=>{b().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function E(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 C(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 r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let R=!1;const A=new class{constructor(){this.name="wechat"}async fetch(e,t){return d(e,t)}async readFile(e){return P(e)}async readTextFile(e){return M(e)}async fileExists(e){return T(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return u(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){wx.onTouchStart(t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},I=1920,F=1080,k=1/60,B={x:0,y:-9.81},D=1/60,U={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const L=4294967295,z=4294967295;function W(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(W);const t={};for(const s in e)t[s]=W(e[s]);return t}let $=0;function O(e,t){const s=++$,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?{...W(t),...e}:W(t):e?{...t,...e}:{...t}}}const H=new Map;function X(){return"undefined"==typeof window?H:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function j(e,t){const s=G.get(e)??X().get(e);if(s)return s;const n=O(e,t);return X().set(e,n),G.set(e,n),N(e,t,!1),n}function Y(e){return X().get(e)}function N(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function V(e){return!0===e._builtin}const G=new Map;function q(e,t){G.set(e,t)}function K(e){return G.get(e)??Y(e)}function J(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return G.set(e,s),s}const Q={Perspective:0,Orthographic:1},Z={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ee={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},te=J("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}}),se=te,ne=te,re=J("Sprite",{texture:L,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}),oe=J("Camera",{projectionType:Q.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:Z.ColorAndDepth}),ie=J("Canvas",{designResolution:{x:I,y:F},pixelsPerUnit:100,scaleMode:ee.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ae=J("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),le=J("Parent",{entity:0}),ce=J("Children",{entities:[]}),de=J("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:z,enabled:!0}),ue=J("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}),he=j("Name",{value:""}),fe=j("SceneOwner",{scene:"",persistent:!1});const pe=J("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ge=J("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ye=J("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),me=J("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),_e={Static:0,Kinematic:1,Dynamic:2};let xe=0;function we(e,t){const s=++xe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ve(e){return{_type:"res",_resource:e}}function be(e){return{_type:"res_mut",_resource:e}}class Se{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 Pe{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 Se(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Me=we({delta:0,elapsed:0,frameCount:0},"Time");function Te(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=Ee(t[e]),o=Ee(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function Ee(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ce(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 Re=null;function Ae(e){Re=e}function Ie(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Re&&Re(e,t)}function Fe(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 ke=1;const Be=new WeakMap;function De(e){let t=Be.get(e);return void 0===t&&(t=ke++,Be.set(e,t)),t}const Ue=[];function Le(e,t=[],s=[]){Ue.length=0;for(const t of e)Ue.push(De(t));Ue.sort((e,t)=>e-t);let n=Ue.join(",");if(t.length>0){Ue.length=0;for(const e of t)Ue.push(De(e));Ue.sort((e,t)=>e-t),n+="|+"+Ue.join(",")}if(s.length>0){Ue.length=0;for(const e of s)Ue.push(De(e));Ue.sort((e,t)=>e-t),n+="|-"+Ue.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.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 Ie(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_;return this.entities_.set(e,t),this.worldVersion_++,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){Ie(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)}}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){Ie(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ie(t,`removeParent(entity=${e})`)}}insert(e,t,s){return V(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(V(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Fe(s))}catch(s){Ie(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 V(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return V(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(V(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Ie(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.");V(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}`],r=s[`get${e}`],o=s[`has${e}`],i=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof r||"function"!=typeof o||"function"!=typeof i)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:r.bind(s),has:o.bind(s),remove:i.bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Te(t._name,t._default,n);if(e.length>0)throw new Error(Ce(t._name,e))}const r={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,Fe(r))}catch(s){Ie(s,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),r}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 r=t[n];if(null!=r&&"object"==typeof r&&!Array.isArray(r)&&"r"in r&&"g"in r&&"b"in r&&"a"in r){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 r=e[s],o=t[s];if(null==r||"object"!=typeof r||Array.isArray(r)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=r;else{const e=r,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}:r}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return Ie(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 Ie(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ie(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 r=Te(t._name,t._default,e);if(r.length>0)throw new Error(Ce(t._name,r));n=e}const r=t.create(n),o=this.getStorage(t),i=!o.has(e);o.set(e,r);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),i&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),r}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 G)if(V(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=X();for(const n of s)for(const[s,r]of e)if(r._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 r=n??Le(e,t,s),o=this.queryCache_.get(r);if(o&&o.version===this.worldVersion_)return o.result;let i=null,a=1/0;for(const t of e)if(!V(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=i?i.keys():this.entities_.keys();for(const n of c){let r=!0;for(const t of e)if(!this.has(n,t)){r=!1;break}if(r)for(const e of t)if(!this.has(n,e)){r=!1;break}if(r)for(const e of s)if(this.has(n,e)){r=!1;break}r&&l.push(n)}return this.queryCache_.set(r,{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 r=n.get(e);return void 0!==r&&r>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const r=n.get(e);return void 0!==r&&r>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 We(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function $e(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Oe(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function He(e){return We(e)||$e(e)||Oe(e)?e._component:e}function Xe(e,t=[],s=[]){const n=[],r=[],o=[];return e.forEach((e,t)=>{We(e)&&n.push(t),$e(e)?r.push({index:t,component:e._component}):Oe(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:r,_changedFilters:o,with:(...n)=>Xe(e,[...t,...n],s),without:(...n)=>Xe(e,t,[...s,...n])}}class je{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(He),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_=Le(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,r=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,i=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of s)if(!o||this.passesChangeFilters_(d)){if(null!==c&&r)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}i[0]=d;for(let e=0;e<n;e++)i[e+1]=this.world_.get(d,t[e]);if(r){for(let t=0;t<l;t++)a[t].data=i[e[t]+1];c=d}yield i}}finally{if(this.world_.endIteration(),null!==c&&r)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 Ye{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 Ne{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=V(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 Ve{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ne(this,null);return this.spawned_.push(e),e}entity(e){return new Ne(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"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}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 Ge{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 qe{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Ge)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Ge,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class Ke{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Je{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Qe;exports.Schedule=void 0,(Qe=exports.Schedule||(exports.Schedule={}))[Qe.Startup=0]="Startup",Qe[Qe.First=1]="First",Qe[Qe.PreUpdate=2]="PreUpdate",Qe[Qe.Update=3]="Update",Qe[Qe.PostUpdate=4]="PostUpdate",Qe[Qe.Last=5]="Last",Qe[Qe.FixedPreUpdate=10]="FixedPreUpdate",Qe[Qe.FixedUpdate=11]="FixedUpdate",Qe[Qe.FixedPostUpdate=12]="FixedPostUpdate";let Ze=0;function et(e,t,s){const n=++Ze;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function tt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class st{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}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]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ve&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new je(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 Ve(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 Ke(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Je(s)}case"removed":{const t=e;return new Ye(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class nt{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 rt=we(new nt,"Input");class ot{constructor(e){this.target_=e??null}build(e){const s=new nt;e.insertResource(rt,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,et([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const it=new ot,at=we({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 lt;function ct(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(lt=exports.BlendMode||(exports.BlendMode={}))[lt.Normal=0]="Normal",lt[lt.Additive=1]="Additive",lt[lt.Multiply=2]="Multiply",lt[lt.Screen=3]="Screen",lt[lt.PremultipliedAlpha=4]="PremultipliedAlpha";let dt=null,ut=null,ht=1;const ft=new Map;function pt(e){dt=e,ut=e.getResourceManager(),Pt()}function gt(){0!==xt&&dt&&(dt._free(xt),xt=0),ft.clear(),ht=1,_t=!1,vt.clear(),bt=null,ut=null,dt=null}function yt(){if(!ut)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return ut}const mt={createShader:(e,t)=>yt().createShader(e,t),releaseShader(e){e>0&&yt().releaseShader(e)},create(e){const t=ht++,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 ft.set(t,s),t},get:e=>ft.get(e),setUniform(e,t,s){const n=ft.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,dt?.invalidateMaterialCache(e))},getUniform(e,t){const s=ft.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=ft.get(e);s&&(s.blendMode=t,dt?.invalidateMaterialCache(e))},getBlendMode(e){const t=ft.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=ft.get(e);s&&(s.depthTest=t,dt?.invalidateMaterialCache(e))},getShader(e){const t=ft.get(e);return t?.shader??0},release(e){ft.delete(e),dt?.invalidateMaterialCache(e)},isValid:e=>ft.has(e),releaseAll(){ft.clear(),dt?.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=ft.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=ht++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return ft.set(s,n),s},toAssetData(e,t){const s=ft.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=ft.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let _t=!1,xt=0;const wt=16384,vt=new Map;let bt=null;function St(e){const t=(0===xt&&dt&&(xt=dt._malloc(wt)),xt);if(0===t||!dt)return{ptr:0,count:0};let s=0,n=0;const r=dt.HEAPU8,o=dt.HEAPU32,i=dt.HEAPF32;for(const[a,l]of e){if(ct(l))continue;let e=vt.get(a);e||(bt||(bt=new TextEncoder),e=bt.encode(a),vt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(s+(4+d+4+16)>wt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${wt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=d;let u=0,h=[0,0,0,0];if("number"==typeof l)u=0,h[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(u=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,h=[l.x,l.y,l.z,0]):"y"in l&&(u=1,h=[l.x,l.y,0,0]);o[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Pt(){if(!dt||_t)return;dt.materialDataProvider=(e,t,s,n,r)=>{const o=ft.get(e);if(!o)return dt.HEAPU32[t>>2]=0,dt.HEAPU32[s>>2]=0,dt.HEAPU32[n>>2]=0,void(dt.HEAPU32[r>>2]=0);dt.HEAPU32[t>>2]=o.shader,dt.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=St(o.uniforms);dt.HEAPU32[n>>2]=i,dt.HEAPU32[r>>2]=a},_t=!0}const Mt={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 Tt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Et{constructor(e,t=""){this.cache_=new Tt,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&&(mt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())mt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await i(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 r=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(r);return{handle:mt.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}}const Ct=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"}]}]]);function Rt(e){return Ct.get(e)?.fields??[]}function At(e){return Ct.get(e)?.spine??null}const It=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Ft(e){return It.get(e)}function kt(e,t){const s=It.get(e.type);if(!s)return;const n=e.data;for(const r of s){const s=n[r];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${r} references entity ${s} which does not exist`),n[r]=void 0!==o?o:0}}}function Bt(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,he,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const r of n.components)kt(r,s),zt(e,t,r,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}function Dt(e,t){return Bt(e,t)}async function Ut(e,t,s){const n=s?.assetServer,r=s?.assetBaseUrl,o=new Map;n&&await async function(e,t,s,n,r){e=JSON.parse(JSON.stringify(e));const o=new Map;for(const e of Lt.keys())o.set(e,new Set);const i=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ct.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),i.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=[...Lt.entries()].map(async([e,r])=>{const i=await r.load(o.get(e),t,s,n);l.set(e,i)}),d=i.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...d]),r){for(const e of n.values())r.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&r.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)r.fontPaths.add(e);for(const e of a)r.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ct.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&(s[e.field]=l.get(e.type)?.get(t)??0)}}}(t,n,r,o,s?.collectAssets);const i=Bt(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 i}const Lt=new Map([["texture",{async load(e,t,s,n){const r=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(o);r.set(e,i.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),r.set(e,0)}});return await Promise.all(o),r}}],["material",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadMaterial(e,s);n.set(e,r.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}],["font",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadBitmapFont(e,s);n.set(e,r)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}]]);function zt(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 r=K(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}class Wt{constructor(e){this.textureCache_=new Tt,this.shaderCache_=new Tt,this.jsonCache_=new Tt,this.textCache_=new Tt,this.binaryCache_=new Tt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Tt,this.prefabCache_=new Tt,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.module_=e,this.canvas_=a(U.textCanvasSize,U.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 Et(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),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.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(),mt.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 r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),d="binary"===m(e)?.contentType,u=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,d);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.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=m(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 r=s?`${s}/${n}`:n;return this.loadFntFile(r)}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],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}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 Ut(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 r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).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 s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,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,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?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 i=this.module_.GL,a=i.getNewId(i.textures);i.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 r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.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.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return mt.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await i(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:r,fragment:a}=this.parseEsShader(n);if(!r||!a)throw new Error(`Invalid shader format: ${e}`);return mt.createShader(r,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://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(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.embedded_.get(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.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(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 r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}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 $t=we(null,"Assets");class Ot{build(e){const t=e.wasmModule;t?e.insertResource($t,new Wt(t)):console.warn("AssetPlugin: No WASM module available")}}const Ht=new Ot;async function Xt(e,t,s){const{entities:n,rootId:r}=await Yt(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}))},i=await Ut(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const jt=10;async function Yt(e,t,s,n,r,o=0){if(o>jt)throw new Error(`Prefab nesting depth exceeded ${jt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.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(r?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Yt(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),l.push(...t.entities);continue}const c=i.get(n.prefabEntityId),d=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:d?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Nt(u.components,i),Vt(u,t),l.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Nt(e,t){for(const s of e){const e=Ft(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const r=t.get(e);void 0!==r&&(s.data[n]=r)}}}}function Vt(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 Gt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Xt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const qt=we(null,"Prefabs");class Kt{constructor(){this.name="PrefabsPlugin",this.dependencies=[$t]}build(e){const t=e.getResource($t);e.insertResource(qt,new Gt(e.world,t))}}const Jt=new Kt;let Qt=null,Zt=0,es=0,ts=0;const ss=new Float32Array(256);function ns(e){Qt=e,Zt=Qt._malloc(64),es=Qt._malloc(64),ts=Qt._malloc(1024)}function rs(){Qt&&(Zt&&(Qt._free(Zt),Zt=0),es&&(Qt._free(es),es=0),ts&&(Qt._free(ts),ts=0)),Qt=null}function os(){if(!Qt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Qt}const is={r:1,g:1,b:1,a:1},as={begin(e){const t=os();try{t.HEAPF32.set(e,Zt/4),t.draw_begin(Zt)}catch(e){Ie(e,"Draw.begin")}},end(){try{os().draw_end()}catch(e){Ie(e,"Draw.end")}},line(e,t,s,n=1){try{os().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ie(e,"Draw.line")}},rect(e,t,s,n=!0){try{os().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ie(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{os().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ie(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{os().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ie(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{os().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ie(e,"Draw.circleOutline")}},texture(e,t,s,n=is){try{os().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ie(e,"Draw.texture")}},textureRotated(e,t,s,n,r=is){try{os().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Ie(e,"Draw.textureRotated")}},setLayer(e){os().draw_setLayer(e)},setDepth(e){os().draw_setDepth(e)},getDrawCallCount:()=>Qt?Qt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Qt?Qt.draw_getPrimitiveCount():0,setBlendMode(e){os().draw_setBlendMode(e)},setDepthTest(e){os().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=os();n.HEAPF32.set(s,es/4),n.draw_mesh(e,t,es)}catch(s){Ie(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=os(),r=mt.get(t);if(!r)return;if(as.setBlendMode(r.blendMode),as.setDepthTest(r.depthTest),0===r.uniforms.size)return void as.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,es/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=ds(t);if(!(n<0)){if(ct(s))ss[o++]=10,ss[o++]=n,ss[o++]=s.slot??e++,ss[o++]=s.textureId;else if("number"==typeof s)ss[o++]=1,ss[o++]=n,ss[o++]=s;else if(Array.isArray(s)){ss[o++]=s.length,ss[o++]=n;for(let e=0;e<s.length;e++)ss[o++]=s[e]}else"w"in s?(ss[o++]=4,ss[o++]=n,ss[o++]=s.x,ss[o++]=s.y,ss[o++]=s.z,ss[o++]=s.w):"z"in s?(ss[o++]=3,ss[o++]=n,ss[o++]=s.x,ss[o++]=s.y,ss[o++]=s.z):(ss[o++]=2,ss[o++]=n,ss[o++]=s.x,ss[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(ss.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,es);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),ts/4),n.draw_meshWithUniforms(e,r.shader,es,ts,o)}catch(s){Ie(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},ls={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},cs=new Set;function ds(e){const t=ls[e];return void 0!==t?t:(cs.has(e)||(cs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(ls).join(", ")}`)),-1)}const us=new Map;function hs(e,t,s){us.set(e,{fn:t,scene:s??""})}function fs(e){us.delete(e)}function ps(){us.clear()}var gs;exports.DataType=void 0,(gs=exports.DataType||(exports.DataType={}))[gs.Float=1]="Float",gs[gs.Float2=2]="Float2",gs[gs.Float3=3]="Float3",gs[gs.Float4=4]="Float4",gs[gs.Int=5]="Int",gs[gs.Int2=6]="Int2",gs[gs.Int3=7]="Int3",gs[gs.Int4=8]="Int4";let ys=null,ms=0,_s=0,xs=0;function ws(e){ys=e,ms=ys._malloc(262144),_s=ys._malloc(65536),xs=ys._malloc(256)}function vs(){ys&&(ms&&ys._free(ms),_s&&ys._free(_s),xs&&ys._free(xs),ms=0,_s=0,xs=0),ys=null}function bs(){if(!ys)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ys}const Ss={create(e){const t=bs(),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,ms/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,xs,r).set(o),t.geometry_init(s,ms,n,xs,r,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,_s,n).set(e.indices),t.geometry_setIndices16(s,_s,n)}else{new Uint32Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices32(s,_s,n)}}return s},updateVertices(e,t,s=0){const n=bs(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,ms/4),n.geometry_updateVertices(e,ms,r,s)},release(e){e>0&&bs().geometry_release(e)},isValid:e=>!(!ys||e<=0)&&ys.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Ss.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 r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Ss.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,r=-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),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Ss.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let Ps=null;function Ms(e){Ps=e}function Ts(){Ps&&Cs.isInitialized()&&Cs.shutdown(),Ps=null}function Es(){if(!Ps)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ps}const Cs={init(e,t){try{return Es().postprocess_init(e,t)}catch(s){return Ie(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Es().postprocess_shutdown()}catch(e){Ie(e,"PostProcess.shutdown")}},resize(e,t){try{Es().postprocess_resize(e,t)}catch(s){Ie(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Es().postprocess_addPass(e,t)}catch(t){return Ie(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Es().postprocess_removePass(e)}catch(t){Ie(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Es().postprocess_setPassEnabled(e,t)}catch(t){Ie(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Es().postprocess_isPassEnabled(e)}catch(t){return Ie(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Es().postprocess_setUniformFloat(e,t,s)}catch(s){Ie(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Es().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Ie(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Es().postprocess_begin()}catch(e){Ie(e,"PostProcess.begin")}},end(){try{Es().postprocess_end()}catch(e){Ie(e,"PostProcess.end")}},getPassCount(){try{return Es().postprocess_getPassCount()}catch(e){return Ie(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ps)return!1;try{return Ps.postprocess_isInitialized()}catch(e){return Ie(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Es().postprocess_setBypass(e)}catch(e){Ie(e,"PostProcess.setBypass")}},isBypassed(){if(!Ps)return!0;try{return Ps.postprocess_isBypassed()}catch(e){return Ie(e,"PostProcess.isBypassed"),!0}},createBlur:()=>mt.createShader(Rs,"#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:()=>mt.createShader(Rs,"#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:()=>mt.createShader(Rs,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>mt.createShader(Rs,"#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")},Rs="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var As;exports.RenderStage=void 0,(As=exports.RenderStage||(exports.RenderStage={}))[As.Background=0]="Background",As[As.Opaque=1]="Opaque",As[As.Transparent=2]="Transparent",As[As.Overlay=3]="Overlay";let Is=null,Fs=0;function ks(e){Is=e,Fs=Is._malloc(64)}function Bs(){Is&&Fs&&(Is._free(Fs),Fs=0),Is=null}const Ds={init(e,t){Is?.renderer_init(e,t)},resize(e,t){Is?.renderer_resize(e,t)},begin(e,t){if(Is&&Fs)try{Is.HEAPF32.set(e,Fs/4),Is.renderer_begin(Fs,t??0)}catch(e){Ie(e,"Renderer.begin")}},flush(){try{Is?.renderer_flush()}catch(e){Ie(e,"Renderer.flush")}},end(){try{Is?.renderer_end()}catch(e){Ie(e,"Renderer.end")}},submitSprites(e){if(Is)try{Is.renderer_submitSprites(e._cpp)}catch(e){Ie(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Is)try{Is.renderer_submitBitmapText(e._cpp)}catch(e){Ie(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Is)try{Is.renderer_submitSpine?.(e._cpp)}catch(e){Ie(e,"Renderer.submitSpine")}},setStage(e){Is?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Is?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Is?.renderer_releaseTarget(e)},getTargetTexture:e=>Is?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Is?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Is?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Is?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Is?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Is?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Is?Is.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Is?{drawCalls:Is.renderer_getDrawCalls(),triangles:Is.renderer_getTriangles(),sprites:Is.renderer_getSprites(),text:Is.renderer_getText(),spine:Is.renderer_getSpine?.()??0,meshes:Is.renderer_getMeshes(),culled:Is.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Us=null;function Ls(e){Us=e}function zs(){Us=null}const Ws={enable(){Us?.gl_enableErrorCheck(!0)},disable(){Us?.gl_enableErrorCheck(!1)},check:e=>Us?.gl_checkErrors(e)??0,diagnose(){Us?.renderer_diagnose()}};class $s{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(Ds.resize(n,r),Cs.isInitialized()&&Cs.getPassCount()>0&&Cs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Ds.setViewport(0,0,n,r),Ds.clearBuffers(3),Ds.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Ds.submitSprites(t),Ds.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ds.submitSpine(t),Ds.flush(),this.executeDrawCallbacks(s,o),Ds.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;Ds.setViewport(n.x,n.y,n.w,n.h),Ds.setScissor(n.x,n.y,n.w,n.h,!0),Ds.clearBuffers(r),Ds.setScissor(0,0,0,0,!1),Ds.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ds.submitSprites(t),Ds.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ds.submitSpine(t),Ds.flush(),this.executeDrawCallbacks(s,o),Ds.end()}executeDrawCallbacks(e,t){const s=us;if(s.size>0){as.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}as.end();for(const e of n)fs(e)}}}const Os="__scene_transition_overlay__";class Hs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Xs{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,fe,{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),hs(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Cs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Cs.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,fe)){const s=this.app_.world.get(e,fe);s.persistent=t,this.app_.world.insert(e,fe,s)}}}class js{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??U.sceneTransitionDuration,r=t.color??{...U.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},hs(Os,()=>{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;as.setLayer(9999),as.setDepth(9999),as.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.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,fs(Os),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,fs(Os),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 Hs(t);this.scenes_.set(e,s);const n=new Xs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource($t)?this.app_.getResource($t):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}return await this.loadSceneData_(s,e,t,r),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}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 Hs(t);this.scenes_.set(e,s);const n=new Xs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource($t)?this.app_.getResource($t):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}return await this.loadSceneData_(s,e,t,r),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}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 r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,fe)){if(this.app_.world.get(e,fe).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())fs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Cs.removePass(e)}catch{}s.postProcessPasses.length=0,this.releaseSceneAssets_(s),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},r={collectAssets:s};this.app_.hasResource($t)&&(r.assetServer=this.app_.getResource($t));const o=await Ut(this.app_.world,n,r);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,fe,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=Ns(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const r=this.contexts_.get(t);s.setup&&await s.setup(r)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource($t)?this.app_.getResource($t):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)mt.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 r=!1;if(s.has(e,re)){const t=s.get(e,re);n.sprite=t.color.a,t.color.a=0,s.insert(e,re,t),r=!0}if(s.has(e,ue)){const t=s.get(e,ue);n.spine=t.color.a,t.color.a=0,s.insert(e,ue,t),r=!0}if(s.has(e,de)){const t=s.get(e,de);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,de,t),r=!0}r&&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,re)){const t=s.get(e,re);t.color.a=n.sprite,s.insert(e,re,t)}if(void 0!==n.spine&&s.has(e,ue)){const t=s.get(e,ue);t.color.a=n.spine,s.insert(e,ue,t)}if(void 0!==n.bitmapText&&s.has(e,de)){const t=s.get(e,de);t.color.a=n.bitmapText,s.insert(e,de,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Cs.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Ys=we(null,"SceneManager");function Ns(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Ys).getSceneStatus(t)&&s._fn(...n)}}}const Vs=et([be(Ys),ve(Me)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Gs={name:"SceneManager",build(e){const t=new js(e);e.insertResource(Ys,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ys),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,Vs)}};class qs{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 qe,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=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=l(),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 ze,this.resources_=new Pe;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new qs}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)}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 Ae(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_}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(Ys).register(e),this}setInitialScene(e){return this.getResource(Ys).setInitial(e),this}tick(e){this.runner_||(this.runner_=new st(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(Me)||this.resources_.insert(Me,{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.runSchedule(exports.Schedule.First),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last);this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new st(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(Me,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=l(),this.mainLoop())}quit(){this.running_=!1,ps();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=[zs,Bs,Ts,vs,gt,rs];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 r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Me);t.delta=e,t.elapsed+=e,t.frameCount++}}const Ks=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Js(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case ee.FixedWidth:return o;case ee.FixedHeight:return i;case ee.Expand:return Math.max(o,i);case ee.Shrink:return Math.min(o,i);case ee.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}const Qs=[];function Zs(e){if(e<Qs.length)return Qs[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 Qs.push(t),t}function en(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,fe);return!t||""===t.scene||o.has(t.scene)}):i;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 r=t.getCamera(e),o=t.getTransform(e),i=r.viewportW*s/(r.viewportH*n);let a,d=0,u=0;if(r.projectionType===Q.Orthographic){if(u=r.orthoSize,l){u=Js(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,i,l.scaleMode,l.matchWidthOrHeight)}d=u*i,a=sn(-d,d,-u,u,-r.farPlane,r.farPlane)}else a=rn(r.fov*Math.PI/180,i,r.nearPlane,r.farPlane);const h=an(o.position.x,o.position.y,o.position.z),f=Zs(c.length);f.entity=e,f.viewProjection.set(cn(a,h)),f.viewportRect.x=r.viewportX,f.viewportRect.y=r.viewportY,f.viewportRect.w=r.viewportW,f.viewportRect.h=r.viewportH,f.clearFlags=r.clearFlags,f.priority=r.priority,f.halfW=d,f.halfH=u,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const tn=new Float32Array(16);function sn(e,t,s,n,r,o){const i=tn;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const nn=new Float32Array(16);function rn(e,t,s,n){const r=nn;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const on=new Float32Array(16);function an(e,t,s){const n=on;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 ln=new Float32Array(16);function cn(e,t){const s=ln;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}const dn={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function un(e,t,s,n,r,o,i={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,d=o.left+t.x*a,u=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+s.x-r.x*i.x,g=f+r.x):(f=c+s.x,g=d+n.x),e.y===t.y?(p=u+s.y-r.y*i.y,y=p+r.y):(p=u+s.y,y=h+n.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+i.x*m,originY:p+i.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const hn=J("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 fn=null,pn=null;function gn(e,t){e.has(t,re)||e.insert(t,re,{texture:L,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 yn(e,t){switch(e){case dn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case dn.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case dn.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 mn(e,t,s,n){if(!e.has(t,hn))return;const r=e.get(t,hn),o=yn(s,n);r.anchorMin=o.anchorMin,r.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(r.size={...r.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(r.size={...r.size,y:0}),e.insert(t,hn,r)}function _n(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function xn(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function wn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(let o=0;o<t.length;o++){const i=t[o],a=n+i;if(e.measureText(a).width>s&&n){if(xn(i.charCodeAt(0))&&n.length>0&&xn(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!xn(n.charCodeAt(t))){e=t;break}e>=0?(r.push(n.substring(0,e+1)),n=n.substring(e+1)+i):(r.push(n),n=i)}else r.push(n),n=i}else n=a}n&&r.push(n)}return r.length>0?r:[""]}function vn(e){let t=1;for(;t<e;)t*=2;return t}function bn(e,t){let s=0,n=t;for(;e.has(n,le);){const t=e.get(n,le).entity;if(!e.valid(t))break;s++,n=t}return s}function Sn(e,t){if(fn&&pn){const e=fn.getUIRectComputedWidth(pn,t);if(e>0)return e}return e.size.x}function Pn(e,t){if(fn&&pn){const e=fn.getUIRectComputedHeight(pn,t);if(e>0)return e}return e.size.y}function Mn(e,t,s){let n=t;for(;e.has(n,le);){const t=e.get(n,le).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Tn(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function En(e,t,s,n,r){if(!e.has(t,hn))return;const o=e.get(t,hn),i=un(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=i.rect.right-i.rect.left,l=i.rect.top-i.rect.bottom;if(e.has(t,re)){const s=e.get(t,re);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,re,s))}if(e.has(t,te)){const s=e.get(t,te);s.position.x=i.originX-n,s.position.y=i.originY-r,e.insert(t,te,s)}}function Cn(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let r=0;r<t.length;r++)n[t[r]]=s[r](e);return n},changed(e,n){for(let r=0;r<t.length;r++)if(e[t[r]]!==s[r](n))return!0;return!1},update(e,n){for(let r=0;r<t.length;r++)e[t[r]]=s[r](n)}}}const Rn=.1,An=30,In={r:.3,g:.5,b:.8,a:1},Fn={Left:0,Center:1,Right:2},kn={Top:0,Middle:1,Bottom:2},Bn={Visible:0,Clip:1,Ellipsis:2},Dn=j("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Fn.Left,verticalAlign:kn.Top,wordWrap:!0,overflow:Bn.Visible,lineHeight:1.2});class Un{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=a(U.textCanvasSize,U.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,vn(this.frameMaxW_)),e.height=Math.max(e.height,vn(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=vn(this.frameMaxW_),e.height=vn(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 r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=wn(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):u+2*d,p=r?Math.ceil(i):h+2*d;if(r&&e.overflow===Bn.Ellipsis&&h>i){const e=Math.floor(i/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,vn(f)),n.height=Math.max(n.height,vn(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=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(${g}, ${y}, ${m}, ${_})`,r&&e.overflow===Bn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const x=l.length*c;let w;if(r)switch(e.verticalAlign){case kn.Top:w=d;break;case kn.Middle:w=d+(p-2*d-x)/2;break;case kn.Bottom:w=p-x-d;break;default:w=d}else w=d;let v=w;for(const t of l){let n;switch(e.align){case Fn.Left:n=d;break;case Fn.Center:n=f/2;break;case Fn.Right:n=f-d;break;default:n=d}s.fillText(t,n,v),v+=c}r&&e.overflow===Bn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{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 r=this.renderText(t,s);return this.cache.set(e,r),r}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 Fn.Left:return"left";case Fn.Center:return"center";case Fn.Right:return"right"}}}const Ln=Cn({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?Sn(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Pn(e.uiRect,e.entity):0});class zn{build(e){q("Text",Dn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Un(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Dn));for(const e of r.keys())if(!n.valid(e)||!n.has(e,Dn)){if(n.valid(e)&&n.has(e,re)){const t=n.get(e,re);n.insert(e,re,{texture:L,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})}r.delete(e)}const e=n.getEntitiesWithComponents([Dn]);for(const t of e){const e=n.get(t,Dn),o=n.has(t,hn)?n.get(t,hn):null,i={text:e,uiRect:o,entity:t},a=r.get(t);if(a&&!Ln.changed(a,i)){if(n.has(t,re)&&n.get(t,re).texture!==L)continue}gn(n,t);const l=o?{size:{x:Sn(o,t),y:Pn(o,t)}}:null,c=s.renderForEntity(t,e,l),d=n.get(t,re);n.insert(t,re,{texture:c.textureHandle,color:{r:d.color.r,g:d.color.g,b:d.color.b,a:d.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:d.layer,flipX:d.flipX,flipY:d.flipY,material:d.material,enabled:d.enabled}),r.set(t,Ln.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Wn=new zn,$n=0,On=1,Hn=J("UIMask",{enabled:!0,mode:$n});function Xn(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=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,r-s),h:Math.max(0,o-n)}}function jn(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],d=e[7],u=e[8],h=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],x=n*l-r*a,w=n*c-o*a,v=n*d-i*a,b=r*c-o*l,S=r*d-i*l,P=o*d-i*c,M=u*y-h*g,T=u*m-f*g,E=u*_-p*g,C=h*m-f*y,R=h*_-p*y,A=f*_-p*m;let I=x*A-w*R+v*C+b*E-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*A-c*R+d*C)*I,s[1]=(o*R-r*A-i*C)*I,s[2]=(y*P-m*S+_*b)*I,s[3]=(f*S-h*P-p*b)*I,s[4]=(c*E-a*A-d*T)*I,s[5]=(n*A-o*E+i*T)*I,s[6]=(m*v-g*P-_*w)*I,s[7]=(u*P-f*v+p*w)*I,s[8]=(a*R-l*E+d*M)*I,s[9]=(r*E-n*R-i*M)*I,s[10]=(g*S-y*v+_*x)*I,s[11]=(h*v-u*S-p*x)*I,s[12]=(l*T-a*C-c*M)*I,s[13]=(n*C-r*T+o*M)*I,s[14]=(y*w-g*b-m*x)*I,s[15]=(u*b-h*w+f*x)*I),s}function Yn(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],d=s[1]*a+s[5]*l+s[13],u=s[3]*a+s[7]*l+s[15];return{x:c/u,y:d/u}}function Nn(e,t){return 2*Math.atan2(e,t)}function Vn(e,t,s,n,r,o,i){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,r+(.5*(l/c)+.5)*i]}function Gn(e,t,s,n,r,o,i){if(!e.has(t,hn)||!e.has(t,te))return null;const a=e.get(t,hn),l=e.get(t,te),c=Sn(a,t)*l.worldScale.x,d=Pn(a,t)*l.worldScale.y,u=l.worldPosition.x,h=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-d*p,_=d*(1-p),x=Nn(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),v=Math.sin(x),b=[[u+g*w-m*v,h+g*v+m*w],[u+y*w-m*v,h+y*v+m*w],[u+y*w-_*v,h+y*v+_*w],[u+g*w-_*v,h+g*v+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=Vn(e,t,s,n,r,o,i);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 qn(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Hn]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,Hn);s.enabled&&(u.add(e),s.mode===On?(d.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,r,o,i,a,l,c){const d=[];for(const e of n){let s=!0;Mn(t,e,e=>{if(r.has(e)){if(t.get(e,Hn).mode===$n)return s=!1,!0}return!1}),s&&d.push(e)}function u(n,d){const h=e.getChildEntities(s,n);for(const s of h){let n=d;if(r.has(s)){if(t.get(s,Hn).mode===$n){const e=Gn(t,s,o,i,a,l,c);e&&(n=Xn(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=Gn(t,e,o,i,a,l,c);s&&u(e,s)}}(e,t,s,c,u,n,r,o,i,a),d.length>0&&function(e,t,s,n,r){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Mn(t,e,e=>!!r.has(e)&&(s=!1,!0)),s&&o.push(e)}let i=1,a=!1;function l(){return i>255?(a||console.warn("Stencil mask overflow"),a=!0,null):i++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}function d(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,d,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Kn{build(e){if(q("UIMask",Hn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(qn(e.wasmModule,e.world))}}const Jn=new Kn,Qn=J("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Zn=J("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),er={Normal:0,Hovered:1,Pressed:2,Disabled:3},tr=j("Button",{state:er.Normal,transition:null});class sr{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 nr=we(new sr,"UIEvents");class rr{build(e){q("UIRect",hn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){fn=e,pn=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(at)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n),s.transform_update(n))},{name:"UILayoutSystem"})),e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(at)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(exports.Schedule.PostUpdate,et([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const or=new rr;let ir=!1,ar=!1;function lr(){return ir}function cr(){return ar}const dr=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&&(jn(t,e),s=!1),e)}}();function ur(e,t,s,n){t.emit(s,n,s),Mn(e,s,r=>{if(!e.has(r,Qn))return!1;const o=e.get(r,Qn);return o.enabled&&t.emit(r,n,s),o.blockRaycast})}class hr{build(e){q("Interactable",Qn),q("Button",tr);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),r=new sr;e.insertResource(nr,r);let o=null,i=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at)],(e,a)=>{if(r.drain(),lr()&&!cr())return;const l=t.getEntitiesWithComponents([Zn]);for(const e of l){const s=t.get(e,Zn);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,Zn,s))}if(!a.valid)return;const d=c(),u=e.mouseX*d,h=a.screenH-e.mouseY*d;dr.update(a.viewProjection);const f=Yn(u,h,dr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=f.x,a.worldMouseY=f.y;const p=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),y=e.isMouseButtonReleased(0);s.uiHitTest_update(n,f.x,f.y,p,g,y);const m=s.uiHitTest_getHitEntity(),_=4294967295===m?null:m;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,Zn)){const e=t.get(o,Zn);e.hovered=!1,t.insert(o,Zn,e),r.emit(o,"hover_exit")}if(null!==_){Tn(t,_,Zn);const e=t.get(_,Zn);e.hovered=!0,t.insert(_,Zn,e),r.emit(_,"hover_enter")}o=_}if(g&&null!==_){const e=t.get(_,Zn);e.pressed=!0,e.justPressed=!0,t.insert(_,Zn,e),i=_,ur(t,r,_,"press")}if(y&&null!==i){if(t.valid(i)&&t.has(i,Zn)){const e=t.get(i,Zn);e.pressed=!1,e.justReleased=!0,t.insert(i,Zn,e),ur(t,r,i,"release"),i===o&&ur(t,r,i,"click")}i=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,et([],()=>{const e=t.getEntitiesWithComponents([tr]);for(const s of e){if(Tn(t,s,Qn,{enabled:!0}),!t.has(s,Zn))continue;const e=t.get(s,Zn),n=t.get(s,tr),r=t.get(s,Qn),o=!a.has(s),i=n.state;if(r.enabled?e.pressed?n.state=er.Pressed:e.hovered?n.state=er.Hovered:n.state=er.Normal:n.state=er.Disabled,o&&a.add(s),(o||i!==n.state)&&n.transition&&t.has(s,re)){const o=t.get(s,re);o.color=_n(n.transition,r.enabled,e.pressed,e.hovered),t.insert(s,re,o)}}},{name:"ButtonSystem"}))}}const fr=new hr,pr=j("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}),gr=j("Focusable",{tabIndex:0,isFocused:!1});class yr{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 mr=we(new yr,"FocusManager");class _r{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(q("TextInput",pr),lr()&&!cr())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=a(U.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=0,l=0,c=!1,d=!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 g(){const t=e.getResource(mr);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,pr)?n:null}const y=()=>{c||null===g()||v()},m=()=>{c=!0},_=()=>{c=!1,v()},x=t=>{const n=g();if(null===n)return;if("Escape"===t.key)return void b();const r=s.get(n,pr);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource(nr).emit(n,"submit"),void b()}let o=r.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,r.cursorPos-1):"ArrowRight"===t.key?o=Math.min(r.value.length,r.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=r.value.length),o!==r.cursorPos&&(r.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,r.dirty=!0,S())},w=()=>{const t=g();if(null!==t){const n=s.get(t,pr);n.focused=!1,n.dirty=!0;e.getResource(mr).blur()}};function v(){const t=g();if(null===t)return;const n=s.get(t,pr);if(n.readOnly)return;let r=p.value;if(n.maxLength>0&&r.length>n.maxLength&&(r=r.substring(0,n.maxLength),p.value=r),r!==n.value){n.value=r;e.getResource(nr).emit(t,"change")}n.cursorPos=p.selectionStart??r.length,n.dirty=!0,S()}function b(){const t=g();if(null!==t){const e=s.get(t,pr);e.focused=!1,e.dirty=!0}e.getResource(mr).blur(),p.blur()}function S(){d=!0,u=0}p.addEventListener("input",y),p.addEventListener("compositionstart",m),p.addEventListener("compositionend",_),p.addEventListener("keydown",x),p.addEventListener("blur",w),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",m),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",x),p.removeEventListener("blur",w),p.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==i&&(t._free(i),i=0,l=0)};let P=null;function M(e,a,c,u){(r.width<c||r.height<u)&&(r.width=vn(Math.max(r.width,c)),r.height=vn(Math.max(r.height,u))),o.clearRect(0,0,r.width,r.height);const h=a.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,u),o.save(),o.beginPath(),o.rect(a.padding,0,c-2*a.padding,u),o.clip(),o.font=`${a.fontSize}px ${a.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===a.value.length,p=f?a.placeholder:a.password?"●".repeat(a.value.length):a.value,g=f?a.placeholderColor:a.color;o.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const y=Math.ceil(1.2*a.fontSize),m=a.padding;if(a.multiline){const e=wn(o,p,c-2*m);let t=m;for(const s of e)o.fillText(s,m,t),t+=y}else{const e=(u-a.fontSize)/2;o.fillText(p,m,e)}if(a.focused&&d){const e=a.password?"●".repeat(a.cursorPos):a.value.substring(0,a.cursorPos);let t,s,n;if(a.multiline){const e=wn(o,a.value,c-2*m);let r=0,i=0,l=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(r+s>=a.cursorPos){i=t,l=a.cursorPos-r;break}r+=s,t<e.length-1&&r<a.value.length&&"\n"===a.value[r]&&r++,i=t+1,l=0}const d=i<e.length?e[i].substring(0,l):"";t=m+o.measureText(d).width,s=m+i*y,n=y}else t=m+o.measureText(e).width,s=(u-a.fontSize)/2,n=a.fontSize;o.fillStyle=`rgba(${Math.round(255*a.color.r)}, ${Math.round(255*a.color.g)}, ${Math.round(255*a.color.b)}, ${a.color.a})`,o.fillRect(t,s,2,n)}o.restore();const _=o.getImageData(0,0,c,u),x=new Uint8Array(_.data.buffer),w=t.getResourceManager();x.length>l&&(0!==i&&t._free(i),i=t._malloc(x.length),l=x.length),t.HEAPU8.set(x,i);const v=n.get(e);void 0!==v&&w.releaseTexture(v);const b=w.createTexture(c,u,i,x.length,1,!0);n.set(e,b);const S=s.get(e,re);S.texture=b,S.size.x=c,S.size.y=u,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,re,S)}e.addSystemToSchedule(exports.Schedule.Update,et([ve(mr)],e=>{const t=s.getEntitiesWithComponents([pr]);for(const e of t)Tn(s,e,gr,{tabIndex:0,isFocused:!1}),Tn(s,e,Qn,{enabled:!0,blockRaycast:!0});const n=g();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,pr)){const e=s.get(P,pr);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,pr);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let r=0===h?0:(e-h)/1e3;h=e,r=Math.min(r,.1);const o=g();if(null!==o&&(u+=r,u>=.5)){u-=.5,d=!d;s.get(o,pr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,pr)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([pr,hn]);for(const e of a){const t=s.get(e,pr);if(!t.dirty)continue;const n=s.get(e,hn),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(gn(s,e),M(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const xr=new _r,wr={Simple:0,Sliced:1,Tiled:2,Filled:3},vr={Horizontal:0,Vertical:1},br={Left:0,Right:1,Bottom:2,Top:3},Sr=j("Image",{texture:L,color:{r:1,g:1,b:1,a:1},imageType:wr.Simple,fillMethod:vr.Horizontal,fillOrigin:br.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Pr=Cn({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?Sn(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Pn(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Mr=new class{build(e){q("Image",Sr);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Sr)||s.delete(e);const e=t.getEntitiesWithComponents([Sr]);for(const n of e){const e=t.get(n,Sr),r=t.has(n,hn)?t.get(n,hn):null,o={image:e,uiRect:r,entity:n},i=s.get(n);if(i&&!Pr.changed(i,o))continue;gn(t,n);const a=t.get(n,re);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,r&&(a.size.x=Sn(r,n),a.size.y=Pn(r,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===wr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===vr.Horizontal?e.fillOrigin===br.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===br.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===wr.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,re,a),s.set(n,Pr.take(o))}else a.color.a=0,t.insert(n,re,a),s.set(n,Pr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Tr=j("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Er=j("ToggleGroup",{allowSwitchOff:!1});const Cr=new class{build(e){q("Toggle",Tr),q("ToggleGroup",Er);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,et([ve(nr)],e=>{const n=t.getEntitiesWithComponents([Tr]);if(!lr()||cr()){const r=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Tr);n.isOn&&0!==n.group&&t.valid(n.group)&&(r.has(n.group)?(n.isOn=!1,t.insert(e,Tr,n)):r.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Tr);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(Tn(t,s,Qn,{enabled:!0}),!t.has(s,Zn))continue;const n=t.get(s,Zn),r=t.get(s,Tr),i=t.get(s,Qn);if(n.justPressed&&i.enabled){const n=r.group,i=0!==n&&t.valid(n)&&t.has(n,Er);if(r.isOn&&i){if(!t.get(n,Er).allowSwitchOff)continue}if(r.isOn=!r.isOn,t.insert(s,Tr,r),r.isOn&&i){const r=o.get(n);if(r)for(const n of r){if(n===s)continue;const r=t.get(n,Tr);r.isOn&&(r.isOn=!1,t.insert(n,Tr,r),e.emit(n,"change"))}}e.emit(s,"change")}if(r.transition&&t.has(s,re)){const e=t.get(s,re);e.color=_n(r.transition,i.enabled,n.pressed,n.hovered),t.insert(s,re,e)}}}for(const e of n){const s=t.get(e,Tr);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,re)){const e=t.get(s.graphicEntity,re);e.enabled=s.isOn,t.insert(s.graphicEntity,re,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Rr=dn,Ar=j("ProgressBar",{value:0,fillEntity:0,direction:dn.LeftToRight});function Ir(e,t,s,n){if(!e.has(t,hn))return;const r=e.get(t,hn),o=s/2,i=n/2,a={left:-o,bottom:-i,right:o,top:i},l=un(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,a,r.pivot);if(e.has(t,re)){const s=e.get(t,re);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,re,s))}if(e.has(t,te)){const s=e.get(t,te),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,te,s))}}class Fr{build(e){q("ProgressBar",Ar);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e=t.getEntitiesWithComponents([Ar,hn]);for(const s of e){const e=t.get(s,Ar);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,hn),r=Math.max(0,Math.min(1,e.value));mn(t,e.fillEntity,e.direction,r);const o=Sn(n,s),i=Pn(n,s);Ir(t,e.fillEntity,o,i)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const kr=new Fr,Br=j("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Dr=j("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});const Ur=new class{build(e){q("Draggable",Br),q("DragState",Dr);const t=e.world,s=e.getResource(nr);let n=null,r={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at)],(e,i)=>{if(lr()&&!cr())return;if(!i.valid)return;const a={x:i.worldMouseX,y:i.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Br,Zn]);let s=null,o=-1/0,i=-1;for(const n of e){if(!t.get(n,Br).enabled)continue;if(t.get(n,Zn).hovered){let e=0;t.has(n,re)&&(e=t.get(n,re).layer);const r=bn(t,n);(e>o||e===o&&r>=i)&&(o=e,i=r,s=n)}}if(null!==s){n=s,r={x:a.x,y:a.y},t.has(s,Dr)||t.insert(s,Dr);const e=t.get(s,Dr),o=t.get(s,te);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,Dr)){t.get(n,Dr).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-r.x,l=a.y-r.y,c=Math.sqrt(e*e+l*l),d=t.get(n,Br);if(c*(i.vpW/(i.worldRight-i.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,Dr).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Dr))return void(o=null);const n=t.get(o,Dr),r=t.get(o,Br),i=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+i,d=n.startWorldPos.y+l;const u=function(e,t,s,n){let r=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,n,c,d);c=u.x,d=u.y;const h=n.currentWorldPos.x,f=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:d-f},n.currentWorldPos={x:c,y:d},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:d-n.startWorldPos.y},t.has(o,te)){const e=function(e,t,s,n){if(!e.has(t,le))return{x:s,y:n};const r=e.get(t,le).entity;if(!e.valid(r)||!e.has(r,te))return{x:s,y:n};const o=e.get(r,te),i=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=Nn(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(s*d-n*c)/i,y:(s*c+n*d)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,te);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,te,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Lr=j("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function zr(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 Wr(e,t,s,n,r){const o=2/(n=Math.max(1e-4,n)),i=o*r,a=1/(1+i+.48*i*i+.235*i*i*i),l=e-t,c=(s+o*l)*r,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(s-o*c)*a}}const $r=new class{build(e){q("ScrollView",Lr);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(rt),ve(at),ve(Me)],(e,r,o)=>{const i=lr()&&!cr(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);r.valid&&(n.x=r.worldMouseX,n.y=r.worldMouseY);const l=t.getEntitiesWithComponents([Lr,hn]);for(const o of l){Tn(t,o,Hn,{enabled:!0,mode:$n});const l=t.get(o,Lr),c=t.get(o,hn);let d=s.get(o);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,d));const u=Sn(c,o),h=Pn(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,ce)){const e=t.get(l.contentEntity,ce).entities;let s=0,n=0,r=0,o=0;for(const i of e){if(!t.valid(i)||!t.has(i,te))continue;const e=t.get(i,te);let a=0,l=0,c=.5,d=.5;if(t.has(i,hn)){const e=t.get(i,hn);a=Sn(e,i)||e.size.x,l=Pn(e,i)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(i,re)){const e=t.get(i,re);a=e.size.x,l=e.size.y}const u=e.position.x-a*c,h=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);u<s&&(s=u),h>n&&(n=h),f<r&&(r=f),p>o&&(o=p)}0===f&&(f=n-s),0===p&&(p=o-r)}const g=Math.max(0,f-u),y=Math.max(0,p-h);if(!i&&r.valid){Tn(t,o,Qn,{enabled:!0,blockRaycast:!0});const s=t.has(o,Zn)?t.get(o,Zn):null;if(s?.justPressed&&(d.isDragging=!0,d.lastWorldX=n.x,d.lastWorldY=n.y,d.velocityX=0,d.velocityY=0),d.isDragging&&e.isMouseButtonDown(0)){const e=n.x-d.lastWorldX,t=n.y-d.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=zr(l.scrollX,0,g,u);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const n=a>0?-e*t/a:0;d.velocityX+=(n-d.velocityX)*s}}if(l.verticalEnabled){const e=zr(l.scrollY,0,y,h);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const n=a>0?t*e/a:0;d.velocityY+=(n-d.velocityY)*s}}d.lastWorldX=n.x,d.lastWorldY=n.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*u,t=5*h;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=zr(l.scrollY,0,y,h);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=zr(l.scrollX,0,g,u);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>y;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Wr(l.scrollX,e,d.velocityX,.1,a);l.scrollX=t.value,d.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(d.velocityX)<Rn&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Rn?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:y,t=Wr(l.scrollY,e,d.velocityY,.1,a);l.scrollY=t.value,d.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(d.velocityY)<Rn&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Rn?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,y)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*u,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,y+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,te)){const e=t.get(l.contentEntity,te),s=e.position.x,n=e.position.y;(isNaN(d.lastAppliedX)||Math.abs(s-d.lastAppliedX)>.01)&&(d.contentBaseX=s),(isNaN(d.lastAppliedY)||Math.abs(n-d.lastAppliedY)>.01)&&(d.contentBaseY=n),e.position.x=d.contentBaseX-l.scrollX,e.position.y=d.contentBaseY+l.scrollY,d.lastAppliedX=e.position.x,d.lastAppliedY=e.position.y,t.insert(l.contentEntity,te,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Or=dn,Hr=j("Slider",{value:0,minValue:0,maxValue:1,direction:dn.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Xr(e,t,s,n,r,o){const i=Sn(n,r)*s.worldScale.x,a=Pn(n,r)*s.worldScale.y,l=Nn(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),u=e-s.worldPosition.x,h=t-s.worldPosition.y,f=u*d-h*c,p=u*c+h*d,g=-n.pivot.x*i,y=-n.pivot.y*a;switch(o){case dn.LeftToRight:return i>0?(f-g)/i:0;case dn.RightToLeft:return i>0?1-(f-g)/i:0;case dn.BottomToTop:return a>0?(p-y)/a:0;case dn.TopToBottom:return a>0?1-(p-y)/a:0}}function jr(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case dn.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case dn.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case dn.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case dn.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class Yr{build(e){q("Slider",Hr);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at),ve(nr)],(e,n,r)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([Hr,hn]);for(const i of o){const o=t.get(i,Hr),a=t.get(i,hn);if(!lr()||cr()){if(t.has(i,te)){Tn(t,i,Qn,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Tn(t,o.handleEntity,Qn,{enabled:!0,blockRaycast:!1});const l=t.get(i,te),c=t.has(i,Zn)?t.get(i,Zn):null;let d=c?.justPressed??!1;if(!d&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Zn)&&(d=t.get(o.handleEntity,Zn).justPressed),d&&(s=i),s===i&&e.isMouseButtonDown(0)){let e=Xr(n.worldMouseX,n.worldMouseY,l,a,i,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(i,Hr,o),o.value!==c&&r.emit(i,"change")}s===i&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,d=Sn(a,i),u=Pn(a,i),h={left:-d/2,bottom:-u/2,right:d/2,top:u/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(mn(t,o.fillEntity,o.direction,c),En(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,hn)){const e=t.get(o.handleEntity,hn);jr(e,o.direction,c),t.insert(o.handleEntity,hn,e),En(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Nr=new Yr;const Vr=new class{build(e){q("Focusable",gr);const t=e.world,s=new yr;e.insertResource(mr,s),e.addSystemToSchedule(exports.Schedule.Update,et([ve(rt),ve(nr)],(e,n)=>{if(lr()&&!cr())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const r=t.getEntitiesWithComponents([gr]);for(const e of r){if(!t.has(e,Zn))continue;t.get(e,Zn).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of r){if(!t.valid(s))continue;if(t.has(s,Qn)){if(!t.get(s,Qn).enabled)continue}const n=t.get(s,gr);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 i=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?n.length-1:0:a?(i-1+n.length)%n.length:(i+1)%n.length,o(n[l])}function o(e){const r=s.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,gr)){t.get(r,gr).isFocused=!1,n.emit(r,"blur",r)}s.focus(e);t.get(e,gr).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},Gr=j("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function qr(){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:r}=t;return{top:s.top,bottom:r-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const Kr=new class{build(e){q("SafeArea",Gr);const t=e.world;let n=qr(),r=!0,o=0,i=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=qr(),r=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=qr(),r=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(at)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===i||(o=e.screenH,i=a,r=!0),!r)return;r=!1;const l=c(),d=s()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([Gr,hn]);for(const e of u){const s=t.get(e,Gr),r=t.get(e,hn),o=s.applyTop?n.top*d:0,i=s.applyBottom?n.bottom*d:0,a=s.applyLeft?n.left*d:0,l=s.applyRight?n.right*d:0;let c=!1;r.offsetMin.x===a&&r.offsetMin.y===i||(r.offsetMin={x:a,y:i},c=!0),r.offsetMax.x===-l&&r.offsetMax.y===-o||(r.offsetMax={x:-l,y:-o},c=!0),c&&t.insert(e,hn,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},Jr=j("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Qr=null;const Zr=new class{build(e){q("ListView",Jr);const t=e.world,s=new Map;Qr=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(rt)],e=>{const n=lr()&&!cr();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 r=t.getEntitiesWithComponents([Jr,hn]);for(const o of r){Tn(t,o,Qn,{enabled:!0,blockRaycast:!0}),Tn(t,o,Hn,{enabled:!0,mode:$n});let r=s.get(o);r||(r={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,r));const i=t.get(o,Jr),a=t.get(o,hn),l=Pn(a,o),c=Sn(a,o);if(!n){const s=t.has(o,Zn)?t.get(o,Zn):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(i.scrollY+=.1*t.y)}}const d=Math.max(0,i.itemCount*i.itemHeight-l);i.scrollY=Math.max(0,Math.min(i.scrollY,d));const u=Math.max(0,Math.floor(i.scrollY/i.itemHeight)-i.overscan),h=Math.min(i.itemCount,Math.ceil((i.scrollY+l)/i.itemHeight)+i.overscan);for(const[e,s]of r.itemEntities)(e<u||e>=h)&&(t.valid(s)&&t.despawn(s),r.itemEntities.delete(e));for(let e=u;e<h;e++){let s=r.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,he,{value:`ListItem_${e}`}),t.insert(s,hn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:i.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),r.itemEntities.set(e,s),r.renderer&&r.renderer(e,s)),t.has(s,te)){const n=t.get(s,te);n.position.y=-(e*i.itemHeight-i.scrollY),t.insert(s,te,n)}}r.visibleStart=u,r.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},eo=j("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const to=new class{build(e){q("Dropdown",eo);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,te))return;const s=t.get(e,te);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,te,{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 r(e){if(t.has(e,re)){const s=t.get(e,re);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,re,{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 r=s.listEntity;if(0===r||!t.valid(r))return;d(r,!0),c(n);const o=t.get(e,re),i=o.size.x,a=o.size.y;n.ddWidth=i;const l=s.options.length*An;t.insert(r,hn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:l},pivot:{x:.5,y:.5}}),t.insert(r,te,{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(r,re,{texture:L,color:{r:1,g:1,b:1,a:1},size:{x:i,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)*An;t.insert(o,he,{value:`Option_${e}`}),t.insert(o,hn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*An},offsetMax:{x:0,y:0},size:{x:i,y:An},pivot:{x:.5,y:.5}}),t.insert(o,te,{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,re,{texture:L,color:{r:.95,g:.95,b:.95,a:1},size:{x:i,y:An},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,Qn,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,r),n.optionEntities.push(o);const c=t.spawn();t.insert(c,te,{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,Dn,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Fn.Left,verticalAlign:kn.Middle,wordWrap:!1,overflow:Bn.Clip,lineHeight:1.2}),t.insert(c,hn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:An},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}u(n)}function i(e,t,s){t.isOpen=!1,c(s),d(t.listEntity,!1)}function a(e,t,s,n,r){t.selectedIndex=n,i(0,t,s),r.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Dn))return;const n=t.get(s,Dn);let r={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,i=!1;if(1===r.r&&1===r.g&&1===r.b&&1===r.a&&(r={r:0,g:0,b:0,a:1},i=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,i=!0)}i&&t.insert(s,Dn,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:r,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function d(e,s){if(0!==e&&t.valid(e)&&(t.has(e,Qn)&&t.insert(e,Qn,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,re))){const n=t.get(e,re);t.insert(e,re,{texture:n.texture,color:{r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:s})}}function u(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,re))continue;const r=s===e.highlightIndex?{...In}:{r:.95,g:.95,b:.95,a:1};t.insert(n,re,{texture:L,color:r,size:{x:e.ddWidth,y:An},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,Zn))continue;if(t.get(s,Zn).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,et([ve(rt),ve(nr)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=lr()&&!cr(),p=t.getEntitiesWithComponents([eo]);for(const g of p){const p=t.get(g,eo);let y=s.get(g);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(g,y)),n(p.listEntity),r(g),p.isOpen||d(p.listEntity,!1),l(p),f)continue;Tn(t,g,Qn,{enabled:!0,blockRaycast:!0});const m=t.has(g,Zn)?t.get(g,Zn):null;if(m?.justPressed&&(p.isOpen?i(g,p,y):o(g,p,y)),p.isOpen){for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,Zn))continue;if(t.get(s,Zn).justPressed){a(g,p,y,e,c);break}}let s=-1;for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,Zn))continue;if(t.get(n,Zn).hovered){s=e;break}}s>=0&&s!==y.highlightIndex&&(y.highlightIndex=s,u(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=p.options.length-1?y.highlightIndex=0:y.highlightIndex++,u(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=p.options.length-1:y.highlightIndex--,u(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?a(g,p,y,y.highlightIndex,c):e.isKeyPressed("Escape")&&i(g,p,y),e.isMouseButtonPressed(0)&&(m?.hovered||h(y)||i(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},so=0,no=0,ro=2,oo=j("LayoutGroup",{direction:so,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:no,reverseOrder:!1});const io=new class{build(e){q("LayoutGroup",oo);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e=t.getEntitiesWithComponents([oo,hn,ce]);for(const s of e){const e=t.get(s,oo),n=t.get(s,hn),r=t.get(s,ce);if(!r.entities||0===r.entities.length)continue;const o=[];for(const e of r.entities)t.valid(e)&&t.has(e,hn)&&t.has(e,te)&&o.push({entity:e,rect:t.get(e,hn)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const i=Sn(n,s),a=Pn(n,s),l=n.pivot.x,c=n.pivot.y,d=e.padding,u=e.direction===so;let h=0;for(let s=0;s<o.length;s++){const n=o[s],r=Sn(n.rect,n.entity),f=Pn(n.rect,n.entity),p=n.rect.pivot.x,g=n.rect.pivot.y;let y,m;u?(y=-l*i+d.left+h+p*r,m=e.childAlignment===no?(1-c)*a-d.top-(1-g)*f:e.childAlignment===ro?-c*a+d.bottom+g*f:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*f,h+=r,s<o.length-1&&(h+=e.spacing)):(y=e.childAlignment===no?-l*i+d.left+p*r:e.childAlignment===ro?(1-l)*i-d.right-(1-p)*r:(.5-l)*i+.5*(d.left-d.right)+(p-.5)*r,m=(1-c)*a-d.top-h-(1-g)*f,h+=f,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,te);_.position.x=y,_.position.y=m,t.insert(n.entity,te,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};J("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),J("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class ao{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,et([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const lo=new ao;async function co(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 uo=we({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ho=we(null,"PhysicsAPI");function fo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function po(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class go{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(uo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=co(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ie]);for(const s of t){const t=e.world.get(s,ie);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;i.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(Me)],a=>{const l=i.getEntitiesWithComponents([pe,te]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,pe),l=i.get(r,te);if(t.has(r)){const e=s.get(r);!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(r,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 i=fo(l.worldRotation);n._physics_createBody(r,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),yo(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===_e.Kinematic){const e=fo(l.worldRotation);n._physics_setBodyTransform(r,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 r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const d=e.world.get(i,te);if(!d)continue;let u=a,h=l,f=c;if(e.world.has(i,le)){const t=e.world.get(i,le);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,te)){const s=e.world.get(t.entity,te),n=fo(s.worldRotation),r=a-s.worldPosition.x,o=l-s.worldPosition.y,i=Math.cos(-n),d=Math.sin(-n);u=(r*i-o*d)/(0!==s.worldScale.x?s.worldScale.x:1),h=(r*d+o*i)/(0!==s.worldScale.y?s.worldScale.y:1),f=c-n}}d.position.x=u,d.position.y=h;const p=po(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(i,te,d)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<d;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(uo,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(ho,mo._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function yo(e,t,s){const n=e.world;if(n.has(s,ge)){const e=n.get(s,ge);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,ye)){const e=n.get(s,ye);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,me)){const e=n.get(s,me);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 mo{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(mo.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const _o={nearest:0,linear:1},xo={repeat:0,clamp:1,mirror:2};function wo(e,t,s=!0,n){const r=e.getResourceManager(),o=e._malloc(t.pixels.length);let i;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&r.createTextureEx){const e=_o[n.filterMode??"linear"]??1,a=xo[n.wrapMode??"clamp"]??1;i=r.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else i=r.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),i}function vo(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 bo(e,t,s,n){const r=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),i=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,u=a+a,h=l+l,f=c+c,p=a*u,g=a*h,y=a*f,m=l*h,_=l*f,x=c*f,w=d*u,v=d*h,b=d*f;return new Float32Array([(1-(m+x))*r,(g+b)*r,(y-v)*r,0,(g-b)*o,(1-(p+x))*o,(_+w)*o,0,(y+v)*i,(_-w)*i,(1-(p+m))*i,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function So(e,t,s,n,r,o,i,a,l){const c=await async function(e,t,s){const n={},r=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=Rt(t.type);for(const i of o){if("texture"!==i.type)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=r?.[o];n[o]=wo(e,await s.loadPixels(o),!0,t)}catch{n[o]=0}}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let d={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),d=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){const i=At(n.type);if(!i||!n.data)continue;const a=n.data[i.skeletonField],l=n.data[i.atlasField];if(!a||!l)continue;const c=r.resolvePath(a),d=r.resolvePath(l);try{const n=await r.readText(l),i="binary"===m(c)?.contentType;let u,h;if(i){const e=await r.readBinary(a);h=e.length,u=t._malloc(h),t.HEAPU8.set(e,u)}else{const e=await r.readText(a),s=(new TextEncoder).encode(e);h=s.length,u=t._malloc(h+1),t.HEAPU8.set(s,u),t.HEAPU8[u+h]=0}const f=s.loadSkeleton(u,h,n,n.length,i);if(t._free(u),f<0)continue;o[a]=f;const p=vo(n),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=g+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=wo(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){const t={gravity:i?.gravity??{...B},fixedTimestep:i?.fixedTimestep??D,subStepCount:i?.subStepCount??4};new go("",t,()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){const r=Rt(t.type).find(e=>"font"===e.type);if(!r)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,r;const i=m(o);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(o)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),r=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),r=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=r?`${r}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=wo(e,c,!1),u=e.getResourceManager();n[o]=u.loadBitmapFont(t,d,c.width,c.height)}catch{n[o]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data)continue;const r=Rt(e.type).find(e=>"material"===e.type);if(!r)continue;const o=e.data[r.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 r=e.vertexSource+e.fragmentSource;let i=n[r];i||(i=mt.createShader(e.vertexSource,e.fragmentSource),n[r]=i),s[o]=mt.createFromAsset(e,i)}catch{s[o]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=Rt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,c,h,f);const p=Dt(e.world,s);if(l&&e.hasResource(Ys))for(const t of p.values())e.world.insert(t,fe,{scene:l,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const i=At(t.type);if(!i||!t.data)continue;const a=s[t.data[i.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(r[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 r}(u,s,d,p);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=k);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,ue)?c.get(o,ue):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&n.update(i,l*u);let h=0;if(c.has(o,te)){const e=bo(c.get(o,te),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=n.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),d=s._malloc(l),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(i,e,c,d,u,f);const p=s.HEAPU32[u>>2],g=s.HEAPU32[f>>2],y=new Float32Array(s.HEAPF32.buffer,c,8*r),m=new Uint16Array(s.HEAPU8.buffer,d,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(_,r,x,o,p,g,h),t._free(_),t._free(x),s._free(c),s._free(d),s._free(u),s._free(f)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource($t);t&&t.setAddressableManifest(a)}}class Po{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 r of e.entities)for(const e of r.components){if(!e.data)continue;const r=At(e.type);if(r){const n=e.data[r.skeletonField],o=e.data[r.atlasField];n&&("binary"===m(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=Rt(e.type);for(const s of o){const r=e.data[s.field];"string"==typeof r&&r&&("font"===s.type?(n.add(r),t.add(r)):"material"===s.type&&t.add(r))}}const r=[];for(const e of t)r.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)r.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(r);const o=[];for(const e of n){const t=m(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(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Mo="__preview__";const To={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ds.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ds.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ds.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ds.releaseRenderTarget(e._handle),To.create({width:t,height:s,depth:!0})),begin(e,t){Ds.begin(t,e._handle)},end(){Ds.end()},getDepthTexture:e=>Ds.getTargetDepthTexture(e._handle)};var Eo;exports.LogLevel=void 0,(Eo=exports.LogLevel||(exports.LogLevel={}))[Eo.Debug=0]="Debug",Eo[Eo.Info=1]="Info",Eo[Eo.Warn=2]="Warn",Eo[Eo.Error=3]="Error";class Co{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 Ro{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Co)}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 r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Ao=new Ro;const Io=[Wn,Jn,or,Mr,kr,fr,Ur,$r,Nr,Cr,xr,Vr,Kr,Zr,to,io,lo];R||(R=!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},r=await d(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.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 u(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 r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}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 r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=A,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.App=qs,exports.AssetPlugin=Ot,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=Wt,exports.Assets=$t,exports.AsyncCache=Tt,exports.BitmapText=de,exports.BodyType=_e,exports.BoxCollider=ge,exports.Button=tr,exports.ButtonState=er,exports.Camera=oe,exports.Canvas=ie,exports.CapsuleCollider=me,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=ce,exports.CircleCollider=ye,exports.ClearFlags=Z,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Ve,exports.DEFAULT_DESIGN_HEIGHT=F,exports.DEFAULT_DESIGN_WIDTH=I,exports.DEFAULT_FALLBACK_DT=k,exports.DEFAULT_FIXED_TIMESTEP=D,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=B,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.DragState=Dr,exports.Draggable=Br,exports.Draw=as,exports.Dropdown=eo,exports.EntityCommands=Ne,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=Je,exports.EventRegistry=qe,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=Ke,exports.FillDirection=dn,exports.FillMethod=vr,exports.FillOrigin=br,exports.FocusManager=mr,exports.FocusManagerState=yr,exports.Focusable=gr,exports.GLDebug=Ws,exports.Geometry=Ss,exports.GetWorld=function(){return{_type:"get_world"}},exports.INVALID_ENTITY=0,exports.INVALID_FONT=z,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=L,exports.Image=Sr,exports.ImageType=wr,exports.Input=rt,exports.InputPlugin=ot,exports.InputState=nt,exports.Interactable=Qn,exports.ListView=Jr,exports.LocalTransform=se,exports.Logger=Ro,exports.Material=mt,exports.MaterialLoader=Et,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=he,exports.Parent=le,exports.Physics=mo,exports.PhysicsEvents=uo,exports.PhysicsPlugin=go,exports.PostProcess=Cs,exports.PrefabServer=Gt,exports.Prefabs=qt,exports.PrefabsPlugin=Kt,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(Ys);t.register({name:Mo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Mo),this.loadPromise_=t.load(Mo).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 Po(this.baseUrl_);await s.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await So(this.app_,this.app_.wasmModule,t,s,r,null,void 0,null,Mo)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([oe]);for(const n of s){if(e.get(n,oe).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([ie]);for(const r of n){const n=e.get(r,ie);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(Ys).getScene(Mo),o=r?r.spawn():e.spawn(),i={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,te,i);const a={isActive:!0,projectionType:Q.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Z.ColorAndDepth};e.insert(o,oe,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(Ys);await e.switchTo(Mo),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=Ar,exports.ProgressBarDirection=Rr,exports.ProgressBarPlugin=Fr,exports.ProjectionType=Q,exports.Query=function(...e){return Xe(e)},exports.QueryInstance=je,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=Ye,exports.RenderPipeline=$s,exports.RenderTexture=To,exports.Renderer=Ds,exports.Res=ve,exports.ResMut=be,exports.RigidBody=pe,exports.RuntimeConfig=U,exports.SafeArea=Gr,exports.ScaleMode=ee,exports.SceneManager=Ys,exports.SceneManagerState=js,exports.SceneOwner=fe,exports.ScrollView=Lr,exports.ShaderSources=Mt,exports.Slider=Hr,exports.SliderDirection=Or,exports.SliderPlugin=Yr,exports.SpineAnimation=ue,exports.Sprite=re,exports.SystemRunner=st,exports.Text=Dn,exports.TextAlign=Fn,exports.TextInput=pr,exports.TextInputPlugin=_r,exports.TextOverflow=Bn,exports.TextPlugin=zn,exports.TextRenderer=Un,exports.TextVerticalAlign=kn,exports.Time=Me,exports.Toggle=Tr,exports.Transform=te,exports.UICameraInfo=at,exports.UIEventQueue=sr,exports.UIEvents=nr,exports.UIInteraction=Zn,exports.UIInteractionPlugin=hr,exports.UILayoutPlugin=rr,exports.UIMask=Hn,exports.UIMaskPlugin=Kn,exports.UIRect=hn,exports.UIRenderOrderPlugin=ao,exports.Velocity=ae,exports.WebAssetProvider=Po,exports.World=ze,exports.WorldTransform=ne,exports.addStartupSystem=function(e){tt().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){tt().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){tt().push({schedule:e,system:t})},exports.applyDirectionalFill=mn,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=U.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=U.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=U.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=U.canvasMatchWidthOrHeight)},exports.assetPlugin=Ht,exports.clearDrawCallbacks=ps,exports.clearUserComponents=function(){const e=X();for(const t of e.keys())G.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=yn,exports.computeFillSize=function(e,t,s,n){switch(e){case dn.BottomToTop:case dn.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case dn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case dn.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case dn.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=un,exports.createMaskProcessor=qn,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,async setup(){await So(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}},exports.createWebApp=function(e,t){return function(e,t){const s=qs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ns(e),pt(e),ws(e),Ms(e),ks(e),Ls(e);const r=new $s;s.setPipeline(r);let o=l();const i=t?.getViewportSize??(()=>{const e=c();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,r,o){o||(o=en(e,n,t,r));const i=s.getResource(at);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(at,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const d={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const d=e.registry_getCanvasEntity(n);if(d>=0){const e=n.getCanvas(d).backgroundColor;Ds.setClearColor(e.x,e.y,e.z,e.w)}const u=(l()-o)/1e3;let h;if(Ds.resize(t,c),Cs.isInitialized()&&Cs.getPassCount()>0&&!Cs.isBypassed()&&Cs.resize(t,c),s.hasResource(Ys)){const e=s.getResource(Ys).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=en(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:Ks,width:t,height:c,elapsed:u});else{for(const e of f){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:l},clearFlags:e.clearFlags,elapsed:u})}Ds.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,d),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(Ht),s.addPlugin(Jt),s.addPlugin(it),s.addPlugin(Gs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Io,...t})},exports.debug=function(e,t,s){Ao.debug(e,t,s)},exports.defineComponent=j,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=we,exports.defineSystem=et,exports.defineTag=function(e){const t=G.get(e)??X().get(e);if(t)return t;const s=O(e,{});return X().set(e,s),G.set(e,s),N(e,{},!0),s},exports.error=function(e,t,s){Ao.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([he]);for(const n of s){const s=e.get(n,he);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return m(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of h)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return g},exports.getAssetMimeType=function(e){return f[e.toLowerCase()]},exports.getAssetTypeEntry=m,exports.getComponent=K,exports.getComponentAssetFieldDescriptors=Rt,exports.getComponentAssetFields=function(e){const t=Ct.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},exports.getComponentDefaults=function(e){const t=K(e);return t?W(t._default):null},exports.getComponentEntityFields=Ft,exports.getComponentSpineFieldDescriptor=At,exports.getCustomExtensions=x,exports.getEditorType=function(e){return m(e)?.editorType??"unknown"},exports.getLogger=function(){return Ao},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=Y,exports.getWeChatPackOptions=function(){return x().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Ao.info(e,t,s)},exports.initDrawAPI=ns,exports.initGLDebugAPI=Ls,exports.initGeometryAPI=ws,exports.initMaterialAPI=pt,exports.initPostProcessAPI=Ms,exports.initRendererAPI=ks,exports.inputPlugin=it,exports.instantiatePrefab=Xt,exports.intersectRects=Xn,exports.invertMatrix4=jn,exports.isBuiltinComponent=V,exports.isCustomExtension=w,exports.isEditor=lr,exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=cr,exports.isRuntime=function(){return!ir},exports.isTextureRef=ct,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=zt,exports.loadPhysicsModule=co,exports.loadRuntimeScene=So,exports.loadSceneData=Dt,exports.loadSceneWithAssets=Ut,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&_(y(e)))},exports.platformFetch=n,exports.platformFileExists=i,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=r,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,r,o,i,a,l,c){const d=Nn(l,c),u=Math.sin(-d),h=Math.cos(-d),f=e-s,p=t-n,g=f*h-p*u+s,y=f*u+p*h+n;return g>=s-r*i&&g<=s+r*(1-i)&&y>=n-o*a&&y<=n+o*(1-a)},exports.pointInWorldRect=function(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)},exports.prefabsPlugin=Jt,exports.progressBarPlugin=kr,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=q,exports.registerComponentAssetFields=function(e,t){Ct.set(e,t)},exports.registerComponentEntityFields=function(e,t){It.set(e,t)},exports.registerDrawCallback=hs,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource($t);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Pt,exports.remapEntityFields=kt,exports.sceneManagerPlugin=Gs,exports.screenToWorld=Yn,exports.setEditorMode=function(e){ir=e},exports.setListViewRenderer=function(e,t){if(!Qr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=Qr.get(e);s?s.renderer=t:Qr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Ao.setMinLevel(e)},exports.setPlayMode=function(e){ar=e},exports.setWasmErrorHandler=Ae,exports.shutdownDrawAPI=rs,exports.shutdownGLDebugAPI=zs,exports.shutdownGeometryAPI=vs,exports.shutdownMaterialAPI=gt,exports.shutdownPostProcessAPI=Ts,exports.shutdownRendererAPI=Bs,exports.sliderPlugin=Nr,exports.syncFillSpriteSize=function(e,t,s,n,r,o){if(!e.has(t,re))return;const i=e.get(t,re);let a,l;switch(s){case dn.BottomToTop:case dn.TopToBottom:a=r,l=o*n;break;default:a=r*n,l=o}i.size.x===a&&i.size.y===l||(i.size.x=a,i.size.y=l,e.insert(t,re,i))},exports.textInputPlugin=xr,exports.textPlugin=Wn,exports.transitionTo=async function(e,t,s){const n=e.getResource(Ys);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=fr,exports.uiLayoutPlugin=or,exports.uiMaskPlugin=Jn,exports.uiPlugins=Io,exports.uiRenderOrderPlugin=lo,exports.unregisterComponent=function(e){X().delete(e),G.delete(e)},exports.unregisterDrawCallback=fs,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([oe]);for(const n of s){const s=e.get(n,oe);s&&(s.aspectRatio=t,e.insert(n,oe,s))}},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){Ao.warn(e,t,s)},exports.wrapSceneSystem=Ns,exports.wxFileExists=T,exports.wxFileExistsSync=function(e){const t=b();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=C,exports.wxLoadImage=E,exports.wxLoadImagePixels=async function(e){return C(await E(e))},exports.wxReadFile=P,exports.wxReadTextFile=M,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{b().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 r(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function i(e){return t().fileExists(e)}function a(e,s){return t().createCanvas(e,s)}function l(){return t().now()}function c(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}function d(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"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 u(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 h=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],f={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},p=new Map,g=new Set;for(const e of h)for(const t of e.extensions)p.set(t,e),g.add(t);function y(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function m(e){return p.get(y(e))}function _(e){return g.has(e.toLowerCase())}function x(){const e=[];for(const t of h)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function w(e){const t=m(e);return t?.wechatPackInclude??!1}let v=null;function b(){return v||(v=wx.getFileSystemManager()),v}function S(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(w(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 P(e){return new Promise((t,s)=>{b().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(S(e,t.errMsg)))}})})}function M(e,t="utf-8"){return new Promise((s,n)=>{b().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(S(e,t.errMsg)))}})})}function T(e){return new Promise(t=>{b().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function E(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 C(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 r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let R=!1;const A=new class{constructor(){this.name="wechat"}async fetch(e,t){return d(e,t)}async readFile(e){return P(e)}async readTextFile(e){return M(e)}async fileExists(e){return T(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return u(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){wx.onTouchStart(t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},I=1920,F=1080,k=1/60,B={x:0,y:-9.81},U=1/60,D={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const L=4294967295,z=4294967295;function W(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(W);const t={};for(const s in e)t[s]=W(e[s]);return t}let $=0;function O(e,t){const s=++$,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?{...W(t),...e}:W(t):e?{...t,...e}:{...t}}}const H=new Map;function X(){return"undefined"==typeof window?H:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function j(e,t){const s=G.get(e)??X().get(e);if(s)return s;const n=O(e,t);return X().set(e,n),G.set(e,n),N(e,t,!1),n}function Y(e){return X().get(e)}function N(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function V(e){return!0===e._builtin}const G=new Map;function q(e,t){G.set(e,t)}function K(e){return G.get(e)??Y(e)}function J(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return G.set(e,s),s}const Q={Perspective:0,Orthographic:1},Z={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ee={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},te=J("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}}),se=te,ne=te,re=J("Sprite",{texture:L,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}),oe=J("Camera",{projectionType:Q.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:Z.ColorAndDepth}),ie=J("Canvas",{designResolution:{x:I,y:F},pixelsPerUnit:100,scaleMode:ee.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ae=J("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),le=J("Parent",{entity:0}),ce=J("Children",{entities:[]}),de=J("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:z,enabled:!0}),ue=J("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}),he=j("Name",{value:""}),fe=j("SceneOwner",{scene:"",persistent:!1});const pe=J("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ge=J("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ye=J("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),me=J("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),_e={Static:0,Kinematic:1,Dynamic:2};let xe=0;function we(e,t){const s=++xe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ve(e){return{_type:"res",_resource:e}}function be(e){return{_type:"res_mut",_resource:e}}class Se{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 Pe{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 Se(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Me=we({delta:0,elapsed:0,frameCount:0},"Time");function Te(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=Ee(t[e]),o=Ee(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function Ee(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ce(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 Re=null;function Ae(e){Re=e}function Ie(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Re&&Re(e,t)}function Fe(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 ke=1;const Be=new WeakMap;function Ue(e){let t=Be.get(e);return void 0===t&&(t=ke++,Be.set(e,t)),t}const De=[];function Le(e,t=[],s=[]){De.length=0;for(const t of e)De.push(Ue(t));De.sort((e,t)=>e-t);let n=De.join(",");if(t.length>0){De.length=0;for(const e of t)De.push(Ue(e));De.sort((e,t)=>e-t),n+="|+"+De.join(",")}if(s.length>0){De.length=0;for(const e of s)De.push(Ue(e));De.sort((e,t)=>e-t),n+="|-"+De.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 Ie(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){Ie(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){Ie(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ie(t,`removeParent(entity=${e})`)}}insert(e,t,s){return V(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(V(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Fe(s))}catch(s){Ie(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 V(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return V(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(V(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Ie(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.");V(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}`],r=s[`get${e}`],o=s[`has${e}`],i=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof r||"function"!=typeof o||"function"!=typeof i)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:r.bind(s),has:o.bind(s),remove:i.bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Te(t._name,t._default,n);if(e.length>0)throw new Error(Ce(t._name,e))}const r={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,Fe(r))}catch(s){Ie(s,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),r}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 r=t[n];if(null!=r&&"object"==typeof r&&!Array.isArray(r)&&"r"in r&&"g"in r&&"b"in r&&"a"in r){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 r=e[s],o=t[s];if(null==r||"object"!=typeof r||Array.isArray(r)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=r;else{const e=r,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}:r}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return Ie(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 Ie(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ie(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 r=Te(t._name,t._default,e);if(r.length>0)throw new Error(Ce(t._name,r));n=e}const r=t.create(n),o=this.getStorage(t),i=!o.has(e);o.set(e,r);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),i&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),r}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 G)if(V(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=X();for(const n of s)for(const[s,r]of e)if(r._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 r=n??Le(e,t,s),o=this.queryCache_.get(r);if(o&&o.version===this.worldVersion_)return o.result;let i=null,a=1/0;for(const t of e)if(!V(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=i?i.keys():this.entities_.keys();for(const n of c){let r=!0;for(const t of e)if(!this.has(n,t)){r=!1;break}if(r)for(const e of t)if(!this.has(n,e)){r=!1;break}if(r)for(const e of s)if(this.has(n,e)){r=!1;break}r&&l.push(n)}return this.queryCache_.set(r,{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 r=n.get(e);return void 0!==r&&r>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const r=n.get(e);return void 0!==r&&r>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 We(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function $e(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Oe(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function He(e){return We(e)||$e(e)||Oe(e)?e._component:e}function Xe(e,t=[],s=[]){const n=[],r=[],o=[];return e.forEach((e,t)=>{We(e)&&n.push(t),$e(e)?r.push({index:t,component:e._component}):Oe(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:r,_changedFilters:o,with:(...n)=>Xe(e,[...t,...n],s),without:(...n)=>Xe(e,t,[...s,...n])}}class je{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(He),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_=Le(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,r=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,i=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of s)if(!o||this.passesChangeFilters_(d)){if(null!==c&&r)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}i[0]=d;for(let e=0;e<n;e++)i[e+1]=this.world_.get(d,t[e]);if(r){for(let t=0;t<l;t++)a[t].data=i[e[t]+1];c=d}yield i}}finally{if(this.world_.endIteration(),null!==c&&r)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 Ye{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 Ne{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=V(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 Ve{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ne(this,null);return this.spawned_.push(e),e}entity(e){return new Ne(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"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}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 Ge{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 qe{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Ge)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Ge,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class Ke{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Je{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Qe;exports.Schedule=void 0,(Qe=exports.Schedule||(exports.Schedule={}))[Qe.Startup=0]="Startup",Qe[Qe.First=1]="First",Qe[Qe.PreUpdate=2]="PreUpdate",Qe[Qe.Update=3]="Update",Qe[Qe.PostUpdate=4]="PostUpdate",Qe[Qe.Last=5]="Last",Qe[Qe.FixedPreUpdate=10]="FixedPreUpdate",Qe[Qe.FixedUpdate=11]="FixedUpdate",Qe[Qe.FixedPostUpdate=12]="FixedPostUpdate";let Ze=0;function et(e,t,s){const n=++Ze;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function tt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class st{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}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]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ve&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new je(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 Ve(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 Ke(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Je(s)}case"removed":{const t=e;return new Ye(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class nt{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 rt=we(new nt,"Input");class ot{constructor(e){this.target_=e??null}build(e){const s=new nt;e.insertResource(rt,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,et([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const it=new ot,at=we({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 lt;function ct(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(lt=exports.BlendMode||(exports.BlendMode={}))[lt.Normal=0]="Normal",lt[lt.Additive=1]="Additive",lt[lt.Multiply=2]="Multiply",lt[lt.Screen=3]="Screen",lt[lt.PremultipliedAlpha=4]="PremultipliedAlpha";let dt=null,ut=null,ht=1;const ft=new Map;function pt(e){dt=e,ut=e.getResourceManager(),Pt()}function gt(){0!==xt&&dt&&(dt._free(xt),xt=0),ft.clear(),ht=1,_t=!1,vt.clear(),bt=null,ut=null,dt=null}function yt(){if(!ut)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return ut}const mt={createShader:(e,t)=>yt().createShader(e,t),releaseShader(e){e>0&&yt().releaseShader(e)},create(e){const t=ht++,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 ft.set(t,s),t},get:e=>ft.get(e),setUniform(e,t,s){const n=ft.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,dt?.invalidateMaterialCache(e))},getUniform(e,t){const s=ft.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=ft.get(e);s&&(s.blendMode=t,dt?.invalidateMaterialCache(e))},getBlendMode(e){const t=ft.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=ft.get(e);s&&(s.depthTest=t,dt?.invalidateMaterialCache(e))},getShader(e){const t=ft.get(e);return t?.shader??0},release(e){ft.delete(e),dt?.invalidateMaterialCache(e)},isValid:e=>ft.has(e),releaseAll(){ft.clear(),dt?.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=ft.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=ht++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return ft.set(s,n),s},toAssetData(e,t){const s=ft.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=ft.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let _t=!1,xt=0;const wt=16384,vt=new Map;let bt=null;function St(e){const t=(0===xt&&dt&&(xt=dt._malloc(wt)),xt);if(0===t||!dt)return{ptr:0,count:0};let s=0,n=0;const r=dt.HEAPU8,o=dt.HEAPU32,i=dt.HEAPF32;for(const[a,l]of e){if(ct(l))continue;let e=vt.get(a);e||(bt||(bt=new TextEncoder),e=bt.encode(a),vt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(s+(4+d+4+16)>wt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${wt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=d;let u=0,h=[0,0,0,0];if("number"==typeof l)u=0,h[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(u=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,h=[l.x,l.y,l.z,0]):"y"in l&&(u=1,h=[l.x,l.y,0,0]);o[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Pt(){if(!dt||_t)return;dt.materialDataProvider=(e,t,s,n,r)=>{const o=ft.get(e);if(!o)return dt.HEAPU32[t>>2]=0,dt.HEAPU32[s>>2]=0,dt.HEAPU32[n>>2]=0,void(dt.HEAPU32[r>>2]=0);dt.HEAPU32[t>>2]=o.shader,dt.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=St(o.uniforms);dt.HEAPU32[n>>2]=i,dt.HEAPU32[r>>2]=a},_t=!0}const Mt={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 Tt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Et{constructor(e,t=""){this.cache_=new Tt,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&&(mt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())mt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await i(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 r=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(r);return{handle:mt.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}}const Ct=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"}]}]]);function Rt(e){const t=Ct.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 At(e){return Ct.get(e)?.fields??[]}function It(e){return Ct.get(e)?.spine??null}const Ft=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function kt(e){return Ft.get(e)}function Bt(e,t){const s=Ft.get(e.type);if(!s)return;const n=e.data;for(const r of s){const s=n[r];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${r} references entity ${s} which does not exist`),n[r]=void 0!==o?o:0}}}function Ut(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,he,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const r of n.components)Bt(r,s),Wt(e,t,r,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}function Dt(e,t){return Ut(e,t)}async function Lt(e,t,s){const n=s?.assetServer,r=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,r){const o=new Map;for(const e of zt.keys())o.set(e,new Set);const i=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ct.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),i.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=[...zt.entries()].map(async([e,r])=>{const i=await r.load(o.get(e),t,s,n);l.set(e,i)}),d=i.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...d]),r){for(const e of n.values())r.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&r.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)r.fontPaths.add(e);for(const e of a)r.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ct.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&(s[e.field]=l.get(e.type)?.get(t)??0)}}}(t,n,r,o,s?.collectAssets);const i=Ut(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 i}const zt=new Map([["texture",{async load(e,t,s,n){const r=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(o);r.set(e,i.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),r.set(e,0)}});return await Promise.all(o),r}}],["material",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadMaterial(e,s);n.set(e,r.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}],["font",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadBitmapFont(e,s);n.set(e,r)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}]]);function Wt(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 r=K(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}class $t{constructor(e){this.textureCache_=new Tt,this.shaderCache_=new Tt,this.jsonCache_=new Tt,this.textCache_=new Tt,this.binaryCache_=new Tt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Tt,this.prefabCache_=new Tt,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_=a(D.textCanvasSize,D.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 Et(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),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.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(),mt.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 r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),d="binary"===m(e)?.contentType,u=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,d);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.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=m(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 r=s?`${s}/${n}`:n;return this.loadFntFile(r)}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],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.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 Rt(e.type)){const n=e.data[s];if("string"==typeof n&&n){const r=t(n);r&&(e.data[s]=r)}}const s=It(e.type);if(s)for(const n of[s.skeletonField,s.atlasField]){const s=e.data[n];if("string"==typeof s&&s){const r=t(s);r&&(e.data[n]=r)}}}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 Lt(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 r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).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.embedded_.get(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 r=t().createImage();r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(r)},r.onerror=()=>n(new Error(`Failed to load image: ${e}`)),r.src=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,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,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?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 i=this.module_.GL,a=i.getNewId(i.textures);i.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 r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.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.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return mt.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await i(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:r,fragment:a}=this.parseEsShader(n);if(!r||!a)throw new Error(`Invalid shader format: ${e}`);return mt.createShader(r,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}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(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.embedded_.get(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.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(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 r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}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 Ot=we(null,"Assets");class Ht{build(e){const t=e.wasmModule;t?e.insertResource(Ot,new $t(t)):console.warn("AssetPlugin: No WASM module available")}}const Xt=new Ht;async function jt(e,t,s){const{entities:n,rootId:r}=await Nt(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}))},i=await Lt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const Yt=10;async function Nt(e,t,s,n,r,o=0){if(o>Yt)throw new Error(`Prefab nesting depth exceeded ${Yt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.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(r?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Nt(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),l.push(...t.entities);continue}const c=i.get(n.prefabEntityId),d=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:d?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Vt(u.components,i),Gt(u,t),l.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Vt(e,t){for(const s of e){const e=kt(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const r=t.get(e);void 0!==r&&(s.data[n]=r)}}}}function Gt(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 qt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return jt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Kt=we(null,"Prefabs");class Jt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ot]}build(e){const t=e.getResource(Ot);e.insertResource(Kt,new qt(e.world,t))}}const Qt=new Jt;let Zt=null,es=0,ts=0,ss=0;const ns=new Float32Array(256);function rs(e){Zt=e,es=Zt._malloc(64),ts=Zt._malloc(64),ss=Zt._malloc(1024)}function os(){Zt&&(es&&(Zt._free(es),es=0),ts&&(Zt._free(ts),ts=0),ss&&(Zt._free(ss),ss=0)),Zt=null}function is(){if(!Zt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Zt}const as={r:1,g:1,b:1,a:1},ls={begin(e){const t=is();try{t.HEAPF32.set(e,es/4),t.draw_begin(es)}catch(e){Ie(e,"Draw.begin")}},end(){try{is().draw_end()}catch(e){Ie(e,"Draw.end")}},line(e,t,s,n=1){try{is().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ie(e,"Draw.line")}},rect(e,t,s,n=!0){try{is().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ie(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{is().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ie(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{is().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ie(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{is().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ie(e,"Draw.circleOutline")}},texture(e,t,s,n=as){try{is().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ie(e,"Draw.texture")}},textureRotated(e,t,s,n,r=as){try{is().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Ie(e,"Draw.textureRotated")}},setLayer(e){is().draw_setLayer(e)},setDepth(e){is().draw_setDepth(e)},getDrawCallCount:()=>Zt?Zt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Zt?Zt.draw_getPrimitiveCount():0,setBlendMode(e){is().draw_setBlendMode(e)},setDepthTest(e){is().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=is();n.HEAPF32.set(s,ts/4),n.draw_mesh(e,t,ts)}catch(s){Ie(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=is(),r=mt.get(t);if(!r)return;if(ls.setBlendMode(r.blendMode),ls.setDepthTest(r.depthTest),0===r.uniforms.size)return void ls.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,ts/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=us(t);if(!(n<0)){if(ct(s))ns[o++]=10,ns[o++]=n,ns[o++]=s.slot??e++,ns[o++]=s.textureId;else if("number"==typeof s)ns[o++]=1,ns[o++]=n,ns[o++]=s;else if(Array.isArray(s)){ns[o++]=s.length,ns[o++]=n;for(let e=0;e<s.length;e++)ns[o++]=s[e]}else"w"in s?(ns[o++]=4,ns[o++]=n,ns[o++]=s.x,ns[o++]=s.y,ns[o++]=s.z,ns[o++]=s.w):"z"in s?(ns[o++]=3,ns[o++]=n,ns[o++]=s.x,ns[o++]=s.y,ns[o++]=s.z):(ns[o++]=2,ns[o++]=n,ns[o++]=s.x,ns[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(ns.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,ts);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),ss/4),n.draw_meshWithUniforms(e,r.shader,ts,ss,o)}catch(s){Ie(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},cs={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},ds=new Set;function us(e){const t=cs[e];return void 0!==t?t:(ds.has(e)||(ds.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(cs).join(", ")}`)),-1)}const hs=new Map;function fs(e,t,s){hs.set(e,{fn:t,scene:s??""})}function ps(e){hs.delete(e)}function gs(){hs.clear()}var ys;exports.DataType=void 0,(ys=exports.DataType||(exports.DataType={}))[ys.Float=1]="Float",ys[ys.Float2=2]="Float2",ys[ys.Float3=3]="Float3",ys[ys.Float4=4]="Float4",ys[ys.Int=5]="Int",ys[ys.Int2=6]="Int2",ys[ys.Int3=7]="Int3",ys[ys.Int4=8]="Int4";let ms=null,_s=0,xs=0,ws=0;function vs(e){ms=e,_s=ms._malloc(262144),xs=ms._malloc(65536),ws=ms._malloc(256)}function bs(){ms&&(_s&&ms._free(_s),xs&&ms._free(xs),ws&&ms._free(ws),_s=0,xs=0,ws=0),ms=null}function Ss(){if(!ms)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ms}const Ps={create(e){const t=Ss(),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,_s/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ws,r).set(o),t.geometry_init(s,_s,n,ws,r,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,xs,n).set(e.indices),t.geometry_setIndices16(s,xs,n)}else{new Uint32Array(t.HEAPU8.buffer,xs,n).set(e.indices),t.geometry_setIndices32(s,xs,n)}}return s},updateVertices(e,t,s=0){const n=Ss(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,_s/4),n.geometry_updateVertices(e,_s,r,s)},release(e){e>0&&Ss().geometry_release(e)},isValid:e=>!(!ms||e<=0)&&ms.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Ps.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 r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Ps.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,r=-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),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Ps.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let Ms=null;function Ts(e){Ms=e}function Es(){Ms&&Rs.isInitialized()&&Rs.shutdown(),Ms=null}function Cs(){if(!Ms)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ms}const Rs={init(e,t){try{return Cs().postprocess_init(e,t)}catch(s){return Ie(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Cs().postprocess_shutdown()}catch(e){Ie(e,"PostProcess.shutdown")}},resize(e,t){try{Cs().postprocess_resize(e,t)}catch(s){Ie(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Cs().postprocess_addPass(e,t)}catch(t){return Ie(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Cs().postprocess_removePass(e)}catch(t){Ie(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Cs().postprocess_setPassEnabled(e,t)}catch(t){Ie(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Cs().postprocess_isPassEnabled(e)}catch(t){return Ie(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Cs().postprocess_setUniformFloat(e,t,s)}catch(s){Ie(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Cs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Ie(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Cs().postprocess_begin()}catch(e){Ie(e,"PostProcess.begin")}},end(){try{Cs().postprocess_end()}catch(e){Ie(e,"PostProcess.end")}},getPassCount(){try{return Cs().postprocess_getPassCount()}catch(e){return Ie(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ms)return!1;try{return Ms.postprocess_isInitialized()}catch(e){return Ie(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Cs().postprocess_setBypass(e)}catch(e){Ie(e,"PostProcess.setBypass")}},isBypassed(){if(!Ms)return!0;try{return Ms.postprocess_isBypassed()}catch(e){return Ie(e,"PostProcess.isBypassed"),!0}},createBlur:()=>mt.createShader(As,"#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:()=>mt.createShader(As,"#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:()=>mt.createShader(As,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>mt.createShader(As,"#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")},As="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Is;exports.RenderStage=void 0,(Is=exports.RenderStage||(exports.RenderStage={}))[Is.Background=0]="Background",Is[Is.Opaque=1]="Opaque",Is[Is.Transparent=2]="Transparent",Is[Is.Overlay=3]="Overlay";let Fs=null,ks=0;function Bs(e){Fs=e,ks=Fs._malloc(64)}function Us(){Fs&&ks&&(Fs._free(ks),ks=0),Fs=null}const Ds={init(e,t){Fs?.renderer_init(e,t)},resize(e,t){Fs?.renderer_resize(e,t)},begin(e,t){if(Fs&&ks)try{Fs.HEAPF32.set(e,ks/4),Fs.renderer_begin(ks,t??0)}catch(e){Ie(e,"Renderer.begin")}},flush(){try{Fs?.renderer_flush()}catch(e){Ie(e,"Renderer.flush")}},end(){try{Fs?.renderer_end()}catch(e){Ie(e,"Renderer.end")}},submitSprites(e){if(Fs)try{Fs.renderer_submitSprites(e._cpp)}catch(e){Ie(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Fs)try{Fs.renderer_submitBitmapText(e._cpp)}catch(e){Ie(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Fs)try{Fs.renderer_submitSpine?.(e._cpp)}catch(e){Ie(e,"Renderer.submitSpine")}},setStage(e){Fs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Fs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Fs?.renderer_releaseTarget(e)},getTargetTexture:e=>Fs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Fs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Fs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Fs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Fs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Fs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Fs?Fs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Fs?{drawCalls:Fs.renderer_getDrawCalls(),triangles:Fs.renderer_getTriangles(),sprites:Fs.renderer_getSprites(),text:Fs.renderer_getText(),spine:Fs.renderer_getSpine?.()??0,meshes:Fs.renderer_getMeshes(),culled:Fs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Ls=null;function zs(e){Ls=e}function Ws(){Ls=null}const $s={enable(){Ls?.gl_enableErrorCheck(!0)},disable(){Ls?.gl_enableErrorCheck(!1)},check:e=>Ls?.gl_checkErrors(e)??0,diagnose(){Ls?.renderer_diagnose()}};class Os{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(Ds.resize(n,r),Rs.isInitialized()&&Rs.getPassCount()>0&&Rs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Ds.setViewport(0,0,n,r),Ds.clearBuffers(3),Ds.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Ds.submitSprites(t),Ds.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ds.submitSpine(t),Ds.flush(),this.executeDrawCallbacks(s,o),Ds.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;Ds.setViewport(n.x,n.y,n.w,n.h),Ds.setScissor(n.x,n.y,n.w,n.h,!0),Ds.clearBuffers(r),Ds.setScissor(0,0,0,0,!1),Ds.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ds.submitSprites(t),Ds.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ds.submitSpine(t),Ds.flush(),this.executeDrawCallbacks(s,o),Ds.end()}executeDrawCallbacks(e,t){const s=hs;if(s.size>0){ls.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}ls.end();for(const e of n)ps(e)}}}const Hs="__scene_transition_overlay__";class Xs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class js{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,fe,{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),fs(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Rs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Rs.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,fe)){const s=this.app_.world.get(e,fe);s.persistent=t,this.app_.world.insert(e,fe,s)}}}class Ys{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??D.sceneTransitionDuration,r=t.color??{...D.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},fs(Hs,()=>{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;ls.setLayer(9999),ls.setDepth(9999),ls.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.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,ps(Hs),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,ps(Hs),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 Xs(t);this.scenes_.set(e,s);const n=new js(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ot)?this.app_.getResource(Ot):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}return await this.loadSceneData_(s,e,t,r),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}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 Xs(t);this.scenes_.set(e,s);const n=new js(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ot)?this.app_.getResource(Ot):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}return await this.loadSceneData_(s,e,t,r),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}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 r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,fe)){if(this.app_.world.get(e,fe).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())ps(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Rs.removePass(e)}catch{}s.postProcessPasses.length=0,this.releaseSceneAssets_(s),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},r={collectAssets:s};this.app_.hasResource(Ot)&&(r.assetServer=this.app_.getResource(Ot));const o=await Lt(this.app_.world,n,r);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,fe,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=Vs(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const r=this.contexts_.get(t);s.setup&&await s.setup(r)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource(Ot)?this.app_.getResource(Ot):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)mt.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 r=!1;if(s.has(e,re)){const t=s.get(e,re);n.sprite=t.color.a,t.color.a=0,s.insert(e,re,t),r=!0}if(s.has(e,ue)){const t=s.get(e,ue);n.spine=t.color.a,t.color.a=0,s.insert(e,ue,t),r=!0}if(s.has(e,de)){const t=s.get(e,de);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,de,t),r=!0}r&&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,re)){const t=s.get(e,re);t.color.a=n.sprite,s.insert(e,re,t)}if(void 0!==n.spine&&s.has(e,ue)){const t=s.get(e,ue);t.color.a=n.spine,s.insert(e,ue,t)}if(void 0!==n.bitmapText&&s.has(e,de)){const t=s.get(e,de);t.color.a=n.bitmapText,s.insert(e,de,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Rs.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Ns=we(null,"SceneManager");function Vs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Ns).getSceneStatus(t)&&s._fn(...n)}}}const Gs=et([be(Ns),ve(Me)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),qs={name:"SceneManager",build(e){const t=new Ys(e);e.insertResource(Ns,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ns),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,Gs)}};class Ks{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 qe,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=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=l(),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 ze,this.resources_=new Pe;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ks}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 r=n.filter(t=>t.system._id!==e);r.length!==n.length&&(this.systems_.set(s,r),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 Ae(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_}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(Ns).register(e),this}setInitialScene(e){return this.getResource(Ns).setInitial(e),this}tick(e){this.runner_||(this.runner_=new st(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(Me)||this.resources_.insert(Me,{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.runSchedule(exports.Schedule.First),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last);this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new st(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(Me,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=l(),this.mainLoop())}quit(){this.running_=!1,gs();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=[Ws,Us,Es,bs,gt,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 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 r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Me);t.delta=e,t.elapsed+=e,t.frameCount++}}const Js=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Qs(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case ee.FixedWidth:return o;case ee.FixedHeight:return i;case ee.Expand:return Math.max(o,i);case ee.Shrink:return Math.min(o,i);case ee.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}const Zs=[];function en(e){if(e<Zs.length)return Zs[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 Zs.push(t),t}function tn(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,fe);return!t||""===t.scene||o.has(t.scene)}):i;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 r=t.getCamera(e),o=t.getTransform(e),i=r.viewportW*s/(r.viewportH*n);let a,d=0,u=0;if(r.projectionType===Q.Orthographic){if(u=r.orthoSize,l){u=Qs(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,i,l.scaleMode,l.matchWidthOrHeight)}d=u*i,a=nn(-d,d,-u,u,-r.farPlane,r.farPlane)}else a=on(r.fov*Math.PI/180,i,r.nearPlane,r.farPlane);const h=ln(o.position.x,o.position.y,o.position.z),f=en(c.length);f.entity=e,f.viewProjection.set(dn(a,h)),f.viewportRect.x=r.viewportX,f.viewportRect.y=r.viewportY,f.viewportRect.w=r.viewportW,f.viewportRect.h=r.viewportH,f.clearFlags=r.clearFlags,f.priority=r.priority,f.halfW=d,f.halfH=u,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const sn=new Float32Array(16);function nn(e,t,s,n,r,o){const i=sn;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const rn=new Float32Array(16);function on(e,t,s,n){const r=rn;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const an=new Float32Array(16);function ln(e,t,s){const n=an;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 cn=new Float32Array(16);function dn(e,t){const s=cn;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}const un={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function hn(e,t,s,n,r,o,i={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,d=o.left+t.x*a,u=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+s.x-r.x*i.x,g=f+r.x):(f=c+s.x,g=d+n.x),e.y===t.y?(p=u+s.y-r.y*i.y,y=p+r.y):(p=u+s.y,y=h+n.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+i.x*m,originY:p+i.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const fn=J("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 pn=null,gn=null;function yn(e,t){e.has(t,re)||e.insert(t,re,{texture:L,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 mn(e,t){switch(e){case un.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case un.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case un.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 _n(e,t,s,n){if(!e.has(t,fn))return;const r=e.get(t,fn),o=mn(s,n);r.anchorMin=o.anchorMin,r.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(r.size={...r.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(r.size={...r.size,y:0}),e.insert(t,fn,r)}function xn(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function wn(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function vn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(let o=0;o<t.length;o++){const i=t[o],a=n+i;if(e.measureText(a).width>s&&n){if(wn(i.charCodeAt(0))&&n.length>0&&wn(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!wn(n.charCodeAt(t))){e=t;break}e>=0?(r.push(n.substring(0,e+1)),n=n.substring(e+1)+i):(r.push(n),n=i)}else r.push(n),n=i}else n=a}n&&r.push(n)}return r.length>0?r:[""]}function bn(e){let t=1;for(;t<e;)t*=2;return t}function Sn(e,t){let s=0,n=t;for(;e.has(n,le);){const t=e.get(n,le).entity;if(!e.valid(t))break;s++,n=t}return s}function Pn(e,t){if(pn&&gn){const e=pn.getUIRectComputedWidth(gn,t);if(e>0)return e}return e.size.x}function Mn(e,t){if(pn&&gn){const e=pn.getUIRectComputedHeight(gn,t);if(e>0)return e}return e.size.y}function Tn(e,t,s){let n=t;for(;e.has(n,le);){const t=e.get(n,le).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function En(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Cn(e,t,s,n,r){if(!e.has(t,fn))return;const o=e.get(t,fn),i=hn(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=i.rect.right-i.rect.left,l=i.rect.top-i.rect.bottom;if(e.has(t,re)){const s=e.get(t,re);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,re,s))}if(e.has(t,te)){const s=e.get(t,te);s.position.x=i.originX-n,s.position.y=i.originY-r,e.insert(t,te,s)}}function Rn(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let r=0;r<t.length;r++)n[t[r]]=s[r](e);return n},changed(e,n){for(let r=0;r<t.length;r++)if(e[t[r]]!==s[r](n))return!0;return!1},update(e,n){for(let r=0;r<t.length;r++)e[t[r]]=s[r](n)}}}const An=.1,In=30,Fn={r:.3,g:.5,b:.8,a:1},kn={Left:0,Center:1,Right:2},Bn={Top:0,Middle:1,Bottom:2},Un={Visible:0,Clip:1,Ellipsis:2},Dn=j("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:kn.Left,verticalAlign:Bn.Top,wordWrap:!0,overflow:Un.Visible,lineHeight:1.2});class Ln{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=a(D.textCanvasSize,D.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,bn(this.frameMaxW_)),e.height=Math.max(e.height,bn(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=bn(this.frameMaxW_),e.height=bn(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 r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=vn(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):u+2*d,p=r?Math.ceil(i):h+2*d;if(r&&e.overflow===Un.Ellipsis&&h>i){const e=Math.floor(i/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,bn(f)),n.height=Math.max(n.height,bn(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=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(${g}, ${y}, ${m}, ${_})`,r&&e.overflow===Un.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const x=l.length*c;let w;if(r)switch(e.verticalAlign){case Bn.Top:w=d;break;case Bn.Middle:w=d+(p-2*d-x)/2;break;case Bn.Bottom:w=p-x-d;break;default:w=d}else w=d;let v=w;for(const t of l){let n;switch(e.align){case kn.Left:n=d;break;case kn.Center:n=f/2;break;case kn.Right:n=f-d;break;default:n=d}s.fillText(t,n,v),v+=c}r&&e.overflow===Un.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{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 r=this.renderText(t,s);return this.cache.set(e,r),r}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 kn.Left:return"left";case kn.Center:return"center";case kn.Right:return"right"}}}const zn=Rn({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?Pn(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Mn(e.uiRect,e.entity):0});class Wn{build(e){q("Text",Dn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Ln(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Dn));for(const e of r.keys())if(!n.valid(e)||!n.has(e,Dn)){if(n.valid(e)&&n.has(e,re)){const t=n.get(e,re);n.insert(e,re,{texture:L,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})}r.delete(e)}const e=n.getEntitiesWithComponents([Dn]);for(const t of e){const e=n.get(t,Dn),o=n.has(t,fn)?n.get(t,fn):null,i={text:e,uiRect:o,entity:t},a=r.get(t);if(a&&!zn.changed(a,i)){if(n.has(t,re)&&n.get(t,re).texture!==L)continue}yn(n,t);const l=o?{size:{x:Pn(o,t),y:Mn(o,t)}}:null,c=s.renderForEntity(t,e,l),d=n.get(t,re);n.insert(t,re,{texture:c.textureHandle,color:{r:d.color.r,g:d.color.g,b:d.color.b,a:d.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:d.layer,flipX:d.flipX,flipY:d.flipY,material:d.material,enabled:d.enabled}),r.set(t,zn.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const $n=new Wn,On=0,Hn=1,Xn=J("UIMask",{enabled:!0,mode:On});function jn(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=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,r-s),h:Math.max(0,o-n)}}function Yn(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],d=e[7],u=e[8],h=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],x=n*l-r*a,w=n*c-o*a,v=n*d-i*a,b=r*c-o*l,S=r*d-i*l,P=o*d-i*c,M=u*y-h*g,T=u*m-f*g,E=u*_-p*g,C=h*m-f*y,R=h*_-p*y,A=f*_-p*m;let I=x*A-w*R+v*C+b*E-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*A-c*R+d*C)*I,s[1]=(o*R-r*A-i*C)*I,s[2]=(y*P-m*S+_*b)*I,s[3]=(f*S-h*P-p*b)*I,s[4]=(c*E-a*A-d*T)*I,s[5]=(n*A-o*E+i*T)*I,s[6]=(m*v-g*P-_*w)*I,s[7]=(u*P-f*v+p*w)*I,s[8]=(a*R-l*E+d*M)*I,s[9]=(r*E-n*R-i*M)*I,s[10]=(g*S-y*v+_*x)*I,s[11]=(h*v-u*S-p*x)*I,s[12]=(l*T-a*C-c*M)*I,s[13]=(n*C-r*T+o*M)*I,s[14]=(y*w-g*b-m*x)*I,s[15]=(u*b-h*w+f*x)*I),s}function Nn(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],d=s[1]*a+s[5]*l+s[13],u=s[3]*a+s[7]*l+s[15];return{x:c/u,y:d/u}}function Vn(e,t){return 2*Math.atan2(e,t)}function Gn(e,t,s,n,r,o,i){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,r+(.5*(l/c)+.5)*i]}function qn(e,t,s,n,r,o,i){if(!e.has(t,fn)||!e.has(t,te))return null;const a=e.get(t,fn),l=e.get(t,te),c=Pn(a,t)*l.worldScale.x,d=Mn(a,t)*l.worldScale.y,u=l.worldPosition.x,h=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-d*p,_=d*(1-p),x=Vn(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),v=Math.sin(x),b=[[u+g*w-m*v,h+g*v+m*w],[u+y*w-m*v,h+y*v+m*w],[u+y*w-_*v,h+y*v+_*w],[u+g*w-_*v,h+g*v+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=Gn(e,t,s,n,r,o,i);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 Kn(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Xn]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,Xn);s.enabled&&(u.add(e),s.mode===Hn?(d.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,r,o,i,a,l,c){const d=[];for(const e of n){let s=!0;Tn(t,e,e=>{if(r.has(e)){if(t.get(e,Xn).mode===On)return s=!1,!0}return!1}),s&&d.push(e)}function u(n,d){const h=e.getChildEntities(s,n);for(const s of h){let n=d;if(r.has(s)){if(t.get(s,Xn).mode===On){const e=qn(t,s,o,i,a,l,c);e&&(n=jn(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=qn(t,e,o,i,a,l,c);s&&u(e,s)}}(e,t,s,c,u,n,r,o,i,a),d.length>0&&function(e,t,s,n,r){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Tn(t,e,e=>!!r.has(e)&&(s=!1,!0)),s&&o.push(e)}let i=1,a=!1;function l(){return i>255?(a||console.warn("Stencil mask overflow"),a=!0,null):i++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}function d(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,d,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Jn{build(e){if(q("UIMask",Xn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Kn(e.wasmModule,e.world))}}const Qn=new Jn,Zn=J("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),er=J("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),tr={Normal:0,Hovered:1,Pressed:2,Disabled:3},sr=j("Button",{state:tr.Normal,transition:null});class nr{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 rr=we(new nr,"UIEvents");class or{build(e){q("UIRect",fn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){pn=e,gn=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(at)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n),s.transform_update(n))},{name:"UILayoutSystem"})),e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(at)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(exports.Schedule.PostUpdate,et([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const ir=new or;let ar=!1,lr=!1;function cr(){return ar}function dr(){return lr}const ur=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&&(Yn(t,e),s=!1),e)}}();function hr(e,t,s,n){t.emit(s,n,s),Tn(e,s,r=>{if(!e.has(r,Zn))return!1;const o=e.get(r,Zn);return o.enabled&&t.emit(r,n,s),o.blockRaycast})}class fr{build(e){q("Interactable",Zn),q("Button",sr);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),r=new nr;e.insertResource(rr,r);let o=null,i=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at)],(e,a)=>{if(r.drain(),cr()&&!dr())return;const l=t.getEntitiesWithComponents([er]);for(const e of l){const s=t.get(e,er);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,er,s))}if(!a.valid)return;const d=c(),u=e.mouseX*d,h=a.screenH-e.mouseY*d;ur.update(a.viewProjection);const f=Nn(u,h,ur.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=f.x,a.worldMouseY=f.y;const p=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),y=e.isMouseButtonReleased(0);s.uiHitTest_update(n,f.x,f.y,p,g,y);const m=s.uiHitTest_getHitEntity(),_=4294967295===m?null:m;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,er)){const e=t.get(o,er);e.hovered=!1,t.insert(o,er,e),r.emit(o,"hover_exit")}if(null!==_){En(t,_,er);const e=t.get(_,er);e.hovered=!0,t.insert(_,er,e),r.emit(_,"hover_enter")}o=_}if(g&&null!==_){const e=t.get(_,er);e.pressed=!0,e.justPressed=!0,t.insert(_,er,e),i=_,hr(t,r,_,"press")}if(y&&null!==i){if(t.valid(i)&&t.has(i,er)){const e=t.get(i,er);e.pressed=!1,e.justReleased=!0,t.insert(i,er,e),hr(t,r,i,"release"),i===o&&hr(t,r,i,"click")}i=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,et([],()=>{const e=t.getEntitiesWithComponents([sr]);for(const s of e){if(En(t,s,Zn,{enabled:!0}),!t.has(s,er))continue;const e=t.get(s,er),n=t.get(s,sr),r=t.get(s,Zn),o=!a.has(s),i=n.state;if(r.enabled?e.pressed?n.state=tr.Pressed:e.hovered?n.state=tr.Hovered:n.state=tr.Normal:n.state=tr.Disabled,o&&a.add(s),(o||i!==n.state)&&n.transition&&t.has(s,re)){const o=t.get(s,re);o.color=xn(n.transition,r.enabled,e.pressed,e.hovered),t.insert(s,re,o)}}},{name:"ButtonSystem"}))}}const pr=new fr,gr=j("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}),yr=j("Focusable",{tabIndex:0,isFocused:!1});class mr{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 _r=we(new mr,"FocusManager");class xr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(q("TextInput",gr),cr()&&!dr())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=a(D.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=0,l=0,c=!1,d=!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 g(){const t=e.getResource(_r);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,gr)?n:null}const y=()=>{c||null===g()||v()},m=()=>{c=!0},_=()=>{c=!1,v()},x=t=>{const n=g();if(null===n)return;if("Escape"===t.key)return void b();const r=s.get(n,gr);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource(rr).emit(n,"submit"),void b()}let o=r.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,r.cursorPos-1):"ArrowRight"===t.key?o=Math.min(r.value.length,r.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=r.value.length),o!==r.cursorPos&&(r.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,r.dirty=!0,S())},w=()=>{const t=g();if(null!==t){const n=s.get(t,gr);n.focused=!1,n.dirty=!0;e.getResource(_r).blur()}};function v(){const t=g();if(null===t)return;const n=s.get(t,gr);if(n.readOnly)return;let r=p.value;if(n.maxLength>0&&r.length>n.maxLength&&(r=r.substring(0,n.maxLength),p.value=r),r!==n.value){n.value=r;e.getResource(rr).emit(t,"change")}n.cursorPos=p.selectionStart??r.length,n.dirty=!0,S()}function b(){const t=g();if(null!==t){const e=s.get(t,gr);e.focused=!1,e.dirty=!0}e.getResource(_r).blur(),p.blur()}function S(){d=!0,u=0}p.addEventListener("input",y),p.addEventListener("compositionstart",m),p.addEventListener("compositionend",_),p.addEventListener("keydown",x),p.addEventListener("blur",w),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",m),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",x),p.removeEventListener("blur",w),p.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==i&&(t._free(i),i=0,l=0)};let P=null;function M(e,a,c,u){(r.width<c||r.height<u)&&(r.width=bn(Math.max(r.width,c)),r.height=bn(Math.max(r.height,u))),o.clearRect(0,0,r.width,r.height);const h=a.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,u),o.save(),o.beginPath(),o.rect(a.padding,0,c-2*a.padding,u),o.clip(),o.font=`${a.fontSize}px ${a.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===a.value.length,p=f?a.placeholder:a.password?"●".repeat(a.value.length):a.value,g=f?a.placeholderColor:a.color;o.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const y=Math.ceil(1.2*a.fontSize),m=a.padding;if(a.multiline){const e=vn(o,p,c-2*m);let t=m;for(const s of e)o.fillText(s,m,t),t+=y}else{const e=(u-a.fontSize)/2;o.fillText(p,m,e)}if(a.focused&&d){const e=a.password?"●".repeat(a.cursorPos):a.value.substring(0,a.cursorPos);let t,s,n;if(a.multiline){const e=vn(o,a.value,c-2*m);let r=0,i=0,l=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(r+s>=a.cursorPos){i=t,l=a.cursorPos-r;break}r+=s,t<e.length-1&&r<a.value.length&&"\n"===a.value[r]&&r++,i=t+1,l=0}const d=i<e.length?e[i].substring(0,l):"";t=m+o.measureText(d).width,s=m+i*y,n=y}else t=m+o.measureText(e).width,s=(u-a.fontSize)/2,n=a.fontSize;o.fillStyle=`rgba(${Math.round(255*a.color.r)}, ${Math.round(255*a.color.g)}, ${Math.round(255*a.color.b)}, ${a.color.a})`,o.fillRect(t,s,2,n)}o.restore();const _=o.getImageData(0,0,c,u),x=new Uint8Array(_.data.buffer),w=t.getResourceManager();x.length>l&&(0!==i&&t._free(i),i=t._malloc(x.length),l=x.length),t.HEAPU8.set(x,i);const v=n.get(e);void 0!==v&&w.releaseTexture(v);const b=w.createTexture(c,u,i,x.length,1,!0);n.set(e,b);const S=s.get(e,re);S.texture=b,S.size.x=c,S.size.y=u,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,re,S)}e.addSystemToSchedule(exports.Schedule.Update,et([ve(_r)],e=>{const t=s.getEntitiesWithComponents([gr]);for(const e of t)En(s,e,yr,{tabIndex:0,isFocused:!1}),En(s,e,Zn,{enabled:!0,blockRaycast:!0});const n=g();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,gr)){const e=s.get(P,gr);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,gr);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let r=0===h?0:(e-h)/1e3;h=e,r=Math.min(r,.1);const o=g();if(null!==o&&(u+=r,u>=.5)){u-=.5,d=!d;s.get(o,gr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,gr)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([gr,fn]);for(const e of a){const t=s.get(e,gr);if(!t.dirty)continue;const n=s.get(e,fn),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(yn(s,e),M(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const wr=new xr,vr={Simple:0,Sliced:1,Tiled:2,Filled:3},br={Horizontal:0,Vertical:1},Sr={Left:0,Right:1,Bottom:2,Top:3},Pr=j("Image",{texture:L,color:{r:1,g:1,b:1,a:1},imageType:vr.Simple,fillMethod:br.Horizontal,fillOrigin:Sr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Mr=Rn({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?Pn(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Mn(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Tr=new class{build(e){q("Image",Pr);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Pr)||s.delete(e);const e=t.getEntitiesWithComponents([Pr]);for(const n of e){const e=t.get(n,Pr),r=t.has(n,fn)?t.get(n,fn):null,o={image:e,uiRect:r,entity:n},i=s.get(n);if(i&&!Mr.changed(i,o))continue;yn(t,n);const a=t.get(n,re);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,r&&(a.size.x=Pn(r,n),a.size.y=Mn(r,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===vr.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===Sr.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===Sr.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===vr.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,re,a),s.set(n,Mr.take(o))}else a.color.a=0,t.insert(n,re,a),s.set(n,Mr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Er=j("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Cr=j("ToggleGroup",{allowSwitchOff:!1});const Rr=new class{build(e){q("Toggle",Er),q("ToggleGroup",Cr);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,et([ve(rr)],e=>{const n=t.getEntitiesWithComponents([Er]);if(!cr()||dr()){const r=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Er);n.isOn&&0!==n.group&&t.valid(n.group)&&(r.has(n.group)?(n.isOn=!1,t.insert(e,Er,n)):r.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Er);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(En(t,s,Zn,{enabled:!0}),!t.has(s,er))continue;const n=t.get(s,er),r=t.get(s,Er),i=t.get(s,Zn);if(n.justPressed&&i.enabled){const n=r.group,i=0!==n&&t.valid(n)&&t.has(n,Cr);if(r.isOn&&i){if(!t.get(n,Cr).allowSwitchOff)continue}if(r.isOn=!r.isOn,t.insert(s,Er,r),r.isOn&&i){const r=o.get(n);if(r)for(const n of r){if(n===s)continue;const r=t.get(n,Er);r.isOn&&(r.isOn=!1,t.insert(n,Er,r),e.emit(n,"change"))}}e.emit(s,"change")}if(r.transition&&t.has(s,re)){const e=t.get(s,re);e.color=xn(r.transition,i.enabled,n.pressed,n.hovered),t.insert(s,re,e)}}}for(const e of n){const s=t.get(e,Er);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,re)){const e=t.get(s.graphicEntity,re);e.enabled=s.isOn,t.insert(s.graphicEntity,re,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Ar=un,Ir=j("ProgressBar",{value:0,fillEntity:0,direction:un.LeftToRight});function Fr(e,t,s,n){if(!e.has(t,fn))return;const r=e.get(t,fn),o=s/2,i=n/2,a={left:-o,bottom:-i,right:o,top:i},l=hn(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,a,r.pivot);if(e.has(t,re)){const s=e.get(t,re);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,re,s))}if(e.has(t,te)){const s=e.get(t,te),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,te,s))}}class kr{build(e){q("ProgressBar",Ir);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e=t.getEntitiesWithComponents([Ir,fn]);for(const s of e){const e=t.get(s,Ir);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,fn),r=Math.max(0,Math.min(1,e.value));_n(t,e.fillEntity,e.direction,r);const o=Pn(n,s),i=Mn(n,s);Fr(t,e.fillEntity,o,i)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Br=new kr,Ur=j("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Dr=j("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});const Lr=new class{build(e){q("Draggable",Ur),q("DragState",Dr);const t=e.world,s=e.getResource(rr);let n=null,r={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at)],(e,i)=>{if(cr()&&!dr())return;if(!i.valid)return;const a={x:i.worldMouseX,y:i.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Ur,er]);let s=null,o=-1/0,i=-1;for(const n of e){if(!t.get(n,Ur).enabled)continue;if(t.get(n,er).hovered){let e=0;t.has(n,re)&&(e=t.get(n,re).layer);const r=Sn(t,n);(e>o||e===o&&r>=i)&&(o=e,i=r,s=n)}}if(null!==s){n=s,r={x:a.x,y:a.y},t.has(s,Dr)||t.insert(s,Dr);const e=t.get(s,Dr),o=t.get(s,te);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,Dr)){t.get(n,Dr).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-r.x,l=a.y-r.y,c=Math.sqrt(e*e+l*l),d=t.get(n,Ur);if(c*(i.vpW/(i.worldRight-i.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,Dr).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Dr))return void(o=null);const n=t.get(o,Dr),r=t.get(o,Ur),i=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+i,d=n.startWorldPos.y+l;const u=function(e,t,s,n){let r=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,n,c,d);c=u.x,d=u.y;const h=n.currentWorldPos.x,f=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:d-f},n.currentWorldPos={x:c,y:d},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:d-n.startWorldPos.y},t.has(o,te)){const e=function(e,t,s,n){if(!e.has(t,le))return{x:s,y:n};const r=e.get(t,le).entity;if(!e.valid(r)||!e.has(r,te))return{x:s,y:n};const o=e.get(r,te),i=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=Vn(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(s*d-n*c)/i,y:(s*c+n*d)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,te);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,te,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},zr=j("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Wr(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 $r(e,t,s,n,r){const o=2/(n=Math.max(1e-4,n)),i=o*r,a=1/(1+i+.48*i*i+.235*i*i*i),l=e-t,c=(s+o*l)*r,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(s-o*c)*a}}const Or=new class{build(e){q("ScrollView",zr);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(rt),ve(at),ve(Me)],(e,r,o)=>{const i=cr()&&!dr(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);r.valid&&(n.x=r.worldMouseX,n.y=r.worldMouseY);const l=t.getEntitiesWithComponents([zr,fn]);for(const o of l){En(t,o,Xn,{enabled:!0,mode:On});const l=t.get(o,zr),c=t.get(o,fn);let d=s.get(o);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,d));const u=Pn(c,o),h=Mn(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,ce)){const e=t.get(l.contentEntity,ce).entities;let s=0,n=0,r=0,o=0;for(const i of e){if(!t.valid(i)||!t.has(i,te))continue;const e=t.get(i,te);let a=0,l=0,c=.5,d=.5;if(t.has(i,fn)){const e=t.get(i,fn);a=Pn(e,i)||e.size.x,l=Mn(e,i)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(i,re)){const e=t.get(i,re);a=e.size.x,l=e.size.y}const u=e.position.x-a*c,h=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);u<s&&(s=u),h>n&&(n=h),f<r&&(r=f),p>o&&(o=p)}0===f&&(f=n-s),0===p&&(p=o-r)}const g=Math.max(0,f-u),y=Math.max(0,p-h);if(!i&&r.valid){En(t,o,Zn,{enabled:!0,blockRaycast:!0});const s=t.has(o,er)?t.get(o,er):null;if(s?.justPressed&&(d.isDragging=!0,d.lastWorldX=n.x,d.lastWorldY=n.y,d.velocityX=0,d.velocityY=0),d.isDragging&&e.isMouseButtonDown(0)){const e=n.x-d.lastWorldX,t=n.y-d.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=Wr(l.scrollX,0,g,u);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const n=a>0?-e*t/a:0;d.velocityX+=(n-d.velocityX)*s}}if(l.verticalEnabled){const e=Wr(l.scrollY,0,y,h);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const n=a>0?t*e/a:0;d.velocityY+=(n-d.velocityY)*s}}d.lastWorldX=n.x,d.lastWorldY=n.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*u,t=5*h;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Wr(l.scrollY,0,y,h);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Wr(l.scrollX,0,g,u);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>y;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=$r(l.scrollX,e,d.velocityX,.1,a);l.scrollX=t.value,d.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(d.velocityX)<An&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>An?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:y,t=$r(l.scrollY,e,d.velocityY,.1,a);l.scrollY=t.value,d.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(d.velocityY)<An&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>An?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,y)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*u,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,y+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,te)){const e=t.get(l.contentEntity,te),s=e.position.x,n=e.position.y;(isNaN(d.lastAppliedX)||Math.abs(s-d.lastAppliedX)>.01)&&(d.contentBaseX=s),(isNaN(d.lastAppliedY)||Math.abs(n-d.lastAppliedY)>.01)&&(d.contentBaseY=n),e.position.x=d.contentBaseX-l.scrollX,e.position.y=d.contentBaseY+l.scrollY,d.lastAppliedX=e.position.x,d.lastAppliedY=e.position.y,t.insert(l.contentEntity,te,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Hr=un,Xr=j("Slider",{value:0,minValue:0,maxValue:1,direction:un.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function jr(e,t,s,n,r,o){const i=Pn(n,r)*s.worldScale.x,a=Mn(n,r)*s.worldScale.y,l=Vn(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),u=e-s.worldPosition.x,h=t-s.worldPosition.y,f=u*d-h*c,p=u*c+h*d,g=-n.pivot.x*i,y=-n.pivot.y*a;switch(o){case un.LeftToRight:return i>0?(f-g)/i:0;case un.RightToLeft:return i>0?1-(f-g)/i:0;case un.BottomToTop:return a>0?(p-y)/a:0;case un.TopToBottom:return a>0?1-(p-y)/a:0}}function Yr(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case un.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case un.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case un.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case un.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class Nr{build(e){q("Slider",Xr);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at),ve(rr)],(e,n,r)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([Xr,fn]);for(const i of o){const o=t.get(i,Xr),a=t.get(i,fn);if(!cr()||dr()){if(t.has(i,te)){En(t,i,Zn,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&En(t,o.handleEntity,Zn,{enabled:!0,blockRaycast:!1});const l=t.get(i,te),c=t.has(i,er)?t.get(i,er):null;let d=c?.justPressed??!1;if(!d&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,er)&&(d=t.get(o.handleEntity,er).justPressed),d&&(s=i),s===i&&e.isMouseButtonDown(0)){let e=jr(n.worldMouseX,n.worldMouseY,l,a,i,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(i,Xr,o),o.value!==c&&r.emit(i,"change")}s===i&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,d=Pn(a,i),u=Mn(a,i),h={left:-d/2,bottom:-u/2,right:d/2,top:u/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(_n(t,o.fillEntity,o.direction,c),Cn(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,fn)){const e=t.get(o.handleEntity,fn);Yr(e,o.direction,c),t.insert(o.handleEntity,fn,e),Cn(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Vr=new Nr;const Gr=new class{build(e){q("Focusable",yr);const t=e.world,s=new mr;e.insertResource(_r,s),e.addSystemToSchedule(exports.Schedule.Update,et([ve(rt),ve(rr)],(e,n)=>{if(cr()&&!dr())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const r=t.getEntitiesWithComponents([yr]);for(const e of r){if(!t.has(e,er))continue;t.get(e,er).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of r){if(!t.valid(s))continue;if(t.has(s,Zn)){if(!t.get(s,Zn).enabled)continue}const n=t.get(s,yr);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 i=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?n.length-1:0:a?(i-1+n.length)%n.length:(i+1)%n.length,o(n[l])}function o(e){const r=s.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,yr)){t.get(r,yr).isFocused=!1,n.emit(r,"blur",r)}s.focus(e);t.get(e,yr).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},qr=j("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Kr(){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:r}=t;return{top:s.top,bottom:r-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const Jr=new class{build(e){q("SafeArea",qr);const t=e.world;let n=Kr(),r=!0,o=0,i=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Kr(),r=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Kr(),r=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(at)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===i||(o=e.screenH,i=a,r=!0),!r)return;r=!1;const l=c(),d=s()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([qr,fn]);for(const e of u){const s=t.get(e,qr),r=t.get(e,fn),o=s.applyTop?n.top*d:0,i=s.applyBottom?n.bottom*d:0,a=s.applyLeft?n.left*d:0,l=s.applyRight?n.right*d:0;let c=!1;r.offsetMin.x===a&&r.offsetMin.y===i||(r.offsetMin={x:a,y:i},c=!0),r.offsetMax.x===-l&&r.offsetMax.y===-o||(r.offsetMax={x:-l,y:-o},c=!0),c&&t.insert(e,fn,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},Qr=j("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Zr=null;const eo=new class{build(e){q("ListView",Qr);const t=e.world,s=new Map;Zr=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(rt)],e=>{const n=cr()&&!dr();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 r=t.getEntitiesWithComponents([Qr,fn]);for(const o of r){En(t,o,Zn,{enabled:!0,blockRaycast:!0}),En(t,o,Xn,{enabled:!0,mode:On});let r=s.get(o);r||(r={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,r));const i=t.get(o,Qr),a=t.get(o,fn),l=Mn(a,o),c=Pn(a,o);if(!n){const s=t.has(o,er)?t.get(o,er):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(i.scrollY+=.1*t.y)}}const d=Math.max(0,i.itemCount*i.itemHeight-l);i.scrollY=Math.max(0,Math.min(i.scrollY,d));const u=Math.max(0,Math.floor(i.scrollY/i.itemHeight)-i.overscan),h=Math.min(i.itemCount,Math.ceil((i.scrollY+l)/i.itemHeight)+i.overscan);for(const[e,s]of r.itemEntities)(e<u||e>=h)&&(t.valid(s)&&t.despawn(s),r.itemEntities.delete(e));for(let e=u;e<h;e++){let s=r.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,he,{value:`ListItem_${e}`}),t.insert(s,fn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:i.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),r.itemEntities.set(e,s),r.renderer&&r.renderer(e,s)),t.has(s,te)){const n=t.get(s,te);n.position.y=-(e*i.itemHeight-i.scrollY),t.insert(s,te,n)}}r.visibleStart=u,r.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},to=j("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const so=new class{build(e){q("Dropdown",to);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,te))return;const s=t.get(e,te);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,te,{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 r(e){if(t.has(e,re)){const s=t.get(e,re);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,re,{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 r=s.listEntity;if(0===r||!t.valid(r))return;d(r,!0),c(n);const o=t.get(e,re),i=o.size.x,a=o.size.y;n.ddWidth=i;const l=s.options.length*In;t.insert(r,fn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:l},pivot:{x:.5,y:.5}}),t.insert(r,te,{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(r,re,{texture:L,color:{r:1,g:1,b:1,a:1},size:{x:i,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)*In;t.insert(o,he,{value:`Option_${e}`}),t.insert(o,fn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*In},offsetMax:{x:0,y:0},size:{x:i,y:In},pivot:{x:.5,y:.5}}),t.insert(o,te,{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,re,{texture:L,color:{r:.95,g:.95,b:.95,a:1},size:{x:i,y:In},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,Zn,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,r),n.optionEntities.push(o);const c=t.spawn();t.insert(c,te,{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,Dn,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:kn.Left,verticalAlign:Bn.Middle,wordWrap:!1,overflow:Un.Clip,lineHeight:1.2}),t.insert(c,fn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:In},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}u(n)}function i(e,t,s){t.isOpen=!1,c(s),d(t.listEntity,!1)}function a(e,t,s,n,r){t.selectedIndex=n,i(0,t,s),r.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Dn))return;const n=t.get(s,Dn);let r={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,i=!1;if(1===r.r&&1===r.g&&1===r.b&&1===r.a&&(r={r:0,g:0,b:0,a:1},i=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,i=!0)}i&&t.insert(s,Dn,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:r,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function d(e,s){if(0!==e&&t.valid(e)&&(t.has(e,Zn)&&t.insert(e,Zn,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,re))){const n=t.get(e,re);t.insert(e,re,{texture:n.texture,color:{r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:s})}}function u(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,re))continue;const r=s===e.highlightIndex?{...Fn}:{r:.95,g:.95,b:.95,a:1};t.insert(n,re,{texture:L,color:r,size:{x:e.ddWidth,y:In},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,er))continue;if(t.get(s,er).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,et([ve(rt),ve(rr)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=cr()&&!dr(),p=t.getEntitiesWithComponents([to]);for(const g of p){const p=t.get(g,to);let y=s.get(g);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(g,y)),n(p.listEntity),r(g),p.isOpen||d(p.listEntity,!1),l(p),f)continue;En(t,g,Zn,{enabled:!0,blockRaycast:!0});const m=t.has(g,er)?t.get(g,er):null;if(m?.justPressed&&(p.isOpen?i(g,p,y):o(g,p,y)),p.isOpen){for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,er))continue;if(t.get(s,er).justPressed){a(g,p,y,e,c);break}}let s=-1;for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,er))continue;if(t.get(n,er).hovered){s=e;break}}s>=0&&s!==y.highlightIndex&&(y.highlightIndex=s,u(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=p.options.length-1?y.highlightIndex=0:y.highlightIndex++,u(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=p.options.length-1:y.highlightIndex--,u(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?a(g,p,y,y.highlightIndex,c):e.isKeyPressed("Escape")&&i(g,p,y),e.isMouseButtonPressed(0)&&(m?.hovered||h(y)||i(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},no=0,ro=0,oo=2,io=j("LayoutGroup",{direction:no,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:ro,reverseOrder:!1});const ao=new class{build(e){q("LayoutGroup",io);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e=t.getEntitiesWithComponents([io,fn,ce]);for(const s of e){const e=t.get(s,io),n=t.get(s,fn),r=t.get(s,ce);if(!r.entities||0===r.entities.length)continue;const o=[];for(const e of r.entities)t.valid(e)&&t.has(e,fn)&&t.has(e,te)&&o.push({entity:e,rect:t.get(e,fn)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const i=Pn(n,s),a=Mn(n,s),l=n.pivot.x,c=n.pivot.y,d=e.padding,u=e.direction===no;let h=0;for(let s=0;s<o.length;s++){const n=o[s],r=Pn(n.rect,n.entity),f=Mn(n.rect,n.entity),p=n.rect.pivot.x,g=n.rect.pivot.y;let y,m;u?(y=-l*i+d.left+h+p*r,m=e.childAlignment===ro?(1-c)*a-d.top-(1-g)*f:e.childAlignment===oo?-c*a+d.bottom+g*f:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*f,h+=r,s<o.length-1&&(h+=e.spacing)):(y=e.childAlignment===ro?-l*i+d.left+p*r:e.childAlignment===oo?(1-l)*i-d.right-(1-p)*r:(.5-l)*i+.5*(d.left-d.right)+(p-.5)*r,m=(1-c)*a-d.top-h-(1-g)*f,h+=f,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,te);_.position.x=y,_.position.y=m,t.insert(n.entity,te,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};J("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),J("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class lo{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,et([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const co=new lo;async function uo(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 ho=we({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),fo=we(null,"PhysicsAPI");function po(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function go(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class yo{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(ho,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=uo(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ie]);for(const s of t){const t=e.world.get(s,ie);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;i.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(Me)],a=>{const l=i.getEntitiesWithComponents([pe,te]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,pe),l=i.get(r,te);if(t.has(r)){const e=s.get(r);!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(r,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 i=po(l.worldRotation);n._physics_createBody(r,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),mo(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===_e.Kinematic){const e=po(l.worldRotation);n._physics_setBodyTransform(r,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 r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const d=e.world.get(i,te);if(!d)continue;let u=a,h=l,f=c;if(e.world.has(i,le)){const t=e.world.get(i,le);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,te)){const s=e.world.get(t.entity,te),n=po(s.worldRotation),r=a-s.worldPosition.x,o=l-s.worldPosition.y,i=Math.cos(-n),d=Math.sin(-n);u=(r*i-o*d)/(0!==s.worldScale.x?s.worldScale.x:1),h=(r*d+o*i)/(0!==s.worldScale.y?s.worldScale.y:1),f=c-n}}d.position.x=u,d.position.y=h;const p=go(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(i,te,d)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<d;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(ho,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(fo,_o._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function mo(e,t,s){const n=e.world;if(n.has(s,ge)){const e=n.get(s,ge);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,ye)){const e=n.get(s,ye);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,me)){const e=n.get(s,me);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 _o{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(_o.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const xo={nearest:0,linear:1},wo={repeat:0,clamp:1,mirror:2};function vo(e,t,s=!0,n){const r=e.getResourceManager(),o=e._malloc(t.pixels.length);let i;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&r.createTextureEx){const e=xo[n.filterMode??"linear"]??1,a=wo[n.wrapMode??"clamp"]??1;i=r.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else i=r.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),i}function bo(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 So(e,t,s,n){const r=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),i=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,u=a+a,h=l+l,f=c+c,p=a*u,g=a*h,y=a*f,m=l*h,_=l*f,x=c*f,w=d*u,v=d*h,b=d*f;return new Float32Array([(1-(m+x))*r,(g+b)*r,(y-v)*r,0,(g-b)*o,(1-(p+x))*o,(_+w)*o,0,(y+v)*i,(_-w)*i,(1-(p+m))*i,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Po(e,t,s,n,r,o,i,a,l){const c=await async function(e,t,s){const n={},r=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=At(t.type);for(const i of o){if("texture"!==i.type)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=r?.[o];n[o]=vo(e,await s.loadPixels(o),!0,t)}catch{n[o]=0}}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let d={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),d=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){const i=It(n.type);if(!i||!n.data)continue;const a=n.data[i.skeletonField],l=n.data[i.atlasField];if(!a||!l)continue;const c=r.resolvePath(a),d=r.resolvePath(l);try{const n=await r.readText(l),i="binary"===m(c)?.contentType;let u,h;if(i){const e=await r.readBinary(a);h=e.length,u=t._malloc(h),t.HEAPU8.set(e,u)}else{const e=await r.readText(a),s=(new TextEncoder).encode(e);h=s.length,u=t._malloc(h+1),t.HEAPU8.set(s,u),t.HEAPU8[u+h]=0}const f=s.loadSkeleton(u,h,n,n.length,i);if(t._free(u),f<0)continue;o[a]=f;const p=bo(n),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=g+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=vo(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){const t={gravity:i?.gravity??{...B},fixedTimestep:i?.fixedTimestep??U,subStepCount:i?.subStepCount??4};new yo("",t,()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){const r=At(t.type).find(e=>"font"===e.type);if(!r)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,r;const i=m(o);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(o)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),r=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),r=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=r?`${r}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=vo(e,c,!1),u=e.getResourceManager();n[o]=u.loadBitmapFont(t,d,c.width,c.height)}catch{n[o]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data)continue;const r=At(e.type).find(e=>"material"===e.type);if(!r)continue;const o=e.data[r.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 r=e.vertexSource+e.fragmentSource;let i=n[r];i||(i=mt.createShader(e.vertexSource,e.fragmentSource),n[r]=i),s[o]=mt.createFromAsset(e,i)}catch{s[o]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=At(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,c,h,f);const p=Dt(e.world,s);if(l&&e.hasResource(Ns))for(const t of p.values())e.world.insert(t,fe,{scene:l,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const i=It(t.type);if(!i||!t.data)continue;const a=s[t.data[i.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(r[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 r}(u,s,d,p);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=k);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,ue)?c.get(o,ue):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&n.update(i,l*u);let h=0;if(c.has(o,te)){const e=So(c.get(o,te),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=n.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),d=s._malloc(l),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(i,e,c,d,u,f);const p=s.HEAPU32[u>>2],g=s.HEAPU32[f>>2],y=new Float32Array(s.HEAPF32.buffer,c,8*r),m=new Uint16Array(s.HEAPU8.buffer,d,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(_,r,x,o,p,g,h),t._free(_),t._free(x),s._free(c),s._free(d),s._free(u),s._free(f)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource(Ot);t&&t.setAddressableManifest(a)}}class Mo{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 r of e.entities)for(const e of r.components){if(!e.data)continue;const r=It(e.type);if(r){const n=e.data[r.skeletonField],o=e.data[r.atlasField];n&&("binary"===m(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=At(e.type);for(const s of o){const r=e.data[s.field];"string"==typeof r&&r&&("font"===s.type?(n.add(r),t.add(r)):"material"===s.type&&t.add(r))}}const r=[];for(const e of t)r.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)r.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(r);const o=[];for(const e of n){const t=m(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(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const To="__preview__";const Eo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ds.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ds.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ds.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ds.releaseRenderTarget(e._handle),Eo.create({width:t,height:s,depth:!0})),begin(e,t){Ds.begin(t,e._handle)},end(){Ds.end()},getDepthTexture:e=>Ds.getTargetDepthTexture(e._handle)};var Co;exports.LogLevel=void 0,(Co=exports.LogLevel||(exports.LogLevel={}))[Co.Debug=0]="Debug",Co[Co.Info=1]="Info",Co[Co.Warn=2]="Warn",Co[Co.Error=3]="Error";class Ro{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 Ao{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Ro)}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 r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Io=new Ao;const Fo=[$n,Qn,ir,Tr,Br,pr,Lr,Or,Vr,Rr,wr,Gr,Jr,eo,so,ao,co];R||(R=!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},r=await d(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.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 u(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 r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}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 r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=A,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.App=Ks,exports.AssetPlugin=Ht,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=$t,exports.Assets=Ot,exports.AsyncCache=Tt,exports.BitmapText=de,exports.BodyType=_e,exports.BoxCollider=ge,exports.Button=sr,exports.ButtonState=tr,exports.Camera=oe,exports.Canvas=ie,exports.CapsuleCollider=me,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=ce,exports.CircleCollider=ye,exports.ClearFlags=Z,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Ve,exports.DEFAULT_DESIGN_HEIGHT=F,exports.DEFAULT_DESIGN_WIDTH=I,exports.DEFAULT_FALLBACK_DT=k,exports.DEFAULT_FIXED_TIMESTEP=U,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=B,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.DragState=Dr,exports.Draggable=Ur,exports.Draw=ls,exports.Dropdown=to,exports.EntityCommands=Ne,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=Je,exports.EventRegistry=qe,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=Ke,exports.FillDirection=un,exports.FillMethod=br,exports.FillOrigin=Sr,exports.FocusManager=_r,exports.FocusManagerState=mr,exports.Focusable=yr,exports.GLDebug=$s,exports.Geometry=Ps,exports.GetWorld=function(){return{_type:"get_world"}},exports.INVALID_ENTITY=0,exports.INVALID_FONT=z,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=L,exports.Image=Pr,exports.ImageType=vr,exports.Input=rt,exports.InputPlugin=ot,exports.InputState=nt,exports.Interactable=Zn,exports.ListView=Qr,exports.LocalTransform=se,exports.Logger=Ao,exports.Material=mt,exports.MaterialLoader=Et,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=he,exports.Parent=le,exports.Physics=_o,exports.PhysicsEvents=ho,exports.PhysicsPlugin=yo,exports.PostProcess=Rs,exports.PrefabServer=qt,exports.Prefabs=Kt,exports.PrefabsPlugin=Jt,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(Ns);t.register({name:To,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(To),this.loadPromise_=t.load(To).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 Mo(this.baseUrl_);await s.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await Po(this.app_,this.app_.wasmModule,t,s,r,null,void 0,null,To)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([oe]);for(const n of s){if(e.get(n,oe).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([ie]);for(const r of n){const n=e.get(r,ie);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(Ns).getScene(To),o=r?r.spawn():e.spawn(),i={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,te,i);const a={isActive:!0,projectionType:Q.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Z.ColorAndDepth};e.insert(o,oe,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(Ns);await e.switchTo(To),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=Ir,exports.ProgressBarDirection=Ar,exports.ProgressBarPlugin=kr,exports.ProjectionType=Q,exports.Query=function(...e){return Xe(e)},exports.QueryInstance=je,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=Ye,exports.RenderPipeline=Os,exports.RenderTexture=Eo,exports.Renderer=Ds,exports.Res=ve,exports.ResMut=be,exports.RigidBody=pe,exports.RuntimeConfig=D,exports.SafeArea=qr,exports.ScaleMode=ee,exports.SceneManager=Ns,exports.SceneManagerState=Ys,exports.SceneOwner=fe,exports.ScrollView=zr,exports.ShaderSources=Mt,exports.Slider=Xr,exports.SliderDirection=Hr,exports.SliderPlugin=Nr,exports.SpineAnimation=ue,exports.Sprite=re,exports.SystemRunner=st,exports.Text=Dn,exports.TextAlign=kn,exports.TextInput=gr,exports.TextInputPlugin=xr,exports.TextOverflow=Un,exports.TextPlugin=Wn,exports.TextRenderer=Ln,exports.TextVerticalAlign=Bn,exports.Time=Me,exports.Toggle=Er,exports.Transform=te,exports.UICameraInfo=at,exports.UIEventQueue=nr,exports.UIEvents=rr,exports.UIInteraction=er,exports.UIInteractionPlugin=fr,exports.UILayoutPlugin=or,exports.UIMask=Xn,exports.UIMaskPlugin=Jn,exports.UIRect=fn,exports.UIRenderOrderPlugin=lo,exports.Velocity=ae,exports.WebAssetProvider=Mo,exports.World=ze,exports.WorldTransform=ne,exports.addStartupSystem=function(e){tt().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){tt().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){tt().push({schedule:e,system:t})},exports.applyDirectionalFill=_n,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=D.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=D.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=D.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=D.canvasMatchWidthOrHeight)},exports.assetPlugin=Xt,exports.clearDrawCallbacks=gs,exports.clearUserComponents=function(){const e=X();for(const t of e.keys())G.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=mn,exports.computeFillSize=function(e,t,s,n){switch(e){case un.BottomToTop:case un.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case un.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case un.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case un.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=hn,exports.createMaskProcessor=Kn,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,async setup(){await Po(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}},exports.createWebApp=function(e,t){return function(e,t){const s=Ks.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),rs(e),pt(e),vs(e),Ts(e),Bs(e),zs(e);const r=new Os;s.setPipeline(r);let o=l();const i=t?.getViewportSize??(()=>{const e=c();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,r,o){o||(o=tn(e,n,t,r));const i=s.getResource(at);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(at,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const d={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const d=e.registry_getCanvasEntity(n);if(d>=0){const e=n.getCanvas(d).backgroundColor;Ds.setClearColor(e.x,e.y,e.z,e.w)}const u=(l()-o)/1e3;let h;if(Ds.resize(t,c),Rs.isInitialized()&&Rs.getPassCount()>0&&!Rs.isBypassed()&&Rs.resize(t,c),s.hasResource(Ns)){const e=s.getResource(Ns).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=tn(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:Js,width:t,height:c,elapsed:u});else{for(const e of f){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:l},clearFlags:e.clearFlags,elapsed:u})}Ds.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,d),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(Xt),s.addPlugin(Qt),s.addPlugin(it),s.addPlugin(qs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Fo,...t})},exports.debug=function(e,t,s){Io.debug(e,t,s)},exports.defineComponent=j,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=we,exports.defineSystem=et,exports.defineTag=function(e){const t=G.get(e)??X().get(e);if(t)return t;const s=O(e,{});return X().set(e,s),G.set(e,s),N(e,{},!0),s},exports.error=function(e,t,s){Io.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([he]);for(const n of s){const s=e.get(n,he);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return m(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of h)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return g},exports.getAssetMimeType=function(e){return f[e.toLowerCase()]},exports.getAssetTypeEntry=m,exports.getComponent=K,exports.getComponentAssetFieldDescriptors=At,exports.getComponentAssetFields=Rt,exports.getComponentDefaults=function(e){const t=K(e);return t?W(t._default):null},exports.getComponentEntityFields=kt,exports.getComponentSpineFieldDescriptor=It,exports.getCustomExtensions=x,exports.getEditorType=function(e){return m(e)?.editorType??"unknown"},exports.getLogger=function(){return Io},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=Y,exports.getWeChatPackOptions=function(){return x().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Io.info(e,t,s)},exports.initDrawAPI=rs,exports.initGLDebugAPI=zs,exports.initGeometryAPI=vs,exports.initMaterialAPI=pt,exports.initPostProcessAPI=Ts,exports.initRendererAPI=Bs,exports.inputPlugin=it,exports.instantiatePrefab=jt,exports.intersectRects=jn,exports.invertMatrix4=Yn,exports.isBuiltinComponent=V,exports.isCustomExtension=w,exports.isEditor=cr,exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=dr,exports.isRuntime=function(){return!ar},exports.isTextureRef=ct,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Wt,exports.loadPhysicsModule=uo,exports.loadRuntimeScene=Po,exports.loadSceneData=Dt,exports.loadSceneWithAssets=Lt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&_(y(e)))},exports.platformFetch=n,exports.platformFileExists=i,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=r,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,r,o,i,a,l,c){const d=Vn(l,c),u=Math.sin(-d),h=Math.cos(-d),f=e-s,p=t-n,g=f*h-p*u+s,y=f*u+p*h+n;return g>=s-r*i&&g<=s+r*(1-i)&&y>=n-o*a&&y<=n+o*(1-a)},exports.pointInWorldRect=function(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)},exports.prefabsPlugin=Qt,exports.progressBarPlugin=Br,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=q,exports.registerComponentAssetFields=function(e,t){Ct.set(e,t)},exports.registerComponentEntityFields=function(e,t){Ft.set(e,t)},exports.registerDrawCallback=fs,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(Ot);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Pt,exports.remapEntityFields=Bt,exports.sceneManagerPlugin=qs,exports.screenToWorld=Nn,exports.setEditorMode=function(e){ar=e},exports.setListViewRenderer=function(e,t){if(!Zr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=Zr.get(e);s?s.renderer=t:Zr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Io.setMinLevel(e)},exports.setPlayMode=function(e){lr=e},exports.setWasmErrorHandler=Ae,exports.shutdownDrawAPI=os,exports.shutdownGLDebugAPI=Ws,exports.shutdownGeometryAPI=bs,exports.shutdownMaterialAPI=gt,exports.shutdownPostProcessAPI=Es,exports.shutdownRendererAPI=Us,exports.sliderPlugin=Vr,exports.syncFillSpriteSize=function(e,t,s,n,r,o){if(!e.has(t,re))return;const i=e.get(t,re);let a,l;switch(s){case un.BottomToTop:case un.TopToBottom:a=r,l=o*n;break;default:a=r*n,l=o}i.size.x===a&&i.size.y===l||(i.size.x=a,i.size.y=l,e.insert(t,re,i))},exports.textInputPlugin=wr,exports.textPlugin=$n,exports.transitionTo=async function(e,t,s){const n=e.getResource(Ns);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=pr,exports.uiLayoutPlugin=ir,exports.uiMaskPlugin=Qn,exports.uiPlugins=Fo,exports.uiRenderOrderPlugin=co,exports.unregisterComponent=function(e){X().delete(e),G.delete(e)},exports.unregisterDrawCallback=ps,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([oe]);for(const n of s){const s=e.get(n,oe);s&&(s.aspectRatio=t,e.insert(n,oe,s))}},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){Io.warn(e,t,s)},exports.wrapSceneSystem=Vs,exports.wxFileExists=T,exports.wxFileExistsSync=function(e){const t=b();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=C,exports.wxLoadImage=E,exports.wxLoadImagePixels=async function(e){return C(await E(e))},exports.wxReadFile=P,exports.wxReadTextFile=M,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{b().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
//# sourceMappingURL=index.wechat.cjs.js.map
diff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.js
index dc49a802a..d30ef96ec 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 r(){return"web"===e?.name}async function o(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 d(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function u(){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}function p(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 g(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 y=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],m={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,w=new Set;for(const e of y)for(const t of e.extensions)_.set(t,e),w.add(t);function x(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function v(e){return _.get(x(e))}function b(e){return v(e)?.editorType??"unknown"}function S(e){return v(e)?.addressableType??null}function M(e){for(const t of y)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return w.has(e.toLowerCase())}function T(){return w}function E(e){return"string"==typeof e&&(!!e.includes("/")&&P(x(e)))}function C(){const e=[];for(const t of y)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function R(){return C().map(e=>({type:"suffix",value:e}))}function A(e){return m[e.toLowerCase()]}function k(e){const t=v(e);return t?.wechatPackInclude??!1}let I=null;function F(){return I||(I=wx.getFileSystemManager()),I}function B(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(k(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 z(e){return new Promise((t,n)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(B(e,t.errMsg)))}})})}function U(e,t="utf-8"){return new Promise((n,s)=>{F().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(B(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function W(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function D(e,t){return new Promise((n,s)=>{F().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function O(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 L(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 H(e){return L(await O(e))}let X=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return p(e,t)}async readFile(e){return z(e)}async readTextFile(e){return U(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return g(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){wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)}),wx.onTouchEnd(t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)})}},Y=1920,N=1080,V=100,G=512,q={x:100,y:100},K="Arial",J=24,Q=1.2,Z=.5,ee=1/60,te={x:0,y:-9.81},ne=1/60,se="default",ie={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function re(e){e.Text&&(e.Text._default.fontFamily=ie.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=ie.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=ie.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=ie.canvasMatchWidthOrHeight)}const oe=0,ae=4294967295,le=4294967295,ce=0,de=(e=0,t=0)=>({x:e,y:t}),he=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),ue=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),fe=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),pe=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function ge(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(ge);const t={};for(const n in e)t[n]=ge(e[n]);return t}let ye=0;function me(e,t){const n=++ye,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?{...ge(t),...e}:ge(t):e?{...t,...e}:{...t}}}const _e=new Map;function we(){return"undefined"==typeof window?_e:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function xe(e,t){const n=Ee.get(e)??we().get(e);if(n)return n;const s=me(e,t);return we().set(e,s),Ee.set(e,s),Pe(e,t,!1),s}function ve(e){const t=Ee.get(e)??we().get(e);if(t)return t;const n=me(e,{});return we().set(e,n),Ee.set(e,n),Pe(e,{},!0),n}function be(e){return we().get(e)}function Se(){const e=we();for(const t of e.keys())Ee.delete(t);e.clear()}function Me(e){we().delete(e),Ee.delete(e)}function Pe(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function Te(e){return!0===e._builtin}const Ee=new Map;function Ce(e,t){Ee.set(e,t)}function Re(e){return Ee.get(e)??be(e)}function Ae(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Ee.set(e,n),n}const ke={Perspective:0,Orthographic:1},Ie={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Fe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},Be=Ae("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}}),ze=Be,Ue=Be,$e=Ae("Sprite",{texture:ae,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}),We=Ae("Camera",{projectionType:ke.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=Ae("Canvas",{designResolution:{x:Y,y:N},pixelsPerUnit:100,scaleMode:Fe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Oe=Ae("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Le=Ae("Parent",{entity:0}),He=Ae("Children",{entities:[]}),Xe=Ae("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:le,enabled:!0}),je=Ae("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=xe("Name",{value:""}),Ne=xe("SceneOwner",{scene:"",persistent:!1});function Ve(e){const t=Re(e);return t?ge(t._default):null}const Ge=Ae("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),qe=Ae("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ke=Ae("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Je=Ae("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Qe={Static:0,Kinematic:1,Dynamic:2};let Ze=0;function et(e,t){const n=++Ze;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function tt(e){return{_type:"res",_resource:e}}function nt(e){return{_type:"res_mut",_resource:e}}class st{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 it{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 st(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const rt=et({delta:0,elapsed:0,frameCount:0},"Time");function ot(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=at(t[e]),r=at(i);"null"!==n&&"undefined"!==n&&(n!==r&&null!=i&&s.push({field:e,expected:n,actual:r,value:i}))}return s}function at(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function lt(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 ct=null;function dt(e){ct=e}function ht(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ct&&ct(e,t)}function ut(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 ft=1;const pt=new WeakMap;function gt(e){let t=pt.get(e);return void 0===t&&(t=ft++,pt.set(e,t)),t}const yt=[];function mt(e,t=[],n=[]){yt.length=0;for(const t of e)yt.push(gt(t));yt.sort((e,t)=>e-t);let s=yt.join(",");if(t.length>0){yt.length=0;for(const e of t)yt.push(gt(e));yt.sort((e,t)=>e-t),s+="|+"+yt.join(",")}if(n.length>0){yt.length=0;for(const e of n)yt.push(gt(e));yt.sort((e,t)=>e-t),s+="|-"+yt.join(",")}return s}class _t{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.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 ht(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_;return this.entities_.set(e,t),this.worldVersion_++,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){ht(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)}}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){ht(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){ht(t,`removeParent(entity=${e})`)}}insert(e,t,n){return Te(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(Te(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,ut(n))}catch(n){ht(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 Te(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Te(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Te(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return ht(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.");Te(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}`],r=n[`has${e}`],o=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof r||"function"!=typeof o)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:r.bind(n),remove:o.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=ot(t._name,t._default,s);if(e.length>0)throw new Error(lt(t._name,e))}const i={...t._default,...s};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,ut(i))}catch(n){ht(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let 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],r=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==r||"object"!=typeof r||Array.isArray(r))s[n]=i;else{const e=i,t=r;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 ht(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 ht(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){ht(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=ot(t._name,t._default,e);if(i.length>0)throw new Error(lt(t._name,i));s=e}const i=t.create(s),r=this.getStorage(t),o=!r.has(e);r.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),o&&(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 Ee)if(Te(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=we();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??mt(e,t,n),r=this.queryCache_.get(i);if(r&&r.version===this.worldVersion_)return r.result;let o=null,a=1/0;for(const t of e)if(!Te(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=o?o.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 wt(e){return{_type:"mut",_component:e}}function xt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function vt(e){return{_filterType:"added",_component:e}}function bt(e){return{_filterType:"changed",_component:e}}function St(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Mt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Pt(e){return xt(e)||St(e)||Mt(e)?e._component:e}function Tt(e,t=[],n=[]){const s=[],i=[],r=[];return e.forEach((e,t)=>{xt(e)&&s.push(t),St(e)?i.push({index:t,component:e._component}):Mt(e)&&r.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:r,with:(...s)=>Tt(e,[...t,...s],n),without:(...s)=>Tt(e,t,[...n,...s])}}function Et(...e){return Tt(e)}class Ct{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Pt),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_=mt(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,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of n)if(!r||this.passesChangeFilters_(d)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}o[0]=d;for(let e=0;e<s;e++)o[e+1]=this.world_.get(d,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=o[e[t]+1];c=d}yield o}}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 Rt(e){return{_type:"removed",_component:e}}class At{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 kt(){return{_type:"commands"}}class It{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=Te(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 Ft{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new It(this,null);return this.spawned_.push(e),e}entity(e){return new It(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"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}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 Bt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class zt{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 Ut{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new zt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new zt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function $t(e){return{_type:"event_writer",_event:e}}function Wt(e){return{_type:"event_reader",_event:e}}class Dt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Ot{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Lt;function Ht(){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"}(Lt||(Lt={}));let Xt=0;function jt(e,t,n){const s=++Xt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Yt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Nt(e){Yt().push({schedule:Lt.Update,system:e})}function Vt(e){Yt().push({schedule:Lt.Startup,system:e})}function Gt(e,t){Yt().push({schedule:e,system:t})}class qt{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}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]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ft&&t[e].flush()}finally{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 Ft(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 Dt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Ot(n)}case"removed":{const t=e;return new At(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Kt{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 Jt=et(new Kt,"Input");class Qt{constructor(e){this.target_=e??null}build(e){const n=new Kt;e.insertResource(Jt,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(Lt.Last,jt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Zt=new Qt,en=et({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 tn;function nn(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"}(tn||(tn={}));let sn=null,rn=null,on=1;const an=new Map;function ln(e){sn=e,rn=e.getResourceManager(),_n()}function cn(){0!==fn&&sn&&(sn._free(fn),fn=0),an.clear(),on=1,un=!1,gn.clear(),yn=null,rn=null,sn=null}function dn(){if(!rn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return rn}const hn={createShader:(e,t)=>dn().createShader(e,t),releaseShader(e){e>0&&dn().releaseShader(e)},create(e){const t=on++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??tn.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 an.set(t,n),t},get:e=>an.get(e),setUniform(e,t,n){const s=an.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,sn?.invalidateMaterialCache(e))},getUniform(e,t){const n=an.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=an.get(e);n&&(n.blendMode=t,sn?.invalidateMaterialCache(e))},getBlendMode(e){const t=an.get(e);return t?.blendMode??tn.Normal},setDepthTest(e,t){const n=an.get(e);n&&(n.depthTest=t,sn?.invalidateMaterialCache(e))},getShader(e){const t=an.get(e);return t?.shader??0},release(e){an.delete(e),sn?.invalidateMaterialCache(e)},isValid:e=>an.has(e),releaseAll(){an.clear(),sn?.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??tn.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=an.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=on++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return an.set(n,s),n},toAssetData(e,t){const n=an.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=an.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let un=!1,fn=0;const pn=16384,gn=new Map;let yn=null;function mn(e){const t=(0===fn&&sn&&(fn=sn._malloc(pn)),fn);if(0===t||!sn)return{ptr:0,count:0};let n=0,s=0;const i=sn.HEAPU8,r=sn.HEAPU32,o=sn.HEAPF32;for(const[a,l]of e){if(nn(l))continue;let e=gn.get(a);e||(yn||(yn=new TextEncoder),e=yn.encode(a),gn.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>pn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${pn} bytes), skipping remaining uniforms`);break}r[t+n>>2]=c,n+=4,i.set(e,t+n),n+=d;let h=0,u=[0,0,0,0];if("number"==typeof l)h=0,u[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++)u[e]=l[e]}else"w"in l?(h=3,u=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,u=[l.x,l.y,l.z,0]):"y"in l&&(h=1,u=[l.x,l.y,0,0]);r[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=u[e],n+=4;s++}return{ptr:t,count:s}}function _n(){if(!sn||un)return;sn.materialDataProvider=(e,t,n,s,i)=>{const r=an.get(e);if(!r)return sn.HEAPU32[t>>2]=0,sn.HEAPU32[n>>2]=0,sn.HEAPU32[s>>2]=0,void(sn.HEAPU32[i>>2]=0);sn.HEAPU32[t>>2]=r.shader,sn.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=mn(r.uniforms);sn.HEAPU32[s>>2]=o,sn.HEAPU32[i>>2]=a},un=!0}const wn={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 xn{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.pending_.get(e);if(i&&!i.aborted)return i.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&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class vn{constructor(e,t=""){this.cache_=new xn,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&&(hn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())hn.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),r=await this.shaderLoader_.load(i);return{handle:hn.createFromAsset(s,r),shaderHandle:r,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}}const bn=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"}]}]]);function Sn(e,t){bn.set(e,t)}function Mn(e){const t=bn.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 Pn(e){return bn.get(e)?.fields??[]}function Tn(e){return bn.get(e)?.spine??null}const En=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Cn(e,t){En.set(e,t)}function Rn(e){return En.get(e)}function An(e,t){const n=En.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 r=t.get(n);void 0===r&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==r?r:0}}}function kn(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,Ye,{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)An(i,n),zn(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 In(e,t){return kn(e,t)}async function Fn(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl,r=new Map;s&&await async function(e,t,n,s,i){e=JSON.parse(JSON.stringify(e));const r=new Map;for(const e of Bn.keys())r.set(e,new Set);const o=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=bn.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),o.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&r.get(e.type)?.add(t)}}const l=new Map,c=[...Bn.entries()].map(async([e,i])=>{const o=await i.load(r.get(e),t,n,s);l.set(e,o)}),d=o.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,...d]),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=r.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=bn.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&(n[e.field]=l.get(e.type)?.get(t)??0)}}}(t,s,i,r,n?.collectAssets);const o=kn(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=r.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return o}const Bn=new Map([["texture",{async load(e,t,n,s){const i=new Map,r=[...e].map(async e=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);i.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(r),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}}]]);function zn(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=Re(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 Un(e,t){const n=e.getEntitiesWithComponents([We]);for(const s of n){const n=e.get(s,We);n&&(n.aspectRatio=t,e.insert(s,We,n))}}function $n(e,t){const n=e.getEntitiesWithComponents([Ye]);for(const s of n){const n=e.get(s,Ye);if(n&&n.value===t)return s}return null}class Wn{constructor(e){this.textureCache_=new xn,this.shaderCache_=new xn,this.jsonCache_=new xn,this.textCache_=new xn,this.binaryCache_=new xn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new xn,this.prefabCache_=new xn,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.module_=e,this.canvas_=h(ie.textCanvasSize,ie.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 vn(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 r=(this.textureRefCounts_.get(s)??1)-1;r<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,r)}}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(),hn.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),r=await this.fetchText(i);if(!this.writeToVirtualFS(t,r))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(r),l=[];for(const e of a){const t=o?`${o}/${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),d="binary"===v(e)?.contentType,h=d?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,r,d);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=v(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("/")),r=i?`${i}/${s}`:s,o=await this.loadTextureRaw(r);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}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 Fn(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 n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const i=s??n;return new Promise((n,s)=>{const r=t().createImage();r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(r)},r.onerror=()=>s(new Error(`Failed to load image: ${e}`)),r.src=i})}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 r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),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 o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=r;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),r=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(r);const o=this.module_.getResourceManager(),a=this.module_._malloc(r.length);this.module_.HEAPU8.set(r,a);const l=o.createTexture(t,n,a,r.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.embedded_.get(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 hn.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:r}=this.parseEsShader(s);if(!i||!r)throw new Error(`Invalid shader format: ${e}`);return hn.createShader(i,r)}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://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(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 o(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.embedded_.get(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 o(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.embedded_.get(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 o(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 Dn=et(null,"Assets");class On{build(e){const t=e.wasmModule;t?e.insertResource(Dn,new Wn(t)):console.warn("AssetPlugin: No WASM module available")}}const Ln=new On;class Hn{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 Xn(e,t){const n=e.getResource(Dn);n&&n.registerEmbeddedAssets(t)}async function jn(e,t,n){const{entities:s,rootId:i}=await Nn(t,n?.overrides??[],n,void 0,new Set),r={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}))},o=await Fn(e,r,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=o.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:o}}const Yn=10;async function Nn(e,t,n,s,i,r=0){if(r>Yn)throw new Error(`Prefab nesting depth exceeded ${Yn}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||o.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 Nn(e,s.nestedPrefab.overrides,n,a,i,r+1);o.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?o.get(s.parent)??null:null),l.push(...t.entities);continue}const c=o.get(s.prefabEntityId),d=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:d?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Vn(h.components,o),Gn(h,t),l.push(h)}const c=o.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Vn(e,t){for(const n of e){const e=Rn(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 Gn(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 qn{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 jn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Kn=et(null,"Prefabs");class Jn{constructor(){this.name="PrefabsPlugin",this.dependencies=[Dn]}build(e){const t=e.getResource(Dn);e.insertResource(Kn,new qn(e.world,t))}}const Qn=new Jn;let Zn=null,es=0,ts=0,ns=0;const ss=new Float32Array(256);function is(e){Zn=e,es=Zn._malloc(64),ts=Zn._malloc(64),ns=Zn._malloc(1024)}function rs(){Zn&&(es&&(Zn._free(es),es=0),ts&&(Zn._free(ts),ts=0),ns&&(Zn._free(ns),ns=0)),Zn=null}function os(){if(!Zn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Zn}const as={r:1,g:1,b:1,a:1},ls={begin(e){const t=os();try{t.HEAPF32.set(e,es/4),t.draw_begin(es)}catch(e){ht(e,"Draw.begin")}},end(){try{os().draw_end()}catch(e){ht(e,"Draw.end")}},line(e,t,n,s=1){try{os().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ht(e,"Draw.line")}},rect(e,t,n,s=!0){try{os().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ht(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{os().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ht(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{os().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ht(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{os().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ht(e,"Draw.circleOutline")}},texture(e,t,n,s=as){try{os().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){ht(e,"Draw.texture")}},textureRotated(e,t,n,s,i=as){try{os().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){ht(e,"Draw.textureRotated")}},setLayer(e){os().draw_setLayer(e)},setDepth(e){os().draw_setDepth(e)},getDrawCallCount:()=>Zn?Zn.draw_getDrawCallCount():0,getPrimitiveCount:()=>Zn?Zn.draw_getPrimitiveCount():0,setBlendMode(e){os().draw_setBlendMode(e)},setDepthTest(e){os().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=os();s.HEAPF32.set(n,ts/4),s.draw_mesh(e,t,ts)}catch(n){ht(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=os(),i=hn.get(t);if(!i)return;if(ls.setBlendMode(i.blendMode),ls.setDepthTest(i.depthTest),0===i.uniforms.size)return void ls.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,ts/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=hs(t);if(!(s<0)){if(nn(n))ss[r++]=10,ss[r++]=s,ss[r++]=n.slot??e++,ss[r++]=n.textureId;else if("number"==typeof n)ss[r++]=1,ss[r++]=s,ss[r++]=n;else if(Array.isArray(n)){ss[r++]=n.length,ss[r++]=s;for(let e=0;e<n.length;e++)ss[r++]=n[e]}else"w"in n?(ss[r++]=4,ss[r++]=s,ss[r++]=n.x,ss[r++]=n.y,ss[r++]=n.z,ss[r++]=n.w):"z"in n?(ss[r++]=3,ss[r++]=s,ss[r++]=n.x,ss[r++]=n.y,ss[r++]=n.z):(ss[r++]=2,ss[r++]=s,ss[r++]=n.x,ss[r++]=n.y);if(r>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<r)&&(i.cachedBuffer_=new Float32Array(r)),i.cachedBuffer_.set(ss.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,ts);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),ns/4),s.draw_meshWithUniforms(e,i.shader,ts,ns,r)}catch(n){ht(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},cs={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},ds=new Set;function hs(e){const t=cs[e];return void 0!==t?t:(ds.has(e)||(ds.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(cs).join(", ")}`)),-1)}const us=new Map;function fs(e,t,n){us.set(e,{fn:t,scene:n??""})}function ps(e){us.delete(e)}function gs(){us.clear()}var ys;!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"}(ys||(ys={}));let ms=null,_s=0,ws=0,xs=0;function vs(e){ms=e,_s=ms._malloc(262144),ws=ms._malloc(65536),xs=ms._malloc(256)}function bs(){ms&&(_s&&ms._free(_s),ws&&ms._free(ws),xs&&ms._free(xs),_s=0,ws=0,xs=0),ms=null}function Ss(){if(!ms)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ms}const Ms={create(e){const t=Ss(),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,_s/4);const i=e.layout.length,r=new Int32Array(i);for(let t=0;t<i;t++)r[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,xs,i).set(r),t.geometry_init(n,_s,s,xs,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,ws,s).set(e.indices),t.geometry_setIndices16(n,ws,s)}else{new Uint32Array(t.HEAPU8.buffer,ws,s).set(e.indices),t.geometry_setIndices32(n,ws,s)}}return n},updateVertices(e,t,n=0){const s=Ss(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,_s/4),s.geometry_updateVertices(e,_s,i,n)},release(e){e>0&&Ss().geometry_release(e)},isValid:e=>!(!ms||e<=0)&&ms.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Ms.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:ys.Float2},{name:"a_texCoord",type:ys.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,r=Math.cos(i)*e,o=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(r,o,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Ms.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:ys.Float2},{name:"a_texCoord",type:ys.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 r of e)t=Math.min(t,r.x),n=Math.min(n,r.y),s=Math.max(s,r.x),i=Math.max(i,r.y);const r=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(i-n);r.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return Ms.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:ys.Float2},{name:"a_texCoord",type:ys.Float2}],indices:new Uint16Array(o)})}};let Ps=null;function Ts(e){Ps=e}function Es(){Ps&&Rs.isInitialized()&&Rs.shutdown(),Ps=null}function Cs(){if(!Ps)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ps}const Rs={init(e,t){try{return Cs().postprocess_init(e,t)}catch(n){return ht(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Cs().postprocess_shutdown()}catch(e){ht(e,"PostProcess.shutdown")}},resize(e,t){try{Cs().postprocess_resize(e,t)}catch(n){ht(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Cs().postprocess_addPass(e,t)}catch(t){return ht(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Cs().postprocess_removePass(e)}catch(t){ht(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Cs().postprocess_setPassEnabled(e,t)}catch(t){ht(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Cs().postprocess_isPassEnabled(e)}catch(t){return ht(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Cs().postprocess_setUniformFloat(e,t,n)}catch(n){ht(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Cs().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){ht(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Cs().postprocess_begin()}catch(e){ht(e,"PostProcess.begin")}},end(){try{Cs().postprocess_end()}catch(e){ht(e,"PostProcess.end")}},getPassCount(){try{return Cs().postprocess_getPassCount()}catch(e){return ht(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ps)return!1;try{return Ps.postprocess_isInitialized()}catch(e){return ht(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Cs().postprocess_setBypass(e)}catch(e){ht(e,"PostProcess.setBypass")}},isBypassed(){if(!Ps)return!0;try{return Ps.postprocess_isBypassed()}catch(e){return ht(e,"PostProcess.isBypassed"),!0}},createBlur:()=>hn.createShader(As,"#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:()=>hn.createShader(As,"#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:()=>hn.createShader(As,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>hn.createShader(As,"#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")},As="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var ks;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(ks||(ks={}));let Is=null,Fs=0;function Bs(e){Is=e,Fs=Is._malloc(64)}function zs(){Is&&Fs&&(Is._free(Fs),Fs=0),Is=null}const Us={init(e,t){Is?.renderer_init(e,t)},resize(e,t){Is?.renderer_resize(e,t)},begin(e,t){if(Is&&Fs)try{Is.HEAPF32.set(e,Fs/4),Is.renderer_begin(Fs,t??0)}catch(e){ht(e,"Renderer.begin")}},flush(){try{Is?.renderer_flush()}catch(e){ht(e,"Renderer.flush")}},end(){try{Is?.renderer_end()}catch(e){ht(e,"Renderer.end")}},submitSprites(e){if(Is)try{Is.renderer_submitSprites(e._cpp)}catch(e){ht(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Is)try{Is.renderer_submitBitmapText(e._cpp)}catch(e){ht(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Is)try{Is.renderer_submitSpine?.(e._cpp)}catch(e){ht(e,"Renderer.submitSpine")}},setStage(e){Is?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Is?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Is?.renderer_releaseTarget(e)},getTargetTexture:e=>Is?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Is?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Is?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Is?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Is?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Is?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Is?Is.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Is?{drawCalls:Is.renderer_getDrawCalls(),triangles:Is.renderer_getTriangles(),sprites:Is.renderer_getSprites(),text:Is.renderer_getText(),spine:Is.renderer_getSpine?.()??0,meshes:Is.renderer_getMeshes(),culled:Is.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let $s=null;function Ws(e){$s=e}function Ds(){$s=null}const Os={enable(){$s?.gl_enableErrorCheck(!0)},disable(){$s?.gl_enableErrorCheck(!1)},check:e=>$s?.gl_checkErrors(e)??0,diagnose(){$s?.renderer_diagnose()}};class Ls{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:r}=e;s===this.lastWidth_&&i===this.lastHeight_||(Us.resize(s,i),Rs.isInitialized()&&Rs.getPassCount()>0&&Rs.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Us.setViewport(0,0,s,i),Us.clearBuffers(3),Us.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),Us.submitSprites(t),Us.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Us.submitSpine(t),Us.flush(),this.executeDrawCallbacks(n,r),Us.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;Us.setViewport(s.x,s.y,s.w,s.h),Us.setScissor(s.x,s.y,s.w,s.h,!0),Us.clearBuffers(i),Us.setScissor(0,0,0,0,!1),Us.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Us.submitSprites(t),Us.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Us.submitSpine(t),Us.flush(),this.executeDrawCallbacks(n,r),Us.end()}executeDrawCallbacks(e,t){const n=us;if(n.size>0){ls.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)}ls.end();for(const e of s)ps(e)}}}const Hs="__scene_transition_overlay__";class Xs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class js{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,Ne,{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),fs(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=Rs.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){Rs.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,Ne)){const n=this.app_.world.get(e,Ne);n.persistent=t,this.app_.world.insert(e,Ne,n)}}}class Ys{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??ie.sceneTransitionDuration,i=t.color??{...ie.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},fs(Hs,()=>{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;ls.setLayer(9999),ls.setDepth(9999),ls.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,ps(Hs),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,ps(Hs),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 Xs(t);this.scenes_.set(e,n);const s=new js(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Dn)?this.app_.getResource(Dn):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 Xs(t);this.scenes_.set(e,n);const s=new js(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Dn)?this.app_.getResource(Dn):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,Ne)){if(this.app_.world.get(e,Ne).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())ps(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{Rs.removePass(e)}catch{}n.postProcessPasses.length=0,this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const r=this.loadOrder_.indexOf(e);-1!==r&&this.loadOrder_.splice(r,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(Dn)&&(i.assetServer=this.app_.getResource(Dn));const r=await Fn(this.app_.world,s,i);e.loadedAssets=n;for(const n of r.values())e.entities.add(n),this.app_.world.insert(n,Ne,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Vs(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(Dn)?this.app_.getResource(Dn):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)hn.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,$e)){const t=n.get(e,$e);s.sprite=t.color.a,t.color.a=0,n.insert(e,$e,t),i=!0}if(n.has(e,je)){const t=n.get(e,je);s.spine=t.color.a,t.color.a=0,n.insert(e,je,t),i=!0}if(n.has(e,Xe)){const t=n.get(e,Xe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Xe,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,$e)){const t=n.get(e,$e);t.color.a=s.sprite,n.insert(e,$e,t)}if(void 0!==s.spine&&n.has(e,je)){const t=n.get(e,je);t.color.a=s.spine,n.insert(e,je,t)}if(void 0!==s.bitmapText&&n.has(e,Xe)){const t=n.get(e,Xe);t.color.a=s.bitmapText,n.insert(e,Xe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{Rs.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,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 Ns=et(null,"SceneManager");function Vs(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Ns).getSceneStatus(t)&&n._fn(...s)}}}const Gs=jt([nt(Ns),tt(rt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),qs={name:"SceneManager",build(e){const t=new Ys(e);e.insertResource(Ns,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ns),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Lt.Startup,n),e.addSystemToSchedule(Lt.Last,Gs)}};class Ks{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 Ut,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=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=u(),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(Lt.Last);else{this.runSchedule(Lt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Lt.FixedPreUpdate),this.runSchedule(Lt.FixedUpdate),this.runSchedule(Lt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Lt.PreUpdate),this.runSchedule(Lt.Update),this.runSchedule(Lt.PostUpdate),this.runSchedule(Lt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new _t,this.resources_=new it;for(const e of Object.values(Lt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ks}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(Lt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Lt.Startup,e)}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 dt(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_}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(Ns).register(e),this}setInitialScene(e){return this.getResource(Ns).setInitial(e),this}tick(e){this.runner_||(this.runner_=new qt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(rt)||this.resources_.insert(rt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Lt.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Lt.First),this.runSchedule(Lt.PreUpdate),this.runSchedule(Lt.Update),this.runSchedule(Lt.PostUpdate),this.runSchedule(Lt.Last);this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new qt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(rt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Lt.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,gs();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=[Ds,zs,Es,bs,cn,rs];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,r=o=>{if(s.has(o))return;if(i.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&r(n)}i.delete(o),s.add(o),n.push(a)};for(let t=0;t<e.length;t++)r(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));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)}}}updateTime(e){const t=this.resources_.get(rt);t.delta=e,t.elapsed+=e,t.frameCount++}}function Js(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Qs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Zs(e,t,n,s,i){const r=e*t/n,o=e;switch(s){case Fe.FixedWidth:return r;case Fe.FixedHeight:return o;case Fe.Expand:return Math.max(r,o);case Fe.Shrink:return Math.min(r,o);case Fe.Match:{const e=i;return Math.pow(r,1-e)*Math.pow(o,e)}default:return o}}const ei=[];function ti(e){if(e<ei.length)return ei[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 ei.push(t),t}function ni(e,t,n,s,i,r){if(0===n||0===s)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=r&&i?o.filter(e=>{const t=i.tryGet(e,Ne);return!t||""===t.scene||r.has(t.scene)}):o;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),r=t.getTransform(e),o=i.viewportW*n/(i.viewportH*s);let a,d=0,h=0;if(i.projectionType===ke.Orthographic){if(h=i.orthoSize,l){h=Zs(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=h*o,a=ii(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=oi(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const u=li(r.position.x,r.position.y,r.position.z),f=ti(c.length);f.entity=e,f.viewProjection.set(di(a,u)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=d,f.halfH=h,f.cameraX=r.position.x,f.cameraY=r.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const si=new Float32Array(16);function ii(e,t,n,s,i,r){const o=si;o.fill(0);const a=t-e,l=s-n,c=r-i;return o[0]=2/a,o[5]=2/l,o[10]=-2/c,o[12]=-(t+e)/a,o[13]=-(s+n)/l,o[14]=-(r+i)/c,o[15]=1,o}const ri=new Float32Array(16);function oi(e,t,n,s){const i=ri;i.fill(0);const r=1/Math.tan(e/2),o=n-s;return i[0]=r/t,i[5]=r,i[10]=(s+n)/o,i[11]=-1,i[14]=2*s*n/o,i}const ai=new Float32Array(16);function li(e,t,n){const s=ai;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 ci=new Float32Array(16);function di(e,t){const n=ci;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 hi={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function ui(e,t,n,s,i,r,o={x:.5,y:.5}){const a=r.right-r.left,l=r.top-r.bottom,c=r.left+e.x*a,d=r.left+t.x*a,h=r.bottom+e.y*l,u=r.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+n.x-i.x*o.x,g=f+i.x):(f=c+n.x,g=d+s.x),e.y===t.y?(p=h+n.y-i.y*o.y,y=p+i.y):(p=h+n.y,y=u+s.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+o.x*m,originY:p+o.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const fi=Ae("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,gi=null;function yi(e,t){e.has(t,$e)||e.insert(t,$e,{texture:ae,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 hi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case hi.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case hi.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 _i(e,t){switch(e){case hi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case hi.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case hi.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 wi(e,t,n,s){switch(e){case hi.BottomToTop:case hi.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function xi(e,t,n,s){if(!e.has(t,fi))return;const i=e.get(t,fi),r=mi(n,s);i.anchorMin=r.anchorMin,i.anchorMax=r.anchorMax,r.anchorMin.x===r.anchorMax.x&&(i.size={...i.size,x:0}),r.anchorMin.y===r.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,fi,i)}function vi(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function bi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Si(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 r=0;r<t.length;r++){const o=t[r],a=s+o;if(e.measureText(a).width>n&&s){if(bi(o.charCodeAt(0))&&s.length>0&&bi(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!bi(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+o):(i.push(s),s=o)}else i.push(s),s=o}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Mi(e){let t=1;for(;t<e;)t*=2;return t}function Pi(e,t){let n=0,s=t;for(;e.has(s,Le);){const t=e.get(s,Le).entity;if(!e.valid(t))break;n++,s=t}return n}function Ti(e,t){if(pi&&gi){const e=pi.getUIRectComputedWidth(gi,t);if(e>0)return e}return e.size.x}function Ei(e,t){if(pi&&gi){const e=pi.getUIRectComputedHeight(gi,t);if(e>0)return e}return e.size.y}function Ci(e,t,n,s,i,r){if(!e.has(t,$e))return;const o=e.get(t,$e);let a,l;switch(n){case hi.BottomToTop:case hi.TopToBottom:a=i,l=r*s;break;default:a=i*s,l=r}o.size.x===a&&o.size.y===l||(o.size.x=a,o.size.y=l,e.insert(t,$e,o))}function Ri(e,t,n){let s=t;for(;e.has(s,Le);){const t=e.get(s,Le).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Ai(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function ki(e,t,n,s,i){if(!e.has(t,fi))return;const r=e.get(t,fi),o=ui(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,n,r.pivot),a=o.rect.right-o.rect.left,l=o.rect.top-o.rect.bottom;if(e.has(t,$e)){const n=e.get(t,$e);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,$e,n))}if(e.has(t,Be)){const n=e.get(t,Be);n.position.x=o.originX-s,n.position.y=o.originY-i,e.insert(t,Be,n)}}function Ii(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 Fi=.1,Bi=30,zi={r:.3,g:.5,b:.8,a:1},Ui={Left:0,Center:1,Right:2},$i={Top:0,Middle:1,Bottom:2},Wi={Visible:0,Clip:1,Ellipsis:2},Di=xe("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ui.Left,verticalAlign:$i.Top,wordWrap:!0,overflow:Wi.Visible,lineHeight:1.2});class Oi{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(ie.textCanvasSize,ie.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,Mi(this.frameMaxW_)),e.height=Math.max(e.height,Mi(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Mi(this.frameMaxW_),e.height=Mi(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,r=i?t.size.x:0,o=i?t.size.y:0,a=e.wordWrap&&i;let l=Si(n,e.content,a?r:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),u=Math.ceil(l.length*c),f=i?Math.ceil(r):h+2*d,p=i?Math.ceil(o):u+2*d;if(i&&e.overflow===Wi.Ellipsis&&u>o){const e=Math.floor(o/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,r)}}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,Mi(f)),s.height=Math.max(s.height,Mi(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=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(${g}, ${y}, ${m}, ${_})`,i&&e.overflow===Wi.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 $i.Top:x=d;break;case $i.Middle:x=d+(p-2*d-w)/2;break;case $i.Bottom:x=p-w-d;break;default:x=d}else x=d;let v=x;for(const t of l){let s;switch(e.align){case Ui.Left:s=d;break;case Ui.Center:s=f/2;break;case Ui.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===Wi.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 Ui.Left:return"left";case Ui.Center:return"center";case Ui.Right:return"right"}}}const Li=Ii({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?Ti(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Ei(e.uiRect,e.entity):0});class Hi{build(e){Ce("Text",Di);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Oi(t),s=e.world,i=new Map;e.addSystemToSchedule(Lt.PreUpdate,jt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Di));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Di)){if(s.valid(e)&&s.has(e,$e)){const t=s.get(e,$e);s.insert(e,$e,{texture:ae,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([Di]);for(const t of e){const e=s.get(t,Di),r=s.has(t,fi)?s.get(t,fi):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Li.changed(a,o)){if(s.has(t,$e)&&s.get(t,$e).texture!==ae)continue}yi(s,t);const l=r?{size:{x:Ti(r,t),y:Ei(r,t)}}:null,c=n.renderForEntity(t,e,l),d=s.get(t,$e);s.insert(t,$e,{texture:c.textureHandle,color:{r:d.color.r,g:d.color.g,b:d.color.b,a:d.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:d.layer,flipX:d.flipX,flipY:d.flipY,material:d.material,enabled:d.enabled}),i.set(t,Li.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Xi=new Hi,ji=0,Yi=1,Ni=Ae("UIMask",{enabled:!0,mode:ji});function Vi(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),r=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,r-s)}}function Gi(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],r=e[2],o=e[3],a=e[4],l=e[5],c=e[6],d=e[7],h=e[8],u=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],w=s*l-i*a,x=s*c-r*a,v=s*d-o*a,b=i*c-r*l,S=i*d-o*l,M=r*d-o*c,P=h*y-u*g,T=h*m-f*g,E=h*_-p*g,C=u*m-f*y,R=u*_-p*y,A=f*_-p*m;let k=w*A-x*R+v*C+b*E-S*T+M*P;return 0===k||(k=1/k,n[0]=(l*A-c*R+d*C)*k,n[1]=(r*R-i*A-o*C)*k,n[2]=(y*M-m*S+_*b)*k,n[3]=(f*S-u*M-p*b)*k,n[4]=(c*E-a*A-d*T)*k,n[5]=(s*A-r*E+o*T)*k,n[6]=(m*v-g*M-_*x)*k,n[7]=(h*M-f*v+p*x)*k,n[8]=(a*R-l*E+d*P)*k,n[9]=(i*E-s*R-o*P)*k,n[10]=(g*S-y*v+_*w)*k,n[11]=(u*v-h*S-p*w)*k,n[12]=(l*T-a*C-c*P)*k,n[13]=(s*C-i*T+r*P)*k,n[14]=(y*x-g*b-m*w)*k,n[15]=(h*b-u*x+f*w)*k),n}function qi(e,t,n,s,i,r,o){const a=(e-s)/r*2-1,l=(t-i)/o*2-1,c=n[0]*a+n[4]*l+n[12],d=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:d/h}}function Ki(e,t,n,s,i,r,o,a){return e>=n-i*o&&e<=n+i*(1-o)&&t>=s-r*a&&t<=s+r*(1-a)}function Ji(e,t){return 2*Math.atan2(e,t)}function Qi(e,t,n,s,i,r,o){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)*r,i+(.5*(l/c)+.5)*o]}function Zi(e,t,n,s,i,r,o,a,l,c){const d=Ji(l,c),h=Math.sin(-d),u=Math.cos(-d),f=e-n,p=t-s,g=f*u-p*h+n,y=f*h+p*u+s;return g>=n-i*o&&g<=n+i*(1-o)&&y>=s-r*a&&y<=s+r*(1-a)}function er(e,t,n,s,i,r,o){if(!e.has(t,fi)||!e.has(t,Be))return null;const a=e.get(t,fi),l=e.get(t,Be),c=Ti(a,t)*l.worldScale.x,d=Ei(a,t)*l.worldScale.y,h=l.worldPosition.x,u=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-d*p,_=d*(1-p),w=Ji(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+g*x-m*v,u+g*v+m*x],[h+y*x-m*v,u+y*v+m*x],[h+y*x-_*v,u+y*v+_*x],[h+g*x-_*v,u+g*v+_*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=Qi(e,t,n,s,i,r,o);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 tr(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ni]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,Ni);n.enabled&&(h.add(e),n.mode===Yi?(d.push(e),u.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,r,o,a,l,c){const d=[];for(const e of s){let n=!0;Ri(t,e,e=>{if(i.has(e)){if(t.get(e,Ni).mode===ji)return n=!1,!0}return!1}),n&&d.push(e)}function h(s,d){const u=e.getChildEntities(n,s);for(const n of u){let s=d;if(i.has(n)){if(t.get(n,Ni).mode===ji){const e=er(t,n,r,o,a,l,c);e&&(s=Vi(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=er(t,e,r,o,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,r,o,a),d.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const r=[];for(const e of s){let n=!0;Ri(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&r.push(e)}let o=1,a=!1;function l(){return o>255?(a||console.warn("Stencil mask overflow"),a=!0,null):o++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}function d(t,s){if(a)return;const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}for(const e of r){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,d,u)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class nr{build(e){if(Ce("UIMask",Ni),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(tr(e.wasmModule,e.world))}}const sr=new nr,ir=Ae("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),rr=Ae("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),or={Normal:0,Hovered:1,Pressed:2,Disabled:3},ar=xe("Button",{state:or.Normal,transition:null});class lr{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=et(new lr,"UIEvents");class dr{build(e){Ce("UIRect",fi);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){pi=e,gi=t}(n,s);e.addSystemToSchedule(Lt.PreUpdate,jt([tt(en)],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(Lt.PostUpdate,jt([tt(en)],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(Lt.PostUpdate,jt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const hr=new dr;let ur=!1,fr=!1;function pr(e){ur=e}function gr(){return ur}function yr(){return!ur}function mr(e){fr=e}function _r(){return fr}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&&(Gi(t,e),n=!1),e)}}();function xr(e,t,n,s){t.emit(n,s,n),Ri(e,n,i=>{if(!e.has(i,ir))return!1;const r=e.get(i,ir);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class vr{build(e){Ce("Interactable",ir),Ce("Button",ar);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new lr;e.insertResource(cr,i);let r=null,o=null;e.addSystemToSchedule(Lt.PreUpdate,jt([tt(Jt),tt(en)],(e,a)=>{if(i.drain(),gr()&&!_r())return;const l=t.getEntitiesWithComponents([rr]);for(const e of l){const n=t.get(e,rr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,rr,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;wr.update(a.viewProjection);const u=qi(d,h,wr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=u.x,a.worldMouseY=u.y;const p=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),y=e.isMouseButtonReleased(0);n.uiHitTest_update(s,u.x,u.y,p,g,y);const m=n.uiHitTest_getHitEntity(),_=4294967295===m?null:m;if(null===r||t.valid(r)||(r=null),r!==_){if(null!==r&&t.valid(r)&&t.has(r,rr)){const e=t.get(r,rr);e.hovered=!1,t.insert(r,rr,e),i.emit(r,"hover_exit")}if(null!==_){Ai(t,_,rr);const e=t.get(_,rr);e.hovered=!0,t.insert(_,rr,e),i.emit(_,"hover_enter")}r=_}if(g&&null!==_){const e=t.get(_,rr);e.pressed=!0,e.justPressed=!0,t.insert(_,rr,e),o=_,xr(t,i,_,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,rr)){const e=t.get(o,rr);e.pressed=!1,e.justReleased=!0,t.insert(o,rr,e),xr(t,i,o,"release"),o===r&&xr(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(Lt.Update,jt([],()=>{const e=t.getEntitiesWithComponents([ar]);for(const n of e){if(Ai(t,n,ir,{enabled:!0}),!t.has(n,rr))continue;const e=t.get(n,rr),s=t.get(n,ar),i=t.get(n,ir),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=or.Pressed:e.hovered?s.state=or.Hovered:s.state=or.Normal:s.state=or.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,$e)){const r=t.get(n,$e);r.color=vi(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,$e,r)}}},{name:"ButtonSystem"}))}}const br=new vr,Sr=xe("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}),Mr=xe("Focusable",{tabIndex:0,isFocused:!1});class Pr{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 Tr=et(new Pr,"FocusManager");class Er{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Ce("TextInput",Sr),gr()&&!_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(ie.textCanvasSize,64),r=i.getContext("2d",{willReadFrequently:!0});let o=0,a=0,l=!1,c=!0,d=0,u=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 g(){const t=e.getResource(Tr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Sr)?s:null}const y=()=>{l||null===g()||v()},m=()=>{l=!0},_=()=>{l=!1,v()},w=t=>{const s=g();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,Sr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(cr).emit(s,"submit"),void b()}let r=i.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?r=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=i.value.length),r!==i.cursorPos&&(i.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,i.dirty=!0,S())},x=()=>{const t=g();if(null!==t){const s=n.get(t,Sr);s.focused=!1,s.dirty=!0;e.getResource(Tr).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,Sr);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 b(){const t=g();if(null!==t){const e=n.get(t,Sr);e.focused=!1,e.dirty=!0}e.getResource(Tr).blur(),p.blur()}function S(){c=!0,d=0}p.addEventListener("input",y),p.addEventListener("compositionstart",m),p.addEventListener("compositionend",_),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",m),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!==o&&(t._free(o),o=0,a=0)};let M=null;function P(e,l,d,h){(i.width<d||i.height<h)&&(i.width=Mi(Math.max(i.width,d)),i.height=Mi(Math.max(i.height,h))),r.clearRect(0,0,i.width,i.height);const u=l.backgroundColor;r.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,r.fillRect(0,0,d,h),r.save(),r.beginPath(),r.rect(l.padding,0,d-2*l.padding,h),r.clip(),r.font=`${l.fontSize}px ${l.fontFamily}`,r.textBaseline="top",r.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,g=f?l.placeholderColor:l.color;r.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const y=Math.ceil(1.2*l.fontSize),m=l.padding;if(l.multiline){const e=Si(r,p,d-2*m);let t=m;for(const n of e)r.fillText(n,m,t),t+=y}else{const e=(h-l.fontSize)/2;r.fillText(p,m,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=Si(r,l.value,d-2*m);let i=0,o=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){o=t,a=l.cursorPos-i;break}i+=n,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,o=t+1,a=0}const c=o<e.length?e[o].substring(0,a):"";t=m+r.measureText(c).width,n=m+o*y,s=y}else t=m+r.measureText(e).width,n=(h-l.fontSize)/2,s=l.fontSize;r.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,r.fillRect(t,n,2,s)}r.restore();const _=r.getImageData(0,0,d,h),w=new Uint8Array(_.data.buffer),x=t.getResourceManager();w.length>a&&(0!==o&&t._free(o),o=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,o);const v=s.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(d,h,o,w.length,1,!0);s.set(e,b);const S=n.get(e,$e);S.texture=b,S.size.x=d,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,$e,S)}e.addSystemToSchedule(Lt.Update,jt([tt(Tr)],e=>{const t=n.getEntitiesWithComponents([Sr]);for(const e of t)Ai(n,e,Mr,{tabIndex:0,isFocused:!1}),Ai(n,e,ir,{enabled:!0,blockRaycast:!0});const s=g();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,Sr)){const e=n.get(M,Sr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,Sr);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(Lt.PreUpdate,jt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===u?0:(e-u)/1e3;u=e,i=Math.min(i,.1);const r=g();if(null!==r&&(d+=i,d>=.5)){d-=.5,c=!c;n.get(r,Sr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Sr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Sr,fi]);for(const e of a){const t=n.get(e,Sr);if(!t.dirty)continue;const s=n.get(e,fi),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(yi(n,e),P(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Cr=new Er,Rr={Simple:0,Sliced:1,Tiled:2,Filled:3},Ar={Horizontal:0,Vertical:1},kr={Left:0,Right:1,Bottom:2,Top:3},Ir=xe("Image",{texture:ae,color:{r:1,g:1,b:1,a:1},imageType:Rr.Simple,fillMethod:Ar.Horizontal,fillOrigin:kr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Fr=Ii({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?Ti(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Ei(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Br=new class{build(e){Ce("Image",Ir);const t=e.world,n=new Map;e.addSystemToSchedule(Lt.PreUpdate,jt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Ir)||n.delete(e);const e=t.getEntitiesWithComponents([Ir]);for(const s of e){const e=t.get(s,Ir),i=t.has(s,fi)?t.get(s,fi):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!Fr.changed(o,r))continue;yi(t,s);const a=t.get(s,$e);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=Ti(i,s),a.size.y=Ei(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Rr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Ar.Horizontal?e.fillOrigin===kr.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===kr.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===Rr.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,$e,a),n.set(s,Fr.take(r))}else a.color.a=0,t.insert(s,$e,a),n.set(s,Fr.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},zr=xe("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Ur=xe("ToggleGroup",{allowSwitchOff:!1});const $r=new class{build(e){Ce("Toggle",zr),Ce("ToggleGroup",Ur);const t=e.world,n=new Set;e.addSystemToSchedule(Lt.Update,jt([tt(cr)],e=>{const s=t.getEntitiesWithComponents([zr]);if(!gr()||_r()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,zr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,zr,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,zr);if(0!==n.group&&t.valid(n.group)){let t=r.get(n.group);t||(t=[],r.set(n.group,t)),t.push(e)}}for(const n of s){if(Ai(t,n,ir,{enabled:!0}),!t.has(n,rr))continue;const s=t.get(n,rr),i=t.get(n,zr),o=t.get(n,ir);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,Ur);if(i.isOn&&o){if(!t.get(s,Ur).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,zr,i),i.isOn&&o){const i=r.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,zr);i.isOn&&(i.isOn=!1,t.insert(s,zr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,$e)){const e=t.get(n,$e);e.color=vi(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,$e,e)}}}for(const e of s){const n=t.get(e,zr);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,$e)){const e=t.get(n.graphicEntity,$e);e.enabled=n.isOn,t.insert(n.graphicEntity,$e,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Wr=hi,Dr=xe("ProgressBar",{value:0,fillEntity:0,direction:hi.LeftToRight});function Or(e,t,n,s){if(!e.has(t,fi))return;const i=e.get(t,fi),r=n/2,o=s/2,a={left:-r,bottom:-o,right:r,top:o},l=ui(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,$e)){const n=e.get(t,$e);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,$e,n))}if(e.has(t,Be)){const n=e.get(t,Be),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,Be,n))}}class Lr{build(e){Ce("ProgressBar",Dr);const t=e.world;e.addSystemToSchedule(Lt.PreUpdate,jt([],()=>{const e=t.getEntitiesWithComponents([Dr,fi]);for(const n of e){const e=t.get(n,Dr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,fi),i=Math.max(0,Math.min(1,e.value));xi(t,e.fillEntity,e.direction,i);const r=Ti(s,n),o=Ei(s,n);Or(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Hr=new Lr,Xr=xe("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),jr=xe("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});const Yr=new class{build(e){Ce("Draggable",Xr),Ce("DragState",jr);const t=e.world,n=e.getResource(cr);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(Lt.PreUpdate,jt([tt(Jt),tt(en)],(e,o)=>{if(gr()&&!_r())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Xr,rr]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,Xr).enabled)continue;if(t.get(s,rr).hovered){let e=0;t.has(s,$e)&&(e=t.get(s,$e).layer);const i=Pi(t,s);(e>r||e===r&&i>=o)&&(r=e,o=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,jr)||t.insert(n,jr);const e=t.get(n,jr),r=t.get(n,Be);e.startWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.currentWorldPos={x:r.worldPosition.x,y:r.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,jr)){t.get(s,jr).isDragging=!1}s=null}if(null!==s&&null===r){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),d=t.get(s,Xr);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,jr).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,jr))return void(r=null);const s=t.get(r,jr),i=t.get(r,Xr),o=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+o,d=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,r=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),r=Math.max(r,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),r=Math.min(r,e.constraintMax.y)),{x:i,y:r}}(i,s,c,d);c=h.x,d=h.y;const u=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-u,y:d-f},s.currentWorldPos={x:c,y:d},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:d-s.startWorldPos.y},t.has(r,Be)){const e=function(e,t,n,s){if(!e.has(t,Le))return{x:n,y:s};const i=e.get(t,Le).entity;if(!e.valid(i)||!e.has(i,Be))return{x:n,y:s};const r=e.get(i,Be),o=0!==r.worldScale.x?r.worldScale.x:1,a=0!==r.worldScale.y?r.worldScale.y:1,l=Ji(r.worldRotation.z,r.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(n*d-s*c)/o,y:(n*c+s*d)/a}}(t,r,s.deltaWorld.x,s.deltaWorld.y),n=t.get(r,Be);n.position.x+=e.x,n.position.y+=e.y,t.insert(r,Be,n)}n.emit(r,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(r,"drag_end"),r=null)}},{name:"DragSystem"}))}},Nr=xe("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Vr(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 Gr(e,t,n,s,i){const r=2/(s=Math.max(1e-4,s)),o=r*i,a=1/(1+o+.48*o*o+.235*o*o*o),l=e-t,c=(n+r*l)*i,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(n-r*c)*a}}const qr=new class{build(e){Ce("ScrollView",Nr);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(Lt.PostUpdate,jt([tt(Jt),tt(en),tt(rt)],(e,i,r)=>{const o=gr()&&!_r(),a=Math.min(r.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([Nr,fi]);for(const r of l){Ai(t,r,Ni,{enabled:!0,mode:ji});const l=t.get(r,Nr),c=t.get(r,fi);let d=n.get(r);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(r,d));const h=Ti(c,r),u=Ei(c,r);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,He)){const e=t.get(l.contentEntity,He).entities;let n=0,s=0,i=0,r=0;for(const o of e){if(!t.valid(o)||!t.has(o,Be))continue;const e=t.get(o,Be);let a=0,l=0,c=.5,d=.5;if(t.has(o,fi)){const e=t.get(o,fi);a=Ti(e,o)||e.size.x,l=Ei(e,o)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(o,$e)){const e=t.get(o,$e);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,u=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);h<n&&(n=h),u>s&&(s=u),f<i&&(i=f),p>r&&(r=p)}0===f&&(f=s-n),0===p&&(p=r-i)}const g=Math.max(0,f-h),y=Math.max(0,p-u);if(!o&&i.valid){Ai(t,r,ir,{enabled:!0,blockRaycast:!0});const n=t.has(r,rr)?t.get(r,rr):null;if(n?.justPressed&&(d.isDragging=!0,d.lastWorldX=s.x,d.lastWorldY=s.y,d.velocityX=0,d.velocityY=0),d.isDragging&&e.isMouseButtonDown(0)){const e=s.x-d.lastWorldX,t=s.y-d.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=Vr(l.scrollX,0,g,h);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const s=a>0?-e*t/a:0;d.velocityX+=(s-d.velocityX)*n}}if(l.verticalEnabled){const e=Vr(l.scrollY,0,y,u);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const s=a>0?t*e/a:0;d.velocityY+=(s-d.velocityY)*n}}d.lastWorldX=s.x,d.lastWorldY=s.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*h,t=5*u;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Vr(l.scrollY,0,y,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Vr(l.scrollX,0,g,h);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>y;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Gr(l.scrollX,e,d.velocityX,.1,a);l.scrollX=t.value,d.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(d.velocityX)<Fi&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Fi?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:y,t=Gr(l.scrollY,e,d.velocityY,.1,a);l.scrollY=t.value,d.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(d.velocityY)<Fi&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Fi?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,y)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*u;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,y+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,Be)){const e=t.get(l.contentEntity,Be),n=e.position.x,s=e.position.y;(isNaN(d.lastAppliedX)||Math.abs(n-d.lastAppliedX)>.01)&&(d.contentBaseX=n),(isNaN(d.lastAppliedY)||Math.abs(s-d.lastAppliedY)>.01)&&(d.contentBaseY=s),e.position.x=d.contentBaseX-l.scrollX,e.position.y=d.contentBaseY+l.scrollY,d.lastAppliedX=e.position.x,d.lastAppliedY=e.position.y,t.insert(l.contentEntity,Be,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Kr=hi,Jr=xe("Slider",{value:0,minValue:0,maxValue:1,direction:hi.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Qr(e,t,n,s,i,r){const o=Ti(s,i)*n.worldScale.x,a=Ei(s,i)*n.worldScale.y,l=Ji(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),h=e-n.worldPosition.x,u=t-n.worldPosition.y,f=h*d-u*c,p=h*c+u*d,g=-s.pivot.x*o,y=-s.pivot.y*a;switch(r){case hi.LeftToRight:return o>0?(f-g)/o:0;case hi.RightToLeft:return o>0?1-(f-g)/o:0;case hi.BottomToTop:return a>0?(p-y)/a:0;case hi.TopToBottom:return a>0?1-(p-y)/a:0}}function Zr(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case hi.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case hi.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case hi.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case hi.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class eo{build(e){Ce("Slider",Jr);const t=e.world;let n=null;e.addSystemToSchedule(Lt.PreUpdate,jt([tt(Jt),tt(en),tt(cr)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([Jr,fi]);for(const o of r){const r=t.get(o,Jr),a=t.get(o,fi);if(!gr()||_r()){if(t.has(o,Be)){Ai(t,o,ir,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&Ai(t,r.handleEntity,ir,{enabled:!0,blockRaycast:!1});const l=t.get(o,Be),c=t.has(o,rr)?t.get(o,rr):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,rr)&&(d=t.get(r.handleEntity,rr).justPressed),d&&(n=o),n===o&&e.isMouseButtonDown(0)){let e=Qr(s.worldMouseX,s.worldMouseY,l,a,o,r.direction);e=Math.max(0,Math.min(1,e));let n=r.minValue+e*(r.maxValue-r.minValue);r.wholeNumbers&&(n=Math.round(n));const c=r.value;r.value=Math.max(r.minValue,Math.min(r.maxValue,n)),t.insert(o,Jr,r),r.value!==c&&i.emit(o,"change")}n===o&&e.isMouseButtonReleased(0)&&(n=null)}}const l=r.maxValue-r.minValue,c=l>0?(r.value-r.minValue)/l:0,d=Ti(a,o),h=Ei(a,o),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(xi(t,r.fillEntity,r.direction,c),ki(t,r.fillEntity,u,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,fi)){const e=t.get(r.handleEntity,fi);Zr(e,r.direction,c),t.insert(r.handleEntity,fi,e),ki(t,r.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const to=new eo;const no=new class{build(e){Ce("Focusable",Mr);const t=e.world,n=new Pr;e.insertResource(Tr,n),e.addSystemToSchedule(Lt.Update,jt([tt(Jt),tt(cr)],(e,s)=>{if(gr()&&!_r())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Mr]);for(const e of i){if(!t.has(e,rr))continue;t.get(e,rr).justPressed&&r(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,ir)){if(!t.get(n,ir).enabled)continue}const s=t.get(n,Mr);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 o=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===o?a?s.length-1:0:a?(o-1+s.length)%s.length:(o+1)%s.length,r(s[l])}function r(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Mr)){t.get(i,Mr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Mr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},so=xe("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function io(){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")}}()}const ro=new class{build(e){Ce("SafeArea",so);const t=e.world;let n=io(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=io(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=io(),s=!0});e.addSystemToSchedule(Lt.PreUpdate,jt([tt(en)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===r&&a===o||(r=e.screenH,o=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([so,fi]);for(const e of d){const s=t.get(e,so),i=t.get(e,fi),r=s.applyTop?n.top*c:0,o=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let d=!1;i.offsetMin.x===a&&i.offsetMin.y===o||(i.offsetMin={x:a,y:o},d=!0),i.offsetMax.x===-l&&i.offsetMax.y===-r||(i.offsetMax={x:-l,y:-r},d=!0),d&&t.insert(e,fi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},oo=xe("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let ao=null;function lo(e,t){if(!ao)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=ao.get(e);n?n.renderer=t:ao.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const co=new class{build(e){Ce("ListView",oo);const t=e.world,n=new Map;ao=n,e.addSystemToSchedule(Lt.PostUpdate,jt([tt(Jt)],e=>{const s=gr()&&!_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([oo,fi]);for(const r of i){Ai(t,r,ir,{enabled:!0,blockRaycast:!0}),Ai(t,r,Ni,{enabled:!0,mode:ji});let i=n.get(r);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(r,i));const o=t.get(r,oo),a=t.get(r,fi),l=Ei(a,r),c=Ti(a,r);if(!s){const n=t.has(r,rr)?t.get(r,rr):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}}const d=Math.max(0,o.itemCount*o.itemHeight-l);o.scrollY=Math.max(0,Math.min(o.scrollY,d));const h=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),u=Math.min(o.itemCount,Math.ceil((o.scrollY+l)/o.itemHeight)+o.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=u)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<u;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Ye,{value:`ListItem_${e}`}),t.insert(n,fi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,r),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,Be)){const s=t.get(n,Be);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,Be,s)}}i.visibleStart=h,i.visibleEnd=u}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},ho=xe("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const uo=new class{build(e){Ce("Dropdown",ho);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,Be))return;const n=t.get(e,Be);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,Be,{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,$e)){const n=t.get(e,$e);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,$e,{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 r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;d(i,!0),c(s);const r=t.get(e,$e),o=r.size.x,a=r.size.y;s.ddWidth=o;const l=n.options.length*Bi;t.insert(i,fi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:l},pivot:{x:.5,y:.5}}),t.insert(i,Be,{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,$e,{texture:ae,color:{r:1,g:1,b:1,a:1},size:{x:o,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 r=t.spawn(),a=l/2-(e+.5)*Bi;t.insert(r,Ye,{value:`Option_${e}`}),t.insert(r,fi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Bi},offsetMax:{x:0,y:0},size:{x:o,y:Bi},pivot:{x:.5,y:.5}}),t.insert(r,Be,{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(r,$e,{texture:ae,color:{r:.95,g:.95,b:.95,a:1},size:{x:o,y:Bi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,ir,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const c=t.spawn();t.insert(c,Be,{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,Di,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Ui.Left,verticalAlign:$i.Middle,wordWrap:!1,overflow:Wi.Clip,lineHeight:1.2}),t.insert(c,fi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:Bi},pivot:{x:.5,y:.5}}),t.setParent(c,r),s.textEntities.push(c)}h(s)}function o(e,t,n){t.isOpen=!1,c(n),d(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,o(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,Di))return;const s=t.get(n,Di);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},r=s.content,o=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},o=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];r!==t&&(r=t,o=!0)}o&&t.insert(n,Di,{content:r,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 d(e,n){if(0!==e&&t.valid(e)&&(t.has(e,ir)&&t.insert(e,ir,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,$e))){const s=t.get(e,$e);t.insert(e,$e,{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,$e))continue;const i=n===e.highlightIndex?{...zi}:{r:.95,g:.95,b:.95,a:1};t.insert(s,$e,{texture:ae,color:i,size:{x:e.ddWidth,y:Bi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function u(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,rr))continue;if(t.get(n,rr).hovered)return!0}return!1}e.addSystemToSchedule(Lt.Update,jt([tt(Jt),tt(cr)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=gr()&&!_r(),p=t.getEntitiesWithComponents([ho]);for(const g of p){const p=t.get(g,ho);let y=n.get(g);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(g,y)),s(p.listEntity),i(g),p.isOpen||d(p.listEntity,!1),l(p),f)continue;Ai(t,g,ir,{enabled:!0,blockRaycast:!0});const m=t.has(g,rr)?t.get(g,rr):null;if(m?.justPressed&&(p.isOpen?o(g,p,y):r(g,p,y)),p.isOpen){for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,rr))continue;if(t.get(n,rr).justPressed){a(g,p,y,e,c);break}}let n=-1;for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,rr))continue;if(t.get(s,rr).hovered){n=e;break}}n>=0&&n!==y.highlightIndex&&(y.highlightIndex=n,h(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=p.options.length-1?y.highlightIndex=0:y.highlightIndex++,h(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=p.options.length-1:y.highlightIndex--,h(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?a(g,p,y,y.highlightIndex,c):e.isKeyPressed("Escape")&&o(g,p,y),e.isMouseButtonPressed(0)&&(m?.hovered||u(y)||o(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},fo=0,po=0,go=2,yo=xe("LayoutGroup",{direction:fo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:po,reverseOrder:!1});const mo=new class{build(e){Ce("LayoutGroup",yo);const t=e.world;e.addSystemToSchedule(Lt.PreUpdate,jt([],()=>{const e=t.getEntitiesWithComponents([yo,fi,He]);for(const n of e){const e=t.get(n,yo),s=t.get(n,fi),i=t.get(n,He);if(!i.entities||0===i.entities.length)continue;const r=[];for(const e of i.entities)t.valid(e)&&t.has(e,fi)&&t.has(e,Be)&&r.push({entity:e,rect:t.get(e,fi)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=Ti(s,n),a=Ei(s,n),l=s.pivot.x,c=s.pivot.y,d=e.padding,h=e.direction===fo;let u=0;for(let n=0;n<r.length;n++){const s=r[n],i=Ti(s.rect,s.entity),f=Ei(s.rect,s.entity),p=s.rect.pivot.x,g=s.rect.pivot.y;let y,m;h?(y=-l*o+d.left+u+p*i,m=e.childAlignment===po?(1-c)*a-d.top-(1-g)*f:e.childAlignment===go?-c*a+d.bottom+g*f:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*f,u+=i,n<r.length-1&&(u+=e.spacing)):(y=e.childAlignment===po?-l*o+d.left+p*i:e.childAlignment===go?(1-l)*o-d.right-(1-p)*i:(.5-l)*o+.5*(d.left-d.right)+(p-.5)*i,m=(1-c)*a-d.top-u-(1-g)*f,u+=f,n<r.length-1&&(u+=e.spacing));const _=t.get(s.entity,Be);_.position.x=y,_.position.y=m,t.insert(s.entity,Be,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};Ae("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),Ae("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class _o{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(Lt.PostUpdate,jt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const wo=new _o;async function xo(e,t,n){const s=e.getResource(Ns);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function vo(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 bo=et({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),So=et(null,"PhysicsAPI");function Mo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Po(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class To{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(bo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=vo(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([De]);for(const n of t){const t=e.world.get(n,De);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),r=1/i,o=e.world;o.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(Lt.PostUpdate,jt([tt(rt)],a=>{const l=o.getEntitiesWithComponents([Ge,Be]),c=new Set;for(const i of l){c.add(i);const a=o.get(i,Ge),l=o.get(i,Be);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 o=Mo(l.worldRotation);s._physics_createBody(i,a.bodyType,l.worldPosition.x*r,l.worldPosition.y*r,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Eo(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===Qe.Kinematic){const e=Mo(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*r,l.worldPosition.y*r,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(),r=i>>2;for(let i=0;i<s;i++){const s=r+4*i,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const d=e.world.get(o,Be);if(!d)continue;let h=a,u=l,f=c;if(e.world.has(o,Le)){const t=e.world.get(o,Le);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Be)){const n=e.world.get(t.entity,Be),s=Mo(n.worldRotation),i=a-n.worldPosition.x,r=l-n.worldPosition.y,o=Math.cos(-s),d=Math.sin(-s);h=(i*o-r*d)/(0!==n.worldScale.x?n.worldScale.x:1),u=(i*d+r*o)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}d.position.x=h,d.position.y=u;const p=Po(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(o,Be,d)}}(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 r=0;r<i;r++){const i=e+6*r;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 r=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;r.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=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<d;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(bo,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(So,Co._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function Eo(e,t,n){const s=e.world;if(s.has(n,qe)){const e=s.get(n,qe);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,Ke)){const e=s.get(n,Ke);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,Je)){const e=s.get(n,Je);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 Co{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(Co.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const Ro={nearest:0,linear:1},Ao={repeat:0,clamp:1,mirror:2};function ko(e,t,n=!0,s){const i=e.getResourceManager(),r=e._malloc(t.pixels.length);let o;if(e.HEAPU8.set(t.pixels,r),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=Ro[s.filterMode??"linear"]??1,a=Ao[s.wrapMode??"clamp"]??1;o=i.createTextureEx(t.width,t.height,r,t.pixels.length,1,n,e,a)}else o=i.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Io(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 Fo(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),r=e.worldScale.y*t*(s?-1:1),o=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,h=a+a,u=l+l,f=c+c,p=a*h,g=a*u,y=a*f,m=l*u,_=l*f,w=c*f,x=d*h,v=d*u,b=d*f;return new Float32Array([(1-(m+w))*i,(g+b)*i,(y-v)*i,0,(g-b)*r,(1-(p+w))*r,(_+x)*r,0,(y+v)*o,(_-x)*o,(1-(p+m))*o,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Bo(e,t,n,s,i,r,o,a,l){const c=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const r of t.entities)for(const t of r.components){const r=Pn(t.type);for(const o of r){if("texture"!==o.type)continue;const r=t.data[o.field];if("string"==typeof r&&r&&void 0===s[r])try{const t=i?.[r];s[r]=ko(e,await n.loadPixels(r),!0,t)}catch{s[r]=0}}}return s}(t,n,s);!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)}}}}(t,n,c);let d={},h=null;if(i&&(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"])}}(i),d=await async function(e,t,n,s,i){const r={};for(const o of s.entities)for(const s of o.components){const o=Tn(s.type);if(!o||!s.data)continue;const a=s.data[o.skeletonField],l=s.data[o.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),d=i.resolvePath(l);try{const s=await i.readText(l),o="binary"===v(c)?.contentType;let h,u;if(o){const e=await i.readBinary(a);u=e.length,h=t._malloc(u),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);u=n.length,h=t._malloc(u+1),t.HEAPU8.set(n,h),t.HEAPU8[h+u]=0}const f=n.loadSkeleton(h,u,s,s.length,o);if(t._free(h),f<0)continue;r[a]=f;const p=Io(s),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const r=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),o=ko(e,r,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,r.width,r.height)}catch{}}}catch{}}return r}(t,i,h,n,s)),r){const t={gravity:o?.gravity??{...te},fixedTimestep:o?.fixedTimestep??ne,subStepCount:o?.subStepCount??4};new To("",t,()=>Promise.resolve(r)).build(e)}const u=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=Pn(t.type).find(e=>"font"===e.type);if(!i)continue;const r=t.data[i.field];if("string"==typeof r&&r&&void 0===s[r])try{let t,i;const o=v(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await n.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${o}`:o;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),d=ko(e,c,!1),h=e.getResourceManager();s[r]=h.loadBitmapFont(t,d,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=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=Pn(e.type).find(e=>"material"===e.type);if(!i)continue;const r=e.data[i.field];if("string"==typeof r&&r&&void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=hn.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=hn.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s);!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=Pn(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=i[e.type][n[e.field]]||0)}}(n,c,u,f);const p=In(e.world,n);if(l&&e.hasResource(Ns))for(const t of p.values())e.world.insert(t,Ne,{scene:l,persistent:!1});if(i&&h){const s=function(e,t,n,s){const i={};for(const r of t.entities)if(!1!==r.visible)for(const t of r.components){const o=Tn(t.type);if(!o||!t.data)continue;const a=n[t.data[o.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(r.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,p);!function(e,t,n,s,i){let r=0;e.setSpineRenderer((o,a)=>{let l=a-r;r=a,(l<=0||l>.5)&&(l=ee);const c=e.world;for(const e in i){const r=Number(e),o=i[e],a=c.has(r,je)?c.get(r,je):null,d=!1!==a?.playing,h=a?.timeScale??1;d&&s.update(o,l*h);let u=0;if(c.has(r,Be)){const e=Fo(c.get(r,Be),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);u=t._malloc(64),t.HEAPF32.set(e,u>>2)}const f=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(o,e),r=s.getMeshBatchIndexCount(o,e);if(!i||!r)continue;const a=8*i*4,l=2*r,c=n._malloc(a),d=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,c,d,h,f);const p=n.HEAPU32[h>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*i),m=new Uint16Array(n.HEAPU8.buffer,d,r),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,w,r).set(m),t.renderer_submitTriangles(_,i,w,r,p,g,u),t._free(_),t._free(w),n._free(c),n._free(d),n._free(h),n._free(f)}u&&t._free(u)}})}(e,t,i,h,s)}if(a){const t=e.getResource(Dn);t&&t.setAddressableManifest(a)}}function zo(e,t,n){return{name:e,async setup(){await Bo(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Uo{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=Tn(e.type);if(i){const s=e.data[i.skeletonField],r=e.data[i.atlasField];s&&("binary"===v(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}const r=Pn(e.type);for(const n of r){const i=e.data[n.field];"string"==typeof i&&i&&("font"===n.type?(s.add(i),t.add(i)):"material"===n.type&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of 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 r=[];for(const e of s){const t=v(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)||r.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{}}r.length>0&&await Promise.all(r)}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),r=new OffscreenCanvas(i.width,i.height).getContext("2d");r.drawImage(i,0,0);const o=r.getImageData(0,0,i.width,i.height);return i.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const $o="__preview__";class Wo{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(Ns);t.register({name:$o,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial($o),this.loadPromise_=t.load($o).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Uo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Bo(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,$o)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([We]);for(const s of n){if(e.get(s,We).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([De]);for(const i of s){const s=e.get(i,De);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(Ns).getScene($o),r=i?i.spawn():e.spawn(),o={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(r,Be,o);const a={isActive:!0,projectionType:ke.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Ie.ColorAndDepth};e.insert(r,We,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(Ns);await e.switchTo($o),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 Do={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Us.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Us.getTargetTexture(n),width:e.width,height:e.height}},release(e){Us.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Us.releaseRenderTarget(e._handle),Do.create({width:t,height:n,depth:!0})),begin(e,t){Us.begin(t,e._handle)},end(){Us.end()},getDepthTexture:e=>Us.getTargetDepthTexture(e._handle)};var Oo;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Oo||(Oo={}));class Lo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Oo[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Oo.Debug:console.debug(t,n);break;case Oo.Info:console.log(t,n);break;case Oo.Warn:console.warn(t,n);break;case Oo.Error:console.error(t,n)}}}class Ho{constructor(){this.handlers_=[],this.minLevel_=Oo.Info,this.addHandler(new Lo)}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(Oo.Debug,e,t,n)}info(e,t,n){this.log(Oo.Info,e,t,n)}warn(e,t,n){this.log(Oo.Warn,e,t,n)}error(e,t,n){this.log(Oo.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 Xo=new Ho;function jo(){return Xo}function Yo(e){Xo.setMinLevel(e)}function No(e,t,n){Xo.debug(e,t,n)}function Vo(e,t,n){Xo.info(e,t,n)}function Go(e,t,n){Xo.warn(e,t,n)}function qo(e,t,n){Xo.error(e,t,n)}const Ko=[Xi,sr,hr,Br,Hr,br,Yr,qr,to,$r,Cr,no,ro,co,uo,mo,wo];function Jo(e,t){return function(e,t){const n=Ks.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),is(e),ln(e),vs(e),Ts(e),Bs(e),Ws(e);const i=new Ls;n.setPipeline(i);let r=u();const o=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,r){r||(r=ni(e,s,t,i));const o=n.getResource(en);if(r.length>0){const e=r[0],n=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(n.x*t),o.vpY=Math.round((1-n.y-n.h)*i),o.vpW=Math.round(n.w*t),o.vpH=Math.round(n.h*i),o.screenW=t,o.screenH=i,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}n.insertResource(en,{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}=o();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=o();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Us.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-r)/1e3;let h;if(Us.resize(t,l),Rs.isInitialized()&&Rs.getPassCount()>0&&!Rs.isBypassed()&&Rs.resize(t,l),n.hasResource(Ns)){const e=n.getResource(Ns).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=ni(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Qs,width:t,height:l,elapsed:d});else{for(const e of f){const n=e.viewportRect,r=Math.round(n.x*t),o=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:r,y:o,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}Us.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Lt.First,l),n.addSystemToSchedule(Lt.Last,c),n.addPlugin(Ln),n.addPlugin(Qn),n.addPlugin(Zt),n.addPlugin(qs),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Ko,...t})}X||(X=!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 p(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 g(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=j;export{vt as Added,Ks as App,On as AssetPlugin,Hn as AssetRefCounter,Wn as AssetServer,Dn as Assets,xn as AsyncCache,Xe as BitmapText,tn as BlendMode,Qe as BodyType,qe as BoxCollider,ar as Button,or as ButtonState,We as Camera,De as Canvas,Je as CapsuleCollider,bt as Changed,He as Children,Ke as CircleCollider,Ie as ClearFlags,kt as Commands,Ft as CommandsInstance,N as DEFAULT_DESIGN_HEIGHT,Y as DEFAULT_DESIGN_WIDTH,ee as DEFAULT_FALLBACK_DT,ne as DEFAULT_FIXED_TIMESTEP,K as DEFAULT_FONT_FAMILY,J as DEFAULT_FONT_SIZE,te as DEFAULT_GRAVITY,Q as DEFAULT_LINE_HEIGHT,Z as DEFAULT_MAX_DELTA_TIME,V as DEFAULT_PIXELS_PER_UNIT,se as DEFAULT_SPINE_SKIN,q as DEFAULT_SPRITE_SIZE,G as DEFAULT_TEXT_CANVAS_SIZE,ys as DataType,jr as DragState,Xr as Draggable,ls as Draw,ho as Dropdown,It as EntityCommands,Wt as EventReader,Ot as EventReaderInstance,Ut as EventRegistry,$t as EventWriter,Dt as EventWriterInstance,hi as FillDirection,Ar as FillMethod,kr as FillOrigin,Tr as FocusManager,Pr as FocusManagerState,Mr as Focusable,Os as GLDebug,Ms as Geometry,Ht as GetWorld,oe as INVALID_ENTITY,le as INVALID_FONT,ce as INVALID_MATERIAL,ae as INVALID_TEXTURE,Ir as Image,Rr as ImageType,Jt as Input,Qt as InputPlugin,Kt as InputState,ir as Interactable,oo as ListView,ze as LocalTransform,Oo as LogLevel,Ho as Logger,hn as Material,vn as MaterialLoader,wt as Mut,Ye as Name,Le as Parent,Co as Physics,bo as PhysicsEvents,To as PhysicsPlugin,Rs as PostProcess,qn as PrefabServer,Kn as Prefabs,Jn as PrefabsPlugin,Wo as PreviewPlugin,Dr as ProgressBar,Wr as ProgressBarDirection,Lr as ProgressBarPlugin,ke as ProjectionType,Et as Query,Ct as QueryInstance,Rt as Removed,At as RemovedQueryInstance,Ls as RenderPipeline,ks as RenderStage,Do as RenderTexture,Us as Renderer,tt as Res,nt as ResMut,Ge as RigidBody,ie as RuntimeConfig,so as SafeArea,Fe as ScaleMode,Ns as SceneManager,Ys as SceneManagerState,Ne as SceneOwner,Lt as Schedule,Nr as ScrollView,wn as ShaderSources,Jr as Slider,Kr as SliderDirection,eo as SliderPlugin,je as SpineAnimation,$e as Sprite,qt as SystemRunner,Di as Text,Ui as TextAlign,Sr as TextInput,Er as TextInputPlugin,Wi as TextOverflow,Hi as TextPlugin,Oi as TextRenderer,$i as TextVerticalAlign,rt as Time,zr as Toggle,Be as Transform,en as UICameraInfo,lr as UIEventQueue,cr as UIEvents,rr as UIInteraction,vr as UIInteractionPlugin,dr as UILayoutPlugin,Ni as UIMask,nr as UIMaskPlugin,fi as UIRect,_o as UIRenderOrderPlugin,Oe as Velocity,Uo as WebAssetProvider,_t as World,Ue as WorldTransform,Vt as addStartupSystem,Nt as addSystem,Gt as addSystemToSchedule,xi as applyDirectionalFill,re as applyRuntimeConfig,Ln as assetPlugin,gs as clearDrawCallbacks,Se as clearUserComponents,fe as color,mi as computeFillAnchors,wi as computeFillSize,_i as computeHandleAnchors,ui as computeUIRectLayout,tr as createMaskProcessor,zo as createRuntimeSceneConfig,Jo as createWebApp,No as debug,xe as defineComponent,Bt as defineEvent,et as defineResource,jt as defineSystem,ve as defineTag,qo as error,$n as findEntityByName,Js as flushPendingSystems,S as getAddressableType,M as getAddressableTypeByEditorType,T as getAllAssetExtensions,A as getAssetMimeType,v as getAssetTypeEntry,Re as getComponent,Pn as getComponentAssetFieldDescriptors,Mn as getComponentAssetFields,Ve as getComponentDefaults,Rn as getComponentEntityFields,Tn as getComponentSpineFieldDescriptor,C as getCustomExtensions,b as getEditorType,jo as getLogger,t as getPlatform,s as getPlatformType,be as getUserComponent,R as getWeChatPackOptions,Vo as info,is as initDrawAPI,Ws as initGLDebugAPI,vs as initGeometryAPI,ln as initMaterialAPI,Ts as initPostProcessAPI,Bs as initRendererAPI,Zt as inputPlugin,jn as instantiatePrefab,Vi as intersectRects,Gi as invertMatrix4,Te as isBuiltinComponent,k as isCustomExtension,gr as isEditor,P as isKnownAssetExtension,n as isPlatformInitialized,_r as isPlayMode,yr as isRuntime,nn as isTextureRef,i as isWeChat,r as isWeb,zn as loadComponent,vo as loadPhysicsModule,Bo as loadRuntimeScene,In as loadSceneData,Fn as loadSceneWithAssets,E as looksLikeAssetPath,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Zi as pointInOBB,Ki as pointInWorldRect,Qn as prefabsPlugin,Hr as progressBarPlugin,pe as quat,Ce as registerComponent,Sn as registerComponentAssetFields,Cn as registerComponentEntityFields,fs as registerDrawCallback,Xn as registerEmbeddedAssets,_n as registerMaterialCallback,An as remapEntityFields,qs as sceneManagerPlugin,qi as screenToWorld,pr as setEditorMode,lo as setListViewRenderer,Yo as setLogLevel,mr as setPlayMode,dt as setWasmErrorHandler,rs as shutdownDrawAPI,Ds as shutdownGLDebugAPI,bs as shutdownGeometryAPI,cn as shutdownMaterialAPI,Es as shutdownPostProcessAPI,zs as shutdownRendererAPI,to as sliderPlugin,Ci as syncFillSpriteSize,Cr as textInputPlugin,Xi as textPlugin,xo as transitionTo,br as uiInteractionPlugin,hr as uiLayoutPlugin,sr as uiMaskPlugin,Ko as uiPlugins,wo as uiRenderOrderPlugin,Me as unregisterComponent,ps as unregisterDrawCallback,Un as updateCameraAspectRatio,de as vec2,he as vec3,ue as vec4,Go as warn,Vs as wrapSceneSystem,$ as wxFileExists,W as wxFileExistsSync,L as wxGetImagePixels,O as wxLoadImage,H as wxLoadImagePixels,z as wxReadFile,U as wxReadTextFile,D 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 r(){return"web"===e?.name}async function o(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 d(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function u(){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}function p(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 g(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 y=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],m={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,w=new Set;for(const e of y)for(const t of e.extensions)_.set(t,e),w.add(t);function x(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function v(e){return _.get(x(e))}function b(e){return v(e)?.editorType??"unknown"}function S(e){return v(e)?.addressableType??null}function P(e){for(const t of y)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function M(e){return w.has(e.toLowerCase())}function T(){return w}function E(e){return"string"==typeof e&&(!!e.includes("/")&&M(x(e)))}function C(){const e=[];for(const t of y)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function R(){return C().map(e=>({type:"suffix",value:e}))}function A(e){return m[e.toLowerCase()]}function k(e){const t=v(e);return t?.wechatPackInclude??!1}let I=null;function F(){return I||(I=wx.getFileSystemManager()),I}function B(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(k(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 z(e){return new Promise((t,n)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(B(e,t.errMsg)))}})})}function U(e,t="utf-8"){return new Promise((n,s)=>{F().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(B(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function W(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function D(e,t){return new Promise((n,s)=>{F().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function O(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 L(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 H(e){return L(await O(e))}let X=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return p(e,t)}async readFile(e){return z(e)}async readTextFile(e){return U(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return g(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){wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)}),wx.onTouchEnd(t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)})}},Y=1920,N=1080,V=100,G=512,q={x:100,y:100},K="Arial",J=24,Q=1.2,Z=.5,ee=1/60,te={x:0,y:-9.81},ne=1/60,se="default",ie={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function re(e){e.Text&&(e.Text._default.fontFamily=ie.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=ie.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=ie.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=ie.canvasMatchWidthOrHeight)}const oe=0,ae=4294967295,le=4294967295,ce=0,de=(e=0,t=0)=>({x:e,y:t}),he=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),ue=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),fe=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),pe=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function ge(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(ge);const t={};for(const n in e)t[n]=ge(e[n]);return t}let ye=0;function me(e,t){const n=++ye,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?{...ge(t),...e}:ge(t):e?{...t,...e}:{...t}}}const _e=new Map;function we(){return"undefined"==typeof window?_e:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function xe(e,t){const n=Ee.get(e)??we().get(e);if(n)return n;const s=me(e,t);return we().set(e,s),Ee.set(e,s),Me(e,t,!1),s}function ve(e){const t=Ee.get(e)??we().get(e);if(t)return t;const n=me(e,{});return we().set(e,n),Ee.set(e,n),Me(e,{},!0),n}function be(e){return we().get(e)}function Se(){const e=we();for(const t of e.keys())Ee.delete(t);e.clear()}function Pe(e){we().delete(e),Ee.delete(e)}function Me(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function Te(e){return!0===e._builtin}const Ee=new Map;function Ce(e,t){Ee.set(e,t)}function Re(e){return Ee.get(e)??be(e)}function Ae(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Ee.set(e,n),n}const ke={Perspective:0,Orthographic:1},Ie={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Fe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},Be=Ae("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}}),ze=Be,Ue=Be,$e=Ae("Sprite",{texture:ae,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}),We=Ae("Camera",{projectionType:ke.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=Ae("Canvas",{designResolution:{x:Y,y:N},pixelsPerUnit:100,scaleMode:Fe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Oe=Ae("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Le=Ae("Parent",{entity:0}),He=Ae("Children",{entities:[]}),Xe=Ae("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:le,enabled:!0}),je=Ae("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=xe("Name",{value:""}),Ne=xe("SceneOwner",{scene:"",persistent:!1});function Ve(e){const t=Re(e);return t?ge(t._default):null}const Ge=Ae("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),qe=Ae("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ke=Ae("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Je=Ae("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Qe={Static:0,Kinematic:1,Dynamic:2};let Ze=0;function et(e,t){const n=++Ze;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function tt(e){return{_type:"res",_resource:e}}function nt(e){return{_type:"res_mut",_resource:e}}class st{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 it{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 st(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const rt=et({delta:0,elapsed:0,frameCount:0},"Time");function ot(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=at(t[e]),r=at(i);"null"!==n&&"undefined"!==n&&(n!==r&&null!=i&&s.push({field:e,expected:n,actual:r,value:i}))}return s}function at(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function lt(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 ct=null;function dt(e){ct=e}function ht(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ct&&ct(e,t)}function ut(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 ft=1;const pt=new WeakMap;function gt(e){let t=pt.get(e);return void 0===t&&(t=ft++,pt.set(e,t)),t}const yt=[];function mt(e,t=[],n=[]){yt.length=0;for(const t of e)yt.push(gt(t));yt.sort((e,t)=>e-t);let s=yt.join(",");if(t.length>0){yt.length=0;for(const e of t)yt.push(gt(e));yt.sort((e,t)=>e-t),s+="|+"+yt.join(",")}if(n.length>0){yt.length=0;for(const e of n)yt.push(gt(e));yt.sort((e,t)=>e-t),s+="|-"+yt.join(",")}return s}class _t{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 ht(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){ht(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){ht(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){ht(t,`removeParent(entity=${e})`)}}insert(e,t,n){return Te(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(Te(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,ut(n))}catch(n){ht(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 Te(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Te(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Te(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return ht(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.");Te(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}`],r=n[`has${e}`],o=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof r||"function"!=typeof o)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:r.bind(n),remove:o.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=ot(t._name,t._default,s);if(e.length>0)throw new Error(lt(t._name,e))}const i={...t._default,...s};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,ut(i))}catch(n){ht(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let 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],r=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==r||"object"!=typeof r||Array.isArray(r))s[n]=i;else{const e=i,t=r;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 ht(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 ht(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){ht(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=ot(t._name,t._default,e);if(i.length>0)throw new Error(lt(t._name,i));s=e}const i=t.create(s),r=this.getStorage(t),o=!r.has(e);r.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),o&&(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 Ee)if(Te(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=we();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??mt(e,t,n),r=this.queryCache_.get(i);if(r&&r.version===this.worldVersion_)return r.result;let o=null,a=1/0;for(const t of e)if(!Te(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=o?o.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 wt(e){return{_type:"mut",_component:e}}function xt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function vt(e){return{_filterType:"added",_component:e}}function bt(e){return{_filterType:"changed",_component:e}}function St(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Pt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Mt(e){return xt(e)||St(e)||Pt(e)?e._component:e}function Tt(e,t=[],n=[]){const s=[],i=[],r=[];return e.forEach((e,t)=>{xt(e)&&s.push(t),St(e)?i.push({index:t,component:e._component}):Pt(e)&&r.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:r,with:(...s)=>Tt(e,[...t,...s],n),without:(...s)=>Tt(e,t,[...n,...s])}}function Et(...e){return Tt(e)}class Ct{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Mt),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_=mt(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,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of n)if(!r||this.passesChangeFilters_(d)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}o[0]=d;for(let e=0;e<s;e++)o[e+1]=this.world_.get(d,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=o[e[t]+1];c=d}yield o}}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 Rt(e){return{_type:"removed",_component:e}}class At{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 kt(){return{_type:"commands"}}class It{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=Te(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 Ft{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new It(this,null);return this.spawned_.push(e),e}entity(e){return new It(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"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}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 Bt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class zt{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 Ut{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new zt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new zt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function $t(e){return{_type:"event_writer",_event:e}}function Wt(e){return{_type:"event_reader",_event:e}}class Dt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Ot{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Lt;function Ht(){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"}(Lt||(Lt={}));let Xt=0;function jt(e,t,n){const s=++Xt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Yt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Nt(e){Yt().push({schedule:Lt.Update,system:e})}function Vt(e){Yt().push({schedule:Lt.Startup,system:e})}function Gt(e,t){Yt().push({schedule:e,system:t})}class qt{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}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]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ft&&t[e].flush()}finally{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 Ft(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 Dt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Ot(n)}case"removed":{const t=e;return new At(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Kt{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 Jt=et(new Kt,"Input");class Qt{constructor(e){this.target_=e??null}build(e){const n=new Kt;e.insertResource(Jt,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(Lt.Last,jt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Zt=new Qt,en=et({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 tn;function nn(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"}(tn||(tn={}));let sn=null,rn=null,on=1;const an=new Map;function ln(e){sn=e,rn=e.getResourceManager(),_n()}function cn(){0!==fn&&sn&&(sn._free(fn),fn=0),an.clear(),on=1,un=!1,gn.clear(),yn=null,rn=null,sn=null}function dn(){if(!rn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return rn}const hn={createShader:(e,t)=>dn().createShader(e,t),releaseShader(e){e>0&&dn().releaseShader(e)},create(e){const t=on++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??tn.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 an.set(t,n),t},get:e=>an.get(e),setUniform(e,t,n){const s=an.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,sn?.invalidateMaterialCache(e))},getUniform(e,t){const n=an.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=an.get(e);n&&(n.blendMode=t,sn?.invalidateMaterialCache(e))},getBlendMode(e){const t=an.get(e);return t?.blendMode??tn.Normal},setDepthTest(e,t){const n=an.get(e);n&&(n.depthTest=t,sn?.invalidateMaterialCache(e))},getShader(e){const t=an.get(e);return t?.shader??0},release(e){an.delete(e),sn?.invalidateMaterialCache(e)},isValid:e=>an.has(e),releaseAll(){an.clear(),sn?.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??tn.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=an.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=on++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return an.set(n,s),n},toAssetData(e,t){const n=an.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=an.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let un=!1,fn=0;const pn=16384,gn=new Map;let yn=null;function mn(e){const t=(0===fn&&sn&&(fn=sn._malloc(pn)),fn);if(0===t||!sn)return{ptr:0,count:0};let n=0,s=0;const i=sn.HEAPU8,r=sn.HEAPU32,o=sn.HEAPF32;for(const[a,l]of e){if(nn(l))continue;let e=gn.get(a);e||(yn||(yn=new TextEncoder),e=yn.encode(a),gn.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>pn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${pn} bytes), skipping remaining uniforms`);break}r[t+n>>2]=c,n+=4,i.set(e,t+n),n+=d;let h=0,u=[0,0,0,0];if("number"==typeof l)h=0,u[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++)u[e]=l[e]}else"w"in l?(h=3,u=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,u=[l.x,l.y,l.z,0]):"y"in l&&(h=1,u=[l.x,l.y,0,0]);r[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=u[e],n+=4;s++}return{ptr:t,count:s}}function _n(){if(!sn||un)return;sn.materialDataProvider=(e,t,n,s,i)=>{const r=an.get(e);if(!r)return sn.HEAPU32[t>>2]=0,sn.HEAPU32[n>>2]=0,sn.HEAPU32[s>>2]=0,void(sn.HEAPU32[i>>2]=0);sn.HEAPU32[t>>2]=r.shader,sn.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=mn(r.uniforms);sn.HEAPU32[s>>2]=o,sn.HEAPU32[i>>2]=a},un=!0}const wn={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 xn{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.pending_.get(e);if(i&&!i.aborted)return i.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&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class vn{constructor(e,t=""){this.cache_=new xn,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&&(hn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())hn.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),r=await this.shaderLoader_.load(i);return{handle:hn.createFromAsset(s,r),shaderHandle:r,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}}const bn=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"}]}]]);function Sn(e,t){bn.set(e,t)}function Pn(e){const t=bn.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 Mn(e){return bn.get(e)?.fields??[]}function Tn(e){return bn.get(e)?.spine??null}const En=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Cn(e,t){En.set(e,t)}function Rn(e){return En.get(e)}function An(e,t){const n=En.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 r=t.get(n);void 0===r&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==r?r:0}}}function kn(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,Ye,{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)An(i,n),zn(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 In(e,t){return kn(e,t)}async function Fn(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,r=new Map;s&&await async function(e,t,n,s,i){const r=new Map;for(const e of Bn.keys())r.set(e,new Set);const o=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=bn.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),o.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&r.get(e.type)?.add(t)}}const l=new Map,c=[...Bn.entries()].map(async([e,i])=>{const o=await i.load(r.get(e),t,n,s);l.set(e,o)}),d=o.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,...d]),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=r.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=bn.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&(n[e.field]=l.get(e.type)?.get(t)??0)}}}(t,s,i,r,n?.collectAssets);const o=kn(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=r.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return o}const Bn=new Map([["texture",{async load(e,t,n,s){const i=new Map,r=[...e].map(async e=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);i.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(r),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}}]]);function zn(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=Re(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 Un(e,t){const n=e.getEntitiesWithComponents([We]);for(const s of n){const n=e.get(s,We);n&&(n.aspectRatio=t,e.insert(s,We,n))}}function $n(e,t){const n=e.getEntitiesWithComponents([Ye]);for(const s of n){const n=e.get(s,Ye);if(n&&n.value===t)return s}return null}class Wn{constructor(e){this.textureCache_=new xn,this.shaderCache_=new xn,this.jsonCache_=new xn,this.textCache_=new xn,this.binaryCache_=new xn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new xn,this.prefabCache_=new xn,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(ie.textCanvasSize,ie.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 vn(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 r=(this.textureRefCounts_.get(s)??1)-1;r<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,r)}}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(),hn.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),r=await this.fetchText(i);if(!this.writeToVirtualFS(t,r))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(r),l=[];for(const e of a){const t=o?`${o}/${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),d="binary"===v(e)?.contentType,h=d?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,r,d);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=v(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("/")),r=i?`${i}/${s}`:s,o=await this.loadTextureRaw(r);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.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 Pn(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=Tn(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 Fn(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.embedded_.get(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 r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),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 o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=r;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),r=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(r);const o=this.module_.getResourceManager(),a=this.module_._malloc(r.length);this.module_.HEAPU8.set(r,a);const l=o.createTexture(t,n,a,r.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.embedded_.get(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 hn.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:r}=this.parseEsShader(s);if(!i||!r)throw new Error(`Invalid shader format: ${e}`);return hn.createShader(i,r)}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}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(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 o(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.embedded_.get(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 o(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.embedded_.get(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 o(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 Dn=et(null,"Assets");class On{build(e){const t=e.wasmModule;t?e.insertResource(Dn,new Wn(t)):console.warn("AssetPlugin: No WASM module available")}}const Ln=new On;class Hn{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 Xn(e,t){const n=e.getResource(Dn);n&&n.registerEmbeddedAssets(t)}async function jn(e,t,n){const{entities:s,rootId:i}=await Nn(t,n?.overrides??[],n,void 0,new Set),r={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}))},o=await Fn(e,r,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=o.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:o}}const Yn=10;async function Nn(e,t,n,s,i,r=0){if(r>Yn)throw new Error(`Prefab nesting depth exceeded ${Yn}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||o.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 Nn(e,s.nestedPrefab.overrides,n,a,i,r+1);o.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?o.get(s.parent)??null:null),l.push(...t.entities);continue}const c=o.get(s.prefabEntityId),d=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:d?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Vn(h.components,o),Gn(h,t),l.push(h)}const c=o.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Vn(e,t){for(const n of e){const e=Rn(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 Gn(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 qn{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 jn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Kn=et(null,"Prefabs");class Jn{constructor(){this.name="PrefabsPlugin",this.dependencies=[Dn]}build(e){const t=e.getResource(Dn);e.insertResource(Kn,new qn(e.world,t))}}const Qn=new Jn;let Zn=null,es=0,ts=0,ns=0;const ss=new Float32Array(256);function is(e){Zn=e,es=Zn._malloc(64),ts=Zn._malloc(64),ns=Zn._malloc(1024)}function rs(){Zn&&(es&&(Zn._free(es),es=0),ts&&(Zn._free(ts),ts=0),ns&&(Zn._free(ns),ns=0)),Zn=null}function os(){if(!Zn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Zn}const as={r:1,g:1,b:1,a:1},ls={begin(e){const t=os();try{t.HEAPF32.set(e,es/4),t.draw_begin(es)}catch(e){ht(e,"Draw.begin")}},end(){try{os().draw_end()}catch(e){ht(e,"Draw.end")}},line(e,t,n,s=1){try{os().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ht(e,"Draw.line")}},rect(e,t,n,s=!0){try{os().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ht(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{os().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ht(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{os().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ht(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{os().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ht(e,"Draw.circleOutline")}},texture(e,t,n,s=as){try{os().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){ht(e,"Draw.texture")}},textureRotated(e,t,n,s,i=as){try{os().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){ht(e,"Draw.textureRotated")}},setLayer(e){os().draw_setLayer(e)},setDepth(e){os().draw_setDepth(e)},getDrawCallCount:()=>Zn?Zn.draw_getDrawCallCount():0,getPrimitiveCount:()=>Zn?Zn.draw_getPrimitiveCount():0,setBlendMode(e){os().draw_setBlendMode(e)},setDepthTest(e){os().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=os();s.HEAPF32.set(n,ts/4),s.draw_mesh(e,t,ts)}catch(n){ht(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=os(),i=hn.get(t);if(!i)return;if(ls.setBlendMode(i.blendMode),ls.setDepthTest(i.depthTest),0===i.uniforms.size)return void ls.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,ts/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=hs(t);if(!(s<0)){if(nn(n))ss[r++]=10,ss[r++]=s,ss[r++]=n.slot??e++,ss[r++]=n.textureId;else if("number"==typeof n)ss[r++]=1,ss[r++]=s,ss[r++]=n;else if(Array.isArray(n)){ss[r++]=n.length,ss[r++]=s;for(let e=0;e<n.length;e++)ss[r++]=n[e]}else"w"in n?(ss[r++]=4,ss[r++]=s,ss[r++]=n.x,ss[r++]=n.y,ss[r++]=n.z,ss[r++]=n.w):"z"in n?(ss[r++]=3,ss[r++]=s,ss[r++]=n.x,ss[r++]=n.y,ss[r++]=n.z):(ss[r++]=2,ss[r++]=s,ss[r++]=n.x,ss[r++]=n.y);if(r>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<r)&&(i.cachedBuffer_=new Float32Array(r)),i.cachedBuffer_.set(ss.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,ts);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),ns/4),s.draw_meshWithUniforms(e,i.shader,ts,ns,r)}catch(n){ht(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},cs={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},ds=new Set;function hs(e){const t=cs[e];return void 0!==t?t:(ds.has(e)||(ds.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(cs).join(", ")}`)),-1)}const us=new Map;function fs(e,t,n){us.set(e,{fn:t,scene:n??""})}function ps(e){us.delete(e)}function gs(){us.clear()}var ys;!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"}(ys||(ys={}));let ms=null,_s=0,ws=0,xs=0;function vs(e){ms=e,_s=ms._malloc(262144),ws=ms._malloc(65536),xs=ms._malloc(256)}function bs(){ms&&(_s&&ms._free(_s),ws&&ms._free(ws),xs&&ms._free(xs),_s=0,ws=0,xs=0),ms=null}function Ss(){if(!ms)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ms}const Ps={create(e){const t=Ss(),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,_s/4);const i=e.layout.length,r=new Int32Array(i);for(let t=0;t<i;t++)r[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,xs,i).set(r),t.geometry_init(n,_s,s,xs,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,ws,s).set(e.indices),t.geometry_setIndices16(n,ws,s)}else{new Uint32Array(t.HEAPU8.buffer,ws,s).set(e.indices),t.geometry_setIndices32(n,ws,s)}}return n},updateVertices(e,t,n=0){const s=Ss(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,_s/4),s.geometry_updateVertices(e,_s,i,n)},release(e){e>0&&Ss().geometry_release(e)},isValid:e=>!(!ms||e<=0)&&ms.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Ps.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:ys.Float2},{name:"a_texCoord",type:ys.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,r=Math.cos(i)*e,o=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(r,o,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Ps.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:ys.Float2},{name:"a_texCoord",type:ys.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 r of e)t=Math.min(t,r.x),n=Math.min(n,r.y),s=Math.max(s,r.x),i=Math.max(i,r.y);const r=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(i-n);r.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return Ps.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:ys.Float2},{name:"a_texCoord",type:ys.Float2}],indices:new Uint16Array(o)})}};let Ms=null;function Ts(e){Ms=e}function Es(){Ms&&Rs.isInitialized()&&Rs.shutdown(),Ms=null}function Cs(){if(!Ms)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ms}const Rs={init(e,t){try{return Cs().postprocess_init(e,t)}catch(n){return ht(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Cs().postprocess_shutdown()}catch(e){ht(e,"PostProcess.shutdown")}},resize(e,t){try{Cs().postprocess_resize(e,t)}catch(n){ht(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Cs().postprocess_addPass(e,t)}catch(t){return ht(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Cs().postprocess_removePass(e)}catch(t){ht(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Cs().postprocess_setPassEnabled(e,t)}catch(t){ht(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Cs().postprocess_isPassEnabled(e)}catch(t){return ht(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Cs().postprocess_setUniformFloat(e,t,n)}catch(n){ht(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Cs().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){ht(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Cs().postprocess_begin()}catch(e){ht(e,"PostProcess.begin")}},end(){try{Cs().postprocess_end()}catch(e){ht(e,"PostProcess.end")}},getPassCount(){try{return Cs().postprocess_getPassCount()}catch(e){return ht(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ms)return!1;try{return Ms.postprocess_isInitialized()}catch(e){return ht(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Cs().postprocess_setBypass(e)}catch(e){ht(e,"PostProcess.setBypass")}},isBypassed(){if(!Ms)return!0;try{return Ms.postprocess_isBypassed()}catch(e){return ht(e,"PostProcess.isBypassed"),!0}},createBlur:()=>hn.createShader(As,"#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:()=>hn.createShader(As,"#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:()=>hn.createShader(As,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>hn.createShader(As,"#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")},As="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var ks;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(ks||(ks={}));let Is=null,Fs=0;function Bs(e){Is=e,Fs=Is._malloc(64)}function zs(){Is&&Fs&&(Is._free(Fs),Fs=0),Is=null}const Us={init(e,t){Is?.renderer_init(e,t)},resize(e,t){Is?.renderer_resize(e,t)},begin(e,t){if(Is&&Fs)try{Is.HEAPF32.set(e,Fs/4),Is.renderer_begin(Fs,t??0)}catch(e){ht(e,"Renderer.begin")}},flush(){try{Is?.renderer_flush()}catch(e){ht(e,"Renderer.flush")}},end(){try{Is?.renderer_end()}catch(e){ht(e,"Renderer.end")}},submitSprites(e){if(Is)try{Is.renderer_submitSprites(e._cpp)}catch(e){ht(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Is)try{Is.renderer_submitBitmapText(e._cpp)}catch(e){ht(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Is)try{Is.renderer_submitSpine?.(e._cpp)}catch(e){ht(e,"Renderer.submitSpine")}},setStage(e){Is?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Is?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Is?.renderer_releaseTarget(e)},getTargetTexture:e=>Is?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Is?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Is?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Is?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Is?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Is?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Is?Is.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Is?{drawCalls:Is.renderer_getDrawCalls(),triangles:Is.renderer_getTriangles(),sprites:Is.renderer_getSprites(),text:Is.renderer_getText(),spine:Is.renderer_getSpine?.()??0,meshes:Is.renderer_getMeshes(),culled:Is.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let $s=null;function Ws(e){$s=e}function Ds(){$s=null}const Os={enable(){$s?.gl_enableErrorCheck(!0)},disable(){$s?.gl_enableErrorCheck(!1)},check:e=>$s?.gl_checkErrors(e)??0,diagnose(){$s?.renderer_diagnose()}};class Ls{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:r}=e;s===this.lastWidth_&&i===this.lastHeight_||(Us.resize(s,i),Rs.isInitialized()&&Rs.getPassCount()>0&&Rs.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Us.setViewport(0,0,s,i),Us.clearBuffers(3),Us.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),Us.submitSprites(t),Us.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Us.submitSpine(t),Us.flush(),this.executeDrawCallbacks(n,r),Us.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;Us.setViewport(s.x,s.y,s.w,s.h),Us.setScissor(s.x,s.y,s.w,s.h,!0),Us.clearBuffers(i),Us.setScissor(0,0,0,0,!1),Us.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Us.submitSprites(t),Us.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Us.submitSpine(t),Us.flush(),this.executeDrawCallbacks(n,r),Us.end()}executeDrawCallbacks(e,t){const n=us;if(n.size>0){ls.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)}ls.end();for(const e of s)ps(e)}}}const Hs="__scene_transition_overlay__";class Xs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class js{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,Ne,{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),fs(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=Rs.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){Rs.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,Ne)){const n=this.app_.world.get(e,Ne);n.persistent=t,this.app_.world.insert(e,Ne,n)}}}class Ys{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??ie.sceneTransitionDuration,i=t.color??{...ie.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},fs(Hs,()=>{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;ls.setLayer(9999),ls.setDepth(9999),ls.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,ps(Hs),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,ps(Hs),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 Xs(t);this.scenes_.set(e,n);const s=new js(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Dn)?this.app_.getResource(Dn):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 Xs(t);this.scenes_.set(e,n);const s=new js(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Dn)?this.app_.getResource(Dn):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,Ne)){if(this.app_.world.get(e,Ne).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())ps(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{Rs.removePass(e)}catch{}n.postProcessPasses.length=0,this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const r=this.loadOrder_.indexOf(e);-1!==r&&this.loadOrder_.splice(r,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(Dn)&&(i.assetServer=this.app_.getResource(Dn));const r=await Fn(this.app_.world,s,i);e.loadedAssets=n;for(const n of r.values())e.entities.add(n),this.app_.world.insert(n,Ne,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Vs(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(Dn)?this.app_.getResource(Dn):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)hn.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,$e)){const t=n.get(e,$e);s.sprite=t.color.a,t.color.a=0,n.insert(e,$e,t),i=!0}if(n.has(e,je)){const t=n.get(e,je);s.spine=t.color.a,t.color.a=0,n.insert(e,je,t),i=!0}if(n.has(e,Xe)){const t=n.get(e,Xe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Xe,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,$e)){const t=n.get(e,$e);t.color.a=s.sprite,n.insert(e,$e,t)}if(void 0!==s.spine&&n.has(e,je)){const t=n.get(e,je);t.color.a=s.spine,n.insert(e,je,t)}if(void 0!==s.bitmapText&&n.has(e,Xe)){const t=n.get(e,Xe);t.color.a=s.bitmapText,n.insert(e,Xe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{Rs.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,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 Ns=et(null,"SceneManager");function Vs(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Ns).getSceneStatus(t)&&n._fn(...s)}}}const Gs=jt([nt(Ns),tt(rt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),qs={name:"SceneManager",build(e){const t=new Ys(e);e.insertResource(Ns,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ns),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Lt.Startup,n),e.addSystemToSchedule(Lt.Last,Gs)}};class Ks{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 Ut,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=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=u(),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(Lt.Last);else{this.runSchedule(Lt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Lt.FixedPreUpdate),this.runSchedule(Lt.FixedUpdate),this.runSchedule(Lt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Lt.PreUpdate),this.runSchedule(Lt.Update),this.runSchedule(Lt.PostUpdate),this.runSchedule(Lt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new _t,this.resources_=new it;for(const e of Object.values(Lt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ks}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(Lt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Lt.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 dt(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_}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(Ns).register(e),this}setInitialScene(e){return this.getResource(Ns).setInitial(e),this}tick(e){this.runner_||(this.runner_=new qt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(rt)||this.resources_.insert(rt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Lt.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Lt.First),this.runSchedule(Lt.PreUpdate),this.runSchedule(Lt.Update),this.runSchedule(Lt.PostUpdate),this.runSchedule(Lt.Last);this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new qt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(rt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Lt.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,gs();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=[Ds,zs,Es,bs,cn,rs];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,r=o=>{if(s.has(o))return;if(i.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&r(n)}i.delete(o),s.add(o),n.push(a)};for(let t=0;t<e.length;t++)r(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));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)}}}updateTime(e){const t=this.resources_.get(rt);t.delta=e,t.elapsed+=e,t.frameCount++}}function Js(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Qs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Zs(e,t,n,s,i){const r=e*t/n,o=e;switch(s){case Fe.FixedWidth:return r;case Fe.FixedHeight:return o;case Fe.Expand:return Math.max(r,o);case Fe.Shrink:return Math.min(r,o);case Fe.Match:{const e=i;return Math.pow(r,1-e)*Math.pow(o,e)}default:return o}}const ei=[];function ti(e){if(e<ei.length)return ei[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 ei.push(t),t}function ni(e,t,n,s,i,r){if(0===n||0===s)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=r&&i?o.filter(e=>{const t=i.tryGet(e,Ne);return!t||""===t.scene||r.has(t.scene)}):o;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),r=t.getTransform(e),o=i.viewportW*n/(i.viewportH*s);let a,d=0,h=0;if(i.projectionType===ke.Orthographic){if(h=i.orthoSize,l){h=Zs(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=h*o,a=ii(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=oi(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const u=li(r.position.x,r.position.y,r.position.z),f=ti(c.length);f.entity=e,f.viewProjection.set(di(a,u)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=d,f.halfH=h,f.cameraX=r.position.x,f.cameraY=r.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const si=new Float32Array(16);function ii(e,t,n,s,i,r){const o=si;o.fill(0);const a=t-e,l=s-n,c=r-i;return o[0]=2/a,o[5]=2/l,o[10]=-2/c,o[12]=-(t+e)/a,o[13]=-(s+n)/l,o[14]=-(r+i)/c,o[15]=1,o}const ri=new Float32Array(16);function oi(e,t,n,s){const i=ri;i.fill(0);const r=1/Math.tan(e/2),o=n-s;return i[0]=r/t,i[5]=r,i[10]=(s+n)/o,i[11]=-1,i[14]=2*s*n/o,i}const ai=new Float32Array(16);function li(e,t,n){const s=ai;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 ci=new Float32Array(16);function di(e,t){const n=ci;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 hi={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function ui(e,t,n,s,i,r,o={x:.5,y:.5}){const a=r.right-r.left,l=r.top-r.bottom,c=r.left+e.x*a,d=r.left+t.x*a,h=r.bottom+e.y*l,u=r.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+n.x-i.x*o.x,g=f+i.x):(f=c+n.x,g=d+s.x),e.y===t.y?(p=h+n.y-i.y*o.y,y=p+i.y):(p=h+n.y,y=u+s.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+o.x*m,originY:p+o.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const fi=Ae("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,gi=null;function yi(e,t){e.has(t,$e)||e.insert(t,$e,{texture:ae,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 hi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case hi.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case hi.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 _i(e,t){switch(e){case hi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case hi.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case hi.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 wi(e,t,n,s){switch(e){case hi.BottomToTop:case hi.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function xi(e,t,n,s){if(!e.has(t,fi))return;const i=e.get(t,fi),r=mi(n,s);i.anchorMin=r.anchorMin,i.anchorMax=r.anchorMax,r.anchorMin.x===r.anchorMax.x&&(i.size={...i.size,x:0}),r.anchorMin.y===r.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,fi,i)}function vi(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function bi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Si(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 r=0;r<t.length;r++){const o=t[r],a=s+o;if(e.measureText(a).width>n&&s){if(bi(o.charCodeAt(0))&&s.length>0&&bi(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!bi(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+o):(i.push(s),s=o)}else i.push(s),s=o}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Pi(e){let t=1;for(;t<e;)t*=2;return t}function Mi(e,t){let n=0,s=t;for(;e.has(s,Le);){const t=e.get(s,Le).entity;if(!e.valid(t))break;n++,s=t}return n}function Ti(e,t){if(pi&&gi){const e=pi.getUIRectComputedWidth(gi,t);if(e>0)return e}return e.size.x}function Ei(e,t){if(pi&&gi){const e=pi.getUIRectComputedHeight(gi,t);if(e>0)return e}return e.size.y}function Ci(e,t,n,s,i,r){if(!e.has(t,$e))return;const o=e.get(t,$e);let a,l;switch(n){case hi.BottomToTop:case hi.TopToBottom:a=i,l=r*s;break;default:a=i*s,l=r}o.size.x===a&&o.size.y===l||(o.size.x=a,o.size.y=l,e.insert(t,$e,o))}function Ri(e,t,n){let s=t;for(;e.has(s,Le);){const t=e.get(s,Le).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Ai(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function ki(e,t,n,s,i){if(!e.has(t,fi))return;const r=e.get(t,fi),o=ui(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,n,r.pivot),a=o.rect.right-o.rect.left,l=o.rect.top-o.rect.bottom;if(e.has(t,$e)){const n=e.get(t,$e);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,$e,n))}if(e.has(t,Be)){const n=e.get(t,Be);n.position.x=o.originX-s,n.position.y=o.originY-i,e.insert(t,Be,n)}}function Ii(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 Fi=.1,Bi=30,zi={r:.3,g:.5,b:.8,a:1},Ui={Left:0,Center:1,Right:2},$i={Top:0,Middle:1,Bottom:2},Wi={Visible:0,Clip:1,Ellipsis:2},Di=xe("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ui.Left,verticalAlign:$i.Top,wordWrap:!0,overflow:Wi.Visible,lineHeight:1.2});class Oi{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(ie.textCanvasSize,ie.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,Pi(this.frameMaxW_)),e.height=Math.max(e.height,Pi(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Pi(this.frameMaxW_),e.height=Pi(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,r=i?t.size.x:0,o=i?t.size.y:0,a=e.wordWrap&&i;let l=Si(n,e.content,a?r:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),u=Math.ceil(l.length*c),f=i?Math.ceil(r):h+2*d,p=i?Math.ceil(o):u+2*d;if(i&&e.overflow===Wi.Ellipsis&&u>o){const e=Math.floor(o/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,r)}}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,Pi(f)),s.height=Math.max(s.height,Pi(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=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(${g}, ${y}, ${m}, ${_})`,i&&e.overflow===Wi.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 $i.Top:x=d;break;case $i.Middle:x=d+(p-2*d-w)/2;break;case $i.Bottom:x=p-w-d;break;default:x=d}else x=d;let v=x;for(const t of l){let s;switch(e.align){case Ui.Left:s=d;break;case Ui.Center:s=f/2;break;case Ui.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===Wi.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{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 Ui.Left:return"left";case Ui.Center:return"center";case Ui.Right:return"right"}}}const Li=Ii({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?Ti(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Ei(e.uiRect,e.entity):0});class Hi{build(e){Ce("Text",Di);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Oi(t),s=e.world,i=new Map;e.addSystemToSchedule(Lt.PreUpdate,jt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Di));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Di)){if(s.valid(e)&&s.has(e,$e)){const t=s.get(e,$e);s.insert(e,$e,{texture:ae,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([Di]);for(const t of e){const e=s.get(t,Di),r=s.has(t,fi)?s.get(t,fi):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Li.changed(a,o)){if(s.has(t,$e)&&s.get(t,$e).texture!==ae)continue}yi(s,t);const l=r?{size:{x:Ti(r,t),y:Ei(r,t)}}:null,c=n.renderForEntity(t,e,l),d=s.get(t,$e);s.insert(t,$e,{texture:c.textureHandle,color:{r:d.color.r,g:d.color.g,b:d.color.b,a:d.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:d.layer,flipX:d.flipX,flipY:d.flipY,material:d.material,enabled:d.enabled}),i.set(t,Li.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Xi=new Hi,ji=0,Yi=1,Ni=Ae("UIMask",{enabled:!0,mode:ji});function Vi(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),r=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,r-s)}}function Gi(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],r=e[2],o=e[3],a=e[4],l=e[5],c=e[6],d=e[7],h=e[8],u=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],w=s*l-i*a,x=s*c-r*a,v=s*d-o*a,b=i*c-r*l,S=i*d-o*l,P=r*d-o*c,M=h*y-u*g,T=h*m-f*g,E=h*_-p*g,C=u*m-f*y,R=u*_-p*y,A=f*_-p*m;let k=w*A-x*R+v*C+b*E-S*T+P*M;return 0===k||(k=1/k,n[0]=(l*A-c*R+d*C)*k,n[1]=(r*R-i*A-o*C)*k,n[2]=(y*P-m*S+_*b)*k,n[3]=(f*S-u*P-p*b)*k,n[4]=(c*E-a*A-d*T)*k,n[5]=(s*A-r*E+o*T)*k,n[6]=(m*v-g*P-_*x)*k,n[7]=(h*P-f*v+p*x)*k,n[8]=(a*R-l*E+d*M)*k,n[9]=(i*E-s*R-o*M)*k,n[10]=(g*S-y*v+_*w)*k,n[11]=(u*v-h*S-p*w)*k,n[12]=(l*T-a*C-c*M)*k,n[13]=(s*C-i*T+r*M)*k,n[14]=(y*x-g*b-m*w)*k,n[15]=(h*b-u*x+f*w)*k),n}function qi(e,t,n,s,i,r,o){const a=(e-s)/r*2-1,l=(t-i)/o*2-1,c=n[0]*a+n[4]*l+n[12],d=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:d/h}}function Ki(e,t,n,s,i,r,o,a){return e>=n-i*o&&e<=n+i*(1-o)&&t>=s-r*a&&t<=s+r*(1-a)}function Ji(e,t){return 2*Math.atan2(e,t)}function Qi(e,t,n,s,i,r,o){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)*r,i+(.5*(l/c)+.5)*o]}function Zi(e,t,n,s,i,r,o,a,l,c){const d=Ji(l,c),h=Math.sin(-d),u=Math.cos(-d),f=e-n,p=t-s,g=f*u-p*h+n,y=f*h+p*u+s;return g>=n-i*o&&g<=n+i*(1-o)&&y>=s-r*a&&y<=s+r*(1-a)}function er(e,t,n,s,i,r,o){if(!e.has(t,fi)||!e.has(t,Be))return null;const a=e.get(t,fi),l=e.get(t,Be),c=Ti(a,t)*l.worldScale.x,d=Ei(a,t)*l.worldScale.y,h=l.worldPosition.x,u=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-d*p,_=d*(1-p),w=Ji(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+g*x-m*v,u+g*v+m*x],[h+y*x-m*v,u+y*v+m*x],[h+y*x-_*v,u+y*v+_*x],[h+g*x-_*v,u+g*v+_*x]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=Qi(e,t,n,s,i,r,o);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 tr(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ni]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,Ni);n.enabled&&(h.add(e),n.mode===Yi?(d.push(e),u.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,r,o,a,l,c){const d=[];for(const e of s){let n=!0;Ri(t,e,e=>{if(i.has(e)){if(t.get(e,Ni).mode===ji)return n=!1,!0}return!1}),n&&d.push(e)}function h(s,d){const u=e.getChildEntities(n,s);for(const n of u){let s=d;if(i.has(n)){if(t.get(n,Ni).mode===ji){const e=er(t,n,r,o,a,l,c);e&&(s=Vi(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=er(t,e,r,o,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,r,o,a),d.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const r=[];for(const e of s){let n=!0;Ri(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&r.push(e)}let o=1,a=!1;function l(){return o>255?(a||console.warn("Stencil mask overflow"),a=!0,null):o++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}function d(t,s){if(a)return;const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}for(const e of r){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,d,u)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class nr{build(e){if(Ce("UIMask",Ni),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(tr(e.wasmModule,e.world))}}const sr=new nr,ir=Ae("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),rr=Ae("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),or={Normal:0,Hovered:1,Pressed:2,Disabled:3},ar=xe("Button",{state:or.Normal,transition:null});class lr{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=et(new lr,"UIEvents");class dr{build(e){Ce("UIRect",fi);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){pi=e,gi=t}(n,s);e.addSystemToSchedule(Lt.PreUpdate,jt([tt(en)],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(Lt.PostUpdate,jt([tt(en)],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(Lt.PostUpdate,jt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const hr=new dr;let ur=!1,fr=!1;function pr(e){ur=e}function gr(){return ur}function yr(){return!ur}function mr(e){fr=e}function _r(){return fr}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&&(Gi(t,e),n=!1),e)}}();function xr(e,t,n,s){t.emit(n,s,n),Ri(e,n,i=>{if(!e.has(i,ir))return!1;const r=e.get(i,ir);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class vr{build(e){Ce("Interactable",ir),Ce("Button",ar);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new lr;e.insertResource(cr,i);let r=null,o=null;e.addSystemToSchedule(Lt.PreUpdate,jt([tt(Jt),tt(en)],(e,a)=>{if(i.drain(),gr()&&!_r())return;const l=t.getEntitiesWithComponents([rr]);for(const e of l){const n=t.get(e,rr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,rr,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;wr.update(a.viewProjection);const u=qi(d,h,wr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=u.x,a.worldMouseY=u.y;const p=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),y=e.isMouseButtonReleased(0);n.uiHitTest_update(s,u.x,u.y,p,g,y);const m=n.uiHitTest_getHitEntity(),_=4294967295===m?null:m;if(null===r||t.valid(r)||(r=null),r!==_){if(null!==r&&t.valid(r)&&t.has(r,rr)){const e=t.get(r,rr);e.hovered=!1,t.insert(r,rr,e),i.emit(r,"hover_exit")}if(null!==_){Ai(t,_,rr);const e=t.get(_,rr);e.hovered=!0,t.insert(_,rr,e),i.emit(_,"hover_enter")}r=_}if(g&&null!==_){const e=t.get(_,rr);e.pressed=!0,e.justPressed=!0,t.insert(_,rr,e),o=_,xr(t,i,_,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,rr)){const e=t.get(o,rr);e.pressed=!1,e.justReleased=!0,t.insert(o,rr,e),xr(t,i,o,"release"),o===r&&xr(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(Lt.Update,jt([],()=>{const e=t.getEntitiesWithComponents([ar]);for(const n of e){if(Ai(t,n,ir,{enabled:!0}),!t.has(n,rr))continue;const e=t.get(n,rr),s=t.get(n,ar),i=t.get(n,ir),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=or.Pressed:e.hovered?s.state=or.Hovered:s.state=or.Normal:s.state=or.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,$e)){const r=t.get(n,$e);r.color=vi(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,$e,r)}}},{name:"ButtonSystem"}))}}const br=new vr,Sr=xe("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}),Pr=xe("Focusable",{tabIndex:0,isFocused:!1});class Mr{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 Tr=et(new Mr,"FocusManager");class Er{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Ce("TextInput",Sr),gr()&&!_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(ie.textCanvasSize,64),r=i.getContext("2d",{willReadFrequently:!0});let o=0,a=0,l=!1,c=!0,d=0,u=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 g(){const t=e.getResource(Tr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Sr)?s:null}const y=()=>{l||null===g()||v()},m=()=>{l=!0},_=()=>{l=!1,v()},w=t=>{const s=g();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,Sr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(cr).emit(s,"submit"),void b()}let r=i.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?r=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=i.value.length),r!==i.cursorPos&&(i.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,i.dirty=!0,S())},x=()=>{const t=g();if(null!==t){const s=n.get(t,Sr);s.focused=!1,s.dirty=!0;e.getResource(Tr).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,Sr);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 b(){const t=g();if(null!==t){const e=n.get(t,Sr);e.focused=!1,e.dirty=!0}e.getResource(Tr).blur(),p.blur()}function S(){c=!0,d=0}p.addEventListener("input",y),p.addEventListener("compositionstart",m),p.addEventListener("compositionend",_),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",m),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!==o&&(t._free(o),o=0,a=0)};let P=null;function M(e,l,d,h){(i.width<d||i.height<h)&&(i.width=Pi(Math.max(i.width,d)),i.height=Pi(Math.max(i.height,h))),r.clearRect(0,0,i.width,i.height);const u=l.backgroundColor;r.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,r.fillRect(0,0,d,h),r.save(),r.beginPath(),r.rect(l.padding,0,d-2*l.padding,h),r.clip(),r.font=`${l.fontSize}px ${l.fontFamily}`,r.textBaseline="top",r.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,g=f?l.placeholderColor:l.color;r.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const y=Math.ceil(1.2*l.fontSize),m=l.padding;if(l.multiline){const e=Si(r,p,d-2*m);let t=m;for(const n of e)r.fillText(n,m,t),t+=y}else{const e=(h-l.fontSize)/2;r.fillText(p,m,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=Si(r,l.value,d-2*m);let i=0,o=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){o=t,a=l.cursorPos-i;break}i+=n,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,o=t+1,a=0}const c=o<e.length?e[o].substring(0,a):"";t=m+r.measureText(c).width,n=m+o*y,s=y}else t=m+r.measureText(e).width,n=(h-l.fontSize)/2,s=l.fontSize;r.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,r.fillRect(t,n,2,s)}r.restore();const _=r.getImageData(0,0,d,h),w=new Uint8Array(_.data.buffer),x=t.getResourceManager();w.length>a&&(0!==o&&t._free(o),o=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,o);const v=s.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(d,h,o,w.length,1,!0);s.set(e,b);const S=n.get(e,$e);S.texture=b,S.size.x=d,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,$e,S)}e.addSystemToSchedule(Lt.Update,jt([tt(Tr)],e=>{const t=n.getEntitiesWithComponents([Sr]);for(const e of t)Ai(n,e,Pr,{tabIndex:0,isFocused:!1}),Ai(n,e,ir,{enabled:!0,blockRaycast:!0});const s=g();if(s!==P){if(null!==P&&n.valid(P)&&n.has(P,Sr)){const e=n.get(P,Sr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,Sr);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(s),P=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(Lt.PreUpdate,jt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===u?0:(e-u)/1e3;u=e,i=Math.min(i,.1);const r=g();if(null!==r&&(d+=i,d>=.5)){d-=.5,c=!c;n.get(r,Sr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Sr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Sr,fi]);for(const e of a){const t=n.get(e,Sr);if(!t.dirty)continue;const s=n.get(e,fi),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(yi(n,e),M(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Cr=new Er,Rr={Simple:0,Sliced:1,Tiled:2,Filled:3},Ar={Horizontal:0,Vertical:1},kr={Left:0,Right:1,Bottom:2,Top:3},Ir=xe("Image",{texture:ae,color:{r:1,g:1,b:1,a:1},imageType:Rr.Simple,fillMethod:Ar.Horizontal,fillOrigin:kr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Fr=Ii({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?Ti(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Ei(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Br=new class{build(e){Ce("Image",Ir);const t=e.world,n=new Map;e.addSystemToSchedule(Lt.PreUpdate,jt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Ir)||n.delete(e);const e=t.getEntitiesWithComponents([Ir]);for(const s of e){const e=t.get(s,Ir),i=t.has(s,fi)?t.get(s,fi):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!Fr.changed(o,r))continue;yi(t,s);const a=t.get(s,$e);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=Ti(i,s),a.size.y=Ei(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Rr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Ar.Horizontal?e.fillOrigin===kr.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===kr.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===Rr.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,$e,a),n.set(s,Fr.take(r))}else a.color.a=0,t.insert(s,$e,a),n.set(s,Fr.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},zr=xe("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Ur=xe("ToggleGroup",{allowSwitchOff:!1});const $r=new class{build(e){Ce("Toggle",zr),Ce("ToggleGroup",Ur);const t=e.world,n=new Set;e.addSystemToSchedule(Lt.Update,jt([tt(cr)],e=>{const s=t.getEntitiesWithComponents([zr]);if(!gr()||_r()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,zr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,zr,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,zr);if(0!==n.group&&t.valid(n.group)){let t=r.get(n.group);t||(t=[],r.set(n.group,t)),t.push(e)}}for(const n of s){if(Ai(t,n,ir,{enabled:!0}),!t.has(n,rr))continue;const s=t.get(n,rr),i=t.get(n,zr),o=t.get(n,ir);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,Ur);if(i.isOn&&o){if(!t.get(s,Ur).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,zr,i),i.isOn&&o){const i=r.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,zr);i.isOn&&(i.isOn=!1,t.insert(s,zr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,$e)){const e=t.get(n,$e);e.color=vi(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,$e,e)}}}for(const e of s){const n=t.get(e,zr);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,$e)){const e=t.get(n.graphicEntity,$e);e.enabled=n.isOn,t.insert(n.graphicEntity,$e,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Wr=hi,Dr=xe("ProgressBar",{value:0,fillEntity:0,direction:hi.LeftToRight});function Or(e,t,n,s){if(!e.has(t,fi))return;const i=e.get(t,fi),r=n/2,o=s/2,a={left:-r,bottom:-o,right:r,top:o},l=ui(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,$e)){const n=e.get(t,$e);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,$e,n))}if(e.has(t,Be)){const n=e.get(t,Be),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,Be,n))}}class Lr{build(e){Ce("ProgressBar",Dr);const t=e.world;e.addSystemToSchedule(Lt.PreUpdate,jt([],()=>{const e=t.getEntitiesWithComponents([Dr,fi]);for(const n of e){const e=t.get(n,Dr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,fi),i=Math.max(0,Math.min(1,e.value));xi(t,e.fillEntity,e.direction,i);const r=Ti(s,n),o=Ei(s,n);Or(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Hr=new Lr,Xr=xe("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),jr=xe("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});const Yr=new class{build(e){Ce("Draggable",Xr),Ce("DragState",jr);const t=e.world,n=e.getResource(cr);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(Lt.PreUpdate,jt([tt(Jt),tt(en)],(e,o)=>{if(gr()&&!_r())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Xr,rr]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,Xr).enabled)continue;if(t.get(s,rr).hovered){let e=0;t.has(s,$e)&&(e=t.get(s,$e).layer);const i=Mi(t,s);(e>r||e===r&&i>=o)&&(r=e,o=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,jr)||t.insert(n,jr);const e=t.get(n,jr),r=t.get(n,Be);e.startWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.currentWorldPos={x:r.worldPosition.x,y:r.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,jr)){t.get(s,jr).isDragging=!1}s=null}if(null!==s&&null===r){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),d=t.get(s,Xr);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,jr).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,jr))return void(r=null);const s=t.get(r,jr),i=t.get(r,Xr),o=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+o,d=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,r=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),r=Math.max(r,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),r=Math.min(r,e.constraintMax.y)),{x:i,y:r}}(i,s,c,d);c=h.x,d=h.y;const u=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-u,y:d-f},s.currentWorldPos={x:c,y:d},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:d-s.startWorldPos.y},t.has(r,Be)){const e=function(e,t,n,s){if(!e.has(t,Le))return{x:n,y:s};const i=e.get(t,Le).entity;if(!e.valid(i)||!e.has(i,Be))return{x:n,y:s};const r=e.get(i,Be),o=0!==r.worldScale.x?r.worldScale.x:1,a=0!==r.worldScale.y?r.worldScale.y:1,l=Ji(r.worldRotation.z,r.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(n*d-s*c)/o,y:(n*c+s*d)/a}}(t,r,s.deltaWorld.x,s.deltaWorld.y),n=t.get(r,Be);n.position.x+=e.x,n.position.y+=e.y,t.insert(r,Be,n)}n.emit(r,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(r,"drag_end"),r=null)}},{name:"DragSystem"}))}},Nr=xe("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Vr(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 Gr(e,t,n,s,i){const r=2/(s=Math.max(1e-4,s)),o=r*i,a=1/(1+o+.48*o*o+.235*o*o*o),l=e-t,c=(n+r*l)*i,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(n-r*c)*a}}const qr=new class{build(e){Ce("ScrollView",Nr);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(Lt.PostUpdate,jt([tt(Jt),tt(en),tt(rt)],(e,i,r)=>{const o=gr()&&!_r(),a=Math.min(r.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([Nr,fi]);for(const r of l){Ai(t,r,Ni,{enabled:!0,mode:ji});const l=t.get(r,Nr),c=t.get(r,fi);let d=n.get(r);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(r,d));const h=Ti(c,r),u=Ei(c,r);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,He)){const e=t.get(l.contentEntity,He).entities;let n=0,s=0,i=0,r=0;for(const o of e){if(!t.valid(o)||!t.has(o,Be))continue;const e=t.get(o,Be);let a=0,l=0,c=.5,d=.5;if(t.has(o,fi)){const e=t.get(o,fi);a=Ti(e,o)||e.size.x,l=Ei(e,o)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(o,$e)){const e=t.get(o,$e);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,u=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);h<n&&(n=h),u>s&&(s=u),f<i&&(i=f),p>r&&(r=p)}0===f&&(f=s-n),0===p&&(p=r-i)}const g=Math.max(0,f-h),y=Math.max(0,p-u);if(!o&&i.valid){Ai(t,r,ir,{enabled:!0,blockRaycast:!0});const n=t.has(r,rr)?t.get(r,rr):null;if(n?.justPressed&&(d.isDragging=!0,d.lastWorldX=s.x,d.lastWorldY=s.y,d.velocityX=0,d.velocityY=0),d.isDragging&&e.isMouseButtonDown(0)){const e=s.x-d.lastWorldX,t=s.y-d.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=Vr(l.scrollX,0,g,h);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const s=a>0?-e*t/a:0;d.velocityX+=(s-d.velocityX)*n}}if(l.verticalEnabled){const e=Vr(l.scrollY,0,y,u);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const s=a>0?t*e/a:0;d.velocityY+=(s-d.velocityY)*n}}d.lastWorldX=s.x,d.lastWorldY=s.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*h,t=5*u;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Vr(l.scrollY,0,y,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Vr(l.scrollX,0,g,h);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>y;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Gr(l.scrollX,e,d.velocityX,.1,a);l.scrollX=t.value,d.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(d.velocityX)<Fi&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Fi?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:y,t=Gr(l.scrollY,e,d.velocityY,.1,a);l.scrollY=t.value,d.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(d.velocityY)<Fi&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Fi?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,y)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*u;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,y+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,Be)){const e=t.get(l.contentEntity,Be),n=e.position.x,s=e.position.y;(isNaN(d.lastAppliedX)||Math.abs(n-d.lastAppliedX)>.01)&&(d.contentBaseX=n),(isNaN(d.lastAppliedY)||Math.abs(s-d.lastAppliedY)>.01)&&(d.contentBaseY=s),e.position.x=d.contentBaseX-l.scrollX,e.position.y=d.contentBaseY+l.scrollY,d.lastAppliedX=e.position.x,d.lastAppliedY=e.position.y,t.insert(l.contentEntity,Be,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Kr=hi,Jr=xe("Slider",{value:0,minValue:0,maxValue:1,direction:hi.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Qr(e,t,n,s,i,r){const o=Ti(s,i)*n.worldScale.x,a=Ei(s,i)*n.worldScale.y,l=Ji(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),h=e-n.worldPosition.x,u=t-n.worldPosition.y,f=h*d-u*c,p=h*c+u*d,g=-s.pivot.x*o,y=-s.pivot.y*a;switch(r){case hi.LeftToRight:return o>0?(f-g)/o:0;case hi.RightToLeft:return o>0?1-(f-g)/o:0;case hi.BottomToTop:return a>0?(p-y)/a:0;case hi.TopToBottom:return a>0?1-(p-y)/a:0}}function Zr(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case hi.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case hi.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case hi.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case hi.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class eo{build(e){Ce("Slider",Jr);const t=e.world;let n=null;e.addSystemToSchedule(Lt.PreUpdate,jt([tt(Jt),tt(en),tt(cr)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([Jr,fi]);for(const o of r){const r=t.get(o,Jr),a=t.get(o,fi);if(!gr()||_r()){if(t.has(o,Be)){Ai(t,o,ir,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&Ai(t,r.handleEntity,ir,{enabled:!0,blockRaycast:!1});const l=t.get(o,Be),c=t.has(o,rr)?t.get(o,rr):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,rr)&&(d=t.get(r.handleEntity,rr).justPressed),d&&(n=o),n===o&&e.isMouseButtonDown(0)){let e=Qr(s.worldMouseX,s.worldMouseY,l,a,o,r.direction);e=Math.max(0,Math.min(1,e));let n=r.minValue+e*(r.maxValue-r.minValue);r.wholeNumbers&&(n=Math.round(n));const c=r.value;r.value=Math.max(r.minValue,Math.min(r.maxValue,n)),t.insert(o,Jr,r),r.value!==c&&i.emit(o,"change")}n===o&&e.isMouseButtonReleased(0)&&(n=null)}}const l=r.maxValue-r.minValue,c=l>0?(r.value-r.minValue)/l:0,d=Ti(a,o),h=Ei(a,o),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(xi(t,r.fillEntity,r.direction,c),ki(t,r.fillEntity,u,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,fi)){const e=t.get(r.handleEntity,fi);Zr(e,r.direction,c),t.insert(r.handleEntity,fi,e),ki(t,r.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const to=new eo;const no=new class{build(e){Ce("Focusable",Pr);const t=e.world,n=new Mr;e.insertResource(Tr,n),e.addSystemToSchedule(Lt.Update,jt([tt(Jt),tt(cr)],(e,s)=>{if(gr()&&!_r())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Pr]);for(const e of i){if(!t.has(e,rr))continue;t.get(e,rr).justPressed&&r(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,ir)){if(!t.get(n,ir).enabled)continue}const s=t.get(n,Pr);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 o=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===o?a?s.length-1:0:a?(o-1+s.length)%s.length:(o+1)%s.length,r(s[l])}function r(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Pr)){t.get(i,Pr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Pr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},so=xe("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function io(){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")}}()}const ro=new class{build(e){Ce("SafeArea",so);const t=e.world;let n=io(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=io(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=io(),s=!0});e.addSystemToSchedule(Lt.PreUpdate,jt([tt(en)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===r&&a===o||(r=e.screenH,o=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([so,fi]);for(const e of d){const s=t.get(e,so),i=t.get(e,fi),r=s.applyTop?n.top*c:0,o=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let d=!1;i.offsetMin.x===a&&i.offsetMin.y===o||(i.offsetMin={x:a,y:o},d=!0),i.offsetMax.x===-l&&i.offsetMax.y===-r||(i.offsetMax={x:-l,y:-r},d=!0),d&&t.insert(e,fi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},oo=xe("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let ao=null;function lo(e,t){if(!ao)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=ao.get(e);n?n.renderer=t:ao.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const co=new class{build(e){Ce("ListView",oo);const t=e.world,n=new Map;ao=n,e.addSystemToSchedule(Lt.PostUpdate,jt([tt(Jt)],e=>{const s=gr()&&!_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([oo,fi]);for(const r of i){Ai(t,r,ir,{enabled:!0,blockRaycast:!0}),Ai(t,r,Ni,{enabled:!0,mode:ji});let i=n.get(r);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(r,i));const o=t.get(r,oo),a=t.get(r,fi),l=Ei(a,r),c=Ti(a,r);if(!s){const n=t.has(r,rr)?t.get(r,rr):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}}const d=Math.max(0,o.itemCount*o.itemHeight-l);o.scrollY=Math.max(0,Math.min(o.scrollY,d));const h=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),u=Math.min(o.itemCount,Math.ceil((o.scrollY+l)/o.itemHeight)+o.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=u)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<u;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Ye,{value:`ListItem_${e}`}),t.insert(n,fi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,r),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,Be)){const s=t.get(n,Be);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,Be,s)}}i.visibleStart=h,i.visibleEnd=u}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},ho=xe("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const uo=new class{build(e){Ce("Dropdown",ho);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,Be))return;const n=t.get(e,Be);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,Be,{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,$e)){const n=t.get(e,$e);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,$e,{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 r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;d(i,!0),c(s);const r=t.get(e,$e),o=r.size.x,a=r.size.y;s.ddWidth=o;const l=n.options.length*Bi;t.insert(i,fi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:l},pivot:{x:.5,y:.5}}),t.insert(i,Be,{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,$e,{texture:ae,color:{r:1,g:1,b:1,a:1},size:{x:o,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 r=t.spawn(),a=l/2-(e+.5)*Bi;t.insert(r,Ye,{value:`Option_${e}`}),t.insert(r,fi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Bi},offsetMax:{x:0,y:0},size:{x:o,y:Bi},pivot:{x:.5,y:.5}}),t.insert(r,Be,{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(r,$e,{texture:ae,color:{r:.95,g:.95,b:.95,a:1},size:{x:o,y:Bi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,ir,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const c=t.spawn();t.insert(c,Be,{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,Di,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Ui.Left,verticalAlign:$i.Middle,wordWrap:!1,overflow:Wi.Clip,lineHeight:1.2}),t.insert(c,fi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:Bi},pivot:{x:.5,y:.5}}),t.setParent(c,r),s.textEntities.push(c)}h(s)}function o(e,t,n){t.isOpen=!1,c(n),d(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,o(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,Di))return;const s=t.get(n,Di);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},r=s.content,o=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},o=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];r!==t&&(r=t,o=!0)}o&&t.insert(n,Di,{content:r,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 d(e,n){if(0!==e&&t.valid(e)&&(t.has(e,ir)&&t.insert(e,ir,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,$e))){const s=t.get(e,$e);t.insert(e,$e,{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,$e))continue;const i=n===e.highlightIndex?{...zi}:{r:.95,g:.95,b:.95,a:1};t.insert(s,$e,{texture:ae,color:i,size:{x:e.ddWidth,y:Bi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function u(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,rr))continue;if(t.get(n,rr).hovered)return!0}return!1}e.addSystemToSchedule(Lt.Update,jt([tt(Jt),tt(cr)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=gr()&&!_r(),p=t.getEntitiesWithComponents([ho]);for(const g of p){const p=t.get(g,ho);let y=n.get(g);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(g,y)),s(p.listEntity),i(g),p.isOpen||d(p.listEntity,!1),l(p),f)continue;Ai(t,g,ir,{enabled:!0,blockRaycast:!0});const m=t.has(g,rr)?t.get(g,rr):null;if(m?.justPressed&&(p.isOpen?o(g,p,y):r(g,p,y)),p.isOpen){for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,rr))continue;if(t.get(n,rr).justPressed){a(g,p,y,e,c);break}}let n=-1;for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,rr))continue;if(t.get(s,rr).hovered){n=e;break}}n>=0&&n!==y.highlightIndex&&(y.highlightIndex=n,h(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=p.options.length-1?y.highlightIndex=0:y.highlightIndex++,h(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=p.options.length-1:y.highlightIndex--,h(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?a(g,p,y,y.highlightIndex,c):e.isKeyPressed("Escape")&&o(g,p,y),e.isMouseButtonPressed(0)&&(m?.hovered||u(y)||o(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},fo=0,po=0,go=2,yo=xe("LayoutGroup",{direction:fo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:po,reverseOrder:!1});const mo=new class{build(e){Ce("LayoutGroup",yo);const t=e.world;e.addSystemToSchedule(Lt.PreUpdate,jt([],()=>{const e=t.getEntitiesWithComponents([yo,fi,He]);for(const n of e){const e=t.get(n,yo),s=t.get(n,fi),i=t.get(n,He);if(!i.entities||0===i.entities.length)continue;const r=[];for(const e of i.entities)t.valid(e)&&t.has(e,fi)&&t.has(e,Be)&&r.push({entity:e,rect:t.get(e,fi)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=Ti(s,n),a=Ei(s,n),l=s.pivot.x,c=s.pivot.y,d=e.padding,h=e.direction===fo;let u=0;for(let n=0;n<r.length;n++){const s=r[n],i=Ti(s.rect,s.entity),f=Ei(s.rect,s.entity),p=s.rect.pivot.x,g=s.rect.pivot.y;let y,m;h?(y=-l*o+d.left+u+p*i,m=e.childAlignment===po?(1-c)*a-d.top-(1-g)*f:e.childAlignment===go?-c*a+d.bottom+g*f:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*f,u+=i,n<r.length-1&&(u+=e.spacing)):(y=e.childAlignment===po?-l*o+d.left+p*i:e.childAlignment===go?(1-l)*o-d.right-(1-p)*i:(.5-l)*o+.5*(d.left-d.right)+(p-.5)*i,m=(1-c)*a-d.top-u-(1-g)*f,u+=f,n<r.length-1&&(u+=e.spacing));const _=t.get(s.entity,Be);_.position.x=y,_.position.y=m,t.insert(s.entity,Be,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};Ae("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),Ae("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class _o{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(Lt.PostUpdate,jt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const wo=new _o;async function xo(e,t,n){const s=e.getResource(Ns);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function vo(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 bo=et({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),So=et(null,"PhysicsAPI");function Po(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Mo(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class To{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(bo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=vo(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([De]);for(const n of t){const t=e.world.get(n,De);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),r=1/i,o=e.world;o.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(Lt.PostUpdate,jt([tt(rt)],a=>{const l=o.getEntitiesWithComponents([Ge,Be]),c=new Set;for(const i of l){c.add(i);const a=o.get(i,Ge),l=o.get(i,Be);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 o=Po(l.worldRotation);s._physics_createBody(i,a.bodyType,l.worldPosition.x*r,l.worldPosition.y*r,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Eo(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===Qe.Kinematic){const e=Po(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*r,l.worldPosition.y*r,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(),r=i>>2;for(let i=0;i<s;i++){const s=r+4*i,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const d=e.world.get(o,Be);if(!d)continue;let h=a,u=l,f=c;if(e.world.has(o,Le)){const t=e.world.get(o,Le);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Be)){const n=e.world.get(t.entity,Be),s=Po(n.worldRotation),i=a-n.worldPosition.x,r=l-n.worldPosition.y,o=Math.cos(-s),d=Math.sin(-s);h=(i*o-r*d)/(0!==n.worldScale.x?n.worldScale.x:1),u=(i*d+r*o)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}d.position.x=h,d.position.y=u;const p=Mo(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(o,Be,d)}}(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 r=0;r<i;r++){const i=e+6*r;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 r=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;r.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=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<d;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(bo,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(So,Co._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function Eo(e,t,n){const s=e.world;if(s.has(n,qe)){const e=s.get(n,qe);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,Ke)){const e=s.get(n,Ke);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,Je)){const e=s.get(n,Je);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 Co{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(Co.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const Ro={nearest:0,linear:1},Ao={repeat:0,clamp:1,mirror:2};function ko(e,t,n=!0,s){const i=e.getResourceManager(),r=e._malloc(t.pixels.length);let o;if(e.HEAPU8.set(t.pixels,r),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=Ro[s.filterMode??"linear"]??1,a=Ao[s.wrapMode??"clamp"]??1;o=i.createTextureEx(t.width,t.height,r,t.pixels.length,1,n,e,a)}else o=i.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Io(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 Fo(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),r=e.worldScale.y*t*(s?-1:1),o=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,h=a+a,u=l+l,f=c+c,p=a*h,g=a*u,y=a*f,m=l*u,_=l*f,w=c*f,x=d*h,v=d*u,b=d*f;return new Float32Array([(1-(m+w))*i,(g+b)*i,(y-v)*i,0,(g-b)*r,(1-(p+w))*r,(_+x)*r,0,(y+v)*o,(_-x)*o,(1-(p+m))*o,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Bo(e,t,n,s,i,r,o,a,l){const c=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const r of t.entities)for(const t of r.components){const r=Mn(t.type);for(const o of r){if("texture"!==o.type)continue;const r=t.data[o.field];if("string"==typeof r&&r&&void 0===s[r])try{const t=i?.[r];s[r]=ko(e,await n.loadPixels(r),!0,t)}catch{s[r]=0}}}return s}(t,n,s);!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)}}}}(t,n,c);let d={},h=null;if(i&&(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"])}}(i),d=await async function(e,t,n,s,i){const r={};for(const o of s.entities)for(const s of o.components){const o=Tn(s.type);if(!o||!s.data)continue;const a=s.data[o.skeletonField],l=s.data[o.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),d=i.resolvePath(l);try{const s=await i.readText(l),o="binary"===v(c)?.contentType;let h,u;if(o){const e=await i.readBinary(a);u=e.length,h=t._malloc(u),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);u=n.length,h=t._malloc(u+1),t.HEAPU8.set(n,h),t.HEAPU8[h+u]=0}const f=n.loadSkeleton(h,u,s,s.length,o);if(t._free(h),f<0)continue;r[a]=f;const p=Io(s),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const r=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),o=ko(e,r,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,r.width,r.height)}catch{}}}catch{}}return r}(t,i,h,n,s)),r){const t={gravity:o?.gravity??{...te},fixedTimestep:o?.fixedTimestep??ne,subStepCount:o?.subStepCount??4};new To("",t,()=>Promise.resolve(r)).build(e)}const u=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=Mn(t.type).find(e=>"font"===e.type);if(!i)continue;const r=t.data[i.field];if("string"==typeof r&&r&&void 0===s[r])try{let t,i;const o=v(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await n.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${o}`:o;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),d=ko(e,c,!1),h=e.getResourceManager();s[r]=h.loadBitmapFont(t,d,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=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=Mn(e.type).find(e=>"material"===e.type);if(!i)continue;const r=e.data[i.field];if("string"==typeof r&&r&&void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=hn.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=hn.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s);!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=Mn(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=i[e.type][n[e.field]]||0)}}(n,c,u,f);const p=In(e.world,n);if(l&&e.hasResource(Ns))for(const t of p.values())e.world.insert(t,Ne,{scene:l,persistent:!1});if(i&&h){const s=function(e,t,n,s){const i={};for(const r of t.entities)if(!1!==r.visible)for(const t of r.components){const o=Tn(t.type);if(!o||!t.data)continue;const a=n[t.data[o.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(r.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,p);!function(e,t,n,s,i){let r=0;e.setSpineRenderer((o,a)=>{let l=a-r;r=a,(l<=0||l>.5)&&(l=ee);const c=e.world;for(const e in i){const r=Number(e),o=i[e],a=c.has(r,je)?c.get(r,je):null,d=!1!==a?.playing,h=a?.timeScale??1;d&&s.update(o,l*h);let u=0;if(c.has(r,Be)){const e=Fo(c.get(r,Be),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);u=t._malloc(64),t.HEAPF32.set(e,u>>2)}const f=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(o,e),r=s.getMeshBatchIndexCount(o,e);if(!i||!r)continue;const a=8*i*4,l=2*r,c=n._malloc(a),d=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,c,d,h,f);const p=n.HEAPU32[h>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*i),m=new Uint16Array(n.HEAPU8.buffer,d,r),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,w,r).set(m),t.renderer_submitTriangles(_,i,w,r,p,g,u),t._free(_),t._free(w),n._free(c),n._free(d),n._free(h),n._free(f)}u&&t._free(u)}})}(e,t,i,h,s)}if(a){const t=e.getResource(Dn);t&&t.setAddressableManifest(a)}}function zo(e,t,n){return{name:e,async setup(){await Bo(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Uo{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=Tn(e.type);if(i){const s=e.data[i.skeletonField],r=e.data[i.atlasField];s&&("binary"===v(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}const r=Mn(e.type);for(const n of r){const i=e.data[n.field];"string"==typeof i&&i&&("font"===n.type?(s.add(i),t.add(i)):"material"===n.type&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of 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 r=[];for(const e of s){const t=v(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)||r.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{}}r.length>0&&await Promise.all(r)}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),r=new OffscreenCanvas(i.width,i.height).getContext("2d");r.drawImage(i,0,0);const o=r.getImageData(0,0,i.width,i.height);return i.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const $o="__preview__";class Wo{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(Ns);t.register({name:$o,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial($o),this.loadPromise_=t.load($o).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Uo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Bo(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,$o)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([We]);for(const s of n){if(e.get(s,We).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([De]);for(const i of s){const s=e.get(i,De);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(Ns).getScene($o),r=i?i.spawn():e.spawn(),o={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(r,Be,o);const a={isActive:!0,projectionType:ke.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Ie.ColorAndDepth};e.insert(r,We,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(Ns);await e.switchTo($o),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 Do={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Us.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Us.getTargetTexture(n),width:e.width,height:e.height}},release(e){Us.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Us.releaseRenderTarget(e._handle),Do.create({width:t,height:n,depth:!0})),begin(e,t){Us.begin(t,e._handle)},end(){Us.end()},getDepthTexture:e=>Us.getTargetDepthTexture(e._handle)};var Oo;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Oo||(Oo={}));class Lo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Oo[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Oo.Debug:console.debug(t,n);break;case Oo.Info:console.log(t,n);break;case Oo.Warn:console.warn(t,n);break;case Oo.Error:console.error(t,n)}}}class Ho{constructor(){this.handlers_=[],this.minLevel_=Oo.Info,this.addHandler(new Lo)}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(Oo.Debug,e,t,n)}info(e,t,n){this.log(Oo.Info,e,t,n)}warn(e,t,n){this.log(Oo.Warn,e,t,n)}error(e,t,n){this.log(Oo.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 Xo=new Ho;function jo(){return Xo}function Yo(e){Xo.setMinLevel(e)}function No(e,t,n){Xo.debug(e,t,n)}function Vo(e,t,n){Xo.info(e,t,n)}function Go(e,t,n){Xo.warn(e,t,n)}function qo(e,t,n){Xo.error(e,t,n)}const Ko=[Xi,sr,hr,Br,Hr,br,Yr,qr,to,$r,Cr,no,ro,co,uo,mo,wo];function Jo(e,t){return function(e,t){const n=Ks.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),is(e),ln(e),vs(e),Ts(e),Bs(e),Ws(e);const i=new Ls;n.setPipeline(i);let r=u();const o=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,r){r||(r=ni(e,s,t,i));const o=n.getResource(en);if(r.length>0){const e=r[0],n=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(n.x*t),o.vpY=Math.round((1-n.y-n.h)*i),o.vpW=Math.round(n.w*t),o.vpH=Math.round(n.h*i),o.screenW=t,o.screenH=i,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}n.insertResource(en,{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}=o();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=o();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Us.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-r)/1e3;let h;if(Us.resize(t,l),Rs.isInitialized()&&Rs.getPassCount()>0&&!Rs.isBypassed()&&Rs.resize(t,l),n.hasResource(Ns)){const e=n.getResource(Ns).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=ni(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Qs,width:t,height:l,elapsed:d});else{for(const e of f){const n=e.viewportRect,r=Math.round(n.x*t),o=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:r,y:o,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}Us.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Lt.First,l),n.addSystemToSchedule(Lt.Last,c),n.addPlugin(Ln),n.addPlugin(Qn),n.addPlugin(Zt),n.addPlugin(qs),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Ko,...t})}X||(X=!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 p(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 g(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=j;export{vt as Added,Ks as App,On as AssetPlugin,Hn as AssetRefCounter,Wn as AssetServer,Dn as Assets,xn as AsyncCache,Xe as BitmapText,tn as BlendMode,Qe as BodyType,qe as BoxCollider,ar as Button,or as ButtonState,We as Camera,De as Canvas,Je as CapsuleCollider,bt as Changed,He as Children,Ke as CircleCollider,Ie as ClearFlags,kt as Commands,Ft as CommandsInstance,N as DEFAULT_DESIGN_HEIGHT,Y as DEFAULT_DESIGN_WIDTH,ee as DEFAULT_FALLBACK_DT,ne as DEFAULT_FIXED_TIMESTEP,K as DEFAULT_FONT_FAMILY,J as DEFAULT_FONT_SIZE,te as DEFAULT_GRAVITY,Q as DEFAULT_LINE_HEIGHT,Z as DEFAULT_MAX_DELTA_TIME,V as DEFAULT_PIXELS_PER_UNIT,se as DEFAULT_SPINE_SKIN,q as DEFAULT_SPRITE_SIZE,G as DEFAULT_TEXT_CANVAS_SIZE,ys as DataType,jr as DragState,Xr as Draggable,ls as Draw,ho as Dropdown,It as EntityCommands,Wt as EventReader,Ot as EventReaderInstance,Ut as EventRegistry,$t as EventWriter,Dt as EventWriterInstance,hi as FillDirection,Ar as FillMethod,kr as FillOrigin,Tr as FocusManager,Mr as FocusManagerState,Pr as Focusable,Os as GLDebug,Ps as Geometry,Ht as GetWorld,oe as INVALID_ENTITY,le as INVALID_FONT,ce as INVALID_MATERIAL,ae as INVALID_TEXTURE,Ir as Image,Rr as ImageType,Jt as Input,Qt as InputPlugin,Kt as InputState,ir as Interactable,oo as ListView,ze as LocalTransform,Oo as LogLevel,Ho as Logger,hn as Material,vn as MaterialLoader,wt as Mut,Ye as Name,Le as Parent,Co as Physics,bo as PhysicsEvents,To as PhysicsPlugin,Rs as PostProcess,qn as PrefabServer,Kn as Prefabs,Jn as PrefabsPlugin,Wo as PreviewPlugin,Dr as ProgressBar,Wr as ProgressBarDirection,Lr as ProgressBarPlugin,ke as ProjectionType,Et as Query,Ct as QueryInstance,Rt as Removed,At as RemovedQueryInstance,Ls as RenderPipeline,ks as RenderStage,Do as RenderTexture,Us as Renderer,tt as Res,nt as ResMut,Ge as RigidBody,ie as RuntimeConfig,so as SafeArea,Fe as ScaleMode,Ns as SceneManager,Ys as SceneManagerState,Ne as SceneOwner,Lt as Schedule,Nr as ScrollView,wn as ShaderSources,Jr as Slider,Kr as SliderDirection,eo as SliderPlugin,je as SpineAnimation,$e as Sprite,qt as SystemRunner,Di as Text,Ui as TextAlign,Sr as TextInput,Er as TextInputPlugin,Wi as TextOverflow,Hi as TextPlugin,Oi as TextRenderer,$i as TextVerticalAlign,rt as Time,zr as Toggle,Be as Transform,en as UICameraInfo,lr as UIEventQueue,cr as UIEvents,rr as UIInteraction,vr as UIInteractionPlugin,dr as UILayoutPlugin,Ni as UIMask,nr as UIMaskPlugin,fi as UIRect,_o as UIRenderOrderPlugin,Oe as Velocity,Uo as WebAssetProvider,_t as World,Ue as WorldTransform,Vt as addStartupSystem,Nt as addSystem,Gt as addSystemToSchedule,xi as applyDirectionalFill,re as applyRuntimeConfig,Ln as assetPlugin,gs as clearDrawCallbacks,Se as clearUserComponents,fe as color,mi as computeFillAnchors,wi as computeFillSize,_i as computeHandleAnchors,ui as computeUIRectLayout,tr as createMaskProcessor,zo as createRuntimeSceneConfig,Jo as createWebApp,No as debug,xe as defineComponent,Bt as defineEvent,et as defineResource,jt as defineSystem,ve as defineTag,qo as error,$n as findEntityByName,Js as flushPendingSystems,S as getAddressableType,P as getAddressableTypeByEditorType,T as getAllAssetExtensions,A as getAssetMimeType,v as getAssetTypeEntry,Re as getComponent,Mn as getComponentAssetFieldDescriptors,Pn as getComponentAssetFields,Ve as getComponentDefaults,Rn as getComponentEntityFields,Tn as getComponentSpineFieldDescriptor,C as getCustomExtensions,b as getEditorType,jo as getLogger,t as getPlatform,s as getPlatformType,be as getUserComponent,R as getWeChatPackOptions,Vo as info,is as initDrawAPI,Ws as initGLDebugAPI,vs as initGeometryAPI,ln as initMaterialAPI,Ts as initPostProcessAPI,Bs as initRendererAPI,Zt as inputPlugin,jn as instantiatePrefab,Vi as intersectRects,Gi as invertMatrix4,Te as isBuiltinComponent,k as isCustomExtension,gr as isEditor,M as isKnownAssetExtension,n as isPlatformInitialized,_r as isPlayMode,yr as isRuntime,nn as isTextureRef,i as isWeChat,r as isWeb,zn as loadComponent,vo as loadPhysicsModule,Bo as loadRuntimeScene,In as loadSceneData,Fn as loadSceneWithAssets,E as looksLikeAssetPath,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Zi as pointInOBB,Ki as pointInWorldRect,Qn as prefabsPlugin,Hr as progressBarPlugin,pe as quat,Ce as registerComponent,Sn as registerComponentAssetFields,Cn as registerComponentEntityFields,fs as registerDrawCallback,Xn as registerEmbeddedAssets,_n as registerMaterialCallback,An as remapEntityFields,qs as sceneManagerPlugin,qi as screenToWorld,pr as setEditorMode,lo as setListViewRenderer,Yo as setLogLevel,mr as setPlayMode,dt as setWasmErrorHandler,rs as shutdownDrawAPI,Ds as shutdownGLDebugAPI,bs as shutdownGeometryAPI,cn as shutdownMaterialAPI,Es as shutdownPostProcessAPI,zs as shutdownRendererAPI,to as sliderPlugin,Ci as syncFillSpriteSize,Cr as textInputPlugin,Xi as textPlugin,xo as transitionTo,br as uiInteractionPlugin,hr as uiLayoutPlugin,sr as uiMaskPlugin,Ko as uiPlugins,wo as uiRenderOrderPlugin,Pe as unregisterComponent,ps as unregisterDrawCallback,Un as updateCameraAspectRatio,de as vec2,he as vec3,ue as vec4,Go as warn,Vs as wrapSceneSystem,$ as wxFileExists,W as wxFileExistsSync,L as wxGetImagePixels,O as wxLoadImage,H as wxLoadImagePixels,z as wxReadFile,U as wxReadTextFile,D as wxWriteFile};
//# sourceMappingURL=index.wechat.js.map
diff --git a/desktop/public/sdk/esm/physics/index.d.ts b/desktop/public/sdk/esm/physics/index.d.ts
index f76b43ce1..b8e0219dc 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -556,6 +556,7 @@ declare class World {
private iterationDepth_;
private nextEntityId_;
private nextGeneration_;
+ private spawnCallbacks_;
private despawnCallbacks_;
private worldTick_;
private componentAddedTicks_;
@@ -567,6 +568,7 @@ declare class World {
getCppRegistry(): CppRegistry | null;
spawn(): Entity;
despawn(entity: Entity): void;
+ onSpawn(callback: (entity: Entity) => void): () => void;
onDespawn(callback: (entity: Entity) => void): () => void;
valid(entity: Entity): boolean;
entityCount(): number;
@@ -871,6 +873,7 @@ declare class App {
}): this;
addSystem(system: SystemDef): this;
addStartupSystem(system: SystemDef): this;
+ removeSystem(systemId: symbol): boolean;
connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;
get wasmModule(): ESEngineModule | null;
get pipeline(): RenderPipeline | null;
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index 9b7fbb88d..79af2b97c 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -508,6 +508,7 @@ declare class World {
private iterationDepth_;
private nextEntityId_;
private nextGeneration_;
+ private spawnCallbacks_;
private despawnCallbacks_;
private worldTick_;
private componentAddedTicks_;
@@ -519,6 +520,7 @@ declare class World {
getCppRegistry(): CppRegistry | null;
spawn(): Entity;
despawn(entity: Entity): void;
+ onSpawn(callback: (entity: Entity) => void): () => void;
onDespawn(callback: (entity: Entity) => void): () => void;
valid(entity: Entity): boolean;
entityCount(): number;
@@ -943,6 +945,7 @@ declare class App {
}): this;
addSystem(system: SystemDef): this;
addStartupSystem(system: SystemDef): this;
+ removeSystem(systemId: symbol): boolean;
connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;
get wasmModule(): ESEngineModule | null;
get pipeline(): RenderPipeline | null;
diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.html
index c40d61f95..a188be7e9 100644
--- a/desktop/src-tauri/src/preview_template.html
+++ b/desktop/src-tauri/src/preview_template.html
@@ -450,6 +450,7 @@
}
try {
+ window.__esengine_shim__ = { esengine: sdk };
await import('/.esengine/preview/user-scripts.js');
} catch (e) {
console.warn('User scripts load skipped:', e);
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index fc6b00452..98f4a9ecd 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -24,6 +24,7 @@ import { lockBuiltinPropertyEditors, clearExtensionPropertyEditors } from './pro
import { registerBuiltinSchemas, lockBuiltinComponentSchemas, clearExtensionComponentSchemas } from './schemas/ComponentSchemas';
import { initBoundsProviders, registerBoundsProvider, lockBuiltinBoundsProviders, clearExtensionBoundsProviders } from './bounds';
import { saveSceneToFile, saveSceneToPath, loadSceneFromFile, loadSceneFromPath, hasFileHandle, clearFileHandle } from './io/SceneSerializer';
+import { isAbsolutePath, joinPath, getProjectDir } from './utils/path';
import { icons } from './utils/icons';
import { ScriptLoader } from './scripting';
import { showBuildSettingsDialog, BuildService } from './builder';
@@ -102,6 +103,7 @@ export class Editor {
private dockLayout_: DockLayoutManager | null = null;
private contentDrawer_: ContentDrawer | null = null;
private assetLibraryReady_: Promise<void> = Promise.resolve();
+ private scriptsReady_: Promise<void> = Promise.resolve();
private clipboard_: EntityData[] | null = null;
private addressableWindow_: { element: HTMLElement; panel: AddressablePanel; keyHandler: (e: KeyboardEvent) => void } | null = null;
private previewUrl_: string | null = null;
@@ -163,7 +165,7 @@ export class Editor {
if (this.projectPath_) {
this.setupEditorGlobals();
this.assetLibraryReady_ = this.initializeAssetLibrary();
- this.initializeAllScripts();
+ this.scriptsReady_ = this.initializeAllScripts();
this.syncProjectSettings();
this.restoreLastScene();
}
@@ -321,16 +323,22 @@ export class Editor {
await this.store_.exitPrefabEditMode();
}
+ let resolvedPath = scenePath;
+ if (!isAbsolutePath(scenePath) && this.projectPath_) {
+ const projectDir = getProjectDir(this.projectPath_);
+ resolvedPath = joinPath(projectDir, scenePath);
+ }
+
await this.assetLibraryReady_;
- const scene = await loadSceneFromPath(scenePath);
+ const scene = await loadSceneFromPath(resolvedPath);
if (scene) {
const migrated = await getAssetLibrary().migrateScene(scene);
if (migrated) {
- await saveSceneToPath(scene, scenePath);
+ await saveSceneToPath(scene, resolvedPath);
}
- this.store_.loadScene(scene, scenePath);
+ this.store_.loadScene(scene, resolvedPath);
this.saveLastOpenedScene(scenePath);
- console.log('Scene loaded:', scenePath);
+ console.log('Scene loaded:', resolvedPath);
}
}
@@ -593,6 +601,7 @@ export class Editor {
private async restoreLastScene(): Promise<void> {
if (!this.projectPath_) return;
+ await this.scriptsReady_;
const settings = await loadEditorLocalSettings(this.projectPath_);
const lastScene = settings?.lastOpenedScene as string | undefined;
if (lastScene) {
@@ -699,6 +708,10 @@ export class Editor {
}
}
+ getCompiledScripts(): string | null {
+ return this.scriptLoader_?.getCompiledCode() ?? null;
+ }
+
async reloadScripts(): Promise<boolean> {
if (!this.scriptLoader_) {
if (this.projectPath_) {
diff --git a/editor/src/renderer/SharedRenderContext.ts b/editor/src/renderer/SharedRenderContext.ts
index 5ea176d7a..2a7201361 100644
--- a/editor/src/renderer/SharedRenderContext.ts
+++ b/editor/src/renderer/SharedRenderContext.ts
@@ -11,6 +11,8 @@ import {
defineSystem,
Schedule,
uiPlugins,
+ assetPlugin,
+ prefabsPlugin,
RenderPipeline,
Renderer,
createMaskProcessor,
@@ -148,6 +150,8 @@ export class SharedRenderContext {
}, { name: 'EditorInputClearSystem' }));
setEditorMode(true);
+ app.addPlugin(assetPlugin);
+ app.addPlugin(prefabsPlugin);
for (const plugin of uiPlugins) {
app.addPlugin(plugin);
}
diff --git a/editor/src/scripting/ScriptLoader.ts b/editor/src/scripting/ScriptLoader.ts
index 04895edb3..7c8ee3e19 100644
--- a/editor/src/scripting/ScriptLoader.ts
+++ b/editor/src/scripting/ScriptLoader.ts
@@ -4,8 +4,9 @@
*/
import * as esbuild from 'esbuild-wasm/esm/browser';
+import * as esengineModule from 'esengine';
import { defineComponent, defineTag, unregisterComponent } from 'esengine';
-import { virtualFsPlugin } from './esbuildPlugins';
+import { virtualFsPlugin, playModeShimPlugin } from './esbuildPlugins';
import type { NativeFS, ScriptLoaderOptions, CompileError } from './types';
import { clearScriptComponents } from '../schemas/ComponentSchemas';
import { getEditorContext } from '../context/EditorContext';
@@ -90,6 +91,10 @@ export class ScriptLoader {
.map(p => `import "${p}";`)
.join('\n');
+ const shimModules = new Map<string, Record<string, unknown>>([
+ ['esengine', esengineModule as unknown as Record<string, unknown>],
+ ]);
+
const result = await esbuild.build({
stdin: {
contents: entryContent,
@@ -102,8 +107,8 @@ export class ScriptLoader {
sourcemap: 'inline',
platform: 'browser',
target: 'es2020',
- external: ['esengine'],
plugins: [
+ playModeShimPlugin(shimModules),
virtualFsPlugin({
fs,
projectDir: this.projectDir_,
@@ -269,6 +274,10 @@ const DEFINE_TAG_RE = /defineTag\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
function extractAndRegisterComponents(source: string): string[] {
const names: string[] = [];
+ const registerSchema = typeof window !== 'undefined'
+ ? window.__esengine_registerComponent as
+ ((name: string, defaults: Record<string, unknown>, isTag: boolean) => void) | undefined
+ : undefined;
DEFINE_COMPONENT_RE.lastIndex = 0;
let match;
@@ -280,6 +289,7 @@ function extractAndRegisterComponents(source: string): string[] {
try {
const defaults = new Function(`return ${objStr}`)() as Record<string, unknown>;
defineComponent(name, defaults);
+ registerSchema?.(name, defaults, false);
names.push(name);
} catch { /* skip complex expressions */ }
}
@@ -287,6 +297,7 @@ function extractAndRegisterComponents(source: string): string[] {
DEFINE_TAG_RE.lastIndex = 0;
while ((match = DEFINE_TAG_RE.exec(source)) !== null) {
defineTag(match[1]);
+ registerSchema?.(match[1], {}, true);
names.push(match[1]);
}
diff --git a/editor/src/scripting/esbuildPlugins.ts b/editor/src/scripting/esbuildPlugins.ts
index 90ebaac31..07433a3c2 100644
--- a/editor/src/scripting/esbuildPlugins.ts
+++ b/editor/src/scripting/esbuildPlugins.ts
@@ -88,6 +88,45 @@ export function esengineShimPlugin(): esbuild.Plugin {
};
}
+// =============================================================================
+// Play Mode Shim Plugin
+// =============================================================================
+
+export function playModeShimPlugin(
+ modules: Map<string, Record<string, unknown>>,
+): esbuild.Plugin {
+ const shimCache = new Map<string, string>();
+ for (const [specifier, mod] of modules) {
+ const names = Object.keys(mod)
+ .filter(k => /^[a-zA-Z_$]/.test(k) && !JS_RESERVED.has(k));
+ const key = JSON.stringify(specifier);
+ const code = [
+ `const __m = window.__esengine_shim__[${key}];`,
+ ...names.map(n => `export const ${n} = __m["${n}"];`),
+ ].join('\n');
+ shimCache.set(specifier, code);
+ }
+
+ return {
+ name: 'play-mode-shim',
+ setup(build) {
+ build.onResolve({ filter: /^[^./]/ }, (args) => {
+ if (shimCache.has(args.path)) {
+ return { path: args.path, namespace: 'play-mode-shim' };
+ }
+ return undefined;
+ });
+ build.onLoad({ filter: /.*/, namespace: 'play-mode-shim' }, (args) => {
+ const code = shimCache.get(args.path);
+ if (!code) {
+ return { errors: [{ text: `Shim not found: ${args.path}` }] };
+ }
+ return { contents: code, loader: 'js' };
+ });
+ },
+ };
+}
+
// =============================================================================
// Virtual FS Plugin
// =============================================================================
@@ -117,10 +156,6 @@ export function virtualFsPlugin(options: VirtualFsPluginOptions): esbuild.Plugin
build.onResolve({ filter: /^[^./]/ }, async (args) => {
if (/^[A-Za-z]:/.test(args.path)) return undefined;
- if (args.path === 'esengine' || args.path === 'esengine/wasm') {
- return { path: args.path, external: true };
- }
-
const pkgName = args.path.startsWith('@')
? args.path.split('/').slice(0, 2).join('/')
: args.path.split('/')[0];
diff --git a/editor/src/services/ScriptInjector.ts b/editor/src/services/ScriptInjector.ts
index 156df8efe..8b6ac2494 100644
--- a/editor/src/services/ScriptInjector.ts
+++ b/editor/src/services/ScriptInjector.ts
@@ -1,14 +1,21 @@
+import * as esengine from 'esengine';
import type { App } from 'esengine';
export class ScriptInjector {
private cleanupFns_: (() => void)[] = [];
private blobUrls_: string[] = [];
+ private app_: App | null = null;
+ private injectedSystemIds_: symbol[] = [];
async inject(app: App, compiledCode: string | null): Promise<void> {
if (!compiledCode) return;
+ this.app_ = app;
+
const pendingBefore = (window as any).__esengine_pendingSystems?.length ?? 0;
+ (window as any).__esengine_shim__ = { esengine };
+
const blob = new Blob([compiledCode], { type: 'text/javascript' });
const url = URL.createObjectURL(blob);
this.blobUrls_.push(url);
@@ -30,6 +37,7 @@ export class ScriptInjector {
for (let i = pendingBefore; i < pending.length; i++) {
const entry = pending[i];
app.addSystemToSchedule(entry.schedule, entry.system);
+ this.injectedSystemIds_.push(entry.system._id);
}
pending.length = 0;
}
@@ -43,9 +51,19 @@ export class ScriptInjector {
}
this.cleanupFns_ = [];
+ if (this.app_) {
+ for (const id of this.injectedSystemIds_) {
+ this.app_.removeSystem(id);
+ }
+ }
+ this.injectedSystemIds_ = [];
+ this.app_ = null;
+
for (const url of this.blobUrls_) {
URL.revokeObjectURL(url);
}
this.blobUrls_ = [];
+
+ delete (window as any).__esengine_shim__;
}
}
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index 99d1001f4..88cbd71fe 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -167,6 +167,19 @@ export class App {
return this.addSystemToSchedule(Schedule.Startup, system);
}
+ removeSystem(systemId: symbol): boolean {
+ let removed = false;
+ for (const [schedule, entries] of this.systems_) {
+ const filtered = entries.filter(e => e.system._id !== systemId);
+ if (filtered.length !== entries.length) {
+ this.systems_.set(schedule, filtered);
+ this.sortedSystemsCache_.delete(schedule);
+ removed = true;
+ }
+ }
+ return removed;
+ }
+
// =========================================================================
// C++ Integration
// =========================================================================