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.

fix: progress bar fill positioning and UIRect move gizmo support

esengine80daca3d57cd
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index b0dd5f113..9cde11280 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_)}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,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 kt(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)Ft(r,s),Lt(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 Bt(e,t){return kt(e,t)}async function Dt(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 Ut.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=[...Ut.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=kt(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 Ut=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 Lt(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 zt{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 Dt(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 Wt=we(null,"Assets");class $t{build(e){const t=e.wasmModule;t?e.insertResource(Wt,new zt(t)):console.warn("AssetPlugin: No WASM module available")}}const Ot=new $t;async function Ht(e,t,s){const{entities:n,rootId:r}=await jt(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 Dt(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 Xt=10;async function jt(e,t,s,n,r,o=0){if(o>Xt)throw new Error(`Prefab nesting depth exceeded ${Xt}. 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 jt(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};Yt(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 Yt(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 Nt{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 Ht(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Vt=we(null,"Prefabs");class Gt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Wt]}build(e){const t=e.getResource(Wt);e.insertResource(Vt,new Nt(e.world,t))}}const qt=new Gt;let Kt=null,Jt=0,Qt=0,Zt=0;const es=new Float32Array(256);function ts(e){Kt=e,Jt=Kt._malloc(64),Qt=Kt._malloc(64),Zt=Kt._malloc(1024)}function ss(){Kt&&(Jt&&(Kt._free(Jt),Jt=0),Qt&&(Kt._free(Qt),Qt=0),Zt&&(Kt._free(Zt),Zt=0)),Kt=null}function ns(){if(!Kt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Kt}const rs={r:1,g:1,b:1,a:1},os={begin(e){const t=ns();try{t.HEAPF32.set(e,Jt/4),t.draw_begin(Jt)}catch(e){Ie(e,"Draw.begin")}},end(){try{ns().draw_end()}catch(e){Ie(e,"Draw.end")}},line(e,t,s,n=1){try{ns().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{ns().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{ns().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{ns().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{ns().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=rs){try{ns().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=rs){try{ns().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){ns().draw_setLayer(e)},setDepth(e){ns().draw_setDepth(e)},getDrawCallCount:()=>Kt?Kt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Kt?Kt.draw_getPrimitiveCount():0,setBlendMode(e){ns().draw_setBlendMode(e)},setDepthTest(e){ns().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ns();n.HEAPF32.set(s,Qt/4),n.draw_mesh(e,t,Qt)}catch(s){Ie(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ns(),r=mt.get(t);if(!r)return;if(os.setBlendMode(r.blendMode),os.setDepthTest(r.depthTest),0===r.uniforms.size)return void os.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,Qt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=ls(t);if(!(n<0)){if(ct(s))es[o++]=10,es[o++]=n,es[o++]=s.slot??e++,es[o++]=s.textureId;else if("number"==typeof s)es[o++]=1,es[o++]=n,es[o++]=s;else if(Array.isArray(s)){es[o++]=s.length,es[o++]=n;for(let e=0;e<s.length;e++)es[o++]=s[e]}else"w"in s?(es[o++]=4,es[o++]=n,es[o++]=s.x,es[o++]=s.y,es[o++]=s.z,es[o++]=s.w):"z"in s?(es[o++]=3,es[o++]=n,es[o++]=s.x,es[o++]=s.y,es[o++]=s.z):(es[o++]=2,es[o++]=n,es[o++]=s.x,es[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(es.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,Qt);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Zt/4),n.draw_meshWithUniforms(e,r.shader,Qt,Zt,o)}catch(s){Ie(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},is={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},as=new Set;function ls(e){const t=is[e];return void 0!==t?t:(as.has(e)||(as.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(is).join(", ")}`)),-1)}const cs=new Map;function ds(e,t,s){cs.set(e,{fn:t,scene:s??""})}function us(e){cs.delete(e)}function hs(){cs.clear()}var fs;exports.DataType=void 0,(fs=exports.DataType||(exports.DataType={}))[fs.Float=1]="Float",fs[fs.Float2=2]="Float2",fs[fs.Float3=3]="Float3",fs[fs.Float4=4]="Float4",fs[fs.Int=5]="Int",fs[fs.Int2=6]="Int2",fs[fs.Int3=7]="Int3",fs[fs.Int4=8]="Int4";let ps=null,gs=0,ys=0,ms=0;function _s(e){ps=e,gs=ps._malloc(262144),ys=ps._malloc(65536),ms=ps._malloc(256)}function xs(){ps&&(gs&&ps._free(gs),ys&&ps._free(ys),ms&&ps._free(ms),gs=0,ys=0,ms=0),ps=null}function ws(){if(!ps)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ps}const vs={create(e){const t=ws(),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,gs/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,ms,r).set(o),t.geometry_init(s,gs,n,ms,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,ys,n).set(e.indices),t.geometry_setIndices16(s,ys,n)}else{new Uint32Array(t.HEAPU8.buffer,ys,n).set(e.indices),t.geometry_setIndices32(s,ys,n)}}return s},updateVertices(e,t,s=0){const n=ws(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,gs/4),n.geometry_updateVertices(e,gs,r,s)},release(e){e>0&&ws().geometry_release(e)},isValid:e=>!(!ps||e<=0)&&ps.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return vs.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 vs.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 vs.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 bs=null;function Ss(e){bs=e}function Ps(){bs&&Ts.isInitialized()&&Ts.shutdown(),bs=null}function Ms(){if(!bs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return bs}const Ts={init(e,t){try{return Ms().postprocess_init(e,t)}catch(s){return Ie(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ms().postprocess_shutdown()}catch(e){Ie(e,"PostProcess.shutdown")}},resize(e,t){try{Ms().postprocess_resize(e,t)}catch(s){Ie(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ms().postprocess_addPass(e,t)}catch(t){return Ie(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ms().postprocess_removePass(e)}catch(t){Ie(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ms().postprocess_setPassEnabled(e,t)}catch(t){Ie(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ms().postprocess_isPassEnabled(e)}catch(t){return Ie(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Ms().postprocess_setUniformFloat(e,t,s)}catch(s){Ie(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Ms().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Ie(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ms().postprocess_begin()}catch(e){Ie(e,"PostProcess.begin")}},end(){try{Ms().postprocess_end()}catch(e){Ie(e,"PostProcess.end")}},getPassCount(){try{return Ms().postprocess_getPassCount()}catch(e){return Ie(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!bs)return!1;try{return bs.postprocess_isInitialized()}catch(e){return Ie(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ms().postprocess_setBypass(e)}catch(e){Ie(e,"PostProcess.setBypass")}},isBypassed(){if(!bs)return!0;try{return bs.postprocess_isBypassed()}catch(e){return Ie(e,"PostProcess.isBypassed"),!0}},createBlur:()=>mt.createShader(Es,"#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(Es,"#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(Es,"#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(Es,"#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")},Es="#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 Cs;exports.RenderStage=void 0,(Cs=exports.RenderStage||(exports.RenderStage={}))[Cs.Background=0]="Background",Cs[Cs.Opaque=1]="Opaque",Cs[Cs.Transparent=2]="Transparent",Cs[Cs.Overlay=3]="Overlay";let Rs=null,As=0;function Is(e){Rs=e,As=Rs._malloc(64)}function Fs(){Rs&&As&&(Rs._free(As),As=0),Rs=null}const ks={init(e,t){Rs?.renderer_init(e,t)},resize(e,t){Rs?.renderer_resize(e,t)},begin(e,t){if(Rs&&As)try{Rs.HEAPF32.set(e,As/4),Rs.renderer_begin(As,t??0)}catch(e){Ie(e,"Renderer.begin")}},flush(){try{Rs?.renderer_flush()}catch(e){Ie(e,"Renderer.flush")}},end(){try{Rs?.renderer_end()}catch(e){Ie(e,"Renderer.end")}},submitSprites(e){if(Rs)try{Rs.renderer_submitSprites(e._cpp)}catch(e){Ie(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Rs)try{Rs.renderer_submitBitmapText(e._cpp)}catch(e){Ie(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Rs)try{Rs.renderer_submitSpine?.(e._cpp)}catch(e){Ie(e,"Renderer.submitSpine")}},setStage(e){Rs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Rs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Rs?.renderer_releaseTarget(e)},getTargetTexture:e=>Rs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Rs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Rs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Rs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Rs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Rs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Rs?Rs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Rs?{drawCalls:Rs.renderer_getDrawCalls(),triangles:Rs.renderer_getTriangles(),sprites:Rs.renderer_getSprites(),text:Rs.renderer_getText(),spine:Rs.renderer_getSpine?.()??0,meshes:Rs.renderer_getMeshes(),culled:Rs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Bs=null;function Ds(e){Bs=e}function Us(){Bs=null}const Ls={enable(){Bs?.gl_enableErrorCheck(!0)},disable(){Bs?.gl_enableErrorCheck(!1)},check:e=>Bs?.gl_checkErrors(e)??0,diagnose(){Bs?.renderer_diagnose()}};class zs{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_||(ks.resize(n,r),Ts.isInitialized()&&Ts.getPassCount()>0&&Ts.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),ks.setViewport(0,0,n,r),ks.clearBuffers(3),ks.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),ks.submitSprites(t),ks.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ks.submitSpine(t),ks.flush(),this.executeDrawCallbacks(s,o),ks.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;ks.setViewport(n.x,n.y,n.w,n.h),ks.setScissor(n.x,n.y,n.w,n.h,!0),ks.clearBuffers(r),ks.setScissor(0,0,0,0,!1),ks.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),ks.submitSprites(t),ks.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ks.submitSpine(t),ks.flush(),this.executeDrawCallbacks(s,o),ks.end()}executeDrawCallbacks(e,t){const s=cs;if(s.size>0){os.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)}os.end();for(const e of n)us(e)}}}const Ws="__scene_transition_overlay__";class $s{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 Os{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),ds(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Ts.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Ts.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 Hs{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},ds(Ws,()=>{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;os.setLayer(9999),os.setDepth(9999),os.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,us(Ws),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,us(Ws),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 $s(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Wt)?this.app_.getResource(Wt):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 $s(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Wt)?this.app_.getResource(Wt):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())us(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Ts.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(Wt)&&(r.assetServer=this.app_.getResource(Wt));const o=await Dt(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=js(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(Wt)?this.app_.getResource(Wt):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{Ts.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 Xs=we(null,"SceneManager");function js(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Xs).getSceneStatus(t)&&s._fn(...n)}}}const Ys=et([be(Xs),ve(Me)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Ns={name:"SceneManager",build(e){const t=new Hs(e);e.insertResource(Xs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Xs),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,Ys)}};class Vs{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 Vs}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(Xs).register(e),this}setInitialScene(e){return this.getResource(Xs).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,hs();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=[Us,Fs,Ps,xs,gt,ss];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 Gs=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 Ks=[];function Js(e){if(e<Ks.length)return Ks[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 Ks.push(t),t}function Qs(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=en(-d,d,-u,u,-r.farPlane,r.farPlane)}else a=sn(r.fov*Math.PI/180,i,r.nearPlane,r.farPlane);const h=rn(o.position.x,o.position.y,o.position.z),f=Js(c.length);f.entity=e,f.viewProjection.set(an(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 Zs=new Float32Array(16);function en(e,t,s,n,r,o){const i=Zs;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 tn=new Float32Array(16);function sn(e,t,s,n){const r=tn;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 nn=new Float32Array(16);function rn(e,t,s){const n=nn;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 on=new Float32Array(16);function an(e,t){const s=on;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 ln={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function cn(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 dn=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 un=null,hn=null;function fn(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 pn(e,t){switch(e){case ln.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case ln.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case ln.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 gn(e,t,s,n){if(!e.has(t,dn))return;const r=e.get(t,dn),o=pn(s,n);r.anchorMin=o.anchorMin,r.anchorMax=o.anchorMax,r.offsetMin=o.offsetMin,r.offsetMax=o.offsetMax,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,dn,r)}function yn(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function mn(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function _n(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(mn(i.charCodeAt(0))&&n.length>0&&mn(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!mn(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 xn(e){let t=1;for(;t<e;)t*=2;return t}function wn(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 vn(e,t){if(un&&hn){const e=un.getUIRectComputedWidth(hn,t);if(e>0)return e}return e.size.x}function bn(e,t){if(un&&hn){const e=un.getUIRectComputedHeight(hn,t);if(e>0)return e}return e.size.y}function Sn(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 Pn(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Mn(e,t,s,n,r){if(!e.has(t,dn))return;const o=e.get(t,dn),i=cn(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 Tn(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 En=.1,Cn=30,Rn={r:.3,g:.5,b:.8,a:1},An={Left:0,Center:1,Right:2},In={Top:0,Middle:1,Bottom:2},Fn={Visible:0,Clip:1,Ellipsis:2},kn=j("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:An.Left,verticalAlign:In.Top,wordWrap:!0,overflow:Fn.Visible,lineHeight:1.2});class Bn{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,xn(this.frameMaxW_)),e.height=Math.max(e.height,xn(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=xn(this.frameMaxW_),e.height=xn(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=_n(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===Fn.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,xn(f)),n.height=Math.max(n.height,xn(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===Fn.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 In.Top:w=d;break;case In.Middle:w=d+(p-2*d-x)/2;break;case In.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 An.Left:n=d;break;case An.Center:n=f/2;break;case An.Right:n=f-d;break;default:n=d}s.fillText(t,n,v),v+=c}r&&e.overflow===Fn.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 An.Left:return"left";case An.Center:return"center";case An.Right:return"right"}}}const Dn=Tn({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?vn(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?bn(e.uiRect,e.entity):0});class Un{build(e){q("Text",kn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Bn(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,kn));for(const e of r.keys())if(!n.valid(e)||!n.has(e,kn)){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([kn]);for(const t of e){const e=n.get(t,kn),o=n.has(t,dn)?n.get(t,dn):null,i={text:e,uiRect:o,entity:t},a=r.get(t);if(a&&!Dn.changed(a,i)){if(n.has(t,re)&&n.get(t,re).texture!==L)continue}fn(n,t);const l=o?{size:{x:vn(o,t),y:bn(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,Dn.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ln=new Un,zn=0,Wn=1,$n=J("UIMask",{enabled:!0,mode:zn});function On(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 Hn(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 Xn(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 jn(e,t){return 2*Math.atan2(e,t)}function Yn(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 Nn(e,t,s,n,r,o,i){if(!e.has(t,dn)||!e.has(t,te))return null;const a=e.get(t,dn),l=e.get(t,te),c=vn(a,t)*l.worldScale.x,d=bn(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=jn(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]=Yn(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 Vn(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([$n]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,$n);s.enabled&&(u.add(e),s.mode===Wn?(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;Sn(t,e,e=>{if(r.has(e)){if(t.get(e,$n).mode===zn)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,$n).mode===zn){const e=Nn(t,s,o,i,a,l,c);e&&(n=On(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=Nn(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;Sn(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 Gn{build(e){if(q("UIMask",$n),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Vn(e.wasmModule,e.world))}}const qn=new Gn,Kn=J("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Jn=J("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Qn={Normal:0,Hovered:1,Pressed:2,Disabled:3},Zn=j("Button",{state:Qn.Normal,transition:null});class er{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 tr=we(new er,"UIEvents");class sr{build(e){q("UIRect",dn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){un=e,hn=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 nr=new sr;let rr=!1,or=!1;function ir(){return rr}function ar(){return or}const lr=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&&(Hn(t,e),s=!1),e)}}();function cr(e,t,s,n){t.emit(s,n,s),Sn(e,s,r=>{if(!e.has(r,Kn))return!1;const o=e.get(r,Kn);return o.enabled&&t.emit(r,n,s),o.blockRaycast})}class dr{build(e){q("Interactable",Kn),q("Button",Zn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),r=new er;e.insertResource(tr,r);let o=null,i=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at)],(e,a)=>{if(r.drain(),ir()&&!ar())return;const l=t.getEntitiesWithComponents([Jn]);for(const e of l){const s=t.get(e,Jn);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,Jn,s))}if(!a.valid)return;const d=c(),u=e.mouseX*d,h=a.screenH-e.mouseY*d;lr.update(a.viewProjection);const f=Xn(u,h,lr.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,Jn)){const e=t.get(o,Jn);e.hovered=!1,t.insert(o,Jn,e),r.emit(o,"hover_exit")}if(null!==_){Pn(t,_,Jn);const e=t.get(_,Jn);e.hovered=!0,t.insert(_,Jn,e),r.emit(_,"hover_enter")}o=_}if(g&&null!==_){const e=t.get(_,Jn);e.pressed=!0,e.justPressed=!0,t.insert(_,Jn,e),i=_,cr(t,r,_,"press")}if(y&&null!==i){if(t.valid(i)&&t.has(i,Jn)){const e=t.get(i,Jn);e.pressed=!1,e.justReleased=!0,t.insert(i,Jn,e),cr(t,r,i,"release"),i===o&&cr(t,r,i,"click")}i=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,et([],()=>{const e=t.getEntitiesWithComponents([Zn]);for(const s of e){if(Pn(t,s,Kn,{enabled:!0}),!t.has(s,Jn))continue;const e=t.get(s,Jn),n=t.get(s,Zn),r=t.get(s,Kn),o=!a.has(s),i=n.state;if(r.enabled?e.pressed?n.state=Qn.Pressed:e.hovered?n.state=Qn.Hovered:n.state=Qn.Normal:n.state=Qn.Disabled,o&&a.add(s),(o||i!==n.state)&&n.transition&&t.has(s,re)){const o=t.get(s,re);o.color=yn(n.transition,r.enabled,e.pressed,e.hovered),t.insert(s,re,o)}}},{name:"ButtonSystem"}))}}const ur=new dr,hr=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}),fr=j("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 gr=we(new pr,"FocusManager");class yr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(q("TextInput",hr),ir()&&!ar())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(gr);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,hr)?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,hr);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource(tr).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,hr);n.focused=!1,n.dirty=!0;e.getResource(gr).blur()}};function v(){const t=g();if(null===t)return;const n=s.get(t,hr);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(tr).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,hr);e.focused=!1,e.dirty=!0}e.getResource(gr).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=xn(Math.max(r.width,c)),r.height=xn(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=_n(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=_n(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(gr)],e=>{const t=s.getEntitiesWithComponents([hr]);for(const e of t)Pn(s,e,fr,{tabIndex:0,isFocused:!1}),Pn(s,e,Kn,{enabled:!0,blockRaycast:!0});const n=g();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,hr)){const e=s.get(P,hr);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,hr);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,hr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,hr)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([hr,dn]);for(const e of a){const t=s.get(e,hr);if(!t.dirty)continue;const n=s.get(e,dn),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(fn(s,e),M(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const mr=new yr,_r={Simple:0,Sliced:1,Tiled:2,Filled:3},xr={Horizontal:0,Vertical:1},wr={Left:0,Right:1,Bottom:2,Top:3},vr=j("Image",{texture:L,color:{r:1,g:1,b:1,a:1},imageType:_r.Simple,fillMethod:xr.Horizontal,fillOrigin:wr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),br=Tn({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?vn(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?bn(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Sr=new class{build(e){q("Image",vr);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,vr)||s.delete(e);const e=t.getEntitiesWithComponents([vr]);for(const n of e){const e=t.get(n,vr),r=t.has(n,dn)?t.get(n,dn):null,o={image:e,uiRect:r,entity:n},i=s.get(n);if(i&&!br.changed(i,o))continue;fn(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=vn(r,n),a.size.y=bn(r,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===_r.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===xr.Horizontal?e.fillOrigin===wr.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===wr.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===_r.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,br.take(o))}else a.color.a=0,t.insert(n,re,a),s.set(n,br.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Pr=j("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Mr=j("ToggleGroup",{allowSwitchOff:!1});const Tr=new class{build(e){q("Toggle",Pr),q("ToggleGroup",Mr);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,et([ve(tr)],e=>{const n=t.getEntitiesWithComponents([Pr]);if(!ir()||ar()){const r=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Pr);n.isOn&&0!==n.group&&t.valid(n.group)&&(r.has(n.group)?(n.isOn=!1,t.insert(e,Pr,n)):r.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Pr);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(Pn(t,s,Kn,{enabled:!0}),!t.has(s,Jn))continue;const n=t.get(s,Jn),r=t.get(s,Pr),i=t.get(s,Kn);if(n.justPressed&&i.enabled){const n=r.group,i=0!==n&&t.valid(n)&&t.has(n,Mr);if(r.isOn&&i){if(!t.get(n,Mr).allowSwitchOff)continue}if(r.isOn=!r.isOn,t.insert(s,Pr,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,Pr);r.isOn&&(r.isOn=!1,t.insert(n,Pr,r),e.emit(n,"change"))}}e.emit(s,"change")}if(r.transition&&t.has(s,re)){const e=t.get(s,re);e.color=yn(r.transition,i.enabled,n.pressed,n.hovered),t.insert(s,re,e)}}}for(const e of n){const s=t.get(e,Pr);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"]})}},Er=ln,Cr=j("ProgressBar",{value:0,fillEntity:0,direction:ln.LeftToRight});function Rr(e,t,s,n){if(!e.has(t,dn))return;const r=e.get(t,dn),o=s/2,i=n/2,a={left:-o,bottom:-i,right:o,top:i},l=cn(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})}}class Ar{build(e){q("ProgressBar",Cr);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e=t.getEntitiesWithComponents([Cr,dn]);for(const s of e){const e=t.get(s,Cr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,dn),r=Math.max(0,Math.min(1,e.value));gn(t,e.fillEntity,e.direction,r);const o=vn(n,s),i=bn(n,s);Rr(t,e.fillEntity,o,i)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Ir=new Ar,Fr=j("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),kr=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 Br=new class{build(e){q("Draggable",Fr),q("DragState",kr);const t=e.world,s=e.getResource(tr);let n=null,r={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at)],(e,i)=>{if(ir()&&!ar())return;if(!i.valid)return;const a={x:i.worldMouseX,y:i.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Fr,Jn]);let s=null,o=-1/0,i=-1;for(const n of e){if(!t.get(n,Fr).enabled)continue;if(t.get(n,Jn).hovered){let e=0;t.has(n,re)&&(e=t.get(n,re).layer);const r=wn(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,kr)||t.insert(s,kr);const e=t.get(s,kr),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,kr)){t.get(n,kr).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-r.x,l=a.y-r.y,c=Math.sqrt(e*e+l*l),d=t.get(n,Fr);if(c*(i.vpW/(i.worldRight-i.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,kr).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,kr))return void(o=null);const n=t.get(o,kr),r=t.get(o,Fr),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=jn(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"}))}},Dr=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 Ur(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 Lr(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 zr=new class{build(e){q("ScrollView",Dr);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=ir()&&!ar(),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([Dr,dn]);for(const o of l){Pn(t,o,$n,{enabled:!0,mode:zn});const l=t.get(o,Dr),c=t.get(o,dn);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=vn(c,o),h=bn(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,dn)){const e=t.get(i,dn);a=vn(e,i)||e.size.x,l=bn(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){Pn(t,o,Kn,{enabled:!0,blockRaycast:!0});const s=t.has(o,Jn)?t.get(o,Jn):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=Ur(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=Ur(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=Ur(l.scrollY,0,y,h);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Ur(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=Lr(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)<En&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>En?(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=Lr(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)<En&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>En?(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"]})}},Wr=ln,$r=j("Slider",{value:0,minValue:0,maxValue:1,direction:ln.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Or(e,t,s,n,r,o){const i=vn(n,r)*s.worldScale.x,a=bn(n,r)*s.worldScale.y,l=jn(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 ln.LeftToRight:return i>0?(f-g)/i:0;case ln.RightToLeft:return i>0?1-(f-g)/i:0;case ln.BottomToTop:return a>0?(p-y)/a:0;case ln.TopToBottom:return a>0?1-(p-y)/a:0}}function Hr(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case ln.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case ln.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case ln.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case ln.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class Xr{build(e){q("Slider",$r);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at),ve(tr)],(e,n,r)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([$r,dn]);for(const i of o){const o=t.get(i,$r),a=t.get(i,dn);if(!ir()||ar()){if(t.has(i,te)){Pn(t,i,Kn,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Pn(t,o.handleEntity,Kn,{enabled:!0,blockRaycast:!1});const l=t.get(i,te),c=t.has(i,Jn)?t.get(i,Jn):null;let d=c?.justPressed??!1;if(!d&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Jn)&&(d=t.get(o.handleEntity,Jn).justPressed),d&&(s=i),s===i&&e.isMouseButtonDown(0)){let e=Or(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,$r,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=vn(a,i),u=bn(a,i),h={left:-d/2,bottom:-u/2,right:d/2,top:u/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(gn(t,o.fillEntity,o.direction,c),Mn(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,dn)){const e=t.get(o.handleEntity,dn);Hr(e,o.direction,c),t.insert(o.handleEntity,dn,e),Mn(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const jr=new Xr;const Yr=new class{build(e){q("Focusable",fr);const t=e.world,s=new pr;e.insertResource(gr,s),e.addSystemToSchedule(exports.Schedule.Update,et([ve(rt),ve(tr)],(e,n)=>{if(ir()&&!ar())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const r=t.getEntitiesWithComponents([fr]);for(const e of r){if(!t.has(e,Jn))continue;t.get(e,Jn).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,Kn)){if(!t.get(s,Kn).enabled)continue}const n=t.get(s,fr);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,fr)){t.get(r,fr).isFocused=!1,n.emit(r,"blur",r)}s.focus(e);t.get(e,fr).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},Nr=j("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Vr(){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 Gr=new class{build(e){q("SafeArea",Nr);const t=e.world;let n=Vr(),r=!0,o=0,i=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Vr(),r=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Vr(),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([Nr,dn]);for(const e of u){const s=t.get(e,Nr),r=t.get(e,dn),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,dn,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},qr=j("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Kr=null;const Jr=new class{build(e){q("ListView",qr);const t=e.world,s=new Map;Kr=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(rt)],e=>{const n=ir()&&!ar();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,dn]);for(const o of r){Pn(t,o,Kn,{enabled:!0,blockRaycast:!0}),Pn(t,o,$n,{enabled:!0,mode:zn});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,dn),l=bn(a,o),c=vn(a,o);if(!n){const s=t.has(o,Jn)?t.get(o,Jn):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,dn,{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"]})}},Qr=j("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Zr=new class{build(e){q("Dropdown",Qr);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*Cn;t.insert(r,dn,{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)*Cn;t.insert(o,he,{value:`Option_${e}`}),t.insert(o,dn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Cn},offsetMax:{x:0,y:0},size:{x:i,y:Cn},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:Cn},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,Kn,{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,kn,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:An.Left,verticalAlign:In.Middle,wordWrap:!1,overflow:Fn.Clip,lineHeight:1.2}),t.insert(c,dn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:Cn},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,kn))return;const n=t.get(s,kn);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,kn,{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,Kn)&&t.insert(e,Kn,{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?{...Rn}:{r:.95,g:.95,b:.95,a:1};t.insert(n,re,{texture:L,color:r,size:{x:e.ddWidth,y:Cn},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,Jn))continue;if(t.get(s,Jn).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,et([ve(rt),ve(tr)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=ir()&&!ar(),p=t.getEntitiesWithComponents([Qr]);for(const g of p){const p=t.get(g,Qr);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;Pn(t,g,Kn,{enabled:!0,blockRaycast:!0});const m=t.has(g,Jn)?t.get(g,Jn):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,Jn))continue;if(t.get(s,Jn).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,Jn))continue;if(t.get(n,Jn).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"]})}},eo=0,to=0,so=2,no=j("LayoutGroup",{direction:eo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:to,reverseOrder:!1});const ro=new class{build(e){q("LayoutGroup",no);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e=t.getEntitiesWithComponents([no,dn,ce]);for(const s of e){const e=t.get(s,no),n=t.get(s,dn),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,dn)&&t.has(e,te)&&o.push({entity:e,rect:t.get(e,dn)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const i=vn(n,s),a=bn(n,s),l=n.pivot.x,c=n.pivot.y,d=e.padding,u=e.direction===eo;let h=0;for(let s=0;s<o.length;s++){const n=o[s],r=vn(n.rect,n.entity),f=bn(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===to?(1-c)*a-d.top-(1-g)*f:e.childAlignment===so?-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===to?-l*i+d.left+p*r:e.childAlignment===so?(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 oo{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 io=new oo;async function ao(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 lo=we({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),co=we(null,"PhysicsAPI");function uo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ho(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class fo{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(lo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=ao(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=uo(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),po(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=uo(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=uo(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=ho(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(lo,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(co,go._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function po(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 go{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(go.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 yo={nearest:0,linear:1},mo={repeat:0,clamp:1,mirror:2};function _o(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=yo[n.filterMode??"linear"]??1,a=mo[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 xo(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 wo(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 vo(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]=_o(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=xo(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=_o(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 fo("",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=_o(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=Bt(e.world,s);if(l&&e.hasResource(Xs))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=wo(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(Wt);t&&t.setAddressableManifest(a)}}class bo{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 So="__preview__";const Po={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=ks.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:ks.getTargetTexture(s),width:e.width,height:e.height}},release(e){ks.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(ks.releaseRenderTarget(e._handle),Po.create({width:t,height:s,depth:!0})),begin(e,t){ks.begin(t,e._handle)},end(){ks.end()},getDepthTexture:e=>ks.getTargetDepthTexture(e._handle)};var Mo;exports.LogLevel=void 0,(Mo=exports.LogLevel||(exports.LogLevel={}))[Mo.Debug=0]="Debug",Mo[Mo.Info=1]="Info",Mo[Mo.Warn=2]="Warn",Mo[Mo.Error=3]="Error";class To{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 Eo{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new To)}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 Co=new Eo;const Ro=[Ln,qn,nr,Sr,Ir,ur,Br,zr,jr,Tr,mr,Yr,Gr,Jr,Zr,ro,io];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=Vs,exports.AssetPlugin=$t,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=zt,exports.Assets=Wt,exports.AsyncCache=Tt,exports.BitmapText=de,exports.BodyType=_e,exports.BoxCollider=ge,exports.Button=Zn,exports.ButtonState=Qn,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=kr,exports.Draggable=Fr,exports.Draw=os,exports.Dropdown=Qr,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=ln,exports.FillMethod=xr,exports.FillOrigin=wr,exports.FocusManager=gr,exports.FocusManagerState=pr,exports.Focusable=fr,exports.GLDebug=Ls,exports.Geometry=vs,exports.INVALID_ENTITY=0,exports.INVALID_FONT=z,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=L,exports.Image=vr,exports.ImageType=_r,exports.Input=rt,exports.InputPlugin=ot,exports.InputState=nt,exports.Interactable=Kn,exports.ListView=qr,exports.LocalTransform=se,exports.Logger=Eo,exports.Material=mt,exports.MaterialLoader=Et,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=he,exports.Parent=le,exports.Physics=go,exports.PhysicsEvents=lo,exports.PhysicsPlugin=fo,exports.PostProcess=Ts,exports.PrefabServer=Nt,exports.Prefabs=Vt,exports.PrefabsPlugin=Gt,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(Xs);t.register({name:So,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(So),this.loadPromise_=t.load(So).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 bo(this.baseUrl_);await s.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await vo(this.app_,this.app_.wasmModule,t,s,r,null,void 0,null,So)}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(Xs).getScene(So),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(Xs);await e.switchTo(So),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=Cr,exports.ProgressBarDirection=Er,exports.ProgressBarPlugin=Ar,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=zs,exports.RenderTexture=Po,exports.Renderer=ks,exports.Res=ve,exports.ResMut=be,exports.RigidBody=pe,exports.RuntimeConfig=U,exports.SafeArea=Nr,exports.ScaleMode=ee,exports.SceneManager=Xs,exports.SceneManagerState=Hs,exports.SceneOwner=fe,exports.ScrollView=Dr,exports.ShaderSources=Mt,exports.Slider=$r,exports.SliderDirection=Wr,exports.SliderPlugin=Xr,exports.SpineAnimation=ue,exports.Sprite=re,exports.SystemRunner=st,exports.Text=kn,exports.TextAlign=An,exports.TextInput=hr,exports.TextInputPlugin=yr,exports.TextOverflow=Fn,exports.TextPlugin=Un,exports.TextRenderer=Bn,exports.TextVerticalAlign=In,exports.Time=Me,exports.Toggle=Pr,exports.Transform=te,exports.UICameraInfo=at,exports.UIEventQueue=er,exports.UIEvents=tr,exports.UIInteraction=Jn,exports.UIInteractionPlugin=dr,exports.UILayoutPlugin=sr,exports.UIMask=$n,exports.UIMaskPlugin=Gn,exports.UIRect=dn,exports.UIRenderOrderPlugin=oo,exports.Velocity=ae,exports.WebAssetProvider=bo,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=gn,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=Ot,exports.clearDrawCallbacks=hs,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=pn,exports.computeFillSize=function(e,t,s,n){switch(e){case ln.BottomToTop:case ln.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case ln.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case ln.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case ln.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=cn,exports.createMaskProcessor=Vn,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await vo(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=Vs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ts(e),pt(e),_s(e),Ss(e),Is(e),Ds(e);const r=new zs;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=Qs(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;ks.setClearColor(e.x,e.y,e.z,e.w)}const u=(l()-o)/1e3;let h;if(ks.resize(t,c),Ts.isInitialized()&&Ts.getPassCount()>0&&!Ts.isBypassed()&&Ts.resize(t,c),s.hasResource(Xs)){const e=s.getResource(Xs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=Qs(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:Gs,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})}ks.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,d),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(Ot),s.addPlugin(qt),s.addPlugin(it),s.addPlugin(Ns),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Ro,...t})},exports.debug=function(e,t,s){Co.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){Co.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.getComponentSpineFieldDescriptor=At,exports.getCustomExtensions=x,exports.getEditorType=function(e){return m(e)?.editorType??"unknown"},exports.getLogger=function(){return Co},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){Co.info(e,t,s)},exports.initDrawAPI=ts,exports.initGLDebugAPI=Ds,exports.initGeometryAPI=_s,exports.initMaterialAPI=pt,exports.initPostProcessAPI=Ss,exports.initRendererAPI=Is,exports.inputPlugin=it,exports.instantiatePrefab=Ht,exports.intersectRects=On,exports.invertMatrix4=Hn,exports.isBuiltinComponent=V,exports.isCustomExtension=w,exports.isEditor=ir,exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=ar,exports.isRuntime=function(){return!rr},exports.isTextureRef=ct,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Lt,exports.loadPhysicsModule=ao,exports.loadRuntimeScene=vo,exports.loadSceneData=Bt,exports.loadSceneWithAssets=Dt,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=jn(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=Ir,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=ds,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(Wt);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Pt,exports.remapEntityFields=Ft,exports.sceneManagerPlugin=Ns,exports.screenToWorld=Xn,exports.setEditorMode=function(e){rr=e},exports.setListViewRenderer=function(e,t){if(!Kr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=Kr.get(e);s?s.renderer=t:Kr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Co.setMinLevel(e)},exports.setPlayMode=function(e){or=e},exports.setWasmErrorHandler=Ae,exports.shutdownDrawAPI=ss,exports.shutdownGLDebugAPI=Us,exports.shutdownGeometryAPI=xs,exports.shutdownMaterialAPI=gt,exports.shutdownPostProcessAPI=Ps,exports.shutdownRendererAPI=Fs,exports.sliderPlugin=jr,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 ln.BottomToTop:case ln.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=mr,exports.textPlugin=Ln,exports.transitionTo=async function(e,t,s){const n=e.getResource(Xs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=ur,exports.uiLayoutPlugin=nr,exports.uiMaskPlugin=qn,exports.uiPlugins=Ro,exports.uiRenderOrderPlugin=io,exports.unregisterComponent=function(e){X().delete(e),G.delete(e)},exports.unregisterDrawCallback=us,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){Co.warn(e,t,s)},exports.wrapSceneSystem=js,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},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_)}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,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 kt(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)Ft(r,s),Lt(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 Bt(e,t){return kt(e,t)}async function Dt(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 Ut.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=[...Ut.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=kt(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 Ut=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 Lt(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 zt{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 Dt(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 Wt=we(null,"Assets");class $t{build(e){const t=e.wasmModule;t?e.insertResource(Wt,new zt(t)):console.warn("AssetPlugin: No WASM module available")}}const Ot=new $t;async function Ht(e,t,s){const{entities:n,rootId:r}=await jt(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 Dt(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 Xt=10;async function jt(e,t,s,n,r,o=0){if(o>Xt)throw new Error(`Prefab nesting depth exceeded ${Xt}. 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 jt(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};Yt(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 Yt(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 Nt{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 Ht(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Vt=we(null,"Prefabs");class Gt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Wt]}build(e){const t=e.getResource(Wt);e.insertResource(Vt,new Nt(e.world,t))}}const qt=new Gt;let Kt=null,Jt=0,Qt=0,Zt=0;const es=new Float32Array(256);function ts(e){Kt=e,Jt=Kt._malloc(64),Qt=Kt._malloc(64),Zt=Kt._malloc(1024)}function ss(){Kt&&(Jt&&(Kt._free(Jt),Jt=0),Qt&&(Kt._free(Qt),Qt=0),Zt&&(Kt._free(Zt),Zt=0)),Kt=null}function ns(){if(!Kt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Kt}const rs={r:1,g:1,b:1,a:1},os={begin(e){const t=ns();try{t.HEAPF32.set(e,Jt/4),t.draw_begin(Jt)}catch(e){Ie(e,"Draw.begin")}},end(){try{ns().draw_end()}catch(e){Ie(e,"Draw.end")}},line(e,t,s,n=1){try{ns().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{ns().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{ns().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{ns().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{ns().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=rs){try{ns().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=rs){try{ns().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){ns().draw_setLayer(e)},setDepth(e){ns().draw_setDepth(e)},getDrawCallCount:()=>Kt?Kt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Kt?Kt.draw_getPrimitiveCount():0,setBlendMode(e){ns().draw_setBlendMode(e)},setDepthTest(e){ns().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ns();n.HEAPF32.set(s,Qt/4),n.draw_mesh(e,t,Qt)}catch(s){Ie(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ns(),r=mt.get(t);if(!r)return;if(os.setBlendMode(r.blendMode),os.setDepthTest(r.depthTest),0===r.uniforms.size)return void os.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,Qt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=ls(t);if(!(n<0)){if(ct(s))es[o++]=10,es[o++]=n,es[o++]=s.slot??e++,es[o++]=s.textureId;else if("number"==typeof s)es[o++]=1,es[o++]=n,es[o++]=s;else if(Array.isArray(s)){es[o++]=s.length,es[o++]=n;for(let e=0;e<s.length;e++)es[o++]=s[e]}else"w"in s?(es[o++]=4,es[o++]=n,es[o++]=s.x,es[o++]=s.y,es[o++]=s.z,es[o++]=s.w):"z"in s?(es[o++]=3,es[o++]=n,es[o++]=s.x,es[o++]=s.y,es[o++]=s.z):(es[o++]=2,es[o++]=n,es[o++]=s.x,es[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(es.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,Qt);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Zt/4),n.draw_meshWithUniforms(e,r.shader,Qt,Zt,o)}catch(s){Ie(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},is={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},as=new Set;function ls(e){const t=is[e];return void 0!==t?t:(as.has(e)||(as.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(is).join(", ")}`)),-1)}const cs=new Map;function ds(e,t,s){cs.set(e,{fn:t,scene:s??""})}function us(e){cs.delete(e)}function hs(){cs.clear()}var fs;exports.DataType=void 0,(fs=exports.DataType||(exports.DataType={}))[fs.Float=1]="Float",fs[fs.Float2=2]="Float2",fs[fs.Float3=3]="Float3",fs[fs.Float4=4]="Float4",fs[fs.Int=5]="Int",fs[fs.Int2=6]="Int2",fs[fs.Int3=7]="Int3",fs[fs.Int4=8]="Int4";let ps=null,gs=0,ys=0,ms=0;function _s(e){ps=e,gs=ps._malloc(262144),ys=ps._malloc(65536),ms=ps._malloc(256)}function xs(){ps&&(gs&&ps._free(gs),ys&&ps._free(ys),ms&&ps._free(ms),gs=0,ys=0,ms=0),ps=null}function ws(){if(!ps)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ps}const vs={create(e){const t=ws(),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,gs/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,ms,r).set(o),t.geometry_init(s,gs,n,ms,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,ys,n).set(e.indices),t.geometry_setIndices16(s,ys,n)}else{new Uint32Array(t.HEAPU8.buffer,ys,n).set(e.indices),t.geometry_setIndices32(s,ys,n)}}return s},updateVertices(e,t,s=0){const n=ws(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,gs/4),n.geometry_updateVertices(e,gs,r,s)},release(e){e>0&&ws().geometry_release(e)},isValid:e=>!(!ps||e<=0)&&ps.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return vs.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 vs.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 vs.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 bs=null;function Ss(e){bs=e}function Ps(){bs&&Ts.isInitialized()&&Ts.shutdown(),bs=null}function Ms(){if(!bs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return bs}const Ts={init(e,t){try{return Ms().postprocess_init(e,t)}catch(s){return Ie(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ms().postprocess_shutdown()}catch(e){Ie(e,"PostProcess.shutdown")}},resize(e,t){try{Ms().postprocess_resize(e,t)}catch(s){Ie(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ms().postprocess_addPass(e,t)}catch(t){return Ie(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ms().postprocess_removePass(e)}catch(t){Ie(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ms().postprocess_setPassEnabled(e,t)}catch(t){Ie(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ms().postprocess_isPassEnabled(e)}catch(t){return Ie(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Ms().postprocess_setUniformFloat(e,t,s)}catch(s){Ie(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Ms().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Ie(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ms().postprocess_begin()}catch(e){Ie(e,"PostProcess.begin")}},end(){try{Ms().postprocess_end()}catch(e){Ie(e,"PostProcess.end")}},getPassCount(){try{return Ms().postprocess_getPassCount()}catch(e){return Ie(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!bs)return!1;try{return bs.postprocess_isInitialized()}catch(e){return Ie(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ms().postprocess_setBypass(e)}catch(e){Ie(e,"PostProcess.setBypass")}},isBypassed(){if(!bs)return!0;try{return bs.postprocess_isBypassed()}catch(e){return Ie(e,"PostProcess.isBypassed"),!0}},createBlur:()=>mt.createShader(Es,"#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(Es,"#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(Es,"#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(Es,"#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")},Es="#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 Cs;exports.RenderStage=void 0,(Cs=exports.RenderStage||(exports.RenderStage={}))[Cs.Background=0]="Background",Cs[Cs.Opaque=1]="Opaque",Cs[Cs.Transparent=2]="Transparent",Cs[Cs.Overlay=3]="Overlay";let Rs=null,As=0;function Is(e){Rs=e,As=Rs._malloc(64)}function Fs(){Rs&&As&&(Rs._free(As),As=0),Rs=null}const ks={init(e,t){Rs?.renderer_init(e,t)},resize(e,t){Rs?.renderer_resize(e,t)},begin(e,t){if(Rs&&As)try{Rs.HEAPF32.set(e,As/4),Rs.renderer_begin(As,t??0)}catch(e){Ie(e,"Renderer.begin")}},flush(){try{Rs?.renderer_flush()}catch(e){Ie(e,"Renderer.flush")}},end(){try{Rs?.renderer_end()}catch(e){Ie(e,"Renderer.end")}},submitSprites(e){if(Rs)try{Rs.renderer_submitSprites(e._cpp)}catch(e){Ie(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Rs)try{Rs.renderer_submitBitmapText(e._cpp)}catch(e){Ie(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Rs)try{Rs.renderer_submitSpine?.(e._cpp)}catch(e){Ie(e,"Renderer.submitSpine")}},setStage(e){Rs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Rs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Rs?.renderer_releaseTarget(e)},getTargetTexture:e=>Rs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Rs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Rs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Rs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Rs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Rs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Rs?Rs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Rs?{drawCalls:Rs.renderer_getDrawCalls(),triangles:Rs.renderer_getTriangles(),sprites:Rs.renderer_getSprites(),text:Rs.renderer_getText(),spine:Rs.renderer_getSpine?.()??0,meshes:Rs.renderer_getMeshes(),culled:Rs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Bs=null;function Ds(e){Bs=e}function Us(){Bs=null}const Ls={enable(){Bs?.gl_enableErrorCheck(!0)},disable(){Bs?.gl_enableErrorCheck(!1)},check:e=>Bs?.gl_checkErrors(e)??0,diagnose(){Bs?.renderer_diagnose()}};class zs{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_||(ks.resize(n,r),Ts.isInitialized()&&Ts.getPassCount()>0&&Ts.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),ks.setViewport(0,0,n,r),ks.clearBuffers(3),ks.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),ks.submitSprites(t),ks.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ks.submitSpine(t),ks.flush(),this.executeDrawCallbacks(s,o),ks.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;ks.setViewport(n.x,n.y,n.w,n.h),ks.setScissor(n.x,n.y,n.w,n.h,!0),ks.clearBuffers(r),ks.setScissor(0,0,0,0,!1),ks.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),ks.submitSprites(t),ks.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ks.submitSpine(t),ks.flush(),this.executeDrawCallbacks(s,o),ks.end()}executeDrawCallbacks(e,t){const s=cs;if(s.size>0){os.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)}os.end();for(const e of n)us(e)}}}const Ws="__scene_transition_overlay__";class $s{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 Os{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),ds(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Ts.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Ts.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 Hs{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},ds(Ws,()=>{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;os.setLayer(9999),os.setDepth(9999),os.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,us(Ws),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,us(Ws),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 $s(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Wt)?this.app_.getResource(Wt):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 $s(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Wt)?this.app_.getResource(Wt):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())us(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Ts.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(Wt)&&(r.assetServer=this.app_.getResource(Wt));const o=await Dt(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=js(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(Wt)?this.app_.getResource(Wt):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{Ts.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 Xs=we(null,"SceneManager");function js(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Xs).getSceneStatus(t)&&s._fn(...n)}}}const Ys=et([be(Xs),ve(Me)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Ns={name:"SceneManager",build(e){const t=new Hs(e);e.insertResource(Xs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Xs),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,Ys)}};class Vs{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 Vs}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(Xs).register(e),this}setInitialScene(e){return this.getResource(Xs).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,hs();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=[Us,Fs,Ps,xs,gt,ss];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 Gs=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 Ks=[];function Js(e){if(e<Ks.length)return Ks[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 Ks.push(t),t}function Qs(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=en(-d,d,-u,u,-r.farPlane,r.farPlane)}else a=sn(r.fov*Math.PI/180,i,r.nearPlane,r.farPlane);const h=rn(o.position.x,o.position.y,o.position.z),f=Js(c.length);f.entity=e,f.viewProjection.set(an(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 Zs=new Float32Array(16);function en(e,t,s,n,r,o){const i=Zs;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 tn=new Float32Array(16);function sn(e,t,s,n){const r=tn;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 nn=new Float32Array(16);function rn(e,t,s){const n=nn;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 on=new Float32Array(16);function an(e,t){const s=on;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 ln={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function cn(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 dn=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 un=null,hn=null;function fn(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 pn(e,t){switch(e){case ln.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case ln.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case ln.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 gn(e,t,s,n){if(!e.has(t,dn))return;const r=e.get(t,dn),o=pn(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,dn,r)}function yn(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function mn(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function _n(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(mn(i.charCodeAt(0))&&n.length>0&&mn(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!mn(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 xn(e){let t=1;for(;t<e;)t*=2;return t}function wn(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 vn(e,t){if(un&&hn){const e=un.getUIRectComputedWidth(hn,t);if(e>0)return e}return e.size.x}function bn(e,t){if(un&&hn){const e=un.getUIRectComputedHeight(hn,t);if(e>0)return e}return e.size.y}function Sn(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 Pn(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Mn(e,t,s,n,r){if(!e.has(t,dn))return;const o=e.get(t,dn),i=cn(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 Tn(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 En=.1,Cn=30,Rn={r:.3,g:.5,b:.8,a:1},An={Left:0,Center:1,Right:2},In={Top:0,Middle:1,Bottom:2},Fn={Visible:0,Clip:1,Ellipsis:2},kn=j("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:An.Left,verticalAlign:In.Top,wordWrap:!0,overflow:Fn.Visible,lineHeight:1.2});class Bn{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,xn(this.frameMaxW_)),e.height=Math.max(e.height,xn(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=xn(this.frameMaxW_),e.height=xn(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=_n(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===Fn.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,xn(f)),n.height=Math.max(n.height,xn(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===Fn.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 In.Top:w=d;break;case In.Middle:w=d+(p-2*d-x)/2;break;case In.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 An.Left:n=d;break;case An.Center:n=f/2;break;case An.Right:n=f-d;break;default:n=d}s.fillText(t,n,v),v+=c}r&&e.overflow===Fn.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 An.Left:return"left";case An.Center:return"center";case An.Right:return"right"}}}const Dn=Tn({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?vn(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?bn(e.uiRect,e.entity):0});class Un{build(e){q("Text",kn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Bn(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,kn));for(const e of r.keys())if(!n.valid(e)||!n.has(e,kn)){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([kn]);for(const t of e){const e=n.get(t,kn),o=n.has(t,dn)?n.get(t,dn):null,i={text:e,uiRect:o,entity:t},a=r.get(t);if(a&&!Dn.changed(a,i)){if(n.has(t,re)&&n.get(t,re).texture!==L)continue}fn(n,t);const l=o?{size:{x:vn(o,t),y:bn(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,Dn.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ln=new Un,zn=0,Wn=1,$n=J("UIMask",{enabled:!0,mode:zn});function On(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 Hn(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 Xn(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 jn(e,t){return 2*Math.atan2(e,t)}function Yn(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 Nn(e,t,s,n,r,o,i){if(!e.has(t,dn)||!e.has(t,te))return null;const a=e.get(t,dn),l=e.get(t,te),c=vn(a,t)*l.worldScale.x,d=bn(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=jn(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]=Yn(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 Vn(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([$n]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,$n);s.enabled&&(u.add(e),s.mode===Wn?(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;Sn(t,e,e=>{if(r.has(e)){if(t.get(e,$n).mode===zn)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,$n).mode===zn){const e=Nn(t,s,o,i,a,l,c);e&&(n=On(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=Nn(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;Sn(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 Gn{build(e){if(q("UIMask",$n),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Vn(e.wasmModule,e.world))}}const qn=new Gn,Kn=J("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Jn=J("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Qn={Normal:0,Hovered:1,Pressed:2,Disabled:3},Zn=j("Button",{state:Qn.Normal,transition:null});class er{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 tr=we(new er,"UIEvents");class sr{build(e){q("UIRect",dn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){un=e,hn=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 nr=new sr;let rr=!1,or=!1;function ir(){return rr}function ar(){return or}const lr=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&&(Hn(t,e),s=!1),e)}}();function cr(e,t,s,n){t.emit(s,n,s),Sn(e,s,r=>{if(!e.has(r,Kn))return!1;const o=e.get(r,Kn);return o.enabled&&t.emit(r,n,s),o.blockRaycast})}class dr{build(e){q("Interactable",Kn),q("Button",Zn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),r=new er;e.insertResource(tr,r);let o=null,i=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at)],(e,a)=>{if(r.drain(),ir()&&!ar())return;const l=t.getEntitiesWithComponents([Jn]);for(const e of l){const s=t.get(e,Jn);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,Jn,s))}if(!a.valid)return;const d=c(),u=e.mouseX*d,h=a.screenH-e.mouseY*d;lr.update(a.viewProjection);const f=Xn(u,h,lr.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,Jn)){const e=t.get(o,Jn);e.hovered=!1,t.insert(o,Jn,e),r.emit(o,"hover_exit")}if(null!==_){Pn(t,_,Jn);const e=t.get(_,Jn);e.hovered=!0,t.insert(_,Jn,e),r.emit(_,"hover_enter")}o=_}if(g&&null!==_){const e=t.get(_,Jn);e.pressed=!0,e.justPressed=!0,t.insert(_,Jn,e),i=_,cr(t,r,_,"press")}if(y&&null!==i){if(t.valid(i)&&t.has(i,Jn)){const e=t.get(i,Jn);e.pressed=!1,e.justReleased=!0,t.insert(i,Jn,e),cr(t,r,i,"release"),i===o&&cr(t,r,i,"click")}i=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,et([],()=>{const e=t.getEntitiesWithComponents([Zn]);for(const s of e){if(Pn(t,s,Kn,{enabled:!0}),!t.has(s,Jn))continue;const e=t.get(s,Jn),n=t.get(s,Zn),r=t.get(s,Kn),o=!a.has(s),i=n.state;if(r.enabled?e.pressed?n.state=Qn.Pressed:e.hovered?n.state=Qn.Hovered:n.state=Qn.Normal:n.state=Qn.Disabled,o&&a.add(s),(o||i!==n.state)&&n.transition&&t.has(s,re)){const o=t.get(s,re);o.color=yn(n.transition,r.enabled,e.pressed,e.hovered),t.insert(s,re,o)}}},{name:"ButtonSystem"}))}}const ur=new dr,hr=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}),fr=j("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 gr=we(new pr,"FocusManager");class yr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(q("TextInput",hr),ir()&&!ar())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(gr);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,hr)?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,hr);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource(tr).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,hr);n.focused=!1,n.dirty=!0;e.getResource(gr).blur()}};function v(){const t=g();if(null===t)return;const n=s.get(t,hr);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(tr).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,hr);e.focused=!1,e.dirty=!0}e.getResource(gr).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=xn(Math.max(r.width,c)),r.height=xn(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=_n(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=_n(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(gr)],e=>{const t=s.getEntitiesWithComponents([hr]);for(const e of t)Pn(s,e,fr,{tabIndex:0,isFocused:!1}),Pn(s,e,Kn,{enabled:!0,blockRaycast:!0});const n=g();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,hr)){const e=s.get(P,hr);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,hr);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,hr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,hr)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([hr,dn]);for(const e of a){const t=s.get(e,hr);if(!t.dirty)continue;const n=s.get(e,dn),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(fn(s,e),M(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const mr=new yr,_r={Simple:0,Sliced:1,Tiled:2,Filled:3},xr={Horizontal:0,Vertical:1},wr={Left:0,Right:1,Bottom:2,Top:3},vr=j("Image",{texture:L,color:{r:1,g:1,b:1,a:1},imageType:_r.Simple,fillMethod:xr.Horizontal,fillOrigin:wr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),br=Tn({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?vn(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?bn(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Sr=new class{build(e){q("Image",vr);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,vr)||s.delete(e);const e=t.getEntitiesWithComponents([vr]);for(const n of e){const e=t.get(n,vr),r=t.has(n,dn)?t.get(n,dn):null,o={image:e,uiRect:r,entity:n},i=s.get(n);if(i&&!br.changed(i,o))continue;fn(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=vn(r,n),a.size.y=bn(r,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===_r.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===xr.Horizontal?e.fillOrigin===wr.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===wr.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===_r.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,br.take(o))}else a.color.a=0,t.insert(n,re,a),s.set(n,br.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Pr=j("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Mr=j("ToggleGroup",{allowSwitchOff:!1});const Tr=new class{build(e){q("Toggle",Pr),q("ToggleGroup",Mr);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,et([ve(tr)],e=>{const n=t.getEntitiesWithComponents([Pr]);if(!ir()||ar()){const r=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Pr);n.isOn&&0!==n.group&&t.valid(n.group)&&(r.has(n.group)?(n.isOn=!1,t.insert(e,Pr,n)):r.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Pr);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(Pn(t,s,Kn,{enabled:!0}),!t.has(s,Jn))continue;const n=t.get(s,Jn),r=t.get(s,Pr),i=t.get(s,Kn);if(n.justPressed&&i.enabled){const n=r.group,i=0!==n&&t.valid(n)&&t.has(n,Mr);if(r.isOn&&i){if(!t.get(n,Mr).allowSwitchOff)continue}if(r.isOn=!r.isOn,t.insert(s,Pr,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,Pr);r.isOn&&(r.isOn=!1,t.insert(n,Pr,r),e.emit(n,"change"))}}e.emit(s,"change")}if(r.transition&&t.has(s,re)){const e=t.get(s,re);e.color=yn(r.transition,i.enabled,n.pressed,n.hovered),t.insert(s,re,e)}}}for(const e of n){const s=t.get(e,Pr);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"]})}},Er=ln,Cr=j("ProgressBar",{value:0,fillEntity:0,direction:ln.LeftToRight});function Rr(e,t,s,n){if(!e.has(t,dn))return;const r=e.get(t,dn),o=s/2,i=n/2,a={left:-o,bottom:-i,right:o,top:i},l=cn(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 Ar{build(e){q("ProgressBar",Cr);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e=t.getEntitiesWithComponents([Cr,dn]);for(const s of e){const e=t.get(s,Cr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,dn),r=Math.max(0,Math.min(1,e.value));gn(t,e.fillEntity,e.direction,r);const o=vn(n,s),i=bn(n,s);Rr(t,e.fillEntity,o,i)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Ir=new Ar,Fr=j("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),kr=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 Br=new class{build(e){q("Draggable",Fr),q("DragState",kr);const t=e.world,s=e.getResource(tr);let n=null,r={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at)],(e,i)=>{if(ir()&&!ar())return;if(!i.valid)return;const a={x:i.worldMouseX,y:i.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Fr,Jn]);let s=null,o=-1/0,i=-1;for(const n of e){if(!t.get(n,Fr).enabled)continue;if(t.get(n,Jn).hovered){let e=0;t.has(n,re)&&(e=t.get(n,re).layer);const r=wn(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,kr)||t.insert(s,kr);const e=t.get(s,kr),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,kr)){t.get(n,kr).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-r.x,l=a.y-r.y,c=Math.sqrt(e*e+l*l),d=t.get(n,Fr);if(c*(i.vpW/(i.worldRight-i.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,kr).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,kr))return void(o=null);const n=t.get(o,kr),r=t.get(o,Fr),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=jn(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"}))}},Dr=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 Ur(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 Lr(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 zr=new class{build(e){q("ScrollView",Dr);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=ir()&&!ar(),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([Dr,dn]);for(const o of l){Pn(t,o,$n,{enabled:!0,mode:zn});const l=t.get(o,Dr),c=t.get(o,dn);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=vn(c,o),h=bn(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,dn)){const e=t.get(i,dn);a=vn(e,i)||e.size.x,l=bn(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){Pn(t,o,Kn,{enabled:!0,blockRaycast:!0});const s=t.has(o,Jn)?t.get(o,Jn):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=Ur(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=Ur(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=Ur(l.scrollY,0,y,h);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Ur(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=Lr(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)<En&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>En?(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=Lr(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)<En&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>En?(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"]})}},Wr=ln,$r=j("Slider",{value:0,minValue:0,maxValue:1,direction:ln.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Or(e,t,s,n,r,o){const i=vn(n,r)*s.worldScale.x,a=bn(n,r)*s.worldScale.y,l=jn(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 ln.LeftToRight:return i>0?(f-g)/i:0;case ln.RightToLeft:return i>0?1-(f-g)/i:0;case ln.BottomToTop:return a>0?(p-y)/a:0;case ln.TopToBottom:return a>0?1-(p-y)/a:0}}function Hr(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case ln.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case ln.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case ln.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case ln.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class Xr{build(e){q("Slider",$r);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at),ve(tr)],(e,n,r)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([$r,dn]);for(const i of o){const o=t.get(i,$r),a=t.get(i,dn);if(!ir()||ar()){if(t.has(i,te)){Pn(t,i,Kn,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Pn(t,o.handleEntity,Kn,{enabled:!0,blockRaycast:!1});const l=t.get(i,te),c=t.has(i,Jn)?t.get(i,Jn):null;let d=c?.justPressed??!1;if(!d&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Jn)&&(d=t.get(o.handleEntity,Jn).justPressed),d&&(s=i),s===i&&e.isMouseButtonDown(0)){let e=Or(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,$r,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=vn(a,i),u=bn(a,i),h={left:-d/2,bottom:-u/2,right:d/2,top:u/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(gn(t,o.fillEntity,o.direction,c),Mn(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,dn)){const e=t.get(o.handleEntity,dn);Hr(e,o.direction,c),t.insert(o.handleEntity,dn,e),Mn(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const jr=new Xr;const Yr=new class{build(e){q("Focusable",fr);const t=e.world,s=new pr;e.insertResource(gr,s),e.addSystemToSchedule(exports.Schedule.Update,et([ve(rt),ve(tr)],(e,n)=>{if(ir()&&!ar())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const r=t.getEntitiesWithComponents([fr]);for(const e of r){if(!t.has(e,Jn))continue;t.get(e,Jn).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,Kn)){if(!t.get(s,Kn).enabled)continue}const n=t.get(s,fr);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,fr)){t.get(r,fr).isFocused=!1,n.emit(r,"blur",r)}s.focus(e);t.get(e,fr).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},Nr=j("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Vr(){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 Gr=new class{build(e){q("SafeArea",Nr);const t=e.world;let n=Vr(),r=!0,o=0,i=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Vr(),r=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Vr(),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([Nr,dn]);for(const e of u){const s=t.get(e,Nr),r=t.get(e,dn),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,dn,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},qr=j("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Kr=null;const Jr=new class{build(e){q("ListView",qr);const t=e.world,s=new Map;Kr=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(rt)],e=>{const n=ir()&&!ar();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,dn]);for(const o of r){Pn(t,o,Kn,{enabled:!0,blockRaycast:!0}),Pn(t,o,$n,{enabled:!0,mode:zn});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,dn),l=bn(a,o),c=vn(a,o);if(!n){const s=t.has(o,Jn)?t.get(o,Jn):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,dn,{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"]})}},Qr=j("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Zr=new class{build(e){q("Dropdown",Qr);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*Cn;t.insert(r,dn,{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)*Cn;t.insert(o,he,{value:`Option_${e}`}),t.insert(o,dn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Cn},offsetMax:{x:0,y:0},size:{x:i,y:Cn},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:Cn},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,Kn,{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,kn,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:An.Left,verticalAlign:In.Middle,wordWrap:!1,overflow:Fn.Clip,lineHeight:1.2}),t.insert(c,dn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:Cn},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,kn))return;const n=t.get(s,kn);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,kn,{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,Kn)&&t.insert(e,Kn,{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?{...Rn}:{r:.95,g:.95,b:.95,a:1};t.insert(n,re,{texture:L,color:r,size:{x:e.ddWidth,y:Cn},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,Jn))continue;if(t.get(s,Jn).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,et([ve(rt),ve(tr)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=ir()&&!ar(),p=t.getEntitiesWithComponents([Qr]);for(const g of p){const p=t.get(g,Qr);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;Pn(t,g,Kn,{enabled:!0,blockRaycast:!0});const m=t.has(g,Jn)?t.get(g,Jn):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,Jn))continue;if(t.get(s,Jn).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,Jn))continue;if(t.get(n,Jn).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"]})}},eo=0,to=0,so=2,no=j("LayoutGroup",{direction:eo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:to,reverseOrder:!1});const ro=new class{build(e){q("LayoutGroup",no);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e=t.getEntitiesWithComponents([no,dn,ce]);for(const s of e){const e=t.get(s,no),n=t.get(s,dn),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,dn)&&t.has(e,te)&&o.push({entity:e,rect:t.get(e,dn)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const i=vn(n,s),a=bn(n,s),l=n.pivot.x,c=n.pivot.y,d=e.padding,u=e.direction===eo;let h=0;for(let s=0;s<o.length;s++){const n=o[s],r=vn(n.rect,n.entity),f=bn(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===to?(1-c)*a-d.top-(1-g)*f:e.childAlignment===so?-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===to?-l*i+d.left+p*r:e.childAlignment===so?(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 oo{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 io=new oo;async function ao(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 lo=we({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),co=we(null,"PhysicsAPI");function uo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ho(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class fo{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(lo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=ao(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=uo(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),po(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=uo(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=uo(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=ho(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(lo,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(co,go._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function po(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 go{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(go.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 yo={nearest:0,linear:1},mo={repeat:0,clamp:1,mirror:2};function _o(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=yo[n.filterMode??"linear"]??1,a=mo[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 xo(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 wo(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 vo(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]=_o(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=xo(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=_o(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 fo("",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=_o(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=Bt(e.world,s);if(l&&e.hasResource(Xs))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=wo(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(Wt);t&&t.setAddressableManifest(a)}}class bo{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 So="__preview__";const Po={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=ks.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:ks.getTargetTexture(s),width:e.width,height:e.height}},release(e){ks.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(ks.releaseRenderTarget(e._handle),Po.create({width:t,height:s,depth:!0})),begin(e,t){ks.begin(t,e._handle)},end(){ks.end()},getDepthTexture:e=>ks.getTargetDepthTexture(e._handle)};var Mo;exports.LogLevel=void 0,(Mo=exports.LogLevel||(exports.LogLevel={}))[Mo.Debug=0]="Debug",Mo[Mo.Info=1]="Info",Mo[Mo.Warn=2]="Warn",Mo[Mo.Error=3]="Error";class To{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 Eo{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new To)}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 Co=new Eo;const Ro=[Ln,qn,nr,Sr,Ir,ur,Br,zr,jr,Tr,mr,Yr,Gr,Jr,Zr,ro,io];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=Vs,exports.AssetPlugin=$t,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=zt,exports.Assets=Wt,exports.AsyncCache=Tt,exports.BitmapText=de,exports.BodyType=_e,exports.BoxCollider=ge,exports.Button=Zn,exports.ButtonState=Qn,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=kr,exports.Draggable=Fr,exports.Draw=os,exports.Dropdown=Qr,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=ln,exports.FillMethod=xr,exports.FillOrigin=wr,exports.FocusManager=gr,exports.FocusManagerState=pr,exports.Focusable=fr,exports.GLDebug=Ls,exports.Geometry=vs,exports.INVALID_ENTITY=0,exports.INVALID_FONT=z,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=L,exports.Image=vr,exports.ImageType=_r,exports.Input=rt,exports.InputPlugin=ot,exports.InputState=nt,exports.Interactable=Kn,exports.ListView=qr,exports.LocalTransform=se,exports.Logger=Eo,exports.Material=mt,exports.MaterialLoader=Et,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=he,exports.Parent=le,exports.Physics=go,exports.PhysicsEvents=lo,exports.PhysicsPlugin=fo,exports.PostProcess=Ts,exports.PrefabServer=Nt,exports.Prefabs=Vt,exports.PrefabsPlugin=Gt,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(Xs);t.register({name:So,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(So),this.loadPromise_=t.load(So).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 bo(this.baseUrl_);await s.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await vo(this.app_,this.app_.wasmModule,t,s,r,null,void 0,null,So)}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(Xs).getScene(So),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(Xs);await e.switchTo(So),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=Cr,exports.ProgressBarDirection=Er,exports.ProgressBarPlugin=Ar,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=zs,exports.RenderTexture=Po,exports.Renderer=ks,exports.Res=ve,exports.ResMut=be,exports.RigidBody=pe,exports.RuntimeConfig=U,exports.SafeArea=Nr,exports.ScaleMode=ee,exports.SceneManager=Xs,exports.SceneManagerState=Hs,exports.SceneOwner=fe,exports.ScrollView=Dr,exports.ShaderSources=Mt,exports.Slider=$r,exports.SliderDirection=Wr,exports.SliderPlugin=Xr,exports.SpineAnimation=ue,exports.Sprite=re,exports.SystemRunner=st,exports.Text=kn,exports.TextAlign=An,exports.TextInput=hr,exports.TextInputPlugin=yr,exports.TextOverflow=Fn,exports.TextPlugin=Un,exports.TextRenderer=Bn,exports.TextVerticalAlign=In,exports.Time=Me,exports.Toggle=Pr,exports.Transform=te,exports.UICameraInfo=at,exports.UIEventQueue=er,exports.UIEvents=tr,exports.UIInteraction=Jn,exports.UIInteractionPlugin=dr,exports.UILayoutPlugin=sr,exports.UIMask=$n,exports.UIMaskPlugin=Gn,exports.UIRect=dn,exports.UIRenderOrderPlugin=oo,exports.Velocity=ae,exports.WebAssetProvider=bo,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=gn,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=Ot,exports.clearDrawCallbacks=hs,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=pn,exports.computeFillSize=function(e,t,s,n){switch(e){case ln.BottomToTop:case ln.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case ln.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case ln.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case ln.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=cn,exports.createMaskProcessor=Vn,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await vo(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=Vs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ts(e),pt(e),_s(e),Ss(e),Is(e),Ds(e);const r=new zs;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=Qs(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;ks.setClearColor(e.x,e.y,e.z,e.w)}const u=(l()-o)/1e3;let h;if(ks.resize(t,c),Ts.isInitialized()&&Ts.getPassCount()>0&&!Ts.isBypassed()&&Ts.resize(t,c),s.hasResource(Xs)){const e=s.getResource(Xs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=Qs(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:Gs,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})}ks.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,d),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(Ot),s.addPlugin(qt),s.addPlugin(it),s.addPlugin(Ns),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Ro,...t})},exports.debug=function(e,t,s){Co.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){Co.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.getComponentSpineFieldDescriptor=At,exports.getCustomExtensions=x,exports.getEditorType=function(e){return m(e)?.editorType??"unknown"},exports.getLogger=function(){return Co},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){Co.info(e,t,s)},exports.initDrawAPI=ts,exports.initGLDebugAPI=Ds,exports.initGeometryAPI=_s,exports.initMaterialAPI=pt,exports.initPostProcessAPI=Ss,exports.initRendererAPI=Is,exports.inputPlugin=it,exports.instantiatePrefab=Ht,exports.intersectRects=On,exports.invertMatrix4=Hn,exports.isBuiltinComponent=V,exports.isCustomExtension=w,exports.isEditor=ir,exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=ar,exports.isRuntime=function(){return!rr},exports.isTextureRef=ct,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Lt,exports.loadPhysicsModule=ao,exports.loadRuntimeScene=vo,exports.loadSceneData=Bt,exports.loadSceneWithAssets=Dt,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=jn(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=Ir,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=ds,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(Wt);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Pt,exports.remapEntityFields=Ft,exports.sceneManagerPlugin=Ns,exports.screenToWorld=Xn,exports.setEditorMode=function(e){rr=e},exports.setListViewRenderer=function(e,t){if(!Kr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=Kr.get(e);s?s.renderer=t:Kr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Co.setMinLevel(e)},exports.setPlayMode=function(e){or=e},exports.setWasmErrorHandler=Ae,exports.shutdownDrawAPI=ss,exports.shutdownGLDebugAPI=Us,exports.shutdownGeometryAPI=xs,exports.shutdownMaterialAPI=gt,exports.shutdownPostProcessAPI=Ps,exports.shutdownRendererAPI=Fs,exports.sliderPlugin=jr,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 ln.BottomToTop:case ln.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=mr,exports.textPlugin=Ln,exports.transitionTo=async function(e,t,s){const n=e.getResource(Xs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=ur,exports.uiLayoutPlugin=nr,exports.uiMaskPlugin=qn,exports.uiPlugins=Ro,exports.uiRenderOrderPlugin=io,exports.unregisterComponent=function(e){X().delete(e),G.delete(e)},exports.unregisterDrawCallback=us,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){Co.warn(e,t,s)},exports.wrapSceneSystem=js,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 6387c605d..d112f3350 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(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 Ht=0;function Xt(e,t,n){const s=++Ht;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function jt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Yt(e){jt().push({schedule:Lt.Update,system:e})}function Nt(e){jt().push({schedule:Lt.Startup,system:e})}function Vt(e,t){jt().push({schedule:e,system:t})}class Gt{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_)}default:throw new Error("Unknown system parameter type")}}}class qt{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Kt=et(new qt,"Input");class Jt{constructor(e){this.target_=e??null}build(e){const n=new qt;e.insertResource(Kt,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,Xt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Qt=new Jt,Zt=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 en;function tn(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"}(en||(en={}));let nn=null,sn=null,rn=1;const on=new Map;function an(e){nn=e,sn=e.getResourceManager(),mn()}function ln(){0!==un&&nn&&(nn._free(un),un=0),on.clear(),rn=1,hn=!1,pn.clear(),gn=null,sn=null,nn=null}function cn(){if(!sn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return sn}const dn={createShader:(e,t)=>cn().createShader(e,t),releaseShader(e){e>0&&cn().releaseShader(e)},create(e){const t=rn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??en.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 on.set(t,n),t},get:e=>on.get(e),setUniform(e,t,n){const s=on.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,nn?.invalidateMaterialCache(e))},getUniform(e,t){const n=on.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=on.get(e);n&&(n.blendMode=t,nn?.invalidateMaterialCache(e))},getBlendMode(e){const t=on.get(e);return t?.blendMode??en.Normal},setDepthTest(e,t){const n=on.get(e);n&&(n.depthTest=t,nn?.invalidateMaterialCache(e))},getShader(e){const t=on.get(e);return t?.shader??0},release(e){on.delete(e),nn?.invalidateMaterialCache(e)},isValid:e=>on.has(e),releaseAll(){on.clear(),nn?.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??en.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=on.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=rn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return on.set(n,s),n},toAssetData(e,t){const n=on.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=on.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let hn=!1,un=0;const fn=16384,pn=new Map;let gn=null;function yn(e){const t=(0===un&&nn&&(un=nn._malloc(fn)),un);if(0===t||!nn)return{ptr:0,count:0};let n=0,s=0;const i=nn.HEAPU8,r=nn.HEAPU32,o=nn.HEAPF32;for(const[a,l]of e){if(tn(l))continue;let e=pn.get(a);e||(gn||(gn=new TextEncoder),e=gn.encode(a),pn.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>fn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${fn} 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 mn(){if(!nn||hn)return;nn.materialDataProvider=(e,t,n,s,i)=>{const r=on.get(e);if(!r)return nn.HEAPU32[t>>2]=0,nn.HEAPU32[n>>2]=0,nn.HEAPU32[s>>2]=0,void(nn.HEAPU32[i>>2]=0);nn.HEAPU32[t>>2]=r.shader,nn.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=yn(r.uniforms);nn.HEAPU32[s>>2]=o,nn.HEAPU32[i>>2]=a},hn=!0}const _n={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 wn{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 xn{constructor(e,t=""){this.cache_=new wn,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&&(dn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())dn.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:dn.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 vn=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 bn(e,t){vn.set(e,t)}function Sn(e){const t=vn.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 vn.get(e)?.fields??[]}function Pn(e){return vn.get(e)?.spine??null}const Tn=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function En(e,t){Tn.set(e,t)}function Cn(e,t){const n=Tn.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 Rn(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)Cn(i,n),Fn(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 An(e,t){return Rn(e,t)}async function kn(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 In.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=vn.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=[...In.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=vn.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=Rn(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 In=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 Fn(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 Bn(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 zn(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 Un{constructor(e){this.textureCache_=new wn,this.shaderCache_=new wn,this.jsonCache_=new wn,this.textCache_=new wn,this.binaryCache_=new wn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new wn,this.prefabCache_=new wn,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 xn(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(),dn.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 kn(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 dn.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 dn.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 $n=et(null,"Assets");class Wn{build(e){const t=e.wasmModule;t?e.insertResource($n,new Un(t)):console.warn("AssetPlugin: No WASM module available")}}const Dn=new Wn;class On{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 Ln(e,t){const n=e.getResource($n);n&&n.registerEmbeddedAssets(t)}async function Hn(e,t,n){const{entities:s,rootId:i}=await jn(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 kn(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 Xn=10;async function jn(e,t,n,s,i,r=0){if(r>Xn)throw new Error(`Prefab nesting depth exceeded ${Xn}. 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 jn(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};Yn(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 Yn(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 Nn{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 Hn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Vn=et(null,"Prefabs");class Gn{constructor(){this.name="PrefabsPlugin",this.dependencies=[$n]}build(e){const t=e.getResource($n);e.insertResource(Vn,new Nn(e.world,t))}}const qn=new Gn;let Kn=null,Jn=0,Qn=0,Zn=0;const es=new Float32Array(256);function ts(e){Kn=e,Jn=Kn._malloc(64),Qn=Kn._malloc(64),Zn=Kn._malloc(1024)}function ns(){Kn&&(Jn&&(Kn._free(Jn),Jn=0),Qn&&(Kn._free(Qn),Qn=0),Zn&&(Kn._free(Zn),Zn=0)),Kn=null}function ss(){if(!Kn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Kn}const is={r:1,g:1,b:1,a:1},rs={begin(e){const t=ss();try{t.HEAPF32.set(e,Jn/4),t.draw_begin(Jn)}catch(e){ht(e,"Draw.begin")}},end(){try{ss().draw_end()}catch(e){ht(e,"Draw.end")}},line(e,t,n,s=1){try{ss().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{ss().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{ss().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{ss().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{ss().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=is){try{ss().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=is){try{ss().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){ss().draw_setLayer(e)},setDepth(e){ss().draw_setDepth(e)},getDrawCallCount:()=>Kn?Kn.draw_getDrawCallCount():0,getPrimitiveCount:()=>Kn?Kn.draw_getPrimitiveCount():0,setBlendMode(e){ss().draw_setBlendMode(e)},setDepthTest(e){ss().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=ss();s.HEAPF32.set(n,Qn/4),s.draw_mesh(e,t,Qn)}catch(n){ht(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=ss(),i=dn.get(t);if(!i)return;if(rs.setBlendMode(i.blendMode),rs.setDepthTest(i.depthTest),0===i.uniforms.size)return void rs.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,Qn/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=ls(t);if(!(s<0)){if(tn(n))es[r++]=10,es[r++]=s,es[r++]=n.slot??e++,es[r++]=n.textureId;else if("number"==typeof n)es[r++]=1,es[r++]=s,es[r++]=n;else if(Array.isArray(n)){es[r++]=n.length,es[r++]=s;for(let e=0;e<n.length;e++)es[r++]=n[e]}else"w"in n?(es[r++]=4,es[r++]=s,es[r++]=n.x,es[r++]=n.y,es[r++]=n.z,es[r++]=n.w):"z"in n?(es[r++]=3,es[r++]=s,es[r++]=n.x,es[r++]=n.y,es[r++]=n.z):(es[r++]=2,es[r++]=s,es[r++]=n.x,es[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(es.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,Qn);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),Zn/4),s.draw_meshWithUniforms(e,i.shader,Qn,Zn,r)}catch(n){ht(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},os={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},as=new Set;function ls(e){const t=os[e];return void 0!==t?t:(as.has(e)||(as.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(os).join(", ")}`)),-1)}const cs=new Map;function ds(e,t,n){cs.set(e,{fn:t,scene:n??""})}function hs(e){cs.delete(e)}function us(){cs.clear()}var fs;!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"}(fs||(fs={}));let ps=null,gs=0,ys=0,ms=0;function _s(e){ps=e,gs=ps._malloc(262144),ys=ps._malloc(65536),ms=ps._malloc(256)}function ws(){ps&&(gs&&ps._free(gs),ys&&ps._free(ys),ms&&ps._free(ms),gs=0,ys=0,ms=0),ps=null}function xs(){if(!ps)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ps}const vs={create(e){const t=xs(),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,gs/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,ms,i).set(r),t.geometry_init(n,gs,s,ms,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,ys,s).set(e.indices),t.geometry_setIndices16(n,ys,s)}else{new Uint32Array(t.HEAPU8.buffer,ys,s).set(e.indices),t.geometry_setIndices32(n,ys,s)}}return n},updateVertices(e,t,n=0){const s=xs(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,gs/4),s.geometry_updateVertices(e,gs,i,n)},release(e){e>0&&xs().geometry_release(e)},isValid:e=>!(!ps||e<=0)&&ps.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return vs.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:fs.Float2},{name:"a_texCoord",type:fs.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 vs.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:fs.Float2},{name:"a_texCoord",type:fs.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 vs.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:fs.Float2},{name:"a_texCoord",type:fs.Float2}],indices:new Uint16Array(o)})}};let bs=null;function Ss(e){bs=e}function Ms(){bs&&Ts.isInitialized()&&Ts.shutdown(),bs=null}function Ps(){if(!bs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return bs}const Ts={init(e,t){try{return Ps().postprocess_init(e,t)}catch(n){return ht(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ps().postprocess_shutdown()}catch(e){ht(e,"PostProcess.shutdown")}},resize(e,t){try{Ps().postprocess_resize(e,t)}catch(n){ht(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ps().postprocess_addPass(e,t)}catch(t){return ht(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ps().postprocess_removePass(e)}catch(t){ht(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ps().postprocess_setPassEnabled(e,t)}catch(t){ht(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ps().postprocess_isPassEnabled(e)}catch(t){return ht(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Ps().postprocess_setUniformFloat(e,t,n)}catch(n){ht(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Ps().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){ht(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ps().postprocess_begin()}catch(e){ht(e,"PostProcess.begin")}},end(){try{Ps().postprocess_end()}catch(e){ht(e,"PostProcess.end")}},getPassCount(){try{return Ps().postprocess_getPassCount()}catch(e){return ht(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!bs)return!1;try{return bs.postprocess_isInitialized()}catch(e){return ht(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ps().postprocess_setBypass(e)}catch(e){ht(e,"PostProcess.setBypass")}},isBypassed(){if(!bs)return!0;try{return bs.postprocess_isBypassed()}catch(e){return ht(e,"PostProcess.isBypassed"),!0}},createBlur:()=>dn.createShader(Es,"#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:()=>dn.createShader(Es,"#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:()=>dn.createShader(Es,"#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:()=>dn.createShader(Es,"#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")},Es="#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 Cs;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Cs||(Cs={}));let Rs=null,As=0;function ks(e){Rs=e,As=Rs._malloc(64)}function Is(){Rs&&As&&(Rs._free(As),As=0),Rs=null}const Fs={init(e,t){Rs?.renderer_init(e,t)},resize(e,t){Rs?.renderer_resize(e,t)},begin(e,t){if(Rs&&As)try{Rs.HEAPF32.set(e,As/4),Rs.renderer_begin(As,t??0)}catch(e){ht(e,"Renderer.begin")}},flush(){try{Rs?.renderer_flush()}catch(e){ht(e,"Renderer.flush")}},end(){try{Rs?.renderer_end()}catch(e){ht(e,"Renderer.end")}},submitSprites(e){if(Rs)try{Rs.renderer_submitSprites(e._cpp)}catch(e){ht(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Rs)try{Rs.renderer_submitBitmapText(e._cpp)}catch(e){ht(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Rs)try{Rs.renderer_submitSpine?.(e._cpp)}catch(e){ht(e,"Renderer.submitSpine")}},setStage(e){Rs?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Rs?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Rs?.renderer_releaseTarget(e)},getTargetTexture:e=>Rs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Rs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Rs?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Rs?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Rs?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Rs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Rs?Rs.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Rs?{drawCalls:Rs.renderer_getDrawCalls(),triangles:Rs.renderer_getTriangles(),sprites:Rs.renderer_getSprites(),text:Rs.renderer_getText(),spine:Rs.renderer_getSpine?.()??0,meshes:Rs.renderer_getMeshes(),culled:Rs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Bs=null;function zs(e){Bs=e}function Us(){Bs=null}const $s={enable(){Bs?.gl_enableErrorCheck(!0)},disable(){Bs?.gl_enableErrorCheck(!1)},check:e=>Bs?.gl_checkErrors(e)??0,diagnose(){Bs?.renderer_diagnose()}};class Ws{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_||(Fs.resize(s,i),Ts.isInitialized()&&Ts.getPassCount()>0&&Ts.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Fs.setViewport(0,0,s,i),Fs.clearBuffers(3),Fs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(n,r),Fs.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;Fs.setViewport(s.x,s.y,s.w,s.h),Fs.setScissor(s.x,s.y,s.w,s.h,!0),Fs.clearBuffers(i),Fs.setScissor(0,0,0,0,!1),Fs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(n,r),Fs.end()}executeDrawCallbacks(e,t){const n=cs;if(n.size>0){rs.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)}rs.end();for(const e of s)hs(e)}}}const Ds="__scene_transition_overlay__";class Os{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 Ls{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),ds(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=Ts.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){Ts.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 Hs{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},ds(Ds,()=>{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;rs.setLayer(9999),rs.setDepth(9999),rs.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,hs(Ds),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,hs(Ds),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 Os(t);this.scenes_.set(e,n);const s=new Ls(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource($n)?this.app_.getResource($n):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 Os(t);this.scenes_.set(e,n);const s=new Ls(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource($n)?this.app_.getResource($n):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())hs(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{Ts.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($n)&&(i.assetServer=this.app_.getResource($n));const r=await kn(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=js(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($n)?this.app_.getResource($n):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)dn.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{Ts.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 Xs=et(null,"SceneManager");function js(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Xs).getSceneStatus(t)&&n._fn(...s)}}}const Ys=Xt([nt(Xs),tt(rt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Ns={name:"SceneManager",build(e){const t=new Hs(e);e.insertResource(Xs,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Xs),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,Ys)}};class Vs{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 Vs}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(Xs).register(e),this}setInitialScene(e){return this.getResource(Xs).setInitial(e),this}tick(e){this.runner_||(this.runner_=new Gt(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 Gt(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,us();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=[Us,Is,Ms,ws,ln,ns];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let 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 Gs(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 Ks(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 Js=[];function Qs(e){if(e<Js.length)return Js[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 Js.push(t),t}function Zs(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=Ks(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=h*o,a=ti(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=si(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const u=ri(r.position.x,r.position.y,r.position.z),f=Qs(c.length);f.entity=e,f.viewProjection.set(ai(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 ei=new Float32Array(16);function ti(e,t,n,s,i,r){const o=ei;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 ni=new Float32Array(16);function si(e,t,n,s){const i=ni;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 ii=new Float32Array(16);function ri(e,t,n){const s=ii;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 oi=new Float32Array(16);function ai(e,t){const n=oi;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 li={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function ci(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 di=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 hi=null,ui=null;function fi(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 pi(e,t){switch(e){case li.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case li.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case li.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 gi(e,t){switch(e){case li.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case li.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case li.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 yi(e,t,n,s){switch(e){case li.BottomToTop:case li.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function mi(e,t,n,s){if(!e.has(t,di))return;const i=e.get(t,di),r=pi(n,s);i.anchorMin=r.anchorMin,i.anchorMax=r.anchorMax,i.offsetMin=r.offsetMin,i.offsetMax=r.offsetMax,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,di,i)}function _i(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function wi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function xi(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(wi(o.charCodeAt(0))&&s.length>0&&wi(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!wi(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 vi(e){let t=1;for(;t<e;)t*=2;return t}function bi(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 Si(e,t){if(hi&&ui){const e=hi.getUIRectComputedWidth(ui,t);if(e>0)return e}return e.size.x}function Mi(e,t){if(hi&&ui){const e=hi.getUIRectComputedHeight(ui,t);if(e>0)return e}return e.size.y}function Pi(e,t,n,s,i,r){if(!e.has(t,$e))return;const o=e.get(t,$e);let a,l;switch(n){case li.BottomToTop:case li.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 Ti(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 Ei(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Ci(e,t,n,s,i){if(!e.has(t,di))return;const r=e.get(t,di),o=ci(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 Ri(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 Ai=.1,ki=30,Ii={r:.3,g:.5,b:.8,a:1},Fi={Left:0,Center:1,Right:2},Bi={Top:0,Middle:1,Bottom:2},zi={Visible:0,Clip:1,Ellipsis:2},Ui=xe("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Fi.Left,verticalAlign:Bi.Top,wordWrap:!0,overflow:zi.Visible,lineHeight:1.2});class $i{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,vi(this.frameMaxW_)),e.height=Math.max(e.height,vi(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=vi(this.frameMaxW_),e.height=vi(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=xi(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===zi.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,vi(f)),s.height=Math.max(s.height,vi(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===zi.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 Bi.Top:x=d;break;case Bi.Middle:x=d+(p-2*d-w)/2;break;case Bi.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 Fi.Left:s=d;break;case Fi.Center:s=f/2;break;case Fi.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===zi.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 Fi.Left:return"left";case Fi.Center:return"center";case Fi.Right:return"right"}}}const Wi=Ri({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?Si(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Mi(e.uiRect,e.entity):0});class Di{build(e){Ce("Text",Ui);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new $i(t),s=e.world,i=new Map;e.addSystemToSchedule(Lt.PreUpdate,Xt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Ui));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Ui)){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([Ui]);for(const t of e){const e=s.get(t,Ui),r=s.has(t,di)?s.get(t,di):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Wi.changed(a,o)){if(s.has(t,$e)&&s.get(t,$e).texture!==ae)continue}fi(s,t);const l=r?{size:{x:Si(r,t),y:Mi(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,Wi.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Oi=new Di,Li=0,Hi=1,Xi=Ae("UIMask",{enabled:!0,mode:Li});function ji(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 Yi(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 Ni(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 Vi(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 Gi(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 Ki(e,t,n,s,i,r,o,a,l,c){const d=Gi(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 Ji(e,t,n,s,i,r,o){if(!e.has(t,di)||!e.has(t,Be))return null;const a=e.get(t,di),l=e.get(t,Be),c=Si(a,t)*l.worldScale.x,d=Mi(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=Gi(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 Qi(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Xi]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,Xi);n.enabled&&(h.add(e),n.mode===Hi?(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;Ti(t,e,e=>{if(i.has(e)){if(t.get(e,Xi).mode===Li)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,Xi).mode===Li){const e=Ji(t,n,r,o,a,l,c);e&&(s=ji(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=Ji(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;Ti(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 Zi{build(e){if(Ce("UIMask",Xi),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Qi(e.wasmModule,e.world))}}const er=new Zi,tr=Ae("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),nr=Ae("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),sr={Normal:0,Hovered:1,Pressed:2,Disabled:3},ir=xe("Button",{state:sr.Normal,transition:null});class rr{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 or=et(new rr,"UIEvents");class ar{build(e){Ce("UIRect",di);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){hi=e,ui=t}(n,s);e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Zt)],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,Xt([tt(Zt)],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,Xt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const lr=new ar;let cr=!1,dr=!1;function hr(e){cr=e}function ur(){return cr}function fr(){return!cr}function pr(e){dr=e}function gr(){return dr}const yr=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&&(Yi(t,e),n=!1),e)}}();function mr(e,t,n,s){t.emit(n,s,n),Ti(e,n,i=>{if(!e.has(i,tr))return!1;const r=e.get(i,tr);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class _r{build(e){Ce("Interactable",tr),Ce("Button",ir);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new rr;e.insertResource(or,i);let r=null,o=null;e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Kt),tt(Zt)],(e,a)=>{if(i.drain(),ur()&&!gr())return;const l=t.getEntitiesWithComponents([nr]);for(const e of l){const n=t.get(e,nr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,nr,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;yr.update(a.viewProjection);const u=Ni(d,h,yr.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,nr)){const e=t.get(r,nr);e.hovered=!1,t.insert(r,nr,e),i.emit(r,"hover_exit")}if(null!==_){Ei(t,_,nr);const e=t.get(_,nr);e.hovered=!0,t.insert(_,nr,e),i.emit(_,"hover_enter")}r=_}if(g&&null!==_){const e=t.get(_,nr);e.pressed=!0,e.justPressed=!0,t.insert(_,nr,e),o=_,mr(t,i,_,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,nr)){const e=t.get(o,nr);e.pressed=!1,e.justReleased=!0,t.insert(o,nr,e),mr(t,i,o,"release"),o===r&&mr(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(Lt.Update,Xt([],()=>{const e=t.getEntitiesWithComponents([ir]);for(const n of e){if(Ei(t,n,tr,{enabled:!0}),!t.has(n,nr))continue;const e=t.get(n,nr),s=t.get(n,ir),i=t.get(n,tr),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=sr.Pressed:e.hovered?s.state=sr.Hovered:s.state=sr.Normal:s.state=sr.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,$e)){const r=t.get(n,$e);r.color=_i(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,$e,r)}}},{name:"ButtonSystem"}))}}const wr=new _r,xr=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}),vr=xe("Focusable",{tabIndex:0,isFocused:!1});class br{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 Sr=et(new br,"FocusManager");class Mr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Ce("TextInput",xr),ur()&&!gr())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(Sr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,xr)?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,xr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(or).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,xr);s.focused=!1,s.dirty=!0;e.getResource(Sr).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,xr);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(or).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,xr);e.focused=!1,e.dirty=!0}e.getResource(Sr).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=vi(Math.max(i.width,d)),i.height=vi(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=xi(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=xi(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,Xt([tt(Sr)],e=>{const t=n.getEntitiesWithComponents([xr]);for(const e of t)Ei(n,e,vr,{tabIndex:0,isFocused:!1}),Ei(n,e,tr,{enabled:!0,blockRaycast:!0});const s=g();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,xr)){const e=n.get(M,xr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,xr);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,Xt([],()=>{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,xr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,xr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([xr,di]);for(const e of a){const t=n.get(e,xr);if(!t.dirty)continue;const s=n.get(e,di),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(fi(n,e),P(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Pr=new Mr,Tr={Simple:0,Sliced:1,Tiled:2,Filled:3},Er={Horizontal:0,Vertical:1},Cr={Left:0,Right:1,Bottom:2,Top:3},Rr=xe("Image",{texture:ae,color:{r:1,g:1,b:1,a:1},imageType:Tr.Simple,fillMethod:Er.Horizontal,fillOrigin:Cr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Ar=Ri({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?Si(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Mi(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const kr=new class{build(e){Ce("Image",Rr);const t=e.world,n=new Map;e.addSystemToSchedule(Lt.PreUpdate,Xt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Rr)||n.delete(e);const e=t.getEntitiesWithComponents([Rr]);for(const s of e){const e=t.get(s,Rr),i=t.has(s,di)?t.get(s,di):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!Ar.changed(o,r))continue;fi(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=Si(i,s),a.size.y=Mi(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Tr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Er.Horizontal?e.fillOrigin===Cr.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===Cr.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===Tr.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,Ar.take(r))}else a.color.a=0,t.insert(s,$e,a),n.set(s,Ar.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Ir=xe("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Fr=xe("ToggleGroup",{allowSwitchOff:!1});const Br=new class{build(e){Ce("Toggle",Ir),Ce("ToggleGroup",Fr);const t=e.world,n=new Set;e.addSystemToSchedule(Lt.Update,Xt([tt(or)],e=>{const s=t.getEntitiesWithComponents([Ir]);if(!ur()||gr()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Ir);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Ir,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,Ir);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(Ei(t,n,tr,{enabled:!0}),!t.has(n,nr))continue;const s=t.get(n,nr),i=t.get(n,Ir),o=t.get(n,tr);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,Fr);if(i.isOn&&o){if(!t.get(s,Fr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Ir,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,Ir);i.isOn&&(i.isOn=!1,t.insert(s,Ir,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,$e)){const e=t.get(n,$e);e.color=_i(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,$e,e)}}}for(const e of s){const n=t.get(e,Ir);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"]})}},zr=li,Ur=xe("ProgressBar",{value:0,fillEntity:0,direction:li.LeftToRight});function $r(e,t,n,s){if(!e.has(t,di))return;const i=e.get(t,di),r=n/2,o=s/2,a={left:-r,bottom:-o,right:r,top:o},l=ci(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})}}class Wr{build(e){Ce("ProgressBar",Ur);const t=e.world;e.addSystemToSchedule(Lt.PreUpdate,Xt([],()=>{const e=t.getEntitiesWithComponents([Ur,di]);for(const n of e){const e=t.get(n,Ur);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,di),i=Math.max(0,Math.min(1,e.value));mi(t,e.fillEntity,e.direction,i);const r=Si(s,n),o=Mi(s,n);$r(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Dr=new Wr,Or=xe("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Lr=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 Hr=new class{build(e){Ce("Draggable",Or),Ce("DragState",Lr);const t=e.world,n=e.getResource(or);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Kt),tt(Zt)],(e,o)=>{if(ur()&&!gr())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Or,nr]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,Or).enabled)continue;if(t.get(s,nr).hovered){let e=0;t.has(s,$e)&&(e=t.get(s,$e).layer);const i=bi(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,Lr)||t.insert(n,Lr);const e=t.get(n,Lr),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,Lr)){t.get(s,Lr).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,Or);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,Lr).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,Lr))return void(r=null);const s=t.get(r,Lr),i=t.get(r,Or),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=Gi(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"}))}},Xr=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 jr(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 Yr(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 Nr=new class{build(e){Ce("ScrollView",Xr);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(Lt.PostUpdate,Xt([tt(Kt),tt(Zt),tt(rt)],(e,i,r)=>{const o=ur()&&!gr(),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([Xr,di]);for(const r of l){Ei(t,r,Xi,{enabled:!0,mode:Li});const l=t.get(r,Xr),c=t.get(r,di);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=Si(c,r),u=Mi(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,di)){const e=t.get(o,di);a=Si(e,o)||e.size.x,l=Mi(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){Ei(t,r,tr,{enabled:!0,blockRaycast:!0});const n=t.has(r,nr)?t.get(r,nr):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=jr(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=jr(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=jr(l.scrollY,0,y,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=jr(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=Yr(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)<Ai&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Ai?(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=Yr(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)<Ai&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Ai?(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"]})}},Vr=li,Gr=xe("Slider",{value:0,minValue:0,maxValue:1,direction:li.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function qr(e,t,n,s,i,r){const o=Si(s,i)*n.worldScale.x,a=Mi(s,i)*n.worldScale.y,l=Gi(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 li.LeftToRight:return o>0?(f-g)/o:0;case li.RightToLeft:return o>0?1-(f-g)/o:0;case li.BottomToTop:return a>0?(p-y)/a:0;case li.TopToBottom:return a>0?1-(p-y)/a:0}}function Kr(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case li.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case li.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case li.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case li.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class Jr{build(e){Ce("Slider",Gr);const t=e.world;let n=null;e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Kt),tt(Zt),tt(or)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([Gr,di]);for(const o of r){const r=t.get(o,Gr),a=t.get(o,di);if(!ur()||gr()){if(t.has(o,Be)){Ei(t,o,tr,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&Ei(t,r.handleEntity,tr,{enabled:!0,blockRaycast:!1});const l=t.get(o,Be),c=t.has(o,nr)?t.get(o,nr):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,nr)&&(d=t.get(r.handleEntity,nr).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,Gr,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=Si(a,o),h=Mi(a,o),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(mi(t,r.fillEntity,r.direction,c),Ci(t,r.fillEntity,u,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,di)){const e=t.get(r.handleEntity,di);Kr(e,r.direction,c),t.insert(r.handleEntity,di,e),Ci(t,r.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Qr=new Jr;const Zr=new class{build(e){Ce("Focusable",vr);const t=e.world,n=new br;e.insertResource(Sr,n),e.addSystemToSchedule(Lt.Update,Xt([tt(Kt),tt(or)],(e,s)=>{if(ur()&&!gr())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([vr]);for(const e of i){if(!t.has(e,nr))continue;t.get(e,nr).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,tr)){if(!t.get(n,tr).enabled)continue}const s=t.get(n,vr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const 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,vr)){t.get(i,vr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,vr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},eo=xe("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function to(){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 no=new class{build(e){Ce("SafeArea",eo);const t=e.world;let n=to(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=to(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=to(),s=!0});e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Zt)],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([eo,di]);for(const e of d){const s=t.get(e,eo),i=t.get(e,di),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,di,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},so=xe("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let io=null;function ro(e,t){if(!io)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=io.get(e);n?n.renderer=t:io.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const oo=new class{build(e){Ce("ListView",so);const t=e.world,n=new Map;io=n,e.addSystemToSchedule(Lt.PostUpdate,Xt([tt(Kt)],e=>{const s=ur()&&!gr();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([so,di]);for(const r of i){Ei(t,r,tr,{enabled:!0,blockRaycast:!0}),Ei(t,r,Xi,{enabled:!0,mode:Li});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,so),a=t.get(r,di),l=Mi(a,r),c=Si(a,r);if(!s){const n=t.has(r,nr)?t.get(r,nr):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,di,{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"]})}},ao=xe("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const lo=new class{build(e){Ce("Dropdown",ao);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*ki;t.insert(i,di,{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)*ki;t.insert(r,Ye,{value:`Option_${e}`}),t.insert(r,di,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*ki},offsetMax:{x:0,y:0},size:{x:o,y:ki},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:ki},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,tr,{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,Ui,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Fi.Left,verticalAlign:Bi.Middle,wordWrap:!1,overflow:zi.Clip,lineHeight:1.2}),t.insert(c,di,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:ki},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,Ui))return;const s=t.get(n,Ui);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,Ui,{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,tr)&&t.insert(e,tr,{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?{...Ii}:{r:.95,g:.95,b:.95,a:1};t.insert(s,$e,{texture:ae,color:i,size:{x:e.ddWidth,y:ki},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,nr))continue;if(t.get(n,nr).hovered)return!0}return!1}e.addSystemToSchedule(Lt.Update,Xt([tt(Kt),tt(or)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=ur()&&!gr(),p=t.getEntitiesWithComponents([ao]);for(const g of p){const p=t.get(g,ao);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;Ei(t,g,tr,{enabled:!0,blockRaycast:!0});const m=t.has(g,nr)?t.get(g,nr):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,nr))continue;if(t.get(n,nr).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,nr))continue;if(t.get(s,nr).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"]})}},co=0,ho=0,uo=2,fo=xe("LayoutGroup",{direction:co,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:ho,reverseOrder:!1});const po=new class{build(e){Ce("LayoutGroup",fo);const t=e.world;e.addSystemToSchedule(Lt.PreUpdate,Xt([],()=>{const e=t.getEntitiesWithComponents([fo,di,He]);for(const n of e){const e=t.get(n,fo),s=t.get(n,di),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,di)&&t.has(e,Be)&&r.push({entity:e,rect:t.get(e,di)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=Si(s,n),a=Mi(s,n),l=s.pivot.x,c=s.pivot.y,d=e.padding,h=e.direction===co;let u=0;for(let n=0;n<r.length;n++){const s=r[n],i=Si(s.rect,s.entity),f=Mi(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===ho?(1-c)*a-d.top-(1-g)*f:e.childAlignment===uo?-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===ho?-l*o+d.left+p*i:e.childAlignment===uo?(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 go{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(Lt.PostUpdate,Xt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const yo=new go;async function mo(e,t,n){const s=e.getResource(Xs);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function _o(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 wo=et({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),xo=et(null,"PhysicsAPI");function vo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function bo(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class So{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(wo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=_o(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,Xt([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=vo(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),Mo(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=vo(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=vo(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=bo(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(wo,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(xo,Po._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function Mo(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 Po{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(Po.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 To={nearest:0,linear:1},Eo={repeat:0,clamp:1,mirror:2};function Co(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=To[s.filterMode??"linear"]??1,a=Eo[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 Ro(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 Ao(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 ko(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]=Co(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=Pn(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=Ro(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=Co(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 So("",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=Co(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=dn.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=dn.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=An(e.world,n);if(l&&e.hasResource(Xs))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=Pn(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=Ao(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($n);t&&t.setAddressableManifest(a)}}function Io(e,t,n){return{name:e,data:t,async setup(){await ko(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Fo{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=Pn(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 Bo="__preview__";class zo{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(Xs);t.register({name:Bo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Bo),this.loadPromise_=t.load(Bo).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 Fo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await ko(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,Bo)}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(Xs).getScene(Bo),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(Xs);await e.switchTo(Bo),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 Uo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Fs.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Fs.getTargetTexture(n),width:e.width,height:e.height}},release(e){Fs.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Fs.releaseRenderTarget(e._handle),Uo.create({width:t,height:n,depth:!0})),begin(e,t){Fs.begin(t,e._handle)},end(){Fs.end()},getDepthTexture:e=>Fs.getTargetDepthTexture(e._handle)};var $o;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}($o||($o={}));class Wo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${$o[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case $o.Debug:console.debug(t,n);break;case $o.Info:console.log(t,n);break;case $o.Warn:console.warn(t,n);break;case $o.Error:console.error(t,n)}}}class Do{constructor(){this.handlers_=[],this.minLevel_=$o.Info,this.addHandler(new Wo)}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($o.Debug,e,t,n)}info(e,t,n){this.log($o.Info,e,t,n)}warn(e,t,n){this.log($o.Warn,e,t,n)}error(e,t,n){this.log($o.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 Oo=new Do;function Lo(){return Oo}function Ho(e){Oo.setMinLevel(e)}function Xo(e,t,n){Oo.debug(e,t,n)}function jo(e,t,n){Oo.info(e,t,n)}function Yo(e,t,n){Oo.warn(e,t,n)}function No(e,t,n){Oo.error(e,t,n)}const Vo=[Oi,er,lr,kr,Dr,wr,Hr,Nr,Qr,Br,Pr,Zr,no,oo,lo,po,yo];function Go(e,t){return function(e,t){const n=Vs.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ts(e),an(e),_s(e),Ss(e),ks(e),zs(e);const i=new Ws;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=Zs(e,s,t,i));const o=n.getResource(Zt);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(Zt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=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;Fs.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-r)/1e3;let h;if(Fs.resize(t,l),Ts.isInitialized()&&Ts.getPassCount()>0&&!Ts.isBypassed()&&Ts.resize(t,l),n.hasResource(Xs)){const e=n.getResource(Xs).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=Zs(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})}Fs.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Lt.First,l),n.addSystemToSchedule(Lt.Last,c),n.addPlugin(Dn),n.addPlugin(qn),n.addPlugin(Qt),n.addPlugin(Ns),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Vo,...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,Vs as App,Wn as AssetPlugin,On as AssetRefCounter,Un as AssetServer,$n as Assets,wn as AsyncCache,Xe as BitmapText,en as BlendMode,Qe as BodyType,qe as BoxCollider,ir as Button,sr 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,fs as DataType,Lr as DragState,Or as Draggable,rs as Draw,ao as Dropdown,It as EntityCommands,Wt as EventReader,Ot as EventReaderInstance,Ut as EventRegistry,$t as EventWriter,Dt as EventWriterInstance,li as FillDirection,Er as FillMethod,Cr as FillOrigin,Sr as FocusManager,br as FocusManagerState,vr as Focusable,$s as GLDebug,vs as Geometry,oe as INVALID_ENTITY,le as INVALID_FONT,ce as INVALID_MATERIAL,ae as INVALID_TEXTURE,Rr as Image,Tr as ImageType,Kt as Input,Jt as InputPlugin,qt as InputState,tr as Interactable,so as ListView,ze as LocalTransform,$o as LogLevel,Do as Logger,dn as Material,xn as MaterialLoader,wt as Mut,Ye as Name,Le as Parent,Po as Physics,wo as PhysicsEvents,So as PhysicsPlugin,Ts as PostProcess,Nn as PrefabServer,Vn as Prefabs,Gn as PrefabsPlugin,zo as PreviewPlugin,Ur as ProgressBar,zr as ProgressBarDirection,Wr as ProgressBarPlugin,ke as ProjectionType,Et as Query,Ct as QueryInstance,Rt as Removed,At as RemovedQueryInstance,Ws as RenderPipeline,Cs as RenderStage,Uo as RenderTexture,Fs as Renderer,tt as Res,nt as ResMut,Ge as RigidBody,ie as RuntimeConfig,eo as SafeArea,Fe as ScaleMode,Xs as SceneManager,Hs as SceneManagerState,Ne as SceneOwner,Lt as Schedule,Xr as ScrollView,_n as ShaderSources,Gr as Slider,Vr as SliderDirection,Jr as SliderPlugin,je as SpineAnimation,$e as Sprite,Gt as SystemRunner,Ui as Text,Fi as TextAlign,xr as TextInput,Mr as TextInputPlugin,zi as TextOverflow,Di as TextPlugin,$i as TextRenderer,Bi as TextVerticalAlign,rt as Time,Ir as Toggle,Be as Transform,Zt as UICameraInfo,rr as UIEventQueue,or as UIEvents,nr as UIInteraction,_r as UIInteractionPlugin,ar as UILayoutPlugin,Xi as UIMask,Zi as UIMaskPlugin,di as UIRect,go as UIRenderOrderPlugin,Oe as Velocity,Fo as WebAssetProvider,_t as World,Ue as WorldTransform,Nt as addStartupSystem,Yt as addSystem,Vt as addSystemToSchedule,mi as applyDirectionalFill,re as applyRuntimeConfig,Dn as assetPlugin,us as clearDrawCallbacks,Se as clearUserComponents,fe as color,pi as computeFillAnchors,yi as computeFillSize,gi as computeHandleAnchors,ci as computeUIRectLayout,Qi as createMaskProcessor,Io as createRuntimeSceneConfig,Go as createWebApp,Xo as debug,xe as defineComponent,Bt as defineEvent,et as defineResource,Xt as defineSystem,ve as defineTag,No as error,zn as findEntityByName,Gs as flushPendingSystems,S as getAddressableType,M as getAddressableTypeByEditorType,T as getAllAssetExtensions,A as getAssetMimeType,v as getAssetTypeEntry,Re as getComponent,Mn as getComponentAssetFieldDescriptors,Sn as getComponentAssetFields,Ve as getComponentDefaults,Pn as getComponentSpineFieldDescriptor,C as getCustomExtensions,b as getEditorType,Lo as getLogger,t as getPlatform,s as getPlatformType,be as getUserComponent,R as getWeChatPackOptions,jo as info,ts as initDrawAPI,zs as initGLDebugAPI,_s as initGeometryAPI,an as initMaterialAPI,Ss as initPostProcessAPI,ks as initRendererAPI,Qt as inputPlugin,Hn as instantiatePrefab,ji as intersectRects,Yi as invertMatrix4,Te as isBuiltinComponent,k as isCustomExtension,ur as isEditor,P as isKnownAssetExtension,n as isPlatformInitialized,gr as isPlayMode,fr as isRuntime,tn as isTextureRef,i as isWeChat,r as isWeb,Fn as loadComponent,_o as loadPhysicsModule,ko as loadRuntimeScene,An as loadSceneData,kn as loadSceneWithAssets,E as looksLikeAssetPath,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ki as pointInOBB,Vi as pointInWorldRect,qn as prefabsPlugin,Dr as progressBarPlugin,pe as quat,Ce as registerComponent,bn as registerComponentAssetFields,En as registerComponentEntityFields,ds as registerDrawCallback,Ln as registerEmbeddedAssets,mn as registerMaterialCallback,Cn as remapEntityFields,Ns as sceneManagerPlugin,Ni as screenToWorld,hr as setEditorMode,ro as setListViewRenderer,Ho as setLogLevel,pr as setPlayMode,dt as setWasmErrorHandler,ns as shutdownDrawAPI,Us as shutdownGLDebugAPI,ws as shutdownGeometryAPI,ln as shutdownMaterialAPI,Ms as shutdownPostProcessAPI,Is as shutdownRendererAPI,Qr as sliderPlugin,Pi as syncFillSpriteSize,Pr as textInputPlugin,Oi as textPlugin,mo as transitionTo,wr as uiInteractionPlugin,lr as uiLayoutPlugin,er as uiMaskPlugin,Vo as uiPlugins,yo as uiRenderOrderPlugin,Me as unregisterComponent,hs as unregisterDrawCallback,Bn as updateCameraAspectRatio,de as vec2,he as vec3,ue as vec4,Yo as warn,js 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 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(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 Ht=0;function Xt(e,t,n){const s=++Ht;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function jt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Yt(e){jt().push({schedule:Lt.Update,system:e})}function Nt(e){jt().push({schedule:Lt.Startup,system:e})}function Vt(e,t){jt().push({schedule:e,system:t})}class Gt{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_)}default:throw new Error("Unknown system parameter type")}}}class qt{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Kt=et(new qt,"Input");class Jt{constructor(e){this.target_=e??null}build(e){const n=new qt;e.insertResource(Kt,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,Xt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Qt=new Jt,Zt=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 en;function tn(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"}(en||(en={}));let nn=null,sn=null,rn=1;const on=new Map;function an(e){nn=e,sn=e.getResourceManager(),mn()}function ln(){0!==un&&nn&&(nn._free(un),un=0),on.clear(),rn=1,hn=!1,pn.clear(),gn=null,sn=null,nn=null}function cn(){if(!sn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return sn}const dn={createShader:(e,t)=>cn().createShader(e,t),releaseShader(e){e>0&&cn().releaseShader(e)},create(e){const t=rn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??en.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 on.set(t,n),t},get:e=>on.get(e),setUniform(e,t,n){const s=on.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,nn?.invalidateMaterialCache(e))},getUniform(e,t){const n=on.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=on.get(e);n&&(n.blendMode=t,nn?.invalidateMaterialCache(e))},getBlendMode(e){const t=on.get(e);return t?.blendMode??en.Normal},setDepthTest(e,t){const n=on.get(e);n&&(n.depthTest=t,nn?.invalidateMaterialCache(e))},getShader(e){const t=on.get(e);return t?.shader??0},release(e){on.delete(e),nn?.invalidateMaterialCache(e)},isValid:e=>on.has(e),releaseAll(){on.clear(),nn?.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??en.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=on.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=rn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return on.set(n,s),n},toAssetData(e,t){const n=on.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=on.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let hn=!1,un=0;const fn=16384,pn=new Map;let gn=null;function yn(e){const t=(0===un&&nn&&(un=nn._malloc(fn)),un);if(0===t||!nn)return{ptr:0,count:0};let n=0,s=0;const i=nn.HEAPU8,r=nn.HEAPU32,o=nn.HEAPF32;for(const[a,l]of e){if(tn(l))continue;let e=pn.get(a);e||(gn||(gn=new TextEncoder),e=gn.encode(a),pn.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>fn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${fn} 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 mn(){if(!nn||hn)return;nn.materialDataProvider=(e,t,n,s,i)=>{const r=on.get(e);if(!r)return nn.HEAPU32[t>>2]=0,nn.HEAPU32[n>>2]=0,nn.HEAPU32[s>>2]=0,void(nn.HEAPU32[i>>2]=0);nn.HEAPU32[t>>2]=r.shader,nn.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=yn(r.uniforms);nn.HEAPU32[s>>2]=o,nn.HEAPU32[i>>2]=a},hn=!0}const _n={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 wn{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 xn{constructor(e,t=""){this.cache_=new wn,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&&(dn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())dn.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:dn.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 vn=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 bn(e,t){vn.set(e,t)}function Sn(e){const t=vn.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 vn.get(e)?.fields??[]}function Pn(e){return vn.get(e)?.spine??null}const Tn=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function En(e,t){Tn.set(e,t)}function Cn(e,t){const n=Tn.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 Rn(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)Cn(i,n),Fn(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 An(e,t){return Rn(e,t)}async function kn(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 In.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=vn.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=[...In.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=vn.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=Rn(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 In=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 Fn(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 Bn(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 zn(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 Un{constructor(e){this.textureCache_=new wn,this.shaderCache_=new wn,this.jsonCache_=new wn,this.textCache_=new wn,this.binaryCache_=new wn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new wn,this.prefabCache_=new wn,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 xn(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(),dn.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 kn(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 dn.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 dn.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 $n=et(null,"Assets");class Wn{build(e){const t=e.wasmModule;t?e.insertResource($n,new Un(t)):console.warn("AssetPlugin: No WASM module available")}}const Dn=new Wn;class On{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 Ln(e,t){const n=e.getResource($n);n&&n.registerEmbeddedAssets(t)}async function Hn(e,t,n){const{entities:s,rootId:i}=await jn(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 kn(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 Xn=10;async function jn(e,t,n,s,i,r=0){if(r>Xn)throw new Error(`Prefab nesting depth exceeded ${Xn}. 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 jn(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};Yn(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 Yn(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 Nn{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 Hn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Vn=et(null,"Prefabs");class Gn{constructor(){this.name="PrefabsPlugin",this.dependencies=[$n]}build(e){const t=e.getResource($n);e.insertResource(Vn,new Nn(e.world,t))}}const qn=new Gn;let Kn=null,Jn=0,Qn=0,Zn=0;const es=new Float32Array(256);function ts(e){Kn=e,Jn=Kn._malloc(64),Qn=Kn._malloc(64),Zn=Kn._malloc(1024)}function ns(){Kn&&(Jn&&(Kn._free(Jn),Jn=0),Qn&&(Kn._free(Qn),Qn=0),Zn&&(Kn._free(Zn),Zn=0)),Kn=null}function ss(){if(!Kn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Kn}const is={r:1,g:1,b:1,a:1},rs={begin(e){const t=ss();try{t.HEAPF32.set(e,Jn/4),t.draw_begin(Jn)}catch(e){ht(e,"Draw.begin")}},end(){try{ss().draw_end()}catch(e){ht(e,"Draw.end")}},line(e,t,n,s=1){try{ss().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{ss().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{ss().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{ss().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{ss().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=is){try{ss().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=is){try{ss().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){ss().draw_setLayer(e)},setDepth(e){ss().draw_setDepth(e)},getDrawCallCount:()=>Kn?Kn.draw_getDrawCallCount():0,getPrimitiveCount:()=>Kn?Kn.draw_getPrimitiveCount():0,setBlendMode(e){ss().draw_setBlendMode(e)},setDepthTest(e){ss().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=ss();s.HEAPF32.set(n,Qn/4),s.draw_mesh(e,t,Qn)}catch(n){ht(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=ss(),i=dn.get(t);if(!i)return;if(rs.setBlendMode(i.blendMode),rs.setDepthTest(i.depthTest),0===i.uniforms.size)return void rs.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,Qn/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=ls(t);if(!(s<0)){if(tn(n))es[r++]=10,es[r++]=s,es[r++]=n.slot??e++,es[r++]=n.textureId;else if("number"==typeof n)es[r++]=1,es[r++]=s,es[r++]=n;else if(Array.isArray(n)){es[r++]=n.length,es[r++]=s;for(let e=0;e<n.length;e++)es[r++]=n[e]}else"w"in n?(es[r++]=4,es[r++]=s,es[r++]=n.x,es[r++]=n.y,es[r++]=n.z,es[r++]=n.w):"z"in n?(es[r++]=3,es[r++]=s,es[r++]=n.x,es[r++]=n.y,es[r++]=n.z):(es[r++]=2,es[r++]=s,es[r++]=n.x,es[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(es.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,Qn);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),Zn/4),s.draw_meshWithUniforms(e,i.shader,Qn,Zn,r)}catch(n){ht(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},os={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},as=new Set;function ls(e){const t=os[e];return void 0!==t?t:(as.has(e)||(as.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(os).join(", ")}`)),-1)}const cs=new Map;function ds(e,t,n){cs.set(e,{fn:t,scene:n??""})}function hs(e){cs.delete(e)}function us(){cs.clear()}var fs;!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"}(fs||(fs={}));let ps=null,gs=0,ys=0,ms=0;function _s(e){ps=e,gs=ps._malloc(262144),ys=ps._malloc(65536),ms=ps._malloc(256)}function ws(){ps&&(gs&&ps._free(gs),ys&&ps._free(ys),ms&&ps._free(ms),gs=0,ys=0,ms=0),ps=null}function xs(){if(!ps)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ps}const vs={create(e){const t=xs(),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,gs/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,ms,i).set(r),t.geometry_init(n,gs,s,ms,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,ys,s).set(e.indices),t.geometry_setIndices16(n,ys,s)}else{new Uint32Array(t.HEAPU8.buffer,ys,s).set(e.indices),t.geometry_setIndices32(n,ys,s)}}return n},updateVertices(e,t,n=0){const s=xs(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,gs/4),s.geometry_updateVertices(e,gs,i,n)},release(e){e>0&&xs().geometry_release(e)},isValid:e=>!(!ps||e<=0)&&ps.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return vs.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:fs.Float2},{name:"a_texCoord",type:fs.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 vs.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:fs.Float2},{name:"a_texCoord",type:fs.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 vs.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:fs.Float2},{name:"a_texCoord",type:fs.Float2}],indices:new Uint16Array(o)})}};let bs=null;function Ss(e){bs=e}function Ms(){bs&&Ts.isInitialized()&&Ts.shutdown(),bs=null}function Ps(){if(!bs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return bs}const Ts={init(e,t){try{return Ps().postprocess_init(e,t)}catch(n){return ht(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ps().postprocess_shutdown()}catch(e){ht(e,"PostProcess.shutdown")}},resize(e,t){try{Ps().postprocess_resize(e,t)}catch(n){ht(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ps().postprocess_addPass(e,t)}catch(t){return ht(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ps().postprocess_removePass(e)}catch(t){ht(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ps().postprocess_setPassEnabled(e,t)}catch(t){ht(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ps().postprocess_isPassEnabled(e)}catch(t){return ht(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Ps().postprocess_setUniformFloat(e,t,n)}catch(n){ht(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Ps().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){ht(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ps().postprocess_begin()}catch(e){ht(e,"PostProcess.begin")}},end(){try{Ps().postprocess_end()}catch(e){ht(e,"PostProcess.end")}},getPassCount(){try{return Ps().postprocess_getPassCount()}catch(e){return ht(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!bs)return!1;try{return bs.postprocess_isInitialized()}catch(e){return ht(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ps().postprocess_setBypass(e)}catch(e){ht(e,"PostProcess.setBypass")}},isBypassed(){if(!bs)return!0;try{return bs.postprocess_isBypassed()}catch(e){return ht(e,"PostProcess.isBypassed"),!0}},createBlur:()=>dn.createShader(Es,"#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:()=>dn.createShader(Es,"#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:()=>dn.createShader(Es,"#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:()=>dn.createShader(Es,"#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")},Es="#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 Cs;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Cs||(Cs={}));let Rs=null,As=0;function ks(e){Rs=e,As=Rs._malloc(64)}function Is(){Rs&&As&&(Rs._free(As),As=0),Rs=null}const Fs={init(e,t){Rs?.renderer_init(e,t)},resize(e,t){Rs?.renderer_resize(e,t)},begin(e,t){if(Rs&&As)try{Rs.HEAPF32.set(e,As/4),Rs.renderer_begin(As,t??0)}catch(e){ht(e,"Renderer.begin")}},flush(){try{Rs?.renderer_flush()}catch(e){ht(e,"Renderer.flush")}},end(){try{Rs?.renderer_end()}catch(e){ht(e,"Renderer.end")}},submitSprites(e){if(Rs)try{Rs.renderer_submitSprites(e._cpp)}catch(e){ht(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Rs)try{Rs.renderer_submitBitmapText(e._cpp)}catch(e){ht(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Rs)try{Rs.renderer_submitSpine?.(e._cpp)}catch(e){ht(e,"Renderer.submitSpine")}},setStage(e){Rs?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Rs?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Rs?.renderer_releaseTarget(e)},getTargetTexture:e=>Rs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Rs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Rs?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Rs?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Rs?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Rs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Rs?Rs.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Rs?{drawCalls:Rs.renderer_getDrawCalls(),triangles:Rs.renderer_getTriangles(),sprites:Rs.renderer_getSprites(),text:Rs.renderer_getText(),spine:Rs.renderer_getSpine?.()??0,meshes:Rs.renderer_getMeshes(),culled:Rs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Bs=null;function zs(e){Bs=e}function Us(){Bs=null}const $s={enable(){Bs?.gl_enableErrorCheck(!0)},disable(){Bs?.gl_enableErrorCheck(!1)},check:e=>Bs?.gl_checkErrors(e)??0,diagnose(){Bs?.renderer_diagnose()}};class Ws{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_||(Fs.resize(s,i),Ts.isInitialized()&&Ts.getPassCount()>0&&Ts.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Fs.setViewport(0,0,s,i),Fs.clearBuffers(3),Fs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(n,r),Fs.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;Fs.setViewport(s.x,s.y,s.w,s.h),Fs.setScissor(s.x,s.y,s.w,s.h,!0),Fs.clearBuffers(i),Fs.setScissor(0,0,0,0,!1),Fs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(n,r),Fs.end()}executeDrawCallbacks(e,t){const n=cs;if(n.size>0){rs.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)}rs.end();for(const e of s)hs(e)}}}const Ds="__scene_transition_overlay__";class Os{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 Ls{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),ds(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=Ts.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){Ts.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 Hs{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},ds(Ds,()=>{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;rs.setLayer(9999),rs.setDepth(9999),rs.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,hs(Ds),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,hs(Ds),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 Os(t);this.scenes_.set(e,n);const s=new Ls(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource($n)?this.app_.getResource($n):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 Os(t);this.scenes_.set(e,n);const s=new Ls(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource($n)?this.app_.getResource($n):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())hs(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{Ts.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($n)&&(i.assetServer=this.app_.getResource($n));const r=await kn(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=js(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($n)?this.app_.getResource($n):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)dn.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{Ts.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 Xs=et(null,"SceneManager");function js(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Xs).getSceneStatus(t)&&n._fn(...s)}}}const Ys=Xt([nt(Xs),tt(rt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Ns={name:"SceneManager",build(e){const t=new Hs(e);e.insertResource(Xs,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Xs),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,Ys)}};class Vs{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 Vs}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(Xs).register(e),this}setInitialScene(e){return this.getResource(Xs).setInitial(e),this}tick(e){this.runner_||(this.runner_=new Gt(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 Gt(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,us();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=[Us,Is,Ms,ws,ln,ns];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let 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 Gs(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 Ks(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 Js=[];function Qs(e){if(e<Js.length)return Js[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 Js.push(t),t}function Zs(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=Ks(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=h*o,a=ti(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=si(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const u=ri(r.position.x,r.position.y,r.position.z),f=Qs(c.length);f.entity=e,f.viewProjection.set(ai(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 ei=new Float32Array(16);function ti(e,t,n,s,i,r){const o=ei;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 ni=new Float32Array(16);function si(e,t,n,s){const i=ni;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 ii=new Float32Array(16);function ri(e,t,n){const s=ii;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 oi=new Float32Array(16);function ai(e,t){const n=oi;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 li={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function ci(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 di=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 hi=null,ui=null;function fi(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 pi(e,t){switch(e){case li.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case li.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case li.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 gi(e,t){switch(e){case li.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case li.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case li.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 yi(e,t,n,s){switch(e){case li.BottomToTop:case li.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function mi(e,t,n,s){if(!e.has(t,di))return;const i=e.get(t,di),r=pi(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,di,i)}function _i(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function wi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function xi(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(wi(o.charCodeAt(0))&&s.length>0&&wi(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!wi(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 vi(e){let t=1;for(;t<e;)t*=2;return t}function bi(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 Si(e,t){if(hi&&ui){const e=hi.getUIRectComputedWidth(ui,t);if(e>0)return e}return e.size.x}function Mi(e,t){if(hi&&ui){const e=hi.getUIRectComputedHeight(ui,t);if(e>0)return e}return e.size.y}function Pi(e,t,n,s,i,r){if(!e.has(t,$e))return;const o=e.get(t,$e);let a,l;switch(n){case li.BottomToTop:case li.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 Ti(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 Ei(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Ci(e,t,n,s,i){if(!e.has(t,di))return;const r=e.get(t,di),o=ci(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 Ri(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 Ai=.1,ki=30,Ii={r:.3,g:.5,b:.8,a:1},Fi={Left:0,Center:1,Right:2},Bi={Top:0,Middle:1,Bottom:2},zi={Visible:0,Clip:1,Ellipsis:2},Ui=xe("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Fi.Left,verticalAlign:Bi.Top,wordWrap:!0,overflow:zi.Visible,lineHeight:1.2});class $i{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,vi(this.frameMaxW_)),e.height=Math.max(e.height,vi(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=vi(this.frameMaxW_),e.height=vi(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=xi(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===zi.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,vi(f)),s.height=Math.max(s.height,vi(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===zi.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 Bi.Top:x=d;break;case Bi.Middle:x=d+(p-2*d-w)/2;break;case Bi.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 Fi.Left:s=d;break;case Fi.Center:s=f/2;break;case Fi.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===zi.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 Fi.Left:return"left";case Fi.Center:return"center";case Fi.Right:return"right"}}}const Wi=Ri({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?Si(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Mi(e.uiRect,e.entity):0});class Di{build(e){Ce("Text",Ui);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new $i(t),s=e.world,i=new Map;e.addSystemToSchedule(Lt.PreUpdate,Xt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Ui));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Ui)){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([Ui]);for(const t of e){const e=s.get(t,Ui),r=s.has(t,di)?s.get(t,di):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Wi.changed(a,o)){if(s.has(t,$e)&&s.get(t,$e).texture!==ae)continue}fi(s,t);const l=r?{size:{x:Si(r,t),y:Mi(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,Wi.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Oi=new Di,Li=0,Hi=1,Xi=Ae("UIMask",{enabled:!0,mode:Li});function ji(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 Yi(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 Ni(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 Vi(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 Gi(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 Ki(e,t,n,s,i,r,o,a,l,c){const d=Gi(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 Ji(e,t,n,s,i,r,o){if(!e.has(t,di)||!e.has(t,Be))return null;const a=e.get(t,di),l=e.get(t,Be),c=Si(a,t)*l.worldScale.x,d=Mi(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=Gi(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 Qi(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Xi]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,Xi);n.enabled&&(h.add(e),n.mode===Hi?(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;Ti(t,e,e=>{if(i.has(e)){if(t.get(e,Xi).mode===Li)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,Xi).mode===Li){const e=Ji(t,n,r,o,a,l,c);e&&(s=ji(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=Ji(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;Ti(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 Zi{build(e){if(Ce("UIMask",Xi),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Qi(e.wasmModule,e.world))}}const er=new Zi,tr=Ae("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),nr=Ae("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),sr={Normal:0,Hovered:1,Pressed:2,Disabled:3},ir=xe("Button",{state:sr.Normal,transition:null});class rr{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 or=et(new rr,"UIEvents");class ar{build(e){Ce("UIRect",di);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){hi=e,ui=t}(n,s);e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Zt)],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,Xt([tt(Zt)],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,Xt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const lr=new ar;let cr=!1,dr=!1;function hr(e){cr=e}function ur(){return cr}function fr(){return!cr}function pr(e){dr=e}function gr(){return dr}const yr=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&&(Yi(t,e),n=!1),e)}}();function mr(e,t,n,s){t.emit(n,s,n),Ti(e,n,i=>{if(!e.has(i,tr))return!1;const r=e.get(i,tr);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class _r{build(e){Ce("Interactable",tr),Ce("Button",ir);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new rr;e.insertResource(or,i);let r=null,o=null;e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Kt),tt(Zt)],(e,a)=>{if(i.drain(),ur()&&!gr())return;const l=t.getEntitiesWithComponents([nr]);for(const e of l){const n=t.get(e,nr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,nr,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;yr.update(a.viewProjection);const u=Ni(d,h,yr.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,nr)){const e=t.get(r,nr);e.hovered=!1,t.insert(r,nr,e),i.emit(r,"hover_exit")}if(null!==_){Ei(t,_,nr);const e=t.get(_,nr);e.hovered=!0,t.insert(_,nr,e),i.emit(_,"hover_enter")}r=_}if(g&&null!==_){const e=t.get(_,nr);e.pressed=!0,e.justPressed=!0,t.insert(_,nr,e),o=_,mr(t,i,_,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,nr)){const e=t.get(o,nr);e.pressed=!1,e.justReleased=!0,t.insert(o,nr,e),mr(t,i,o,"release"),o===r&&mr(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(Lt.Update,Xt([],()=>{const e=t.getEntitiesWithComponents([ir]);for(const n of e){if(Ei(t,n,tr,{enabled:!0}),!t.has(n,nr))continue;const e=t.get(n,nr),s=t.get(n,ir),i=t.get(n,tr),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=sr.Pressed:e.hovered?s.state=sr.Hovered:s.state=sr.Normal:s.state=sr.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,$e)){const r=t.get(n,$e);r.color=_i(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,$e,r)}}},{name:"ButtonSystem"}))}}const wr=new _r,xr=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}),vr=xe("Focusable",{tabIndex:0,isFocused:!1});class br{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 Sr=et(new br,"FocusManager");class Mr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Ce("TextInput",xr),ur()&&!gr())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(Sr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,xr)?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,xr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(or).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,xr);s.focused=!1,s.dirty=!0;e.getResource(Sr).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,xr);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(or).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,xr);e.focused=!1,e.dirty=!0}e.getResource(Sr).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=vi(Math.max(i.width,d)),i.height=vi(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=xi(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=xi(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,Xt([tt(Sr)],e=>{const t=n.getEntitiesWithComponents([xr]);for(const e of t)Ei(n,e,vr,{tabIndex:0,isFocused:!1}),Ei(n,e,tr,{enabled:!0,blockRaycast:!0});const s=g();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,xr)){const e=n.get(M,xr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,xr);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,Xt([],()=>{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,xr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,xr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([xr,di]);for(const e of a){const t=n.get(e,xr);if(!t.dirty)continue;const s=n.get(e,di),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(fi(n,e),P(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Pr=new Mr,Tr={Simple:0,Sliced:1,Tiled:2,Filled:3},Er={Horizontal:0,Vertical:1},Cr={Left:0,Right:1,Bottom:2,Top:3},Rr=xe("Image",{texture:ae,color:{r:1,g:1,b:1,a:1},imageType:Tr.Simple,fillMethod:Er.Horizontal,fillOrigin:Cr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Ar=Ri({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?Si(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Mi(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const kr=new class{build(e){Ce("Image",Rr);const t=e.world,n=new Map;e.addSystemToSchedule(Lt.PreUpdate,Xt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Rr)||n.delete(e);const e=t.getEntitiesWithComponents([Rr]);for(const s of e){const e=t.get(s,Rr),i=t.has(s,di)?t.get(s,di):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!Ar.changed(o,r))continue;fi(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=Si(i,s),a.size.y=Mi(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Tr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Er.Horizontal?e.fillOrigin===Cr.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===Cr.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===Tr.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,Ar.take(r))}else a.color.a=0,t.insert(s,$e,a),n.set(s,Ar.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Ir=xe("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Fr=xe("ToggleGroup",{allowSwitchOff:!1});const Br=new class{build(e){Ce("Toggle",Ir),Ce("ToggleGroup",Fr);const t=e.world,n=new Set;e.addSystemToSchedule(Lt.Update,Xt([tt(or)],e=>{const s=t.getEntitiesWithComponents([Ir]);if(!ur()||gr()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Ir);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Ir,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,Ir);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(Ei(t,n,tr,{enabled:!0}),!t.has(n,nr))continue;const s=t.get(n,nr),i=t.get(n,Ir),o=t.get(n,tr);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,Fr);if(i.isOn&&o){if(!t.get(s,Fr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Ir,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,Ir);i.isOn&&(i.isOn=!1,t.insert(s,Ir,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,$e)){const e=t.get(n,$e);e.color=_i(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,$e,e)}}}for(const e of s){const n=t.get(e,Ir);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"]})}},zr=li,Ur=xe("ProgressBar",{value:0,fillEntity:0,direction:li.LeftToRight});function $r(e,t,n,s){if(!e.has(t,di))return;const i=e.get(t,di),r=n/2,o=s/2,a={left:-r,bottom:-o,right:r,top:o},l=ci(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 Wr{build(e){Ce("ProgressBar",Ur);const t=e.world;e.addSystemToSchedule(Lt.PreUpdate,Xt([],()=>{const e=t.getEntitiesWithComponents([Ur,di]);for(const n of e){const e=t.get(n,Ur);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,di),i=Math.max(0,Math.min(1,e.value));mi(t,e.fillEntity,e.direction,i);const r=Si(s,n),o=Mi(s,n);$r(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Dr=new Wr,Or=xe("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Lr=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 Hr=new class{build(e){Ce("Draggable",Or),Ce("DragState",Lr);const t=e.world,n=e.getResource(or);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Kt),tt(Zt)],(e,o)=>{if(ur()&&!gr())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Or,nr]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,Or).enabled)continue;if(t.get(s,nr).hovered){let e=0;t.has(s,$e)&&(e=t.get(s,$e).layer);const i=bi(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,Lr)||t.insert(n,Lr);const e=t.get(n,Lr),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,Lr)){t.get(s,Lr).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,Or);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,Lr).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,Lr))return void(r=null);const s=t.get(r,Lr),i=t.get(r,Or),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=Gi(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"}))}},Xr=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 jr(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 Yr(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 Nr=new class{build(e){Ce("ScrollView",Xr);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(Lt.PostUpdate,Xt([tt(Kt),tt(Zt),tt(rt)],(e,i,r)=>{const o=ur()&&!gr(),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([Xr,di]);for(const r of l){Ei(t,r,Xi,{enabled:!0,mode:Li});const l=t.get(r,Xr),c=t.get(r,di);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=Si(c,r),u=Mi(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,di)){const e=t.get(o,di);a=Si(e,o)||e.size.x,l=Mi(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){Ei(t,r,tr,{enabled:!0,blockRaycast:!0});const n=t.has(r,nr)?t.get(r,nr):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=jr(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=jr(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=jr(l.scrollY,0,y,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=jr(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=Yr(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)<Ai&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Ai?(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=Yr(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)<Ai&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Ai?(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"]})}},Vr=li,Gr=xe("Slider",{value:0,minValue:0,maxValue:1,direction:li.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function qr(e,t,n,s,i,r){const o=Si(s,i)*n.worldScale.x,a=Mi(s,i)*n.worldScale.y,l=Gi(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 li.LeftToRight:return o>0?(f-g)/o:0;case li.RightToLeft:return o>0?1-(f-g)/o:0;case li.BottomToTop:return a>0?(p-y)/a:0;case li.TopToBottom:return a>0?1-(p-y)/a:0}}function Kr(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case li.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case li.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case li.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case li.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class Jr{build(e){Ce("Slider",Gr);const t=e.world;let n=null;e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Kt),tt(Zt),tt(or)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([Gr,di]);for(const o of r){const r=t.get(o,Gr),a=t.get(o,di);if(!ur()||gr()){if(t.has(o,Be)){Ei(t,o,tr,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&Ei(t,r.handleEntity,tr,{enabled:!0,blockRaycast:!1});const l=t.get(o,Be),c=t.has(o,nr)?t.get(o,nr):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,nr)&&(d=t.get(r.handleEntity,nr).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,Gr,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=Si(a,o),h=Mi(a,o),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(mi(t,r.fillEntity,r.direction,c),Ci(t,r.fillEntity,u,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,di)){const e=t.get(r.handleEntity,di);Kr(e,r.direction,c),t.insert(r.handleEntity,di,e),Ci(t,r.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Qr=new Jr;const Zr=new class{build(e){Ce("Focusable",vr);const t=e.world,n=new br;e.insertResource(Sr,n),e.addSystemToSchedule(Lt.Update,Xt([tt(Kt),tt(or)],(e,s)=>{if(ur()&&!gr())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([vr]);for(const e of i){if(!t.has(e,nr))continue;t.get(e,nr).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,tr)){if(!t.get(n,tr).enabled)continue}const s=t.get(n,vr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const 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,vr)){t.get(i,vr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,vr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},eo=xe("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function to(){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 no=new class{build(e){Ce("SafeArea",eo);const t=e.world;let n=to(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=to(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=to(),s=!0});e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Zt)],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([eo,di]);for(const e of d){const s=t.get(e,eo),i=t.get(e,di),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,di,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},so=xe("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let io=null;function ro(e,t){if(!io)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=io.get(e);n?n.renderer=t:io.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const oo=new class{build(e){Ce("ListView",so);const t=e.world,n=new Map;io=n,e.addSystemToSchedule(Lt.PostUpdate,Xt([tt(Kt)],e=>{const s=ur()&&!gr();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([so,di]);for(const r of i){Ei(t,r,tr,{enabled:!0,blockRaycast:!0}),Ei(t,r,Xi,{enabled:!0,mode:Li});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,so),a=t.get(r,di),l=Mi(a,r),c=Si(a,r);if(!s){const n=t.has(r,nr)?t.get(r,nr):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,di,{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"]})}},ao=xe("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const lo=new class{build(e){Ce("Dropdown",ao);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*ki;t.insert(i,di,{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)*ki;t.insert(r,Ye,{value:`Option_${e}`}),t.insert(r,di,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*ki},offsetMax:{x:0,y:0},size:{x:o,y:ki},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:ki},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,tr,{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,Ui,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Fi.Left,verticalAlign:Bi.Middle,wordWrap:!1,overflow:zi.Clip,lineHeight:1.2}),t.insert(c,di,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:ki},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,Ui))return;const s=t.get(n,Ui);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,Ui,{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,tr)&&t.insert(e,tr,{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?{...Ii}:{r:.95,g:.95,b:.95,a:1};t.insert(s,$e,{texture:ae,color:i,size:{x:e.ddWidth,y:ki},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,nr))continue;if(t.get(n,nr).hovered)return!0}return!1}e.addSystemToSchedule(Lt.Update,Xt([tt(Kt),tt(or)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=ur()&&!gr(),p=t.getEntitiesWithComponents([ao]);for(const g of p){const p=t.get(g,ao);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;Ei(t,g,tr,{enabled:!0,blockRaycast:!0});const m=t.has(g,nr)?t.get(g,nr):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,nr))continue;if(t.get(n,nr).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,nr))continue;if(t.get(s,nr).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"]})}},co=0,ho=0,uo=2,fo=xe("LayoutGroup",{direction:co,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:ho,reverseOrder:!1});const po=new class{build(e){Ce("LayoutGroup",fo);const t=e.world;e.addSystemToSchedule(Lt.PreUpdate,Xt([],()=>{const e=t.getEntitiesWithComponents([fo,di,He]);for(const n of e){const e=t.get(n,fo),s=t.get(n,di),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,di)&&t.has(e,Be)&&r.push({entity:e,rect:t.get(e,di)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=Si(s,n),a=Mi(s,n),l=s.pivot.x,c=s.pivot.y,d=e.padding,h=e.direction===co;let u=0;for(let n=0;n<r.length;n++){const s=r[n],i=Si(s.rect,s.entity),f=Mi(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===ho?(1-c)*a-d.top-(1-g)*f:e.childAlignment===uo?-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===ho?-l*o+d.left+p*i:e.childAlignment===uo?(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 go{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(Lt.PostUpdate,Xt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const yo=new go;async function mo(e,t,n){const s=e.getResource(Xs);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function _o(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 wo=et({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),xo=et(null,"PhysicsAPI");function vo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function bo(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class So{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(wo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=_o(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,Xt([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=vo(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),Mo(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=vo(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=vo(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=bo(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(wo,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(xo,Po._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function Mo(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 Po{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(Po.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 To={nearest:0,linear:1},Eo={repeat:0,clamp:1,mirror:2};function Co(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=To[s.filterMode??"linear"]??1,a=Eo[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 Ro(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 Ao(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 ko(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]=Co(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=Pn(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=Ro(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=Co(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 So("",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=Co(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=dn.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=dn.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=An(e.world,n);if(l&&e.hasResource(Xs))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=Pn(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=Ao(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($n);t&&t.setAddressableManifest(a)}}function Io(e,t,n){return{name:e,data:t,async setup(){await ko(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Fo{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=Pn(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 Bo="__preview__";class zo{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(Xs);t.register({name:Bo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Bo),this.loadPromise_=t.load(Bo).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 Fo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await ko(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,Bo)}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(Xs).getScene(Bo),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(Xs);await e.switchTo(Bo),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 Uo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Fs.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Fs.getTargetTexture(n),width:e.width,height:e.height}},release(e){Fs.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Fs.releaseRenderTarget(e._handle),Uo.create({width:t,height:n,depth:!0})),begin(e,t){Fs.begin(t,e._handle)},end(){Fs.end()},getDepthTexture:e=>Fs.getTargetDepthTexture(e._handle)};var $o;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}($o||($o={}));class Wo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${$o[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case $o.Debug:console.debug(t,n);break;case $o.Info:console.log(t,n);break;case $o.Warn:console.warn(t,n);break;case $o.Error:console.error(t,n)}}}class Do{constructor(){this.handlers_=[],this.minLevel_=$o.Info,this.addHandler(new Wo)}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($o.Debug,e,t,n)}info(e,t,n){this.log($o.Info,e,t,n)}warn(e,t,n){this.log($o.Warn,e,t,n)}error(e,t,n){this.log($o.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 Oo=new Do;function Lo(){return Oo}function Ho(e){Oo.setMinLevel(e)}function Xo(e,t,n){Oo.debug(e,t,n)}function jo(e,t,n){Oo.info(e,t,n)}function Yo(e,t,n){Oo.warn(e,t,n)}function No(e,t,n){Oo.error(e,t,n)}const Vo=[Oi,er,lr,kr,Dr,wr,Hr,Nr,Qr,Br,Pr,Zr,no,oo,lo,po,yo];function Go(e,t){return function(e,t){const n=Vs.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ts(e),an(e),_s(e),Ss(e),ks(e),zs(e);const i=new Ws;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=Zs(e,s,t,i));const o=n.getResource(Zt);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(Zt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=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;Fs.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-r)/1e3;let h;if(Fs.resize(t,l),Ts.isInitialized()&&Ts.getPassCount()>0&&!Ts.isBypassed()&&Ts.resize(t,l),n.hasResource(Xs)){const e=n.getResource(Xs).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=Zs(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})}Fs.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Lt.First,l),n.addSystemToSchedule(Lt.Last,c),n.addPlugin(Dn),n.addPlugin(qn),n.addPlugin(Qt),n.addPlugin(Ns),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Vo,...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,Vs as App,Wn as AssetPlugin,On as AssetRefCounter,Un as AssetServer,$n as Assets,wn as AsyncCache,Xe as BitmapText,en as BlendMode,Qe as BodyType,qe as BoxCollider,ir as Button,sr 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,fs as DataType,Lr as DragState,Or as Draggable,rs as Draw,ao as Dropdown,It as EntityCommands,Wt as EventReader,Ot as EventReaderInstance,Ut as EventRegistry,$t as EventWriter,Dt as EventWriterInstance,li as FillDirection,Er as FillMethod,Cr as FillOrigin,Sr as FocusManager,br as FocusManagerState,vr as Focusable,$s as GLDebug,vs as Geometry,oe as INVALID_ENTITY,le as INVALID_FONT,ce as INVALID_MATERIAL,ae as INVALID_TEXTURE,Rr as Image,Tr as ImageType,Kt as Input,Jt as InputPlugin,qt as InputState,tr as Interactable,so as ListView,ze as LocalTransform,$o as LogLevel,Do as Logger,dn as Material,xn as MaterialLoader,wt as Mut,Ye as Name,Le as Parent,Po as Physics,wo as PhysicsEvents,So as PhysicsPlugin,Ts as PostProcess,Nn as PrefabServer,Vn as Prefabs,Gn as PrefabsPlugin,zo as PreviewPlugin,Ur as ProgressBar,zr as ProgressBarDirection,Wr as ProgressBarPlugin,ke as ProjectionType,Et as Query,Ct as QueryInstance,Rt as Removed,At as RemovedQueryInstance,Ws as RenderPipeline,Cs as RenderStage,Uo as RenderTexture,Fs as Renderer,tt as Res,nt as ResMut,Ge as RigidBody,ie as RuntimeConfig,eo as SafeArea,Fe as ScaleMode,Xs as SceneManager,Hs as SceneManagerState,Ne as SceneOwner,Lt as Schedule,Xr as ScrollView,_n as ShaderSources,Gr as Slider,Vr as SliderDirection,Jr as SliderPlugin,je as SpineAnimation,$e as Sprite,Gt as SystemRunner,Ui as Text,Fi as TextAlign,xr as TextInput,Mr as TextInputPlugin,zi as TextOverflow,Di as TextPlugin,$i as TextRenderer,Bi as TextVerticalAlign,rt as Time,Ir as Toggle,Be as Transform,Zt as UICameraInfo,rr as UIEventQueue,or as UIEvents,nr as UIInteraction,_r as UIInteractionPlugin,ar as UILayoutPlugin,Xi as UIMask,Zi as UIMaskPlugin,di as UIRect,go as UIRenderOrderPlugin,Oe as Velocity,Fo as WebAssetProvider,_t as World,Ue as WorldTransform,Nt as addStartupSystem,Yt as addSystem,Vt as addSystemToSchedule,mi as applyDirectionalFill,re as applyRuntimeConfig,Dn as assetPlugin,us as clearDrawCallbacks,Se as clearUserComponents,fe as color,pi as computeFillAnchors,yi as computeFillSize,gi as computeHandleAnchors,ci as computeUIRectLayout,Qi as createMaskProcessor,Io as createRuntimeSceneConfig,Go as createWebApp,Xo as debug,xe as defineComponent,Bt as defineEvent,et as defineResource,Xt as defineSystem,ve as defineTag,No as error,zn as findEntityByName,Gs as flushPendingSystems,S as getAddressableType,M as getAddressableTypeByEditorType,T as getAllAssetExtensions,A as getAssetMimeType,v as getAssetTypeEntry,Re as getComponent,Mn as getComponentAssetFieldDescriptors,Sn as getComponentAssetFields,Ve as getComponentDefaults,Pn as getComponentSpineFieldDescriptor,C as getCustomExtensions,b as getEditorType,Lo as getLogger,t as getPlatform,s as getPlatformType,be as getUserComponent,R as getWeChatPackOptions,jo as info,ts as initDrawAPI,zs as initGLDebugAPI,_s as initGeometryAPI,an as initMaterialAPI,Ss as initPostProcessAPI,ks as initRendererAPI,Qt as inputPlugin,Hn as instantiatePrefab,ji as intersectRects,Yi as invertMatrix4,Te as isBuiltinComponent,k as isCustomExtension,ur as isEditor,P as isKnownAssetExtension,n as isPlatformInitialized,gr as isPlayMode,fr as isRuntime,tn as isTextureRef,i as isWeChat,r as isWeb,Fn as loadComponent,_o as loadPhysicsModule,ko as loadRuntimeScene,An as loadSceneData,kn as loadSceneWithAssets,E as looksLikeAssetPath,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ki as pointInOBB,Vi as pointInWorldRect,qn as prefabsPlugin,Dr as progressBarPlugin,pe as quat,Ce as registerComponent,bn as registerComponentAssetFields,En as registerComponentEntityFields,ds as registerDrawCallback,Ln as registerEmbeddedAssets,mn as registerMaterialCallback,Cn as remapEntityFields,Ns as sceneManagerPlugin,Ni as screenToWorld,hr as setEditorMode,ro as setListViewRenderer,Ho as setLogLevel,pr as setPlayMode,dt as setWasmErrorHandler,ns as shutdownDrawAPI,Us as shutdownGLDebugAPI,ws as shutdownGeometryAPI,ln as shutdownMaterialAPI,Ms as shutdownPostProcessAPI,Is as shutdownRendererAPI,Qr as sliderPlugin,Pi as syncFillSpriteSize,Pr as textInputPlugin,Oi as textPlugin,mo as transitionTo,wr as uiInteractionPlugin,lr as uiLayoutPlugin,er as uiMaskPlugin,Vo as uiPlugins,yo as uiRenderOrderPlugin,Me as unregisterComponent,hs as unregisterDrawCallback,Bn as updateCameraAspectRatio,de as vec2,he as vec3,ue as vec4,Yo as warn,js 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/esengine.js b/desktop/public/sdk/esm/esengine.js
index 522d138f7..dc35ca7c9 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function 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}const p=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),r=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},o=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},d=()=>{e.onPointerUp(0)},h=t=>{const n=t;let s=n.deltaX,i=n.deltaY;1===n.deltaMode?(s*=16,i*=16):2===n.deltaMode&&(s*=window.innerWidth,i*=window.innerHeight),e.onWheel(s,i)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",r),n.addEventListener("mousedown",o),document.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",d),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",i),n.removeEventListener("mousemove",r),n.removeEventListener("mousedown",o),document.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",d),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},g=1920,y=1080,_=100,m=512,w={x:100,y:100},x="Arial",v=24,b=1.2,S=.5,M=1/60,P={x:0,y:-9.81},T=1/60,E="default",R={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function C(e){e.Text&&(e.Text._default.fontFamily=R.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=R.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=R.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=R.canvasMatchWidthOrHeight)}const A=0,k=4294967295,I=4294967295,F=0,B=(e=0,t=0)=>({x:e,y:t}),z=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),U=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),$=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),D=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function L(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(L);const t={};for(const n in e)t[n]=L(e[n]);return t}let W=0;function O(e,t){const n=++W,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?{...L(t),...e}:L(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 Y(e,t){const n=J.get(e)??X().get(e);if(n)return n;const s=O(e,t);return X().set(e,s),J.set(e,s),q(e,t,!1),s}function j(e){const t=J.get(e)??X().get(e);if(t)return t;const n=O(e,{});return X().set(e,n),J.set(e,n),q(e,{},!0),n}function N(e){return X().get(e)}function V(){const e=X();for(const t of e.keys())J.delete(t);e.clear()}function G(e){X().delete(e),J.delete(e)}function q(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function K(e){return!0===e._builtin}const J=new Map;function Q(e,t){J.set(e,t)}function Z(e){return J.get(e)??N(e)}function ee(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return J.set(e,n),n}const te={Perspective:0,Orthographic:1},ne={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},se={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ie=ee("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}}),re=ie,oe=ie,ae=ee("Sprite",{texture:k,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}),le=ee("Camera",{projectionType:te.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:ne.ColorAndDepth}),ce=ee("Canvas",{designResolution:{x:g,y:y},pixelsPerUnit:100,scaleMode:se.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),de=ee("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),he=ee("Parent",{entity:0}),ue=ee("Children",{entities:[]}),fe=ee("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:I,enabled:!0}),pe=ee("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}),ge=Y("Name",{value:""}),ye=Y("SceneOwner",{scene:"",persistent:!1});function _e(e){const t=Z(e);return t?L(t._default):null}const me=ee("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),we=ee("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),xe=ee("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ve=ee("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),be={Static:0,Kinematic:1,Dynamic:2};let Se=0;function Me(e,t){const n=++Se;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Pe(e){return{_type:"res",_resource:e}}function Te(e){return{_type:"res_mut",_resource:e}}class Ee{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 Re{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 Ee(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ce=Me({delta:0,elapsed:0,frameCount:0},"Time");function Ae(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=ke(t[e]),r=ke(i);"null"!==n&&"undefined"!==n&&(n!==r&&null!=i&&s.push({field:e,expected:n,actual:r,value:i}))}return s}function ke(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ie(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 Fe=null;function Be(e){Fe=e}function ze(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Fe&&Fe(e,t)}function Ue(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 $e=1;const De=new WeakMap;function Le(e){let t=De.get(e);return void 0===t&&(t=$e++,De.set(e,t)),t}const We=[];function Oe(e,t=[],n=[]){We.length=0;for(const t of e)We.push(Le(t));We.sort((e,t)=>e-t);let s=We.join(",");if(t.length>0){We.length=0;for(const e of t)We.push(Le(e));We.sort((e,t)=>e-t),s+="|+"+We.join(",")}if(n.length>0){We.length=0;for(const e of n)We.push(Le(e));We.sort((e,t)=>e-t),s+="|-"+We.join(",")}return s}class He{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 ze(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){ze(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){ze(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){ze(t,`removeParent(entity=${e})`)}}insert(e,t,n){return K(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(K(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Ue(n))}catch(n){ze(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 K(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return K(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(K(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return ze(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.");K(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=Ae(t._name,t._default,s);if(e.length>0)throw new Error(Ie(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,Ue(i))}catch(n){ze(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 ze(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 ze(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){ze(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=Ae(t._name,t._default,e);if(i.length>0)throw new Error(Ie(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 J)if(K(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=X();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??Oe(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(!K(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 Xe(e){return{_type:"mut",_component:e}}function Ye(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function je(e){return{_filterType:"added",_component:e}}function Ne(e){return{_filterType:"changed",_component:e}}function Ve(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Ge(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function qe(e){return Ye(e)||Ve(e)||Ge(e)?e._component:e}function Ke(e,t=[],n=[]){const s=[],i=[],r=[];return e.forEach((e,t)=>{Ye(e)&&s.push(t),Ve(e)?i.push({index:t,component:e._component}):Ge(e)&&r.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:r,with:(...s)=>Ke(e,[...t,...s],n),without:(...s)=>Ke(e,t,[...n,...s])}}function Je(...e){return Ke(e)}class Qe{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(qe),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=Oe(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 Ze(e){return{_type:"removed",_component:e}}class et{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 tt(){return{_type:"commands"}}class nt{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=K(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 st{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new nt(this,null);return this.spawned_.push(e),e}entity(e){return new nt(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"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 it(e){return{_id:Symbol(`Event_${e}`),_name:e}}class rt{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 ot{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new rt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new rt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function at(e){return{_type:"event_writer",_event:e}}function lt(e){return{_type:"event_reader",_event:e}}class ct{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class dt{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var ht;!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"}(ht||(ht={}));let ut=0;function ft(e,t,n){const s=++ut;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function pt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function gt(e){pt().push({schedule:ht.Update,system:e})}function yt(e){pt().push({schedule:ht.Startup,system:e})}function _t(e,t){pt().push({schedule:e,system:t})}class mt{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 st&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new Qe(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 st(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 ct(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new dt(n)}case"removed":{const t=e;return new et(this.world_,t._component,this.currentLastRunTick_)}default:throw new Error("Unknown system parameter type")}}}class wt{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 xt=Me(new wt,"Input");class vt{constructor(e){this.target_=e??null}build(e){const n=new wt;e.insertResource(xt,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(ht.Last,ft([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const bt=new vt,St=Me({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 Mt;function Pt(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"}(Mt||(Mt={}));let Tt=null,Et=null,Rt=1;const Ct=new Map;function At(e){Tt=e,Et=e.getResourceManager(),Wt()}function kt(){0!==zt&&Tt&&(Tt._free(zt),zt=0),Ct.clear(),Rt=1,Bt=!1,$t.clear(),Dt=null,Et=null,Tt=null}function It(){if(!Et)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Et}const Ft={createShader:(e,t)=>It().createShader(e,t),releaseShader(e){e>0&&It().releaseShader(e)},create(e){const t=Rt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Mt.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 Ct.set(t,n),t},get:e=>Ct.get(e),setUniform(e,t,n){const s=Ct.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,Tt?.invalidateMaterialCache(e))},getUniform(e,t){const n=Ct.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ct.get(e);n&&(n.blendMode=t,Tt?.invalidateMaterialCache(e))},getBlendMode(e){const t=Ct.get(e);return t?.blendMode??Mt.Normal},setDepthTest(e,t){const n=Ct.get(e);n&&(n.depthTest=t,Tt?.invalidateMaterialCache(e))},getShader(e){const t=Ct.get(e);return t?.shader??0},release(e){Ct.delete(e),Tt?.invalidateMaterialCache(e)},isValid:e=>Ct.has(e),releaseAll(){Ct.clear(),Tt?.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??Mt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ct.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Rt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ct.set(n,s),n},toAssetData(e,t){const n=Ct.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=Ct.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Bt=!1,zt=0;const Ut=16384,$t=new Map;let Dt=null;function Lt(e){const t=(0===zt&&Tt&&(zt=Tt._malloc(Ut)),zt);if(0===t||!Tt)return{ptr:0,count:0};let n=0,s=0;const i=Tt.HEAPU8,r=Tt.HEAPU32,o=Tt.HEAPF32;for(const[a,l]of e){if(Pt(l))continue;let e=$t.get(a);e||(Dt||(Dt=new TextEncoder),e=Dt.encode(a),$t.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>Ut){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Ut} 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 Wt(){if(!Tt||Bt)return;Tt.materialDataProvider=(e,t,n,s,i)=>{const r=Ct.get(e);if(!r)return Tt.HEAPU32[t>>2]=0,Tt.HEAPU32[n>>2]=0,Tt.HEAPU32[s>>2]=0,void(Tt.HEAPU32[i>>2]=0);Tt.HEAPU32[t>>2]=r.shader,Tt.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=Lt(r.uniforms);Tt.HEAPU32[s>>2]=o,Tt.HEAPU32[i>>2]=a},Bt=!0}const Ot={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 Ht{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 Xt{constructor(e,t=""){this.cache_=new Ht,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&&(Ft.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ft.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:Ft.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 Yt=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 jt(e,t){Yt.set(e,t)}function Nt(e){const t=Yt.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 Vt(e){return Yt.get(e)?.fields??[]}function Gt(e){return Yt.get(e)?.spine??null}const qt=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Kt(e,t){qt.set(e,t)}function Jt(e,t){const n=qt.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 Qt(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,ge,{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)Jt(i,n),nn(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 Zt(e,t){return Qt(e,t)}async function en(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 tn.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=Yt.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=[...tn.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=Yt.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=Qt(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 tn=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 nn(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=Z(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 sn(e,t){const n=e.getEntitiesWithComponents([le]);for(const s of n){const n=e.get(s,le);n&&(n.aspectRatio=t,e.insert(s,le,n))}}function rn(e,t){const n=e.getEntitiesWithComponents([ge]);for(const s of n){const n=e.get(s,ge);if(n&&n.value===t)return s}return null}const on=[{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}],an={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"},ln=new Map,cn=new Set;for(const e of on)for(const t of e.extensions)ln.set(t,e),cn.add(t);function dn(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function hn(e){return ln.get(dn(e))}function un(e){return hn(e)?.editorType??"unknown"}function fn(e){return hn(e)?.addressableType??null}function pn(e){for(const t of on)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function gn(e){return cn.has(e.toLowerCase())}function yn(){return cn}function _n(e){return"string"==typeof e&&(!!e.includes("/")&&gn(dn(e)))}function mn(){const e=[];for(const t of on)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function wn(){return mn().map(e=>({type:"suffix",value:e}))}function xn(e){return an[e.toLowerCase()]}function vn(e){const t=hn(e);return t?.wechatPackInclude??!1}class bn{constructor(e){this.textureCache_=new Ht,this.shaderCache_=new Ht,this.jsonCache_=new Ht,this.textCache_=new Ht,this.binaryCache_=new Ht,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ht,this.prefabCache_=new Ht,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(R.textCanvasSize,R.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 Xt(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(),Ft.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"===hn(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=hn(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 en(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 Ft.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 Ft.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 Sn=Me(null,"Assets");class Mn{build(e){const t=e.wasmModule;t?e.insertResource(Sn,new bn(t)):console.warn("AssetPlugin: No WASM module available")}}const Pn=new Mn;class Tn{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 En(e,t){const n=e.getResource(Sn);n&&n.registerEmbeddedAssets(t)}async function Rn(e,t,n){const{entities:s,rootId:i}=await An(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 en(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 Cn=10;async function An(e,t,n,s,i,r=0){if(r>Cn)throw new Error(`Prefab nesting depth exceeded ${Cn}. 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 An(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};kn(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 kn(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 In{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 Rn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Fn=Me(null,"Prefabs");class Bn{constructor(){this.name="PrefabsPlugin",this.dependencies=[Sn]}build(e){const t=e.getResource(Sn);e.insertResource(Fn,new In(e.world,t))}}const zn=new Bn;let Un=null,$n=0,Dn=0,Ln=0;const Wn=new Float32Array(256);function On(e){Un=e,$n=Un._malloc(64),Dn=Un._malloc(64),Ln=Un._malloc(1024)}function Hn(){Un&&($n&&(Un._free($n),$n=0),Dn&&(Un._free(Dn),Dn=0),Ln&&(Un._free(Ln),Ln=0)),Un=null}function Xn(){if(!Un)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Un}const Yn={r:1,g:1,b:1,a:1},jn={begin(e){const t=Xn();try{t.HEAPF32.set(e,$n/4),t.draw_begin($n)}catch(e){ze(e,"Draw.begin")}},end(){try{Xn().draw_end()}catch(e){ze(e,"Draw.end")}},line(e,t,n,s=1){try{Xn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ze(e,"Draw.line")}},rect(e,t,n,s=!0){try{Xn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ze(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{Xn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ze(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{Xn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ze(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{Xn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ze(e,"Draw.circleOutline")}},texture(e,t,n,s=Yn){try{Xn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){ze(e,"Draw.texture")}},textureRotated(e,t,n,s,i=Yn){try{Xn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){ze(e,"Draw.textureRotated")}},setLayer(e){Xn().draw_setLayer(e)},setDepth(e){Xn().draw_setDepth(e)},getDrawCallCount:()=>Un?Un.draw_getDrawCallCount():0,getPrimitiveCount:()=>Un?Un.draw_getPrimitiveCount():0,setBlendMode(e){Xn().draw_setBlendMode(e)},setDepthTest(e){Xn().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=Xn();s.HEAPF32.set(n,Dn/4),s.draw_mesh(e,t,Dn)}catch(n){ze(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Xn(),i=Ft.get(t);if(!i)return;if(jn.setBlendMode(i.blendMode),jn.setDepthTest(i.depthTest),0===i.uniforms.size)return void jn.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,Dn/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=Gn(t);if(!(s<0)){if(Pt(n))Wn[r++]=10,Wn[r++]=s,Wn[r++]=n.slot??e++,Wn[r++]=n.textureId;else if("number"==typeof n)Wn[r++]=1,Wn[r++]=s,Wn[r++]=n;else if(Array.isArray(n)){Wn[r++]=n.length,Wn[r++]=s;for(let e=0;e<n.length;e++)Wn[r++]=n[e]}else"w"in n?(Wn[r++]=4,Wn[r++]=s,Wn[r++]=n.x,Wn[r++]=n.y,Wn[r++]=n.z,Wn[r++]=n.w):"z"in n?(Wn[r++]=3,Wn[r++]=s,Wn[r++]=n.x,Wn[r++]=n.y,Wn[r++]=n.z):(Wn[r++]=2,Wn[r++]=s,Wn[r++]=n.x,Wn[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(Wn.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,Dn);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),Ln/4),s.draw_meshWithUniforms(e,i.shader,Dn,Ln,r)}catch(n){ze(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Nn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},Vn=new Set;function Gn(e){const t=Nn[e];return void 0!==t?t:(Vn.has(e)||(Vn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Nn).join(", ")}`)),-1)}const qn=new Map;function Kn(e,t,n){qn.set(e,{fn:t,scene:n??""})}function Jn(e){qn.delete(e)}function Qn(){qn.clear()}var Zn;!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"}(Zn||(Zn={}));let es=null,ts=0,ns=0,ss=0;function is(e){es=e,ts=es._malloc(262144),ns=es._malloc(65536),ss=es._malloc(256)}function rs(){es&&(ts&&es._free(ts),ns&&es._free(ns),ss&&es._free(ss),ts=0,ns=0,ss=0),es=null}function os(){if(!es)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return es}const as={create(e){const t=os(),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,ts/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,ss,i).set(r),t.geometry_init(n,ts,s,ss,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,ns,s).set(e.indices),t.geometry_setIndices16(n,ns,s)}else{new Uint32Array(t.HEAPU8.buffer,ns,s).set(e.indices),t.geometry_setIndices32(n,ns,s)}}return n},updateVertices(e,t,n=0){const s=os(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,ts/4),s.geometry_updateVertices(e,ts,i,n)},release(e){e>0&&os().geometry_release(e)},isValid:e=>!(!es||e<=0)&&es.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return as.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:Zn.Float2},{name:"a_texCoord",type:Zn.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 as.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Zn.Float2},{name:"a_texCoord",type:Zn.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 as.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:Zn.Float2},{name:"a_texCoord",type:Zn.Float2}],indices:new Uint16Array(o)})}};let ls=null;function cs(e){ls=e}function ds(){ls&&us.isInitialized()&&us.shutdown(),ls=null}function hs(){if(!ls)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ls}const us={init(e,t){try{return hs().postprocess_init(e,t)}catch(n){return ze(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{hs().postprocess_shutdown()}catch(e){ze(e,"PostProcess.shutdown")}},resize(e,t){try{hs().postprocess_resize(e,t)}catch(n){ze(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return hs().postprocess_addPass(e,t)}catch(t){return ze(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{hs().postprocess_removePass(e)}catch(t){ze(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{hs().postprocess_setPassEnabled(e,t)}catch(t){ze(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return hs().postprocess_isPassEnabled(e)}catch(t){return ze(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{hs().postprocess_setUniformFloat(e,t,n)}catch(n){ze(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{hs().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){ze(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{hs().postprocess_begin()}catch(e){ze(e,"PostProcess.begin")}},end(){try{hs().postprocess_end()}catch(e){ze(e,"PostProcess.end")}},getPassCount(){try{return hs().postprocess_getPassCount()}catch(e){return ze(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!ls)return!1;try{return ls.postprocess_isInitialized()}catch(e){return ze(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{hs().postprocess_setBypass(e)}catch(e){ze(e,"PostProcess.setBypass")}},isBypassed(){if(!ls)return!0;try{return ls.postprocess_isBypassed()}catch(e){return ze(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ft.createShader(fs,"#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:()=>Ft.createShader(fs,"#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:()=>Ft.createShader(fs,"#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:()=>Ft.createShader(fs,"#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")},fs="#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 ps;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(ps||(ps={}));let gs=null,ys=0;function _s(e){gs=e,ys=gs._malloc(64)}function ms(){gs&&ys&&(gs._free(ys),ys=0),gs=null}const ws={init(e,t){gs?.renderer_init(e,t)},resize(e,t){gs?.renderer_resize(e,t)},begin(e,t){if(gs&&ys)try{gs.HEAPF32.set(e,ys/4),gs.renderer_begin(ys,t??0)}catch(e){ze(e,"Renderer.begin")}},flush(){try{gs?.renderer_flush()}catch(e){ze(e,"Renderer.flush")}},end(){try{gs?.renderer_end()}catch(e){ze(e,"Renderer.end")}},submitSprites(e){if(gs)try{gs.renderer_submitSprites(e._cpp)}catch(e){ze(e,"Renderer.submitSprites")}},submitBitmapText(e){if(gs)try{gs.renderer_submitBitmapText(e._cpp)}catch(e){ze(e,"Renderer.submitBitmapText")}},submitSpine(e){if(gs)try{gs.renderer_submitSpine?.(e._cpp)}catch(e){ze(e,"Renderer.submitSpine")}},setStage(e){gs?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>gs?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){gs?.renderer_releaseTarget(e)},getTargetTexture:e=>gs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>gs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){gs?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){gs?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){gs?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){gs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>gs?gs.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>gs?{drawCalls:gs.renderer_getDrawCalls(),triangles:gs.renderer_getTriangles(),sprites:gs.renderer_getSprites(),text:gs.renderer_getText(),spine:gs.renderer_getSpine?.()??0,meshes:gs.renderer_getMeshes(),culled:gs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let xs=null;function vs(e){xs=e}function bs(){xs=null}const Ss={enable(){xs?.gl_enableErrorCheck(!0)},disable(){xs?.gl_enableErrorCheck(!1)},check:e=>xs?.gl_checkErrors(e)??0,diagnose(){xs?.renderer_diagnose()}};class Ms{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_||(ws.resize(s,i),us.isInitialized()&&us.getPassCount()>0&&us.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),ws.setViewport(0,0,s,i),ws.clearBuffers(3),ws.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),ws.submitSprites(t),ws.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):ws.submitSpine(t),ws.flush(),this.executeDrawCallbacks(n,r),ws.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;ws.setViewport(s.x,s.y,s.w,s.h),ws.setScissor(s.x,s.y,s.w,s.h,!0),ws.clearBuffers(i),ws.setScissor(0,0,0,0,!1),ws.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),ws.submitSprites(t),ws.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):ws.submitSpine(t),ws.flush(),this.executeDrawCallbacks(n,r),ws.end()}executeDrawCallbacks(e,t){const n=qn;if(n.size>0){jn.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)}jn.end();for(const e of s)Jn(e)}}}const Ps="__scene_transition_overlay__";class Ts{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 Es{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,ye,{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),Kn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=us.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){us.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,ye)){const n=this.app_.world.get(e,ye);n.persistent=t,this.app_.world.insert(e,ye,n)}}}class Rs{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??R.sceneTransitionDuration,i=t.color??{...R.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},Kn(Ps,()=>{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;jn.setLayer(9999),jn.setDepth(9999),jn.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,Jn(Ps),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Jn(Ps),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 Ts(t);this.scenes_.set(e,n);const s=new Es(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Sn)?this.app_.getResource(Sn):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 Ts(t);this.scenes_.set(e,n);const s=new Es(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Sn)?this.app_.getResource(Sn):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,ye)){if(this.app_.world.get(e,ye).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Jn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{us.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(Sn)&&(i.assetServer=this.app_.getResource(Sn));const r=await en(this.app_.world,s,i);e.loadedAssets=n;for(const n of r.values())e.entities.add(n),this.app_.world.insert(n,ye,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=As(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(Sn)?this.app_.getResource(Sn):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)Ft.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,ae)){const t=n.get(e,ae);s.sprite=t.color.a,t.color.a=0,n.insert(e,ae,t),i=!0}if(n.has(e,pe)){const t=n.get(e,pe);s.spine=t.color.a,t.color.a=0,n.insert(e,pe,t),i=!0}if(n.has(e,fe)){const t=n.get(e,fe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,fe,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,ae)){const t=n.get(e,ae);t.color.a=s.sprite,n.insert(e,ae,t)}if(void 0!==s.spine&&n.has(e,pe)){const t=n.get(e,pe);t.color.a=s.spine,n.insert(e,pe,t)}if(void 0!==s.bitmapText&&n.has(e,fe)){const t=n.get(e,fe);t.color.a=s.bitmapText,n.insert(e,fe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{us.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 Cs=Me(null,"SceneManager");function As(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Cs).getSceneStatus(t)&&n._fn(...s)}}}const ks=ft([Te(Cs),Pe(Ce)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Is={name:"SceneManager",build(e){const t=new Rs(e);e.insertResource(Cs,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Cs),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(ht.Startup,n),e.addSystemToSchedule(ht.Last,ks)}};class Fs{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 ot,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(ht.Last);else{this.runSchedule(ht.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ht.FixedPreUpdate),this.runSchedule(ht.FixedUpdate),this.runSchedule(ht.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(ht.PreUpdate),this.runSchedule(ht.Update),this.runSchedule(ht.PostUpdate),this.runSchedule(ht.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new He,this.resources_=new Re;for(const e of Object.values(ht))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Fs}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(ht.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ht.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 Be(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(Cs).register(e),this}setInitialScene(e){return this.getResource(Cs).setInitial(e),this}tick(e){this.runner_||(this.runner_=new mt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(Ce)||this.resources_.insert(Ce,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(ht.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(ht.First),this.runSchedule(ht.PreUpdate),this.runSchedule(ht.Update),this.runSchedule(ht.PostUpdate),this.runSchedule(ht.Last);this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new mt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(Ce,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(ht.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,Qn();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[bs,ms,ds,rs,kt,Hn];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(Ce);t.delta=e,t.elapsed+=e,t.frameCount++}}function Bs(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 zs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Us(e,t,n,s,i){const r=e*t/n,o=e;switch(s){case se.FixedWidth:return r;case se.FixedHeight:return o;case se.Expand:return Math.max(r,o);case se.Shrink:return Math.min(r,o);case se.Match:{const e=i;return Math.pow(r,1-e)*Math.pow(o,e)}default:return o}}const $s=[];function Ds(e){if(e<$s.length)return $s[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 $s.push(t),t}function Ls(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,ye);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===te.Orthographic){if(h=i.orthoSize,l){h=Us(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=h*o,a=Os(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=Xs(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const u=js(r.position.x,r.position.y,r.position.z),f=Ds(c.length);f.entity=e,f.viewProjection.set(Vs(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 Ws=new Float32Array(16);function Os(e,t,n,s,i,r){const o=Ws;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 Hs=new Float32Array(16);function Xs(e,t,n,s){const i=Hs;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 Ys=new Float32Array(16);function js(e,t,n){const s=Ys;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 Ns=new Float32Array(16);function Vs(e,t){const n=Ns;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 Gs={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function qs(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 _=Math.max(0,g-f),m=Math.max(0,y-p);return{originX:f+o.x*_,originY:p+o.y*m,width:_,height:m,rect:{left:f,bottom:p,right:g,top:y}}}const Ks=ee("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 Js=null,Qs=null;function Zs(e,t){e.has(t,ae)||e.insert(t,ae,{texture:k,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 ei(e,t){switch(e){case Gs.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Gs.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Gs.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function ti(e,t){switch(e){case Gs.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Gs.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Gs.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 ni(e,t,n,s){switch(e){case Gs.BottomToTop:case Gs.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function si(e,t,n,s){if(!e.has(t,Ks))return;const i=e.get(t,Ks),r=ei(n,s);i.anchorMin=r.anchorMin,i.anchorMax=r.anchorMax,i.offsetMin=r.offsetMin,i.offsetMax=r.offsetMax,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,Ks,i)}function ii(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function ri(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function oi(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(ri(o.charCodeAt(0))&&s.length>0&&ri(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!ri(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 ai(e){let t=1;for(;t<e;)t*=2;return t}function li(e,t){let n=0,s=t;for(;e.has(s,he);){const t=e.get(s,he).entity;if(!e.valid(t))break;n++,s=t}return n}function ci(e,t){if(Js&&Qs){const e=Js.getUIRectComputedWidth(Qs,t);if(e>0)return e}return e.size.x}function di(e,t){if(Js&&Qs){const e=Js.getUIRectComputedHeight(Qs,t);if(e>0)return e}return e.size.y}function hi(e,t,n,s,i,r){if(!e.has(t,ae))return;const o=e.get(t,ae);let a,l;switch(n){case Gs.BottomToTop:case Gs.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,ae,o))}function ui(e,t,n){let s=t;for(;e.has(s,he);){const t=e.get(s,he).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function fi(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function pi(e,t,n,s,i){if(!e.has(t,Ks))return;const r=e.get(t,Ks),o=qs(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,ae)){const n=e.get(t,ae);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,ae,n))}if(e.has(t,ie)){const n=e.get(t,ie);n.position.x=o.originX-s,n.position.y=o.originY-i,e.insert(t,ie,n)}}function gi(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 yi=.1,_i=30,mi={r:.3,g:.5,b:.8,a:1},wi={Left:0,Center:1,Right:2},xi={Top:0,Middle:1,Bottom:2},vi={Visible:0,Clip:1,Ellipsis:2},bi=Y("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:wi.Left,verticalAlign:xi.Top,wordWrap:!0,overflow:vi.Visible,lineHeight:1.2});class Si{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(R.textCanvasSize,R.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,ai(this.frameMaxW_)),e.height=Math.max(e.height,ai(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=ai(this.frameMaxW_),e.height=ai(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=oi(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===vi.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,ai(f)),s.height=Math.max(s.height,ai(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),_=Math.round(255*e.color.b),m=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===vi.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 xi.Top:x=d;break;case xi.Middle:x=d+(p-2*d-w)/2;break;case xi.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 wi.Left:s=d;break;case wi.Center:s=f/2;break;case wi.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===vi.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 wi.Left:return"left";case wi.Center:return"center";case wi.Right:return"right"}}}const Mi=gi({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?ci(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?di(e.uiRect,e.entity):0});class Pi{build(e){Q("Text",bi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Si(t),s=e.world,i=new Map;e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,bi));for(const e of i.keys())if(!s.valid(e)||!s.has(e,bi)){if(s.valid(e)&&s.has(e,ae)){const t=s.get(e,ae);s.insert(e,ae,{texture:k,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([bi]);for(const t of e){const e=s.get(t,bi),r=s.has(t,Ks)?s.get(t,Ks):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Mi.changed(a,o)){if(s.has(t,ae)&&s.get(t,ae).texture!==k)continue}Zs(s,t);const l=r?{size:{x:ci(r,t),y:di(r,t)}}:null,c=n.renderForEntity(t,e,l),d=s.get(t,ae);s.insert(t,ae,{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,Mi.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ti=new Pi,Ei=0,Ri=1,Ci=ee("UIMask",{enabled:!0,mode:Ei});function Ai(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 ki(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],_=e[14],m=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*_-f*g,E=h*m-p*g,R=u*_-f*y,C=u*m-p*y,A=f*m-p*_;let k=w*A-x*C+v*R+b*E-S*T+M*P;return 0===k||(k=1/k,n[0]=(l*A-c*C+d*R)*k,n[1]=(r*C-i*A-o*R)*k,n[2]=(y*M-_*S+m*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]=(_*v-g*M-m*x)*k,n[7]=(h*M-f*v+p*x)*k,n[8]=(a*C-l*E+d*P)*k,n[9]=(i*E-s*C-o*P)*k,n[10]=(g*S-y*v+m*w)*k,n[11]=(u*v-h*S-p*w)*k,n[12]=(l*T-a*R-c*P)*k,n[13]=(s*R-i*T+r*P)*k,n[14]=(y*x-g*b-_*w)*k,n[15]=(h*b-u*x+f*w)*k),n}function Ii(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 Fi(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 Bi(e,t){return 2*Math.atan2(e,t)}function zi(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 Ui(e,t,n,s,i,r,o,a,l,c){const d=Bi(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 $i(e,t,n,s,i,r,o){if(!e.has(t,Ks)||!e.has(t,ie))return null;const a=e.get(t,Ks),l=e.get(t,ie),c=ci(a,t)*l.worldScale.x,d=di(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),_=-d*p,m=d*(1-p),w=Bi(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+g*x-_*v,u+g*v+_*x],[h+y*x-_*v,u+y*v+_*x],[h+y*x-m*v,u+y*v+m*x],[h+g*x-m*v,u+g*v+m*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=zi(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 Di(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ci]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,Ci);n.enabled&&(h.add(e),n.mode===Ri?(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;ui(t,e,e=>{if(i.has(e)){if(t.get(e,Ci).mode===Ei)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,Ci).mode===Ei){const e=$i(t,n,r,o,a,l,c);e&&(s=Ai(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=$i(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;ui(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 Li{build(e){if(Q("UIMask",Ci),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Di(e.wasmModule,e.world))}}const Wi=new Li,Oi=ee("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Hi=ee("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Xi={Normal:0,Hovered:1,Pressed:2,Disabled:3},Yi=Y("Button",{state:Xi.Normal,transition:null});class ji{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 Ni=Me(new ji,"UIEvents");class Vi{build(e){Q("UIRect",Ks);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){Js=e,Qs=t}(n,s);e.addSystemToSchedule(ht.PreUpdate,ft([Pe(St)],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(ht.PostUpdate,ft([Pe(St)],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(ht.PostUpdate,ft([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Gi=new Vi;let qi=!1,Ki=!1;function Ji(e){qi=e}function Qi(){return qi}function Zi(){return!qi}function er(e){Ki=e}function tr(){return Ki}const nr=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&&(ki(t,e),n=!1),e)}}();function sr(e,t,n,s){t.emit(n,s,n),ui(e,n,i=>{if(!e.has(i,Oi))return!1;const r=e.get(i,Oi);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class ir{build(e){Q("Interactable",Oi),Q("Button",Yi);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new ji;e.insertResource(Ni,i);let r=null,o=null;e.addSystemToSchedule(ht.PreUpdate,ft([Pe(xt),Pe(St)],(e,a)=>{if(i.drain(),Qi()&&!tr())return;const l=t.getEntitiesWithComponents([Hi]);for(const e of l){const n=t.get(e,Hi);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Hi,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;nr.update(a.viewProjection);const u=Ii(d,h,nr.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 _=n.uiHitTest_getHitEntity(),m=4294967295===_?null:_;if(null===r||t.valid(r)||(r=null),r!==m){if(null!==r&&t.valid(r)&&t.has(r,Hi)){const e=t.get(r,Hi);e.hovered=!1,t.insert(r,Hi,e),i.emit(r,"hover_exit")}if(null!==m){fi(t,m,Hi);const e=t.get(m,Hi);e.hovered=!0,t.insert(m,Hi,e),i.emit(m,"hover_enter")}r=m}if(g&&null!==m){const e=t.get(m,Hi);e.pressed=!0,e.justPressed=!0,t.insert(m,Hi,e),o=m,sr(t,i,m,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,Hi)){const e=t.get(o,Hi);e.pressed=!1,e.justReleased=!0,t.insert(o,Hi,e),sr(t,i,o,"release"),o===r&&sr(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(ht.Update,ft([],()=>{const e=t.getEntitiesWithComponents([Yi]);for(const n of e){if(fi(t,n,Oi,{enabled:!0}),!t.has(n,Hi))continue;const e=t.get(n,Hi),s=t.get(n,Yi),i=t.get(n,Oi),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=Xi.Pressed:e.hovered?s.state=Xi.Hovered:s.state=Xi.Normal:s.state=Xi.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,ae)){const r=t.get(n,ae);r.color=ii(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,ae,r)}}},{name:"ButtonSystem"}))}}const rr=new ir,or=Y("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),ar=Y("Focusable",{tabIndex:0,isFocused:!1});class lr{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 cr=Me(new lr,"FocusManager");class dr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Q("TextInput",or),Qi()&&!tr())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(R.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(cr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,or)?s:null}const y=()=>{l||null===g()||v()},_=()=>{l=!0},m=()=>{l=!1,v()},w=t=>{const s=g();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,or);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(Ni).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,or);s.focused=!1,s.dirty=!0;e.getResource(cr).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,or);if(s.readOnly)return;let i=p.value;if(s.maxLength>0&&i.length>s.maxLength&&(i=i.substring(0,s.maxLength),p.value=i),i!==s.value){s.value=i;e.getResource(Ni).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,or);e.focused=!1,e.dirty=!0}e.getResource(cr).blur(),p.blur()}function S(){c=!0,d=0}p.addEventListener("input",y),p.addEventListener("compositionstart",_),p.addEventListener("compositionend",m),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",_),p.removeEventListener("compositionend",m),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=ai(Math.max(i.width,d)),i.height=ai(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),_=l.padding;if(l.multiline){const e=oi(r,p,d-2*_);let t=_;for(const n of e)r.fillText(n,_,t),t+=y}else{const e=(h-l.fontSize)/2;r.fillText(p,_,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=oi(r,l.value,d-2*_);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=_+r.measureText(c).width,n=_+o*y,s=y}else t=_+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 m=r.getImageData(0,0,d,h),w=new Uint8Array(m.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,ae);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,ae,S)}e.addSystemToSchedule(ht.Update,ft([Pe(cr)],e=>{const t=n.getEntitiesWithComponents([or]);for(const e of t)fi(n,e,ar,{tabIndex:0,isFocused:!1}),fi(n,e,Oi,{enabled:!0,blockRaycast:!0});const s=g();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,or)){const e=n.get(M,or);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,or);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(s),M=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{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,or).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,or)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([or,Ks]);for(const e of a){const t=n.get(e,or);if(!t.dirty)continue;const s=n.get(e,Ks),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(Zs(n,e),P(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const hr=new dr,ur={Simple:0,Sliced:1,Tiled:2,Filled:3},fr={Horizontal:0,Vertical:1},pr={Left:0,Right:1,Bottom:2,Top:3},gr=Y("Image",{texture:k,color:{r:1,g:1,b:1,a:1},imageType:ur.Simple,fillMethod:fr.Horizontal,fillOrigin:pr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),yr=gi({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?ci(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?di(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const _r=new class{build(e){Q("Image",gr);const t=e.world,n=new Map;e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,gr)||n.delete(e);const e=t.getEntitiesWithComponents([gr]);for(const s of e){const e=t.get(s,gr),i=t.has(s,Ks)?t.get(s,Ks):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!yr.changed(o,r))continue;Zs(t,s);const a=t.get(s,ae);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=ci(i,s),a.size.y=di(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===ur.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===fr.Horizontal?e.fillOrigin===pr.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===pr.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===ur.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,ae,a),n.set(s,yr.take(r))}else a.color.a=0,t.insert(s,ae,a),n.set(s,yr.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},mr=Y("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),wr=Y("ToggleGroup",{allowSwitchOff:!1});const xr=new class{build(e){Q("Toggle",mr),Q("ToggleGroup",wr);const t=e.world,n=new Set;e.addSystemToSchedule(ht.Update,ft([Pe(Ni)],e=>{const s=t.getEntitiesWithComponents([mr]);if(!Qi()||tr()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,mr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,mr,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,mr);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(fi(t,n,Oi,{enabled:!0}),!t.has(n,Hi))continue;const s=t.get(n,Hi),i=t.get(n,mr),o=t.get(n,Oi);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,wr);if(i.isOn&&o){if(!t.get(s,wr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,mr,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,mr);i.isOn&&(i.isOn=!1,t.insert(s,mr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,ae)){const e=t.get(n,ae);e.color=ii(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,ae,e)}}}for(const e of s){const n=t.get(e,mr);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,ae)){const e=t.get(n.graphicEntity,ae);e.enabled=n.isOn,t.insert(n.graphicEntity,ae,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},vr=Gs,br=Y("ProgressBar",{value:0,fillEntity:0,direction:Gs.LeftToRight});function Sr(e,t,n,s){if(!e.has(t,Ks))return;const i=e.get(t,Ks),r=n/2,o=s/2,a={left:-r,bottom:-o,right:r,top:o},l=qs(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,ae)){const n=e.get(t,ae);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,ae,n))}if(e.has(t,ie)){const n=e.get(t,ie),s=n.position;s.x===l.originX&&s.y===l.originY||(n.position={x:l.originX,y:l.originY,z:s.z})}}class Mr{build(e){Q("ProgressBar",br);const t=e.world;e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{const e=t.getEntitiesWithComponents([br,Ks]);for(const n of e){const e=t.get(n,br);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Ks),i=Math.max(0,Math.min(1,e.value));si(t,e.fillEntity,e.direction,i);const r=ci(s,n),o=di(s,n);Sr(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Pr=new Mr,Tr=Y("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Er=Y("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 Rr=new class{build(e){Q("Draggable",Tr),Q("DragState",Er);const t=e.world,n=e.getResource(Ni);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(ht.PreUpdate,ft([Pe(xt),Pe(St)],(e,o)=>{if(Qi()&&!tr())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Tr,Hi]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,Tr).enabled)continue;if(t.get(s,Hi).hovered){let e=0;t.has(s,ae)&&(e=t.get(s,ae).layer);const i=li(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,Er)||t.insert(n,Er);const e=t.get(n,Er),r=t.get(n,ie);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,Er)){t.get(s,Er).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,Tr);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,Er).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,Er))return void(r=null);const s=t.get(r,Er),i=t.get(r,Tr),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,ie)){const e=function(e,t,n,s){if(!e.has(t,he))return{x:n,y:s};const i=e.get(t,he).entity;if(!e.valid(i)||!e.has(i,ie))return{x:n,y:s};const r=e.get(i,ie),o=0!==r.worldScale.x?r.worldScale.x:1,a=0!==r.worldScale.y?r.worldScale.y:1,l=Bi(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,ie);n.position.x+=e.x,n.position.y+=e.y,t.insert(r,ie,n)}n.emit(r,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(r,"drag_end"),r=null)}},{name:"DragSystem"}))}},Cr=Y("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Ar(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 kr(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 Ir=new class{build(e){Q("ScrollView",Cr);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(ht.PostUpdate,ft([Pe(xt),Pe(St),Pe(Ce)],(e,i,r)=>{const o=Qi()&&!tr(),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([Cr,Ks]);for(const r of l){fi(t,r,Ci,{enabled:!0,mode:Ei});const l=t.get(r,Cr),c=t.get(r,Ks);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=ci(c,r),u=di(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,ue)){const e=t.get(l.contentEntity,ue).entities;let n=0,s=0,i=0,r=0;for(const o of e){if(!t.valid(o)||!t.has(o,ie))continue;const e=t.get(o,ie);let a=0,l=0,c=.5,d=.5;if(t.has(o,Ks)){const e=t.get(o,Ks);a=ci(e,o)||e.size.x,l=di(e,o)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(o,ae)){const e=t.get(o,ae);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){fi(t,r,Oi,{enabled:!0,blockRaycast:!0});const n=t.has(r,Hi)?t.get(r,Hi):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=Ar(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=Ar(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=Ar(l.scrollY,0,y,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Ar(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=kr(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)<yi&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>yi?(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=kr(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)<yi&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>yi?(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,ie)){const e=t.get(l.contentEntity,ie),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,ie,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Fr=Gs,Br=Y("Slider",{value:0,minValue:0,maxValue:1,direction:Gs.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function zr(e,t,n,s,i,r){const o=ci(s,i)*n.worldScale.x,a=di(s,i)*n.worldScale.y,l=Bi(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 Gs.LeftToRight:return o>0?(f-g)/o:0;case Gs.RightToLeft:return o>0?1-(f-g)/o:0;case Gs.BottomToTop:return a>0?(p-y)/a:0;case Gs.TopToBottom:return a>0?1-(p-y)/a:0}}function Ur(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Gs.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case Gs.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case Gs.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case Gs.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class $r{build(e){Q("Slider",Br);const t=e.world;let n=null;e.addSystemToSchedule(ht.PreUpdate,ft([Pe(xt),Pe(St),Pe(Ni)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([Br,Ks]);for(const o of r){const r=t.get(o,Br),a=t.get(o,Ks);if(!Qi()||tr()){if(t.has(o,ie)){fi(t,o,Oi,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&fi(t,r.handleEntity,Oi,{enabled:!0,blockRaycast:!1});const l=t.get(o,ie),c=t.has(o,Hi)?t.get(o,Hi):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,Hi)&&(d=t.get(r.handleEntity,Hi).justPressed),d&&(n=o),n===o&&e.isMouseButtonDown(0)){let e=zr(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,Br,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=ci(a,o),h=di(a,o),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(si(t,r.fillEntity,r.direction,c),pi(t,r.fillEntity,u,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,Ks)){const e=t.get(r.handleEntity,Ks);Ur(e,r.direction,c),t.insert(r.handleEntity,Ks,e),pi(t,r.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Dr=new $r;const Lr=new class{build(e){Q("Focusable",ar);const t=e.world,n=new lr;e.insertResource(cr,n),e.addSystemToSchedule(ht.Update,ft([Pe(xt),Pe(Ni)],(e,s)=>{if(Qi()&&!tr())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([ar]);for(const e of i){if(!t.has(e,Hi))continue;t.get(e,Hi).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,Oi)){if(!t.get(n,Oi).enabled)continue}const s=t.get(n,ar);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const 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,ar)){t.get(i,ar).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,ar).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},Wr=Y("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Or(){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 Hr=new class{build(e){Q("SafeArea",Wr);const t=e.world;let n=Or(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Or(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Or(),s=!0});e.addSystemToSchedule(ht.PreUpdate,ft([Pe(St)],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([Wr,Ks]);for(const e of d){const s=t.get(e,Wr),i=t.get(e,Ks),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,Ks,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},Xr=Y("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Yr=null;function jr(e,t){if(!Yr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Yr.get(e);n?n.renderer=t:Yr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const Nr=new class{build(e){Q("ListView",Xr);const t=e.world,n=new Map;Yr=n,e.addSystemToSchedule(ht.PostUpdate,ft([Pe(xt)],e=>{const s=Qi()&&!tr();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([Xr,Ks]);for(const r of i){fi(t,r,Oi,{enabled:!0,blockRaycast:!0}),fi(t,r,Ci,{enabled:!0,mode:Ei});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,Xr),a=t.get(r,Ks),l=di(a,r),c=ci(a,r);if(!s){const n=t.has(r,Hi)?t.get(r,Hi):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,ge,{value:`ListItem_${e}`}),t.insert(n,Ks,{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,ie)){const s=t.get(n,ie);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,ie,s)}}i.visibleStart=h,i.visibleEnd=u}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Vr=Y("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Gr=new class{build(e){Q("Dropdown",Vr);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,ie))return;const n=t.get(e,ie);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,ie,{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,ae)){const n=t.get(e,ae);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,ae,{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,ae),o=r.size.x,a=r.size.y;s.ddWidth=o;const l=n.options.length*_i;t.insert(i,Ks,{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,ie,{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,ae,{texture:k,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)*_i;t.insert(r,ge,{value:`Option_${e}`}),t.insert(r,Ks,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*_i},offsetMax:{x:0,y:0},size:{x:o,y:_i},pivot:{x:.5,y:.5}}),t.insert(r,ie,{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,ae,{texture:k,color:{r:.95,g:.95,b:.95,a:1},size:{x:o,y:_i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,Oi,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const c=t.spawn();t.insert(c,ie,{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,bi,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:wi.Left,verticalAlign:xi.Middle,wordWrap:!1,overflow:vi.Clip,lineHeight:1.2}),t.insert(c,Ks,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:_i},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,bi))return;const s=t.get(n,bi);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,bi,{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,Oi)&&t.insert(e,Oi,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,ae))){const s=t.get(e,ae);t.insert(e,ae,{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,ae))continue;const i=n===e.highlightIndex?{...mi}:{r:.95,g:.95,b:.95,a:1};t.insert(s,ae,{texture:k,color:i,size:{x:e.ddWidth,y:_i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function u(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,Hi))continue;if(t.get(n,Hi).hovered)return!0}return!1}e.addSystemToSchedule(ht.Update,ft([Pe(xt),Pe(Ni)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=Qi()&&!tr(),p=t.getEntitiesWithComponents([Vr]);for(const g of p){const p=t.get(g,Vr);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;fi(t,g,Oi,{enabled:!0,blockRaycast:!0});const _=t.has(g,Hi)?t.get(g,Hi):null;if(_?.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,Hi))continue;if(t.get(n,Hi).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,Hi))continue;if(t.get(s,Hi).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)&&(_?.hovered||u(y)||o(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},qr=0,Kr=0,Jr=2,Qr=Y("LayoutGroup",{direction:qr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Kr,reverseOrder:!1});const Zr=new class{build(e){Q("LayoutGroup",Qr);const t=e.world;e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{const e=t.getEntitiesWithComponents([Qr,Ks,ue]);for(const n of e){const e=t.get(n,Qr),s=t.get(n,Ks),i=t.get(n,ue);if(!i.entities||0===i.entities.length)continue;const r=[];for(const e of i.entities)t.valid(e)&&t.has(e,Ks)&&t.has(e,ie)&&r.push({entity:e,rect:t.get(e,Ks)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=ci(s,n),a=di(s,n),l=s.pivot.x,c=s.pivot.y,d=e.padding,h=e.direction===qr;let u=0;for(let n=0;n<r.length;n++){const s=r[n],i=ci(s.rect,s.entity),f=di(s.rect,s.entity),p=s.rect.pivot.x,g=s.rect.pivot.y;let y,_;h?(y=-l*o+d.left+u+p*i,_=e.childAlignment===Kr?(1-c)*a-d.top-(1-g)*f:e.childAlignment===Jr?-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===Kr?-l*o+d.left+p*i:e.childAlignment===Jr?(1-l)*o-d.right-(1-p)*i:(.5-l)*o+.5*(d.left-d.right)+(p-.5)*i,_=(1-c)*a-d.top-u-(1-g)*f,u+=f,n<r.length-1&&(u+=e.spacing));const m=t.get(s.entity,ie);m.position.x=y,m.position.y=_,t.insert(s.entity,ie,m)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};ee("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),ee("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class eo{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(ht.PostUpdate,ft([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const to=new eo;async function no(e,t,n){const s=e.getResource(Cs);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function so(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 io=Me({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ro=Me(null,"PhysicsAPI");function oo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ao(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class lo{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(io,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=so(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([ce]);for(const n of t){const t=e.world.get(n,ce);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(ht.PostUpdate,ft([Pe(Ce)],a=>{const l=o.getEntitiesWithComponents([me,ie]),c=new Set;for(const i of l){c.add(i);const a=o.get(i,me),l=o.get(i,ie);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=oo(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),co(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===be.Kinematic){const e=oo(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,ie);if(!d)continue;let h=a,u=l,f=c;if(e.world.has(o,he)){const t=e.world.get(o,he);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ie)){const n=e.world.get(t.entity,ie),s=oo(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=ao(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,ie,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(io,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(ro,ho._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function co(e,t,n){const s=e.world;if(s.has(n,we)){const e=s.get(n,we);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,xe)){const e=s.get(n,xe);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,ve)){const e=s.get(n,ve);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 ho{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(ho.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 uo={nearest:0,linear:1},fo={repeat:0,clamp:1,mirror:2};function po(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=uo[s.filterMode??"linear"]??1,a=fo[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 go(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 yo(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,_=l*u,m=l*f,w=c*f,x=d*h,v=d*u,b=d*f;return new Float32Array([(1-(_+w))*i,(g+b)*i,(y-v)*i,0,(g-b)*r,(1-(p+w))*r,(m+x)*r,0,(y+v)*o,(m-x)*o,(1-(p+_))*o,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function _o(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=Vt(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]=po(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=Gt(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"===hn(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=go(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=po(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??{...P},fixedTimestep:o?.fixedTimestep??T,subStepCount:o?.subStepCount??4};new lo("",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=Vt(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=hn(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=po(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=Vt(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=Ft.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=Ft.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=Vt(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=Zt(e.world,n);if(l&&e.hasResource(Cs))for(const t of p.values())e.world.insert(t,ye,{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=Gt(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=M);const c=e.world;for(const e in i){const r=Number(e),o=i[e],a=c.has(r,pe)?c.get(r,pe):null,d=!1!==a?.playing,h=a?.timeScale??1;d&&s.update(o,l*h);let u=0;if(c.has(r,ie)){const e=yo(c.get(r,ie),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),_=new Uint16Array(n.HEAPU8.buffer,d,r),m=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,m>>2),new Uint16Array(t.HEAPU8.buffer,w,r).set(_),t.renderer_submitTriangles(m,i,w,r,p,g,u),t._free(m),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(Sn);t&&t.setAddressableManifest(a)}}function mo(e,t,n){return{name:e,data:t,async setup(){await _o(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class wo{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=Gt(e.type);if(i){const s=e.data[i.skeletonField],r=e.data[i.atlasField];s&&("binary"===hn(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}const r=Vt(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=hn(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 xo="__preview__";class vo{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(Cs);t.register({name:xo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(xo),this.loadPromise_=t.load(xo).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 wo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await _o(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,xo)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([le]);for(const s of n){if(e.get(s,le).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([ce]);for(const i of s){const s=e.get(i,ce);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(Cs).getScene(xo),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,ie,o);const a={isActive:!0,projectionType:te.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:ne.ColorAndDepth};e.insert(r,le,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(Cs);await e.switchTo(xo),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 bo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=ws.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:ws.getTargetTexture(n),width:e.width,height:e.height}},release(e){ws.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(ws.releaseRenderTarget(e._handle),bo.create({width:t,height:n,depth:!0})),begin(e,t){ws.begin(t,e._handle)},end(){ws.end()},getDepthTexture:e=>ws.getTargetDepthTexture(e._handle)};var So;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(So||(So={}));class Mo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${So[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case So.Debug:console.debug(t,n);break;case So.Info:console.log(t,n);break;case So.Warn:console.warn(t,n);break;case So.Error:console.error(t,n)}}}class Po{constructor(){this.handlers_=[],this.minLevel_=So.Info,this.addHandler(new Mo)}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(So.Debug,e,t,n)}info(e,t,n){this.log(So.Info,e,t,n)}warn(e,t,n){this.log(So.Warn,e,t,n)}error(e,t,n){this.log(So.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 To=new Po;function Eo(){return To}function Ro(e){To.setMinLevel(e)}function Co(e,t,n){To.debug(e,t,n)}function Ao(e,t,n){To.info(e,t,n)}function ko(e,t,n){To.warn(e,t,n)}function Io(e,t,n){To.error(e,t,n)}const Fo=[Ti,Wi,Gi,_r,Pr,rr,Rr,Ir,Dr,xr,hr,Lr,Hr,Nr,Gr,Zr,to];function Bo(e,t){return function(e,t){const n=Fs.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),On(e),At(e),is(e),cs(e),_s(e),vs(e);const i=new Ms;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=Ls(e,s,t,i));const o=n.getResource(St);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(St,{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;ws.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-r)/1e3;let h;if(ws.resize(t,l),us.isInitialized()&&us.getPassCount()>0&&!us.isBypassed()&&us.resize(t,l),n.hasResource(Cs)){const e=n.getResource(Cs).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=Ls(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:zs,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})}ws.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(ht.First,l),n.addSystemToSchedule(ht.Last,c),n.addPlugin(Pn),n.addPlugin(zn),n.addPlugin(bt),n.addPlugin(Is),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Fo,...t})}e=p;export{je as Added,Fs as App,Mn as AssetPlugin,Tn as AssetRefCounter,bn as AssetServer,Sn as Assets,Ht as AsyncCache,fe as BitmapText,Mt as BlendMode,be as BodyType,we as BoxCollider,Yi as Button,Xi as ButtonState,le as Camera,ce as Canvas,ve as CapsuleCollider,Ne as Changed,ue as Children,xe as CircleCollider,ne as ClearFlags,tt as Commands,st as CommandsInstance,y as DEFAULT_DESIGN_HEIGHT,g as DEFAULT_DESIGN_WIDTH,M as DEFAULT_FALLBACK_DT,T as DEFAULT_FIXED_TIMESTEP,x as DEFAULT_FONT_FAMILY,v as DEFAULT_FONT_SIZE,P as DEFAULT_GRAVITY,b as DEFAULT_LINE_HEIGHT,S as DEFAULT_MAX_DELTA_TIME,_ as DEFAULT_PIXELS_PER_UNIT,E as DEFAULT_SPINE_SKIN,w as DEFAULT_SPRITE_SIZE,m as DEFAULT_TEXT_CANVAS_SIZE,Zn as DataType,Er as DragState,Tr as Draggable,jn as Draw,Vr as Dropdown,nt as EntityCommands,lt as EventReader,dt as EventReaderInstance,ot as EventRegistry,at as EventWriter,ct as EventWriterInstance,Gs as FillDirection,fr as FillMethod,pr as FillOrigin,cr as FocusManager,lr as FocusManagerState,ar as Focusable,Ss as GLDebug,as as Geometry,A as INVALID_ENTITY,I as INVALID_FONT,F as INVALID_MATERIAL,k as INVALID_TEXTURE,gr as Image,ur as ImageType,xt as Input,vt as InputPlugin,wt as InputState,Oi as Interactable,Xr as ListView,re as LocalTransform,So as LogLevel,Po as Logger,Ft as Material,Xt as MaterialLoader,Xe as Mut,ge as Name,he as Parent,ho as Physics,io as PhysicsEvents,lo as PhysicsPlugin,us as PostProcess,In as PrefabServer,Fn as Prefabs,Bn as PrefabsPlugin,vo as PreviewPlugin,br as ProgressBar,vr as ProgressBarDirection,Mr as ProgressBarPlugin,te as ProjectionType,Je as Query,Qe as QueryInstance,Ze as Removed,et as RemovedQueryInstance,Ms as RenderPipeline,ps as RenderStage,bo as RenderTexture,ws as Renderer,Pe as Res,Te as ResMut,me as RigidBody,R as RuntimeConfig,Wr as SafeArea,se as ScaleMode,Cs as SceneManager,Rs as SceneManagerState,ye as SceneOwner,ht as Schedule,Cr as ScrollView,Ot as ShaderSources,Br as Slider,Fr as SliderDirection,$r as SliderPlugin,pe as SpineAnimation,ae as Sprite,mt as SystemRunner,bi as Text,wi as TextAlign,or as TextInput,dr as TextInputPlugin,vi as TextOverflow,Pi as TextPlugin,Si as TextRenderer,xi as TextVerticalAlign,Ce as Time,mr as Toggle,ie as Transform,St as UICameraInfo,ji as UIEventQueue,Ni as UIEvents,Hi as UIInteraction,ir as UIInteractionPlugin,Vi as UILayoutPlugin,Ci as UIMask,Li as UIMaskPlugin,Ks as UIRect,eo as UIRenderOrderPlugin,de as Velocity,wo as WebAssetProvider,He as World,oe as WorldTransform,yt as addStartupSystem,gt as addSystem,_t as addSystemToSchedule,si as applyDirectionalFill,C as applyRuntimeConfig,Pn as assetPlugin,Qn as clearDrawCallbacks,V as clearUserComponents,$ as color,ei as computeFillAnchors,ni as computeFillSize,ti as computeHandleAnchors,qs as computeUIRectLayout,Di as createMaskProcessor,mo as createRuntimeSceneConfig,Bo as createWebApp,Co as debug,Y as defineComponent,it as defineEvent,Me as defineResource,ft as defineSystem,j as defineTag,Io as error,rn as findEntityByName,Bs as flushPendingSystems,fn as getAddressableType,pn as getAddressableTypeByEditorType,yn as getAllAssetExtensions,xn as getAssetMimeType,hn as getAssetTypeEntry,Z as getComponent,Vt as getComponentAssetFieldDescriptors,Nt as getComponentAssetFields,_e as getComponentDefaults,Gt as getComponentSpineFieldDescriptor,mn as getCustomExtensions,un as getEditorType,Eo as getLogger,t as getPlatform,s as getPlatformType,N as getUserComponent,wn as getWeChatPackOptions,Ao as info,On as initDrawAPI,vs as initGLDebugAPI,is as initGeometryAPI,At as initMaterialAPI,cs as initPostProcessAPI,_s as initRendererAPI,bt as inputPlugin,Rn as instantiatePrefab,Ai as intersectRects,ki as invertMatrix4,K as isBuiltinComponent,vn as isCustomExtension,Qi as isEditor,gn as isKnownAssetExtension,n as isPlatformInitialized,tr as isPlayMode,Zi as isRuntime,Pt as isTextureRef,i as isWeChat,r as isWeb,nn as loadComponent,so as loadPhysicsModule,_o as loadRuntimeScene,Zt as loadSceneData,en as loadSceneWithAssets,_n as looksLikeAssetPath,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ui as pointInOBB,Fi as pointInWorldRect,zn as prefabsPlugin,Pr as progressBarPlugin,D as quat,Q as registerComponent,jt as registerComponentAssetFields,Kt as registerComponentEntityFields,Kn as registerDrawCallback,En as registerEmbeddedAssets,Wt as registerMaterialCallback,Jt as remapEntityFields,Is as sceneManagerPlugin,Ii as screenToWorld,Ji as setEditorMode,jr as setListViewRenderer,Ro as setLogLevel,er as setPlayMode,Be as setWasmErrorHandler,Hn as shutdownDrawAPI,bs as shutdownGLDebugAPI,rs as shutdownGeometryAPI,kt as shutdownMaterialAPI,ds as shutdownPostProcessAPI,ms as shutdownRendererAPI,Dr as sliderPlugin,hi as syncFillSpriteSize,hr as textInputPlugin,Ti as textPlugin,no as transitionTo,rr as uiInteractionPlugin,Gi as uiLayoutPlugin,Wi as uiMaskPlugin,Fo as uiPlugins,to as uiRenderOrderPlugin,G as unregisterComponent,Jn as unregisterDrawCallback,sn as updateCameraAspectRatio,B as vec2,z as vec3,U as vec4,ko as warn,As as wrapSceneSystem};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function i(){return"wechat"===e?.name}function 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}const p=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),r=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},o=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},d=()=>{e.onPointerUp(0)},h=t=>{const n=t;let s=n.deltaX,i=n.deltaY;1===n.deltaMode?(s*=16,i*=16):2===n.deltaMode&&(s*=window.innerWidth,i*=window.innerHeight),e.onWheel(s,i)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",r),n.addEventListener("mousedown",o),document.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",d),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",i),n.removeEventListener("mousemove",r),n.removeEventListener("mousedown",o),document.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",d),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},g=1920,y=1080,_=100,m=512,w={x:100,y:100},x="Arial",v=24,b=1.2,S=.5,M=1/60,P={x:0,y:-9.81},T=1/60,E="default",R={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function C(e){e.Text&&(e.Text._default.fontFamily=R.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=R.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=R.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=R.canvasMatchWidthOrHeight)}const A=0,k=4294967295,I=4294967295,F=0,B=(e=0,t=0)=>({x:e,y:t}),z=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),U=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),$=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),D=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function L(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(L);const t={};for(const n in e)t[n]=L(e[n]);return t}let W=0;function O(e,t){const n=++W,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?{...L(t),...e}:L(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 Y(e,t){const n=J.get(e)??X().get(e);if(n)return n;const s=O(e,t);return X().set(e,s),J.set(e,s),q(e,t,!1),s}function j(e){const t=J.get(e)??X().get(e);if(t)return t;const n=O(e,{});return X().set(e,n),J.set(e,n),q(e,{},!0),n}function N(e){return X().get(e)}function V(){const e=X();for(const t of e.keys())J.delete(t);e.clear()}function G(e){X().delete(e),J.delete(e)}function q(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function K(e){return!0===e._builtin}const J=new Map;function Q(e,t){J.set(e,t)}function Z(e){return J.get(e)??N(e)}function ee(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return J.set(e,n),n}const te={Perspective:0,Orthographic:1},ne={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},se={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ie=ee("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}}),re=ie,oe=ie,ae=ee("Sprite",{texture:k,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}),le=ee("Camera",{projectionType:te.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:ne.ColorAndDepth}),ce=ee("Canvas",{designResolution:{x:g,y:y},pixelsPerUnit:100,scaleMode:se.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),de=ee("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),he=ee("Parent",{entity:0}),ue=ee("Children",{entities:[]}),fe=ee("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:I,enabled:!0}),pe=ee("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}),ge=Y("Name",{value:""}),ye=Y("SceneOwner",{scene:"",persistent:!1});function _e(e){const t=Z(e);return t?L(t._default):null}const me=ee("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),we=ee("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),xe=ee("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ve=ee("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),be={Static:0,Kinematic:1,Dynamic:2};let Se=0;function Me(e,t){const n=++Se;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Pe(e){return{_type:"res",_resource:e}}function Te(e){return{_type:"res_mut",_resource:e}}class Ee{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 Re{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 Ee(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ce=Me({delta:0,elapsed:0,frameCount:0},"Time");function Ae(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=ke(t[e]),r=ke(i);"null"!==n&&"undefined"!==n&&(n!==r&&null!=i&&s.push({field:e,expected:n,actual:r,value:i}))}return s}function ke(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ie(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 Fe=null;function Be(e){Fe=e}function ze(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Fe&&Fe(e,t)}function Ue(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 $e=1;const De=new WeakMap;function Le(e){let t=De.get(e);return void 0===t&&(t=$e++,De.set(e,t)),t}const We=[];function Oe(e,t=[],n=[]){We.length=0;for(const t of e)We.push(Le(t));We.sort((e,t)=>e-t);let s=We.join(",");if(t.length>0){We.length=0;for(const e of t)We.push(Le(e));We.sort((e,t)=>e-t),s+="|+"+We.join(",")}if(n.length>0){We.length=0;for(const e of n)We.push(Le(e));We.sort((e,t)=>e-t),s+="|-"+We.join(",")}return s}class He{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 ze(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){ze(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){ze(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){ze(t,`removeParent(entity=${e})`)}}insert(e,t,n){return K(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(K(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Ue(n))}catch(n){ze(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 K(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return K(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(K(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return ze(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.");K(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=Ae(t._name,t._default,s);if(e.length>0)throw new Error(Ie(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,Ue(i))}catch(n){ze(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 ze(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 ze(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){ze(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=Ae(t._name,t._default,e);if(i.length>0)throw new Error(Ie(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 J)if(K(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=X();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??Oe(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(!K(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 Xe(e){return{_type:"mut",_component:e}}function Ye(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function je(e){return{_filterType:"added",_component:e}}function Ne(e){return{_filterType:"changed",_component:e}}function Ve(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Ge(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function qe(e){return Ye(e)||Ve(e)||Ge(e)?e._component:e}function Ke(e,t=[],n=[]){const s=[],i=[],r=[];return e.forEach((e,t)=>{Ye(e)&&s.push(t),Ve(e)?i.push({index:t,component:e._component}):Ge(e)&&r.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:r,with:(...s)=>Ke(e,[...t,...s],n),without:(...s)=>Ke(e,t,[...n,...s])}}function Je(...e){return Ke(e)}class Qe{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(qe),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=Oe(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 Ze(e){return{_type:"removed",_component:e}}class et{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 tt(){return{_type:"commands"}}class nt{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=K(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 st{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new nt(this,null);return this.spawned_.push(e),e}entity(e){return new nt(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"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 it(e){return{_id:Symbol(`Event_${e}`),_name:e}}class rt{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 ot{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new rt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new rt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function at(e){return{_type:"event_writer",_event:e}}function lt(e){return{_type:"event_reader",_event:e}}class ct{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class dt{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var ht;!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"}(ht||(ht={}));let ut=0;function ft(e,t,n){const s=++ut;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function pt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function gt(e){pt().push({schedule:ht.Update,system:e})}function yt(e){pt().push({schedule:ht.Startup,system:e})}function _t(e,t){pt().push({schedule:e,system:t})}class mt{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 st&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new Qe(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 st(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 ct(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new dt(n)}case"removed":{const t=e;return new et(this.world_,t._component,this.currentLastRunTick_)}default:throw new Error("Unknown system parameter type")}}}class wt{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 xt=Me(new wt,"Input");class vt{constructor(e){this.target_=e??null}build(e){const n=new wt;e.insertResource(xt,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(ht.Last,ft([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const bt=new vt,St=Me({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 Mt;function Pt(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"}(Mt||(Mt={}));let Tt=null,Et=null,Rt=1;const Ct=new Map;function At(e){Tt=e,Et=e.getResourceManager(),Wt()}function kt(){0!==zt&&Tt&&(Tt._free(zt),zt=0),Ct.clear(),Rt=1,Bt=!1,$t.clear(),Dt=null,Et=null,Tt=null}function It(){if(!Et)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Et}const Ft={createShader:(e,t)=>It().createShader(e,t),releaseShader(e){e>0&&It().releaseShader(e)},create(e){const t=Rt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Mt.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 Ct.set(t,n),t},get:e=>Ct.get(e),setUniform(e,t,n){const s=Ct.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,Tt?.invalidateMaterialCache(e))},getUniform(e,t){const n=Ct.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ct.get(e);n&&(n.blendMode=t,Tt?.invalidateMaterialCache(e))},getBlendMode(e){const t=Ct.get(e);return t?.blendMode??Mt.Normal},setDepthTest(e,t){const n=Ct.get(e);n&&(n.depthTest=t,Tt?.invalidateMaterialCache(e))},getShader(e){const t=Ct.get(e);return t?.shader??0},release(e){Ct.delete(e),Tt?.invalidateMaterialCache(e)},isValid:e=>Ct.has(e),releaseAll(){Ct.clear(),Tt?.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??Mt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ct.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Rt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ct.set(n,s),n},toAssetData(e,t){const n=Ct.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=Ct.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Bt=!1,zt=0;const Ut=16384,$t=new Map;let Dt=null;function Lt(e){const t=(0===zt&&Tt&&(zt=Tt._malloc(Ut)),zt);if(0===t||!Tt)return{ptr:0,count:0};let n=0,s=0;const i=Tt.HEAPU8,r=Tt.HEAPU32,o=Tt.HEAPF32;for(const[a,l]of e){if(Pt(l))continue;let e=$t.get(a);e||(Dt||(Dt=new TextEncoder),e=Dt.encode(a),$t.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>Ut){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Ut} 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 Wt(){if(!Tt||Bt)return;Tt.materialDataProvider=(e,t,n,s,i)=>{const r=Ct.get(e);if(!r)return Tt.HEAPU32[t>>2]=0,Tt.HEAPU32[n>>2]=0,Tt.HEAPU32[s>>2]=0,void(Tt.HEAPU32[i>>2]=0);Tt.HEAPU32[t>>2]=r.shader,Tt.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=Lt(r.uniforms);Tt.HEAPU32[s>>2]=o,Tt.HEAPU32[i>>2]=a},Bt=!0}const Ot={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 Ht{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 Xt{constructor(e,t=""){this.cache_=new Ht,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&&(Ft.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ft.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:Ft.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 Yt=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 jt(e,t){Yt.set(e,t)}function Nt(e){const t=Yt.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 Vt(e){return Yt.get(e)?.fields??[]}function Gt(e){return Yt.get(e)?.spine??null}const qt=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Kt(e,t){qt.set(e,t)}function Jt(e,t){const n=qt.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 Qt(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,ge,{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)Jt(i,n),nn(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 Zt(e,t){return Qt(e,t)}async function en(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 tn.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=Yt.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=[...tn.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=Yt.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=Qt(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 tn=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 nn(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=Z(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 sn(e,t){const n=e.getEntitiesWithComponents([le]);for(const s of n){const n=e.get(s,le);n&&(n.aspectRatio=t,e.insert(s,le,n))}}function rn(e,t){const n=e.getEntitiesWithComponents([ge]);for(const s of n){const n=e.get(s,ge);if(n&&n.value===t)return s}return null}const on=[{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}],an={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"},ln=new Map,cn=new Set;for(const e of on)for(const t of e.extensions)ln.set(t,e),cn.add(t);function dn(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function hn(e){return ln.get(dn(e))}function un(e){return hn(e)?.editorType??"unknown"}function fn(e){return hn(e)?.addressableType??null}function pn(e){for(const t of on)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function gn(e){return cn.has(e.toLowerCase())}function yn(){return cn}function _n(e){return"string"==typeof e&&(!!e.includes("/")&&gn(dn(e)))}function mn(){const e=[];for(const t of on)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function wn(){return mn().map(e=>({type:"suffix",value:e}))}function xn(e){return an[e.toLowerCase()]}function vn(e){const t=hn(e);return t?.wechatPackInclude??!1}class bn{constructor(e){this.textureCache_=new Ht,this.shaderCache_=new Ht,this.jsonCache_=new Ht,this.textCache_=new Ht,this.binaryCache_=new Ht,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ht,this.prefabCache_=new Ht,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(R.textCanvasSize,R.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 Xt(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(),Ft.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"===hn(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=hn(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 en(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 Ft.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 Ft.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 Sn=Me(null,"Assets");class Mn{build(e){const t=e.wasmModule;t?e.insertResource(Sn,new bn(t)):console.warn("AssetPlugin: No WASM module available")}}const Pn=new Mn;class Tn{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 En(e,t){const n=e.getResource(Sn);n&&n.registerEmbeddedAssets(t)}async function Rn(e,t,n){const{entities:s,rootId:i}=await An(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 en(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 Cn=10;async function An(e,t,n,s,i,r=0){if(r>Cn)throw new Error(`Prefab nesting depth exceeded ${Cn}. 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 An(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};kn(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 kn(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 In{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 Rn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Fn=Me(null,"Prefabs");class Bn{constructor(){this.name="PrefabsPlugin",this.dependencies=[Sn]}build(e){const t=e.getResource(Sn);e.insertResource(Fn,new In(e.world,t))}}const zn=new Bn;let Un=null,$n=0,Dn=0,Ln=0;const Wn=new Float32Array(256);function On(e){Un=e,$n=Un._malloc(64),Dn=Un._malloc(64),Ln=Un._malloc(1024)}function Hn(){Un&&($n&&(Un._free($n),$n=0),Dn&&(Un._free(Dn),Dn=0),Ln&&(Un._free(Ln),Ln=0)),Un=null}function Xn(){if(!Un)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Un}const Yn={r:1,g:1,b:1,a:1},jn={begin(e){const t=Xn();try{t.HEAPF32.set(e,$n/4),t.draw_begin($n)}catch(e){ze(e,"Draw.begin")}},end(){try{Xn().draw_end()}catch(e){ze(e,"Draw.end")}},line(e,t,n,s=1){try{Xn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ze(e,"Draw.line")}},rect(e,t,n,s=!0){try{Xn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ze(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{Xn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ze(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{Xn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ze(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{Xn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ze(e,"Draw.circleOutline")}},texture(e,t,n,s=Yn){try{Xn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){ze(e,"Draw.texture")}},textureRotated(e,t,n,s,i=Yn){try{Xn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){ze(e,"Draw.textureRotated")}},setLayer(e){Xn().draw_setLayer(e)},setDepth(e){Xn().draw_setDepth(e)},getDrawCallCount:()=>Un?Un.draw_getDrawCallCount():0,getPrimitiveCount:()=>Un?Un.draw_getPrimitiveCount():0,setBlendMode(e){Xn().draw_setBlendMode(e)},setDepthTest(e){Xn().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=Xn();s.HEAPF32.set(n,Dn/4),s.draw_mesh(e,t,Dn)}catch(n){ze(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Xn(),i=Ft.get(t);if(!i)return;if(jn.setBlendMode(i.blendMode),jn.setDepthTest(i.depthTest),0===i.uniforms.size)return void jn.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,Dn/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=Gn(t);if(!(s<0)){if(Pt(n))Wn[r++]=10,Wn[r++]=s,Wn[r++]=n.slot??e++,Wn[r++]=n.textureId;else if("number"==typeof n)Wn[r++]=1,Wn[r++]=s,Wn[r++]=n;else if(Array.isArray(n)){Wn[r++]=n.length,Wn[r++]=s;for(let e=0;e<n.length;e++)Wn[r++]=n[e]}else"w"in n?(Wn[r++]=4,Wn[r++]=s,Wn[r++]=n.x,Wn[r++]=n.y,Wn[r++]=n.z,Wn[r++]=n.w):"z"in n?(Wn[r++]=3,Wn[r++]=s,Wn[r++]=n.x,Wn[r++]=n.y,Wn[r++]=n.z):(Wn[r++]=2,Wn[r++]=s,Wn[r++]=n.x,Wn[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(Wn.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,Dn);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),Ln/4),s.draw_meshWithUniforms(e,i.shader,Dn,Ln,r)}catch(n){ze(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Nn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},Vn=new Set;function Gn(e){const t=Nn[e];return void 0!==t?t:(Vn.has(e)||(Vn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Nn).join(", ")}`)),-1)}const qn=new Map;function Kn(e,t,n){qn.set(e,{fn:t,scene:n??""})}function Jn(e){qn.delete(e)}function Qn(){qn.clear()}var Zn;!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"}(Zn||(Zn={}));let es=null,ts=0,ns=0,ss=0;function is(e){es=e,ts=es._malloc(262144),ns=es._malloc(65536),ss=es._malloc(256)}function rs(){es&&(ts&&es._free(ts),ns&&es._free(ns),ss&&es._free(ss),ts=0,ns=0,ss=0),es=null}function os(){if(!es)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return es}const as={create(e){const t=os(),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,ts/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,ss,i).set(r),t.geometry_init(n,ts,s,ss,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,ns,s).set(e.indices),t.geometry_setIndices16(n,ns,s)}else{new Uint32Array(t.HEAPU8.buffer,ns,s).set(e.indices),t.geometry_setIndices32(n,ns,s)}}return n},updateVertices(e,t,n=0){const s=os(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,ts/4),s.geometry_updateVertices(e,ts,i,n)},release(e){e>0&&os().geometry_release(e)},isValid:e=>!(!es||e<=0)&&es.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return as.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:Zn.Float2},{name:"a_texCoord",type:Zn.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 as.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Zn.Float2},{name:"a_texCoord",type:Zn.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 as.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:Zn.Float2},{name:"a_texCoord",type:Zn.Float2}],indices:new Uint16Array(o)})}};let ls=null;function cs(e){ls=e}function ds(){ls&&us.isInitialized()&&us.shutdown(),ls=null}function hs(){if(!ls)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ls}const us={init(e,t){try{return hs().postprocess_init(e,t)}catch(n){return ze(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{hs().postprocess_shutdown()}catch(e){ze(e,"PostProcess.shutdown")}},resize(e,t){try{hs().postprocess_resize(e,t)}catch(n){ze(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return hs().postprocess_addPass(e,t)}catch(t){return ze(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{hs().postprocess_removePass(e)}catch(t){ze(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{hs().postprocess_setPassEnabled(e,t)}catch(t){ze(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return hs().postprocess_isPassEnabled(e)}catch(t){return ze(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{hs().postprocess_setUniformFloat(e,t,n)}catch(n){ze(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{hs().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){ze(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{hs().postprocess_begin()}catch(e){ze(e,"PostProcess.begin")}},end(){try{hs().postprocess_end()}catch(e){ze(e,"PostProcess.end")}},getPassCount(){try{return hs().postprocess_getPassCount()}catch(e){return ze(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!ls)return!1;try{return ls.postprocess_isInitialized()}catch(e){return ze(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{hs().postprocess_setBypass(e)}catch(e){ze(e,"PostProcess.setBypass")}},isBypassed(){if(!ls)return!0;try{return ls.postprocess_isBypassed()}catch(e){return ze(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ft.createShader(fs,"#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:()=>Ft.createShader(fs,"#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:()=>Ft.createShader(fs,"#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:()=>Ft.createShader(fs,"#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")},fs="#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 ps;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(ps||(ps={}));let gs=null,ys=0;function _s(e){gs=e,ys=gs._malloc(64)}function ms(){gs&&ys&&(gs._free(ys),ys=0),gs=null}const ws={init(e,t){gs?.renderer_init(e,t)},resize(e,t){gs?.renderer_resize(e,t)},begin(e,t){if(gs&&ys)try{gs.HEAPF32.set(e,ys/4),gs.renderer_begin(ys,t??0)}catch(e){ze(e,"Renderer.begin")}},flush(){try{gs?.renderer_flush()}catch(e){ze(e,"Renderer.flush")}},end(){try{gs?.renderer_end()}catch(e){ze(e,"Renderer.end")}},submitSprites(e){if(gs)try{gs.renderer_submitSprites(e._cpp)}catch(e){ze(e,"Renderer.submitSprites")}},submitBitmapText(e){if(gs)try{gs.renderer_submitBitmapText(e._cpp)}catch(e){ze(e,"Renderer.submitBitmapText")}},submitSpine(e){if(gs)try{gs.renderer_submitSpine?.(e._cpp)}catch(e){ze(e,"Renderer.submitSpine")}},setStage(e){gs?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>gs?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){gs?.renderer_releaseTarget(e)},getTargetTexture:e=>gs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>gs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){gs?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){gs?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){gs?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){gs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>gs?gs.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>gs?{drawCalls:gs.renderer_getDrawCalls(),triangles:gs.renderer_getTriangles(),sprites:gs.renderer_getSprites(),text:gs.renderer_getText(),spine:gs.renderer_getSpine?.()??0,meshes:gs.renderer_getMeshes(),culled:gs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let xs=null;function vs(e){xs=e}function bs(){xs=null}const Ss={enable(){xs?.gl_enableErrorCheck(!0)},disable(){xs?.gl_enableErrorCheck(!1)},check:e=>xs?.gl_checkErrors(e)??0,diagnose(){xs?.renderer_diagnose()}};class Ms{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_||(ws.resize(s,i),us.isInitialized()&&us.getPassCount()>0&&us.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),ws.setViewport(0,0,s,i),ws.clearBuffers(3),ws.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),ws.submitSprites(t),ws.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):ws.submitSpine(t),ws.flush(),this.executeDrawCallbacks(n,r),ws.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;ws.setViewport(s.x,s.y,s.w,s.h),ws.setScissor(s.x,s.y,s.w,s.h,!0),ws.clearBuffers(i),ws.setScissor(0,0,0,0,!1),ws.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),ws.submitSprites(t),ws.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):ws.submitSpine(t),ws.flush(),this.executeDrawCallbacks(n,r),ws.end()}executeDrawCallbacks(e,t){const n=qn;if(n.size>0){jn.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)}jn.end();for(const e of s)Jn(e)}}}const Ps="__scene_transition_overlay__";class Ts{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 Es{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,ye,{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),Kn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=us.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){us.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,ye)){const n=this.app_.world.get(e,ye);n.persistent=t,this.app_.world.insert(e,ye,n)}}}class Rs{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??R.sceneTransitionDuration,i=t.color??{...R.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},Kn(Ps,()=>{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;jn.setLayer(9999),jn.setDepth(9999),jn.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,Jn(Ps),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Jn(Ps),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 Ts(t);this.scenes_.set(e,n);const s=new Es(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Sn)?this.app_.getResource(Sn):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 Ts(t);this.scenes_.set(e,n);const s=new Es(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Sn)?this.app_.getResource(Sn):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,ye)){if(this.app_.world.get(e,ye).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Jn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{us.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(Sn)&&(i.assetServer=this.app_.getResource(Sn));const r=await en(this.app_.world,s,i);e.loadedAssets=n;for(const n of r.values())e.entities.add(n),this.app_.world.insert(n,ye,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=As(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(Sn)?this.app_.getResource(Sn):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)Ft.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,ae)){const t=n.get(e,ae);s.sprite=t.color.a,t.color.a=0,n.insert(e,ae,t),i=!0}if(n.has(e,pe)){const t=n.get(e,pe);s.spine=t.color.a,t.color.a=0,n.insert(e,pe,t),i=!0}if(n.has(e,fe)){const t=n.get(e,fe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,fe,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,ae)){const t=n.get(e,ae);t.color.a=s.sprite,n.insert(e,ae,t)}if(void 0!==s.spine&&n.has(e,pe)){const t=n.get(e,pe);t.color.a=s.spine,n.insert(e,pe,t)}if(void 0!==s.bitmapText&&n.has(e,fe)){const t=n.get(e,fe);t.color.a=s.bitmapText,n.insert(e,fe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{us.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 Cs=Me(null,"SceneManager");function As(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Cs).getSceneStatus(t)&&n._fn(...s)}}}const ks=ft([Te(Cs),Pe(Ce)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Is={name:"SceneManager",build(e){const t=new Rs(e);e.insertResource(Cs,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Cs),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(ht.Startup,n),e.addSystemToSchedule(ht.Last,ks)}};class Fs{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 ot,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(ht.Last);else{this.runSchedule(ht.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ht.FixedPreUpdate),this.runSchedule(ht.FixedUpdate),this.runSchedule(ht.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(ht.PreUpdate),this.runSchedule(ht.Update),this.runSchedule(ht.PostUpdate),this.runSchedule(ht.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new He,this.resources_=new Re;for(const e of Object.values(ht))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Fs}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(ht.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ht.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 Be(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(Cs).register(e),this}setInitialScene(e){return this.getResource(Cs).setInitial(e),this}tick(e){this.runner_||(this.runner_=new mt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(Ce)||this.resources_.insert(Ce,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(ht.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(ht.First),this.runSchedule(ht.PreUpdate),this.runSchedule(ht.Update),this.runSchedule(ht.PostUpdate),this.runSchedule(ht.Last);this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new mt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(Ce,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(ht.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,Qn();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[bs,ms,ds,rs,kt,Hn];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(Ce);t.delta=e,t.elapsed+=e,t.frameCount++}}function Bs(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 zs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Us(e,t,n,s,i){const r=e*t/n,o=e;switch(s){case se.FixedWidth:return r;case se.FixedHeight:return o;case se.Expand:return Math.max(r,o);case se.Shrink:return Math.min(r,o);case se.Match:{const e=i;return Math.pow(r,1-e)*Math.pow(o,e)}default:return o}}const $s=[];function Ds(e){if(e<$s.length)return $s[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 $s.push(t),t}function Ls(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,ye);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===te.Orthographic){if(h=i.orthoSize,l){h=Us(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=h*o,a=Os(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=Xs(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const u=js(r.position.x,r.position.y,r.position.z),f=Ds(c.length);f.entity=e,f.viewProjection.set(Vs(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 Ws=new Float32Array(16);function Os(e,t,n,s,i,r){const o=Ws;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 Hs=new Float32Array(16);function Xs(e,t,n,s){const i=Hs;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 Ys=new Float32Array(16);function js(e,t,n){const s=Ys;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 Ns=new Float32Array(16);function Vs(e,t){const n=Ns;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 Gs={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function qs(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 _=Math.max(0,g-f),m=Math.max(0,y-p);return{originX:f+o.x*_,originY:p+o.y*m,width:_,height:m,rect:{left:f,bottom:p,right:g,top:y}}}const Ks=ee("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 Js=null,Qs=null;function Zs(e,t){e.has(t,ae)||e.insert(t,ae,{texture:k,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 ei(e,t){switch(e){case Gs.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Gs.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Gs.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function ti(e,t){switch(e){case Gs.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Gs.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Gs.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 ni(e,t,n,s){switch(e){case Gs.BottomToTop:case Gs.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function si(e,t,n,s){if(!e.has(t,Ks))return;const i=e.get(t,Ks),r=ei(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,Ks,i)}function ii(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function ri(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function oi(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(ri(o.charCodeAt(0))&&s.length>0&&ri(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!ri(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 ai(e){let t=1;for(;t<e;)t*=2;return t}function li(e,t){let n=0,s=t;for(;e.has(s,he);){const t=e.get(s,he).entity;if(!e.valid(t))break;n++,s=t}return n}function ci(e,t){if(Js&&Qs){const e=Js.getUIRectComputedWidth(Qs,t);if(e>0)return e}return e.size.x}function di(e,t){if(Js&&Qs){const e=Js.getUIRectComputedHeight(Qs,t);if(e>0)return e}return e.size.y}function hi(e,t,n,s,i,r){if(!e.has(t,ae))return;const o=e.get(t,ae);let a,l;switch(n){case Gs.BottomToTop:case Gs.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,ae,o))}function ui(e,t,n){let s=t;for(;e.has(s,he);){const t=e.get(s,he).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function fi(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function pi(e,t,n,s,i){if(!e.has(t,Ks))return;const r=e.get(t,Ks),o=qs(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,ae)){const n=e.get(t,ae);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,ae,n))}if(e.has(t,ie)){const n=e.get(t,ie);n.position.x=o.originX-s,n.position.y=o.originY-i,e.insert(t,ie,n)}}function gi(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 yi=.1,_i=30,mi={r:.3,g:.5,b:.8,a:1},wi={Left:0,Center:1,Right:2},xi={Top:0,Middle:1,Bottom:2},vi={Visible:0,Clip:1,Ellipsis:2},bi=Y("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:wi.Left,verticalAlign:xi.Top,wordWrap:!0,overflow:vi.Visible,lineHeight:1.2});class Si{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(R.textCanvasSize,R.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,ai(this.frameMaxW_)),e.height=Math.max(e.height,ai(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=ai(this.frameMaxW_),e.height=ai(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=oi(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===vi.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,ai(f)),s.height=Math.max(s.height,ai(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),_=Math.round(255*e.color.b),m=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===vi.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 xi.Top:x=d;break;case xi.Middle:x=d+(p-2*d-w)/2;break;case xi.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 wi.Left:s=d;break;case wi.Center:s=f/2;break;case wi.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===vi.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 wi.Left:return"left";case wi.Center:return"center";case wi.Right:return"right"}}}const Mi=gi({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?ci(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?di(e.uiRect,e.entity):0});class Pi{build(e){Q("Text",bi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Si(t),s=e.world,i=new Map;e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,bi));for(const e of i.keys())if(!s.valid(e)||!s.has(e,bi)){if(s.valid(e)&&s.has(e,ae)){const t=s.get(e,ae);s.insert(e,ae,{texture:k,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([bi]);for(const t of e){const e=s.get(t,bi),r=s.has(t,Ks)?s.get(t,Ks):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Mi.changed(a,o)){if(s.has(t,ae)&&s.get(t,ae).texture!==k)continue}Zs(s,t);const l=r?{size:{x:ci(r,t),y:di(r,t)}}:null,c=n.renderForEntity(t,e,l),d=s.get(t,ae);s.insert(t,ae,{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,Mi.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ti=new Pi,Ei=0,Ri=1,Ci=ee("UIMask",{enabled:!0,mode:Ei});function Ai(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 ki(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],_=e[14],m=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*_-f*g,E=h*m-p*g,R=u*_-f*y,C=u*m-p*y,A=f*m-p*_;let k=w*A-x*C+v*R+b*E-S*T+M*P;return 0===k||(k=1/k,n[0]=(l*A-c*C+d*R)*k,n[1]=(r*C-i*A-o*R)*k,n[2]=(y*M-_*S+m*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]=(_*v-g*M-m*x)*k,n[7]=(h*M-f*v+p*x)*k,n[8]=(a*C-l*E+d*P)*k,n[9]=(i*E-s*C-o*P)*k,n[10]=(g*S-y*v+m*w)*k,n[11]=(u*v-h*S-p*w)*k,n[12]=(l*T-a*R-c*P)*k,n[13]=(s*R-i*T+r*P)*k,n[14]=(y*x-g*b-_*w)*k,n[15]=(h*b-u*x+f*w)*k),n}function Ii(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 Fi(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 Bi(e,t){return 2*Math.atan2(e,t)}function zi(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 Ui(e,t,n,s,i,r,o,a,l,c){const d=Bi(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 $i(e,t,n,s,i,r,o){if(!e.has(t,Ks)||!e.has(t,ie))return null;const a=e.get(t,Ks),l=e.get(t,ie),c=ci(a,t)*l.worldScale.x,d=di(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),_=-d*p,m=d*(1-p),w=Bi(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+g*x-_*v,u+g*v+_*x],[h+y*x-_*v,u+y*v+_*x],[h+y*x-m*v,u+y*v+m*x],[h+g*x-m*v,u+g*v+m*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=zi(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 Di(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ci]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,Ci);n.enabled&&(h.add(e),n.mode===Ri?(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;ui(t,e,e=>{if(i.has(e)){if(t.get(e,Ci).mode===Ei)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,Ci).mode===Ei){const e=$i(t,n,r,o,a,l,c);e&&(s=Ai(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=$i(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;ui(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 Li{build(e){if(Q("UIMask",Ci),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Di(e.wasmModule,e.world))}}const Wi=new Li,Oi=ee("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Hi=ee("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Xi={Normal:0,Hovered:1,Pressed:2,Disabled:3},Yi=Y("Button",{state:Xi.Normal,transition:null});class ji{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 Ni=Me(new ji,"UIEvents");class Vi{build(e){Q("UIRect",Ks);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){Js=e,Qs=t}(n,s);e.addSystemToSchedule(ht.PreUpdate,ft([Pe(St)],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(ht.PostUpdate,ft([Pe(St)],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(ht.PostUpdate,ft([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Gi=new Vi;let qi=!1,Ki=!1;function Ji(e){qi=e}function Qi(){return qi}function Zi(){return!qi}function er(e){Ki=e}function tr(){return Ki}const nr=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&&(ki(t,e),n=!1),e)}}();function sr(e,t,n,s){t.emit(n,s,n),ui(e,n,i=>{if(!e.has(i,Oi))return!1;const r=e.get(i,Oi);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class ir{build(e){Q("Interactable",Oi),Q("Button",Yi);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new ji;e.insertResource(Ni,i);let r=null,o=null;e.addSystemToSchedule(ht.PreUpdate,ft([Pe(xt),Pe(St)],(e,a)=>{if(i.drain(),Qi()&&!tr())return;const l=t.getEntitiesWithComponents([Hi]);for(const e of l){const n=t.get(e,Hi);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Hi,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;nr.update(a.viewProjection);const u=Ii(d,h,nr.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 _=n.uiHitTest_getHitEntity(),m=4294967295===_?null:_;if(null===r||t.valid(r)||(r=null),r!==m){if(null!==r&&t.valid(r)&&t.has(r,Hi)){const e=t.get(r,Hi);e.hovered=!1,t.insert(r,Hi,e),i.emit(r,"hover_exit")}if(null!==m){fi(t,m,Hi);const e=t.get(m,Hi);e.hovered=!0,t.insert(m,Hi,e),i.emit(m,"hover_enter")}r=m}if(g&&null!==m){const e=t.get(m,Hi);e.pressed=!0,e.justPressed=!0,t.insert(m,Hi,e),o=m,sr(t,i,m,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,Hi)){const e=t.get(o,Hi);e.pressed=!1,e.justReleased=!0,t.insert(o,Hi,e),sr(t,i,o,"release"),o===r&&sr(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(ht.Update,ft([],()=>{const e=t.getEntitiesWithComponents([Yi]);for(const n of e){if(fi(t,n,Oi,{enabled:!0}),!t.has(n,Hi))continue;const e=t.get(n,Hi),s=t.get(n,Yi),i=t.get(n,Oi),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=Xi.Pressed:e.hovered?s.state=Xi.Hovered:s.state=Xi.Normal:s.state=Xi.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,ae)){const r=t.get(n,ae);r.color=ii(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,ae,r)}}},{name:"ButtonSystem"}))}}const rr=new ir,or=Y("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),ar=Y("Focusable",{tabIndex:0,isFocused:!1});class lr{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 cr=Me(new lr,"FocusManager");class dr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Q("TextInput",or),Qi()&&!tr())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(R.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(cr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,or)?s:null}const y=()=>{l||null===g()||v()},_=()=>{l=!0},m=()=>{l=!1,v()},w=t=>{const s=g();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,or);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(Ni).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,or);s.focused=!1,s.dirty=!0;e.getResource(cr).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,or);if(s.readOnly)return;let i=p.value;if(s.maxLength>0&&i.length>s.maxLength&&(i=i.substring(0,s.maxLength),p.value=i),i!==s.value){s.value=i;e.getResource(Ni).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,or);e.focused=!1,e.dirty=!0}e.getResource(cr).blur(),p.blur()}function S(){c=!0,d=0}p.addEventListener("input",y),p.addEventListener("compositionstart",_),p.addEventListener("compositionend",m),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",_),p.removeEventListener("compositionend",m),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=ai(Math.max(i.width,d)),i.height=ai(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),_=l.padding;if(l.multiline){const e=oi(r,p,d-2*_);let t=_;for(const n of e)r.fillText(n,_,t),t+=y}else{const e=(h-l.fontSize)/2;r.fillText(p,_,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=oi(r,l.value,d-2*_);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=_+r.measureText(c).width,n=_+o*y,s=y}else t=_+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 m=r.getImageData(0,0,d,h),w=new Uint8Array(m.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,ae);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,ae,S)}e.addSystemToSchedule(ht.Update,ft([Pe(cr)],e=>{const t=n.getEntitiesWithComponents([or]);for(const e of t)fi(n,e,ar,{tabIndex:0,isFocused:!1}),fi(n,e,Oi,{enabled:!0,blockRaycast:!0});const s=g();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,or)){const e=n.get(M,or);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,or);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(s),M=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{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,or).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,or)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([or,Ks]);for(const e of a){const t=n.get(e,or);if(!t.dirty)continue;const s=n.get(e,Ks),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(Zs(n,e),P(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const hr=new dr,ur={Simple:0,Sliced:1,Tiled:2,Filled:3},fr={Horizontal:0,Vertical:1},pr={Left:0,Right:1,Bottom:2,Top:3},gr=Y("Image",{texture:k,color:{r:1,g:1,b:1,a:1},imageType:ur.Simple,fillMethod:fr.Horizontal,fillOrigin:pr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),yr=gi({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?ci(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?di(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const _r=new class{build(e){Q("Image",gr);const t=e.world,n=new Map;e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,gr)||n.delete(e);const e=t.getEntitiesWithComponents([gr]);for(const s of e){const e=t.get(s,gr),i=t.has(s,Ks)?t.get(s,Ks):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!yr.changed(o,r))continue;Zs(t,s);const a=t.get(s,ae);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=ci(i,s),a.size.y=di(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===ur.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===fr.Horizontal?e.fillOrigin===pr.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===pr.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===ur.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,ae,a),n.set(s,yr.take(r))}else a.color.a=0,t.insert(s,ae,a),n.set(s,yr.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},mr=Y("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),wr=Y("ToggleGroup",{allowSwitchOff:!1});const xr=new class{build(e){Q("Toggle",mr),Q("ToggleGroup",wr);const t=e.world,n=new Set;e.addSystemToSchedule(ht.Update,ft([Pe(Ni)],e=>{const s=t.getEntitiesWithComponents([mr]);if(!Qi()||tr()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,mr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,mr,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,mr);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(fi(t,n,Oi,{enabled:!0}),!t.has(n,Hi))continue;const s=t.get(n,Hi),i=t.get(n,mr),o=t.get(n,Oi);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,wr);if(i.isOn&&o){if(!t.get(s,wr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,mr,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,mr);i.isOn&&(i.isOn=!1,t.insert(s,mr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,ae)){const e=t.get(n,ae);e.color=ii(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,ae,e)}}}for(const e of s){const n=t.get(e,mr);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,ae)){const e=t.get(n.graphicEntity,ae);e.enabled=n.isOn,t.insert(n.graphicEntity,ae,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},vr=Gs,br=Y("ProgressBar",{value:0,fillEntity:0,direction:Gs.LeftToRight});function Sr(e,t,n,s){if(!e.has(t,Ks))return;const i=e.get(t,Ks),r=n/2,o=s/2,a={left:-r,bottom:-o,right:r,top:o},l=qs(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,ae)){const n=e.get(t,ae);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,ae,n))}if(e.has(t,ie)){const n=e.get(t,ie),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,ie,n))}}class Mr{build(e){Q("ProgressBar",br);const t=e.world;e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{const e=t.getEntitiesWithComponents([br,Ks]);for(const n of e){const e=t.get(n,br);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Ks),i=Math.max(0,Math.min(1,e.value));si(t,e.fillEntity,e.direction,i);const r=ci(s,n),o=di(s,n);Sr(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Pr=new Mr,Tr=Y("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Er=Y("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 Rr=new class{build(e){Q("Draggable",Tr),Q("DragState",Er);const t=e.world,n=e.getResource(Ni);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(ht.PreUpdate,ft([Pe(xt),Pe(St)],(e,o)=>{if(Qi()&&!tr())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Tr,Hi]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,Tr).enabled)continue;if(t.get(s,Hi).hovered){let e=0;t.has(s,ae)&&(e=t.get(s,ae).layer);const i=li(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,Er)||t.insert(n,Er);const e=t.get(n,Er),r=t.get(n,ie);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,Er)){t.get(s,Er).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,Tr);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,Er).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,Er))return void(r=null);const s=t.get(r,Er),i=t.get(r,Tr),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,ie)){const e=function(e,t,n,s){if(!e.has(t,he))return{x:n,y:s};const i=e.get(t,he).entity;if(!e.valid(i)||!e.has(i,ie))return{x:n,y:s};const r=e.get(i,ie),o=0!==r.worldScale.x?r.worldScale.x:1,a=0!==r.worldScale.y?r.worldScale.y:1,l=Bi(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,ie);n.position.x+=e.x,n.position.y+=e.y,t.insert(r,ie,n)}n.emit(r,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(r,"drag_end"),r=null)}},{name:"DragSystem"}))}},Cr=Y("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Ar(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 kr(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 Ir=new class{build(e){Q("ScrollView",Cr);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(ht.PostUpdate,ft([Pe(xt),Pe(St),Pe(Ce)],(e,i,r)=>{const o=Qi()&&!tr(),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([Cr,Ks]);for(const r of l){fi(t,r,Ci,{enabled:!0,mode:Ei});const l=t.get(r,Cr),c=t.get(r,Ks);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=ci(c,r),u=di(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,ue)){const e=t.get(l.contentEntity,ue).entities;let n=0,s=0,i=0,r=0;for(const o of e){if(!t.valid(o)||!t.has(o,ie))continue;const e=t.get(o,ie);let a=0,l=0,c=.5,d=.5;if(t.has(o,Ks)){const e=t.get(o,Ks);a=ci(e,o)||e.size.x,l=di(e,o)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(o,ae)){const e=t.get(o,ae);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){fi(t,r,Oi,{enabled:!0,blockRaycast:!0});const n=t.has(r,Hi)?t.get(r,Hi):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=Ar(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=Ar(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=Ar(l.scrollY,0,y,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Ar(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=kr(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)<yi&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>yi?(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=kr(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)<yi&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>yi?(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,ie)){const e=t.get(l.contentEntity,ie),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,ie,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Fr=Gs,Br=Y("Slider",{value:0,minValue:0,maxValue:1,direction:Gs.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function zr(e,t,n,s,i,r){const o=ci(s,i)*n.worldScale.x,a=di(s,i)*n.worldScale.y,l=Bi(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 Gs.LeftToRight:return o>0?(f-g)/o:0;case Gs.RightToLeft:return o>0?1-(f-g)/o:0;case Gs.BottomToTop:return a>0?(p-y)/a:0;case Gs.TopToBottom:return a>0?1-(p-y)/a:0}}function Ur(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Gs.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case Gs.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case Gs.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case Gs.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class $r{build(e){Q("Slider",Br);const t=e.world;let n=null;e.addSystemToSchedule(ht.PreUpdate,ft([Pe(xt),Pe(St),Pe(Ni)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([Br,Ks]);for(const o of r){const r=t.get(o,Br),a=t.get(o,Ks);if(!Qi()||tr()){if(t.has(o,ie)){fi(t,o,Oi,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&fi(t,r.handleEntity,Oi,{enabled:!0,blockRaycast:!1});const l=t.get(o,ie),c=t.has(o,Hi)?t.get(o,Hi):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,Hi)&&(d=t.get(r.handleEntity,Hi).justPressed),d&&(n=o),n===o&&e.isMouseButtonDown(0)){let e=zr(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,Br,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=ci(a,o),h=di(a,o),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(si(t,r.fillEntity,r.direction,c),pi(t,r.fillEntity,u,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,Ks)){const e=t.get(r.handleEntity,Ks);Ur(e,r.direction,c),t.insert(r.handleEntity,Ks,e),pi(t,r.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Dr=new $r;const Lr=new class{build(e){Q("Focusable",ar);const t=e.world,n=new lr;e.insertResource(cr,n),e.addSystemToSchedule(ht.Update,ft([Pe(xt),Pe(Ni)],(e,s)=>{if(Qi()&&!tr())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([ar]);for(const e of i){if(!t.has(e,Hi))continue;t.get(e,Hi).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,Oi)){if(!t.get(n,Oi).enabled)continue}const s=t.get(n,ar);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const 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,ar)){t.get(i,ar).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,ar).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},Wr=Y("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Or(){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 Hr=new class{build(e){Q("SafeArea",Wr);const t=e.world;let n=Or(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Or(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Or(),s=!0});e.addSystemToSchedule(ht.PreUpdate,ft([Pe(St)],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([Wr,Ks]);for(const e of d){const s=t.get(e,Wr),i=t.get(e,Ks),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,Ks,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},Xr=Y("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Yr=null;function jr(e,t){if(!Yr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Yr.get(e);n?n.renderer=t:Yr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const Nr=new class{build(e){Q("ListView",Xr);const t=e.world,n=new Map;Yr=n,e.addSystemToSchedule(ht.PostUpdate,ft([Pe(xt)],e=>{const s=Qi()&&!tr();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([Xr,Ks]);for(const r of i){fi(t,r,Oi,{enabled:!0,blockRaycast:!0}),fi(t,r,Ci,{enabled:!0,mode:Ei});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,Xr),a=t.get(r,Ks),l=di(a,r),c=ci(a,r);if(!s){const n=t.has(r,Hi)?t.get(r,Hi):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,ge,{value:`ListItem_${e}`}),t.insert(n,Ks,{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,ie)){const s=t.get(n,ie);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,ie,s)}}i.visibleStart=h,i.visibleEnd=u}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Vr=Y("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Gr=new class{build(e){Q("Dropdown",Vr);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,ie))return;const n=t.get(e,ie);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,ie,{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,ae)){const n=t.get(e,ae);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,ae,{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,ae),o=r.size.x,a=r.size.y;s.ddWidth=o;const l=n.options.length*_i;t.insert(i,Ks,{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,ie,{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,ae,{texture:k,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)*_i;t.insert(r,ge,{value:`Option_${e}`}),t.insert(r,Ks,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*_i},offsetMax:{x:0,y:0},size:{x:o,y:_i},pivot:{x:.5,y:.5}}),t.insert(r,ie,{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,ae,{texture:k,color:{r:.95,g:.95,b:.95,a:1},size:{x:o,y:_i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,Oi,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const c=t.spawn();t.insert(c,ie,{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,bi,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:wi.Left,verticalAlign:xi.Middle,wordWrap:!1,overflow:vi.Clip,lineHeight:1.2}),t.insert(c,Ks,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:_i},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,bi))return;const s=t.get(n,bi);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,bi,{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,Oi)&&t.insert(e,Oi,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,ae))){const s=t.get(e,ae);t.insert(e,ae,{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,ae))continue;const i=n===e.highlightIndex?{...mi}:{r:.95,g:.95,b:.95,a:1};t.insert(s,ae,{texture:k,color:i,size:{x:e.ddWidth,y:_i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function u(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,Hi))continue;if(t.get(n,Hi).hovered)return!0}return!1}e.addSystemToSchedule(ht.Update,ft([Pe(xt),Pe(Ni)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=Qi()&&!tr(),p=t.getEntitiesWithComponents([Vr]);for(const g of p){const p=t.get(g,Vr);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;fi(t,g,Oi,{enabled:!0,blockRaycast:!0});const _=t.has(g,Hi)?t.get(g,Hi):null;if(_?.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,Hi))continue;if(t.get(n,Hi).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,Hi))continue;if(t.get(s,Hi).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)&&(_?.hovered||u(y)||o(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},qr=0,Kr=0,Jr=2,Qr=Y("LayoutGroup",{direction:qr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Kr,reverseOrder:!1});const Zr=new class{build(e){Q("LayoutGroup",Qr);const t=e.world;e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{const e=t.getEntitiesWithComponents([Qr,Ks,ue]);for(const n of e){const e=t.get(n,Qr),s=t.get(n,Ks),i=t.get(n,ue);if(!i.entities||0===i.entities.length)continue;const r=[];for(const e of i.entities)t.valid(e)&&t.has(e,Ks)&&t.has(e,ie)&&r.push({entity:e,rect:t.get(e,Ks)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=ci(s,n),a=di(s,n),l=s.pivot.x,c=s.pivot.y,d=e.padding,h=e.direction===qr;let u=0;for(let n=0;n<r.length;n++){const s=r[n],i=ci(s.rect,s.entity),f=di(s.rect,s.entity),p=s.rect.pivot.x,g=s.rect.pivot.y;let y,_;h?(y=-l*o+d.left+u+p*i,_=e.childAlignment===Kr?(1-c)*a-d.top-(1-g)*f:e.childAlignment===Jr?-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===Kr?-l*o+d.left+p*i:e.childAlignment===Jr?(1-l)*o-d.right-(1-p)*i:(.5-l)*o+.5*(d.left-d.right)+(p-.5)*i,_=(1-c)*a-d.top-u-(1-g)*f,u+=f,n<r.length-1&&(u+=e.spacing));const m=t.get(s.entity,ie);m.position.x=y,m.position.y=_,t.insert(s.entity,ie,m)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};ee("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),ee("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class eo{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(ht.PostUpdate,ft([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const to=new eo;async function no(e,t,n){const s=e.getResource(Cs);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function so(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 io=Me({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ro=Me(null,"PhysicsAPI");function oo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ao(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class lo{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(io,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=so(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([ce]);for(const n of t){const t=e.world.get(n,ce);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(ht.PostUpdate,ft([Pe(Ce)],a=>{const l=o.getEntitiesWithComponents([me,ie]),c=new Set;for(const i of l){c.add(i);const a=o.get(i,me),l=o.get(i,ie);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=oo(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),co(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===be.Kinematic){const e=oo(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,ie);if(!d)continue;let h=a,u=l,f=c;if(e.world.has(o,he)){const t=e.world.get(o,he);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ie)){const n=e.world.get(t.entity,ie),s=oo(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=ao(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,ie,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(io,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(ro,ho._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function co(e,t,n){const s=e.world;if(s.has(n,we)){const e=s.get(n,we);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,xe)){const e=s.get(n,xe);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,ve)){const e=s.get(n,ve);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 ho{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(ho.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 uo={nearest:0,linear:1},fo={repeat:0,clamp:1,mirror:2};function po(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=uo[s.filterMode??"linear"]??1,a=fo[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 go(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 yo(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,_=l*u,m=l*f,w=c*f,x=d*h,v=d*u,b=d*f;return new Float32Array([(1-(_+w))*i,(g+b)*i,(y-v)*i,0,(g-b)*r,(1-(p+w))*r,(m+x)*r,0,(y+v)*o,(m-x)*o,(1-(p+_))*o,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function _o(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=Vt(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]=po(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=Gt(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"===hn(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=go(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=po(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??{...P},fixedTimestep:o?.fixedTimestep??T,subStepCount:o?.subStepCount??4};new lo("",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=Vt(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=hn(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=po(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=Vt(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=Ft.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=Ft.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=Vt(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=Zt(e.world,n);if(l&&e.hasResource(Cs))for(const t of p.values())e.world.insert(t,ye,{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=Gt(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=M);const c=e.world;for(const e in i){const r=Number(e),o=i[e],a=c.has(r,pe)?c.get(r,pe):null,d=!1!==a?.playing,h=a?.timeScale??1;d&&s.update(o,l*h);let u=0;if(c.has(r,ie)){const e=yo(c.get(r,ie),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),_=new Uint16Array(n.HEAPU8.buffer,d,r),m=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,m>>2),new Uint16Array(t.HEAPU8.buffer,w,r).set(_),t.renderer_submitTriangles(m,i,w,r,p,g,u),t._free(m),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(Sn);t&&t.setAddressableManifest(a)}}function mo(e,t,n){return{name:e,data:t,async setup(){await _o(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class wo{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=Gt(e.type);if(i){const s=e.data[i.skeletonField],r=e.data[i.atlasField];s&&("binary"===hn(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}const r=Vt(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=hn(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 xo="__preview__";class vo{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(Cs);t.register({name:xo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(xo),this.loadPromise_=t.load(xo).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 wo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await _o(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,xo)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([le]);for(const s of n){if(e.get(s,le).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([ce]);for(const i of s){const s=e.get(i,ce);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(Cs).getScene(xo),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,ie,o);const a={isActive:!0,projectionType:te.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:ne.ColorAndDepth};e.insert(r,le,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(Cs);await e.switchTo(xo),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 bo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=ws.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:ws.getTargetTexture(n),width:e.width,height:e.height}},release(e){ws.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(ws.releaseRenderTarget(e._handle),bo.create({width:t,height:n,depth:!0})),begin(e,t){ws.begin(t,e._handle)},end(){ws.end()},getDepthTexture:e=>ws.getTargetDepthTexture(e._handle)};var So;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(So||(So={}));class Mo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${So[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case So.Debug:console.debug(t,n);break;case So.Info:console.log(t,n);break;case So.Warn:console.warn(t,n);break;case So.Error:console.error(t,n)}}}class Po{constructor(){this.handlers_=[],this.minLevel_=So.Info,this.addHandler(new Mo)}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(So.Debug,e,t,n)}info(e,t,n){this.log(So.Info,e,t,n)}warn(e,t,n){this.log(So.Warn,e,t,n)}error(e,t,n){this.log(So.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 To=new Po;function Eo(){return To}function Ro(e){To.setMinLevel(e)}function Co(e,t,n){To.debug(e,t,n)}function Ao(e,t,n){To.info(e,t,n)}function ko(e,t,n){To.warn(e,t,n)}function Io(e,t,n){To.error(e,t,n)}const Fo=[Ti,Wi,Gi,_r,Pr,rr,Rr,Ir,Dr,xr,hr,Lr,Hr,Nr,Gr,Zr,to];function Bo(e,t){return function(e,t){const n=Fs.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),On(e),At(e),is(e),cs(e),_s(e),vs(e);const i=new Ms;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=Ls(e,s,t,i));const o=n.getResource(St);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(St,{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;ws.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-r)/1e3;let h;if(ws.resize(t,l),us.isInitialized()&&us.getPassCount()>0&&!us.isBypassed()&&us.resize(t,l),n.hasResource(Cs)){const e=n.getResource(Cs).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=Ls(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:zs,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})}ws.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(ht.First,l),n.addSystemToSchedule(ht.Last,c),n.addPlugin(Pn),n.addPlugin(zn),n.addPlugin(bt),n.addPlugin(Is),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Fo,...t})}e=p;export{je as Added,Fs as App,Mn as AssetPlugin,Tn as AssetRefCounter,bn as AssetServer,Sn as Assets,Ht as AsyncCache,fe as BitmapText,Mt as BlendMode,be as BodyType,we as BoxCollider,Yi as Button,Xi as ButtonState,le as Camera,ce as Canvas,ve as CapsuleCollider,Ne as Changed,ue as Children,xe as CircleCollider,ne as ClearFlags,tt as Commands,st as CommandsInstance,y as DEFAULT_DESIGN_HEIGHT,g as DEFAULT_DESIGN_WIDTH,M as DEFAULT_FALLBACK_DT,T as DEFAULT_FIXED_TIMESTEP,x as DEFAULT_FONT_FAMILY,v as DEFAULT_FONT_SIZE,P as DEFAULT_GRAVITY,b as DEFAULT_LINE_HEIGHT,S as DEFAULT_MAX_DELTA_TIME,_ as DEFAULT_PIXELS_PER_UNIT,E as DEFAULT_SPINE_SKIN,w as DEFAULT_SPRITE_SIZE,m as DEFAULT_TEXT_CANVAS_SIZE,Zn as DataType,Er as DragState,Tr as Draggable,jn as Draw,Vr as Dropdown,nt as EntityCommands,lt as EventReader,dt as EventReaderInstance,ot as EventRegistry,at as EventWriter,ct as EventWriterInstance,Gs as FillDirection,fr as FillMethod,pr as FillOrigin,cr as FocusManager,lr as FocusManagerState,ar as Focusable,Ss as GLDebug,as as Geometry,A as INVALID_ENTITY,I as INVALID_FONT,F as INVALID_MATERIAL,k as INVALID_TEXTURE,gr as Image,ur as ImageType,xt as Input,vt as InputPlugin,wt as InputState,Oi as Interactable,Xr as ListView,re as LocalTransform,So as LogLevel,Po as Logger,Ft as Material,Xt as MaterialLoader,Xe as Mut,ge as Name,he as Parent,ho as Physics,io as PhysicsEvents,lo as PhysicsPlugin,us as PostProcess,In as PrefabServer,Fn as Prefabs,Bn as PrefabsPlugin,vo as PreviewPlugin,br as ProgressBar,vr as ProgressBarDirection,Mr as ProgressBarPlugin,te as ProjectionType,Je as Query,Qe as QueryInstance,Ze as Removed,et as RemovedQueryInstance,Ms as RenderPipeline,ps as RenderStage,bo as RenderTexture,ws as Renderer,Pe as Res,Te as ResMut,me as RigidBody,R as RuntimeConfig,Wr as SafeArea,se as ScaleMode,Cs as SceneManager,Rs as SceneManagerState,ye as SceneOwner,ht as Schedule,Cr as ScrollView,Ot as ShaderSources,Br as Slider,Fr as SliderDirection,$r as SliderPlugin,pe as SpineAnimation,ae as Sprite,mt as SystemRunner,bi as Text,wi as TextAlign,or as TextInput,dr as TextInputPlugin,vi as TextOverflow,Pi as TextPlugin,Si as TextRenderer,xi as TextVerticalAlign,Ce as Time,mr as Toggle,ie as Transform,St as UICameraInfo,ji as UIEventQueue,Ni as UIEvents,Hi as UIInteraction,ir as UIInteractionPlugin,Vi as UILayoutPlugin,Ci as UIMask,Li as UIMaskPlugin,Ks as UIRect,eo as UIRenderOrderPlugin,de as Velocity,wo as WebAssetProvider,He as World,oe as WorldTransform,yt as addStartupSystem,gt as addSystem,_t as addSystemToSchedule,si as applyDirectionalFill,C as applyRuntimeConfig,Pn as assetPlugin,Qn as clearDrawCallbacks,V as clearUserComponents,$ as color,ei as computeFillAnchors,ni as computeFillSize,ti as computeHandleAnchors,qs as computeUIRectLayout,Di as createMaskProcessor,mo as createRuntimeSceneConfig,Bo as createWebApp,Co as debug,Y as defineComponent,it as defineEvent,Me as defineResource,ft as defineSystem,j as defineTag,Io as error,rn as findEntityByName,Bs as flushPendingSystems,fn as getAddressableType,pn as getAddressableTypeByEditorType,yn as getAllAssetExtensions,xn as getAssetMimeType,hn as getAssetTypeEntry,Z as getComponent,Vt as getComponentAssetFieldDescriptors,Nt as getComponentAssetFields,_e as getComponentDefaults,Gt as getComponentSpineFieldDescriptor,mn as getCustomExtensions,un as getEditorType,Eo as getLogger,t as getPlatform,s as getPlatformType,N as getUserComponent,wn as getWeChatPackOptions,Ao as info,On as initDrawAPI,vs as initGLDebugAPI,is as initGeometryAPI,At as initMaterialAPI,cs as initPostProcessAPI,_s as initRendererAPI,bt as inputPlugin,Rn as instantiatePrefab,Ai as intersectRects,ki as invertMatrix4,K as isBuiltinComponent,vn as isCustomExtension,Qi as isEditor,gn as isKnownAssetExtension,n as isPlatformInitialized,tr as isPlayMode,Zi as isRuntime,Pt as isTextureRef,i as isWeChat,r as isWeb,nn as loadComponent,so as loadPhysicsModule,_o as loadRuntimeScene,Zt as loadSceneData,en as loadSceneWithAssets,_n as looksLikeAssetPath,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ui as pointInOBB,Fi as pointInWorldRect,zn as prefabsPlugin,Pr as progressBarPlugin,D as quat,Q as registerComponent,jt as registerComponentAssetFields,Kt as registerComponentEntityFields,Kn as registerDrawCallback,En as registerEmbeddedAssets,Wt as registerMaterialCallback,Jt as remapEntityFields,Is as sceneManagerPlugin,Ii as screenToWorld,Ji as setEditorMode,jr as setListViewRenderer,Ro as setLogLevel,er as setPlayMode,Be as setWasmErrorHandler,Hn as shutdownDrawAPI,bs as shutdownGLDebugAPI,rs as shutdownGeometryAPI,kt as shutdownMaterialAPI,ds as shutdownPostProcessAPI,ms as shutdownRendererAPI,Dr as sliderPlugin,hi as syncFillSpriteSize,hr as textInputPlugin,Ti as textPlugin,no as transitionTo,rr as uiInteractionPlugin,Gi as uiLayoutPlugin,Wi as uiMaskPlugin,Fo as uiPlugins,to as uiRenderOrderPlugin,G as unregisterComponent,Jn as unregisterDrawCallback,sn as updateCameraAspectRatio,B as vec2,z as vec3,U as vec4,ko as warn,As as wrapSceneSystem};
//# sourceMappingURL=index.js.map
diff --git a/editor/src/gizmos/builtinGizmos.ts b/editor/src/gizmos/builtinGizmos.ts
index 5787a538e..f44c150ba 100644
--- a/editor/src/gizmos/builtinGizmos.ts
+++ b/editor/src/gizmos/builtinGizmos.ts
@@ -76,11 +76,21 @@ export function createSelectGizmo(): GizmoDescriptor {
// Move Gizmo
// =============================================================================
+interface UIRectDragInfo {
+ startOffsetMin: { x: number; y: number };
+ startOffsetMax: { x: number; y: number };
+ originalOffsetMin: { x: number; y: number };
+ originalOffsetMax: { x: number; y: number };
+ stretchedX: boolean;
+ stretchedY: boolean;
+}
+
interface MoveGizmoDragState {
startValue: { x: number; y: number; z: number };
originalValue: { x: number; y: number; z: number };
startWorldX: number;
startWorldY: number;
+ uiRect: UIRectDragInfo | null;
}
export function createMoveGizmo(): GizmoDescriptor {
@@ -173,11 +183,29 @@ export function createMoveGizmo(): GizmoDescriptor {
const transform = entityData?.components.find(c => c.type === 'Transform');
if (transform) {
const value = transform.data.position as { x: number; y: number; z: number };
+ let uiRect: UIRectDragInfo | null = null;
+ const uiRectComp = entityData?.components.find(c => c.type === 'UIRect');
+ if (uiRectComp) {
+ const d = uiRectComp.data;
+ const anchorMin = d.anchorMin as { x: number; y: number };
+ const anchorMax = d.anchorMax as { x: number; y: number };
+ const offsetMin = d.offsetMin as { x: number; y: number };
+ const offsetMax = d.offsetMax as { x: number; y: number };
+ uiRect = {
+ startOffsetMin: { ...offsetMin },
+ startOffsetMax: { ...offsetMax },
+ originalOffsetMin: { ...offsetMin },
+ originalOffsetMax: { ...offsetMax },
+ stretchedX: anchorMin.x !== anchorMax.x,
+ stretchedY: anchorMin.y !== anchorMax.y,
+ };
+ }
dragState = {
startValue: { ...value },
originalValue: { ...value },
startWorldX: worldX,
startWorldY: worldY,
+ uiRect,
};
}
},
@@ -202,6 +230,23 @@ export function createMoveGizmo(): GizmoDescriptor {
newY = Math.round(newY / gridSize) * gridSize;
}
+ if (dragState.uiRect) {
+ const effectiveDx = newX - dragState.startValue.x;
+ const effectiveDy = newY - dragState.startValue.y;
+ const ui = dragState.uiRect;
+
+ gctx.store.updatePropertyDirect(entity, 'UIRect', 'offsetMin', {
+ x: ui.startOffsetMin.x + effectiveDx,
+ y: ui.startOffsetMin.y + effectiveDy,
+ });
+ if (ui.stretchedX || ui.stretchedY) {
+ gctx.store.updatePropertyDirect(entity, 'UIRect', 'offsetMax', {
+ x: ui.startOffsetMax.x + (ui.stretchedX ? effectiveDx : 0),
+ y: ui.startOffsetMax.y + (ui.stretchedY ? effectiveDy : 0),
+ });
+ }
+ }
+
gctx.store.updatePropertyDirect(entity, 'Transform', 'position', {
x: newX, y: newY, z: dragState.startValue.z,
});
@@ -215,11 +260,32 @@ export function createMoveGizmo(): GizmoDescriptor {
const entityData = gctx.store.getSelectedEntityData();
const transform = entityData?.components.find(c => c.type === 'Transform');
if (transform) {
- const currentValue = transform.data.position;
- if (currentValue && !valuesEqual(dragState.originalValue, currentValue)) {
+ const currentPos = transform.data.position;
+ const posChanged = currentPos && !valuesEqual(dragState.originalValue, currentPos);
+
+ if (dragState.uiRect) {
+ const uiRectComp = entityData?.components.find(c => c.type === 'UIRect');
+ const curOffsetMin = uiRectComp?.data.offsetMin;
+ const curOffsetMax = uiRectComp?.data.offsetMax;
+ const ui = dragState.uiRect;
+ const changes: { componentType: string; property: string; oldValue: unknown; newValue: unknown }[] = [];
+
+ if (curOffsetMin && !valuesEqual(ui.originalOffsetMin, curOffsetMin)) {
+ changes.push({ componentType: 'UIRect', property: 'offsetMin', oldValue: { ...ui.originalOffsetMin }, newValue: deepClone(curOffsetMin) });
+ }
+ if (curOffsetMax && !valuesEqual(ui.originalOffsetMax, curOffsetMax)) {
+ changes.push({ componentType: 'UIRect', property: 'offsetMax', oldValue: { ...ui.originalOffsetMax }, newValue: deepClone(curOffsetMax) });
+ }
+ if (posChanged) {
+ changes.push({ componentType: 'Transform', property: 'position', oldValue: { ...dragState.originalValue }, newValue: deepClone(currentPos) });
+ }
+ if (changes.length > 0) {
+ gctx.store.updateBatchProperties(entity, changes, 'Move UIRect entity');
+ }
+ } else if (posChanged) {
gctx.store.updateProperty(
entity, 'Transform', 'position',
- { ...dragState.originalValue }, deepClone(currentValue),
+ { ...dragState.originalValue }, deepClone(currentPos),
);
}
}
diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.ts
index 795fef7cb..8914121b4 100644
--- a/editor/src/store/EditorStore.ts
+++ b/editor/src/store/EditorStore.ts
@@ -421,6 +421,14 @@ export class EditorStore {
this.sceneOps_.updateProperties(entity, componentType, changes);
}
+ updateBatchProperties(
+ entity: Entity,
+ changes: { componentType: string; property: string; oldValue: unknown; newValue: unknown }[],
+ description?: string
+ ): void {
+ this.sceneOps_.updateBatchProperties(entity, changes, description);
+ }
+
getComponent(entity: Entity, type: string): ComponentData | null {
return this.sceneOps_.getComponent(entity, type);
}
diff --git a/editor/src/store/SceneOperations.ts b/editor/src/store/SceneOperations.ts
index bd8bad9d2..9dec75c5e 100644
--- a/editor/src/store/SceneOperations.ts
+++ b/editor/src/store/SceneOperations.ts
@@ -229,6 +229,36 @@ export class SceneOperations {
this.host_.executeCommand(compound);
}
+ updateBatchProperties(
+ entity: Entity,
+ changes: { componentType: string; property: string; oldValue: unknown; newValue: unknown }[],
+ description?: string
+ ): void {
+ const commands = changes.map(c => new PropertyCommand(
+ this.host_.state_.scene,
+ this.host_.entityMap_,
+ entity,
+ c.componentType,
+ c.property,
+ c.oldValue,
+ c.newValue
+ ));
+ const compound = new CompoundCommand(commands, description ?? 'Update properties');
+ this.host_.executeCommand(compound);
+
+ if (this.isPrefabInstance(entity as number)) {
+ for (const c of changes) {
+ recordPropertyOverride(
+ this.host_.state_.scene,
+ entity as number,
+ c.componentType,
+ c.property,
+ c.newValue
+ );
+ }
+ }
+ }
+
getComponent(entity: Entity, type: string): ComponentData | null {
const entityData = this.host_.entityMap_.get(entity as number);
if (!entityData) return null;
diff --git a/sdk/src/ui/ProgressBarPlugin.ts b/sdk/src/ui/ProgressBarPlugin.ts
index 3ff07b09d..5a13d2da6 100644
--- a/sdk/src/ui/ProgressBarPlugin.ts
+++ b/sdk/src/ui/ProgressBarPlugin.ts
@@ -40,6 +40,7 @@ function syncFillLayout(
const curPos = t.position;
if (curPos.x !== result.originX || curPos.y !== result.originY) {
t.position = { x: result.originX, y: result.originY, z: curPos.z };
+ world.insert(fillEntity, Transform, t);
}
}
}
diff --git a/sdk/src/ui/uiHelpers.ts b/sdk/src/ui/uiHelpers.ts
index 6f9665a18..8ddd9b978 100644
--- a/sdk/src/ui/uiHelpers.ts
+++ b/sdk/src/ui/uiHelpers.ts
@@ -104,8 +104,6 @@ export function applyDirectionalFill(
const anchors = computeFillAnchors(direction, value);
fillRect.anchorMin = anchors.anchorMin;
fillRect.anchorMax = anchors.anchorMax;
- fillRect.offsetMin = anchors.offsetMin;
- fillRect.offsetMax = anchors.offsetMax;
if (anchors.anchorMin.x === anchors.anchorMax.x) {
fillRect.size = { ...fillRect.size, x: 0 };
}