A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat: add asset ref resolver to AssetServer for UUID-based prefabs
esengine0ca6d4bea74e
diff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex 59a763d31..92b789895 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -780,6 +780,7 @@ declare class World {private iterationDepth_;private nextEntityId_;private nextGeneration_;+ private spawnCallbacks_;private despawnCallbacks_;private worldTick_;private componentAddedTicks_;@@ -791,6 +792,7 @@ declare class World {getCppRegistry(): CppRegistry | null;spawn(): Entity;despawn(entity: Entity): void;+ onSpawn(callback: (entity: Entity) => void): () => void;onDespawn(callback: (entity: Entity) => void): () => void;valid(entity: Entity): boolean;entityCount(): number;@@ -1581,6 +1583,7 @@ declare class AssetServer {private spineController_;private spineSkeletons_;private textureRefCounts_;+ private assetRefResolver_;constructor(module: ESEngineModule);registerEmbeddedAssets(assets: Record<string, string>): void;setEmbeddedOnly(value: boolean): void;@@ -1612,7 +1615,9 @@ declare class AssetServer {releaseFont(fontPath: string): void;private loadBmfontAsset;private loadFntFile;+ setAssetRefResolver(resolver: (ref: string) => string | null): void;loadPrefab(path: string, baseUrl?: string): Promise<PrefabData>;+ private resolvePrefabRefs_;loadMaterial(path: string, baseUrl?: string): Promise<LoadedMaterial>;getMaterial(path: string, baseUrl?: string): LoadedMaterial | undefined;hasMaterial(path: string, baseUrl?: string): boolean;@@ -1633,6 +1638,7 @@ declare class AssetServer {private loadTextureWithFlip;private loadTextureInternal;private loadImage;+ private loadImageFromSrc;private createTextureFromImage;private getWebGL2Context;private createTextureWebGL2;@@ -1868,6 +1874,7 @@ declare class App {}): this;addSystem(system: SystemDef): this;addStartupSystem(system: SystemDef): this;+ removeSystem(systemId: symbol): boolean;connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;get wasmModule(): ESEngineModule | null;get pipeline(): RenderPipeline | null;diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.jsindex 739b5fd05..ea370540f 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 ut(){return{_type:"get_world"}}!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(ht||(ht={}));let ft=0;function pt(e,t,n){const s=++ft;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function gt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function yt(e){gt().push({schedule:ht.Update,system:e})}function _t(e){gt().push({schedule:ht.Startup,system:e})}function mt(e,t){gt().push({schedule:e,system:t})}class wt{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_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class xt{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 vt=Me(new xt,"Input");class bt{constructor(e){this.target_=e??null}build(e){const n=new xt;e.insertResource(vt,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,pt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const St=new bt,Mt=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 Pt;function Tt(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"}(Pt||(Pt={}));let Et=null,Rt=null,Ct=1;const At=new Map;function kt(e){Et=e,Rt=e.getResourceManager(),Ot()}function It(){0!==Ut&&Et&&(Et._free(Ut),Ut=0),At.clear(),Ct=1,zt=!1,Dt.clear(),Lt=null,Rt=null,Et=null}function Ft(){if(!Rt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Rt}const Bt={createShader:(e,t)=>Ft().createShader(e,t),releaseShader(e){e>0&&Ft().releaseShader(e)},create(e){const t=Ct++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Pt.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 At.set(t,n),t},get:e=>At.get(e),setUniform(e,t,n){const s=At.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,Et?.invalidateMaterialCache(e))},getUniform(e,t){const n=At.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=At.get(e);n&&(n.blendMode=t,Et?.invalidateMaterialCache(e))},getBlendMode(e){const t=At.get(e);return t?.blendMode??Pt.Normal},setDepthTest(e,t){const n=At.get(e);n&&(n.depthTest=t,Et?.invalidateMaterialCache(e))},getShader(e){const t=At.get(e);return t?.shader??0},release(e){At.delete(e),Et?.invalidateMaterialCache(e)},isValid:e=>At.has(e),releaseAll(){At.clear(),Et?.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??Pt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=At.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ct++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return At.set(n,s),n},toAssetData(e,t){const n=At.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=At.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let zt=!1,Ut=0;const $t=16384,Dt=new Map;let Lt=null;function Wt(e){const t=(0===Ut&&Et&&(Ut=Et._malloc($t)),Ut);if(0===t||!Et)return{ptr:0,count:0};let n=0,s=0;const i=Et.HEAPU8,r=Et.HEAPU32,o=Et.HEAPF32;for(const[a,l]of e){if(Tt(l))continue;let e=Dt.get(a);e||(Lt||(Lt=new TextEncoder),e=Lt.encode(a),Dt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>$t){console.warn(`[ESEngine] Material uniform buffer full (${n}/${$t} 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 Ot(){if(!Et||zt)return;Et.materialDataProvider=(e,t,n,s,i)=>{const r=At.get(e);if(!r)return Et.HEAPU32[t>>2]=0,Et.HEAPU32[n>>2]=0,Et.HEAPU32[s>>2]=0,void(Et.HEAPU32[i>>2]=0);Et.HEAPU32[t>>2]=r.shader,Et.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=Wt(r.uniforms);Et.HEAPU32[s>>2]=o,Et.HEAPU32[i>>2]=a},zt=!0}const Ht={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 Xt{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 Yt{constructor(e,t=""){this.cache_=new Xt,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&&(Bt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Bt.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:Bt.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 jt=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 Nt(e,t){jt.set(e,t)}function Vt(e){const t=jt.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 Gt(e){return jt.get(e)?.fields??[]}function qt(e){return jt.get(e)?.spine??null}const Kt=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Jt(e,t){Kt.set(e,t)}function Qt(e){return Kt.get(e)}function Zt(e,t){const n=Kt.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 en(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)Zt(i,n),rn(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 tn(e,t){return en(e,t)}async function nn(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 sn.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=jt.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=[...sn.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=jt.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=en(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 sn=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 rn(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 on(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 an(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 ln=[{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}],cn={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"},dn=new Map,hn=new Set;for(const e of ln)for(const t of e.extensions)dn.set(t,e),hn.add(t);function un(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function fn(e){return dn.get(un(e))}function pn(e){return fn(e)?.editorType??"unknown"}function gn(e){return fn(e)?.addressableType??null}function yn(e){for(const t of ln)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function _n(e){return hn.has(e.toLowerCase())}function mn(){return hn}function wn(e){return"string"==typeof e&&(!!e.includes("/")&&_n(un(e)))}function xn(){const e=[];for(const t of ln)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function vn(){return xn().map(e=>({type:"suffix",value:e}))}function bn(e){return cn[e.toLowerCase()]}function Sn(e){const t=fn(e);return t?.wechatPackInclude??!1}class Mn{constructor(e){this.textureCache_=new Xt,this.shaderCache_=new Xt,this.jsonCache_=new Xt,this.textCache_=new Xt,this.binaryCache_=new Xt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Xt,this.prefabCache_=new Xt,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 Yt(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(),Bt.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"===fn(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=fn(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 nn(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 Bt.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 Bt.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 Pn=Me(null,"Assets");class Tn{build(e){const t=e.wasmModule;t?e.insertResource(Pn,new Mn(t)):console.warn("AssetPlugin: No WASM module available")}}const En=new Tn;class Rn{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 Cn(e,t){const n=e.getResource(Pn);n&&n.registerEmbeddedAssets(t)}async function An(e,t,n){const{entities:s,rootId:i}=await In(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 nn(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 kn=10;async function In(e,t,n,s,i,r=0){if(r>kn)throw new Error(`Prefab nesting depth exceeded ${kn}. 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 In(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};Fn(h.components,o),Bn(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 Fn(e,t){for(const n of e){const e=Qt(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function Bn(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 zn{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 An(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Un=Me(null,"Prefabs");class $n{constructor(){this.name="PrefabsPlugin",this.dependencies=[Pn]}build(e){const t=e.getResource(Pn);e.insertResource(Un,new zn(e.world,t))}}const Dn=new $n;let Ln=null,Wn=0,On=0,Hn=0;const Xn=new Float32Array(256);function Yn(e){Ln=e,Wn=Ln._malloc(64),On=Ln._malloc(64),Hn=Ln._malloc(1024)}function jn(){Ln&&(Wn&&(Ln._free(Wn),Wn=0),On&&(Ln._free(On),On=0),Hn&&(Ln._free(Hn),Hn=0)),Ln=null}function Nn(){if(!Ln)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ln}const Vn={r:1,g:1,b:1,a:1},Gn={begin(e){const t=Nn();try{t.HEAPF32.set(e,Wn/4),t.draw_begin(Wn)}catch(e){ze(e,"Draw.begin")}},end(){try{Nn().draw_end()}catch(e){ze(e,"Draw.end")}},line(e,t,n,s=1){try{Nn().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{Nn().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{Nn().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{Nn().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{Nn().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=Vn){try{Nn().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=Vn){try{Nn().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){Nn().draw_setLayer(e)},setDepth(e){Nn().draw_setDepth(e)},getDrawCallCount:()=>Ln?Ln.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ln?Ln.draw_getPrimitiveCount():0,setBlendMode(e){Nn().draw_setBlendMode(e)},setDepthTest(e){Nn().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=Nn();s.HEAPF32.set(n,On/4),s.draw_mesh(e,t,On)}catch(n){ze(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Nn(),i=Bt.get(t);if(!i)return;if(Gn.setBlendMode(i.blendMode),Gn.setDepthTest(i.depthTest),0===i.uniforms.size)return void Gn.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,On/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=Jn(t);if(!(s<0)){if(Tt(n))Xn[r++]=10,Xn[r++]=s,Xn[r++]=n.slot??e++,Xn[r++]=n.textureId;else if("number"==typeof n)Xn[r++]=1,Xn[r++]=s,Xn[r++]=n;else if(Array.isArray(n)){Xn[r++]=n.length,Xn[r++]=s;for(let e=0;e<n.length;e++)Xn[r++]=n[e]}else"w"in n?(Xn[r++]=4,Xn[r++]=s,Xn[r++]=n.x,Xn[r++]=n.y,Xn[r++]=n.z,Xn[r++]=n.w):"z"in n?(Xn[r++]=3,Xn[r++]=s,Xn[r++]=n.x,Xn[r++]=n.y,Xn[r++]=n.z):(Xn[r++]=2,Xn[r++]=s,Xn[r++]=n.x,Xn[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(Xn.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,On);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),Hn/4),s.draw_meshWithUniforms(e,i.shader,On,Hn,r)}catch(n){ze(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},qn={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},Kn=new Set;function Jn(e){const t=qn[e];return void 0!==t?t:(Kn.has(e)||(Kn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(qn).join(", ")}`)),-1)}const Qn=new Map;function Zn(e,t,n){Qn.set(e,{fn:t,scene:n??""})}function es(e){Qn.delete(e)}function ts(){Qn.clear()}var ns;!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"}(ns||(ns={}));let ss=null,is=0,rs=0,os=0;function as(e){ss=e,is=ss._malloc(262144),rs=ss._malloc(65536),os=ss._malloc(256)}function ls(){ss&&(is&&ss._free(is),rs&&ss._free(rs),os&&ss._free(os),is=0,rs=0,os=0),ss=null}function cs(){if(!ss)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ss}const ds={create(e){const t=cs(),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,is/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,os,i).set(r),t.geometry_init(n,is,s,os,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,rs,s).set(e.indices),t.geometry_setIndices16(n,rs,s)}else{new Uint32Array(t.HEAPU8.buffer,rs,s).set(e.indices),t.geometry_setIndices32(n,rs,s)}}return n},updateVertices(e,t,n=0){const s=cs(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,is/4),s.geometry_updateVertices(e,is,i,n)},release(e){e>0&&cs().geometry_release(e)},isValid:e=>!(!ss||e<=0)&&ss.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return ds.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:ns.Float2},{name:"a_texCoord",type:ns.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 ds.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:ns.Float2},{name:"a_texCoord",type:ns.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 ds.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:ns.Float2},{name:"a_texCoord",type:ns.Float2}],indices:new Uint16Array(o)})}};let hs=null;function us(e){hs=e}function fs(){hs&&gs.isInitialized()&&gs.shutdown(),hs=null}function ps(){if(!hs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return hs}const gs={init(e,t){try{return ps().postprocess_init(e,t)}catch(n){return ze(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{ps().postprocess_shutdown()}catch(e){ze(e,"PostProcess.shutdown")}},resize(e,t){try{ps().postprocess_resize(e,t)}catch(n){ze(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return ps().postprocess_addPass(e,t)}catch(t){return ze(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{ps().postprocess_removePass(e)}catch(t){ze(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{ps().postprocess_setPassEnabled(e,t)}catch(t){ze(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return ps().postprocess_isPassEnabled(e)}catch(t){return ze(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{ps().postprocess_setUniformFloat(e,t,n)}catch(n){ze(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){ze(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{ps().postprocess_begin()}catch(e){ze(e,"PostProcess.begin")}},end(){try{ps().postprocess_end()}catch(e){ze(e,"PostProcess.end")}},getPassCount(){try{return ps().postprocess_getPassCount()}catch(e){return ze(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!hs)return!1;try{return hs.postprocess_isInitialized()}catch(e){return ze(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{ps().postprocess_setBypass(e)}catch(e){ze(e,"PostProcess.setBypass")}},isBypassed(){if(!hs)return!0;try{return hs.postprocess_isBypassed()}catch(e){return ze(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Bt.createShader(ys,"#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:()=>Bt.createShader(ys,"#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:()=>Bt.createShader(ys,"#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:()=>Bt.createShader(ys,"#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")},ys="#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 _s;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(_s||(_s={}));let ms=null,ws=0;function xs(e){ms=e,ws=ms._malloc(64)}function vs(){ms&&ws&&(ms._free(ws),ws=0),ms=null}const bs={init(e,t){ms?.renderer_init(e,t)},resize(e,t){ms?.renderer_resize(e,t)},begin(e,t){if(ms&&ws)try{ms.HEAPF32.set(e,ws/4),ms.renderer_begin(ws,t??0)}catch(e){ze(e,"Renderer.begin")}},flush(){try{ms?.renderer_flush()}catch(e){ze(e,"Renderer.flush")}},end(){try{ms?.renderer_end()}catch(e){ze(e,"Renderer.end")}},submitSprites(e){if(ms)try{ms.renderer_submitSprites(e._cpp)}catch(e){ze(e,"Renderer.submitSprites")}},submitBitmapText(e){if(ms)try{ms.renderer_submitBitmapText(e._cpp)}catch(e){ze(e,"Renderer.submitBitmapText")}},submitSpine(e){if(ms)try{ms.renderer_submitSpine?.(e._cpp)}catch(e){ze(e,"Renderer.submitSpine")}},setStage(e){ms?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>ms?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){ms?.renderer_releaseTarget(e)},getTargetTexture:e=>ms?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>ms?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){ms?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){ms?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){ms?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){ms?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>ms?ms.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>ms?{drawCalls:ms.renderer_getDrawCalls(),triangles:ms.renderer_getTriangles(),sprites:ms.renderer_getSprites(),text:ms.renderer_getText(),spine:ms.renderer_getSpine?.()??0,meshes:ms.renderer_getMeshes(),culled:ms.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Ss=null;function Ms(e){Ss=e}function Ps(){Ss=null}const Ts={enable(){Ss?.gl_enableErrorCheck(!0)},disable(){Ss?.gl_enableErrorCheck(!1)},check:e=>Ss?.gl_checkErrors(e)??0,diagnose(){Ss?.renderer_diagnose()}};class Es{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_||(bs.resize(s,i),gs.isInitialized()&&gs.getPassCount()>0&&gs.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),bs.setViewport(0,0,s,i),bs.clearBuffers(3),bs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),bs.submitSprites(t),bs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):bs.submitSpine(t),bs.flush(),this.executeDrawCallbacks(n,r),bs.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;bs.setViewport(s.x,s.y,s.w,s.h),bs.setScissor(s.x,s.y,s.w,s.h,!0),bs.clearBuffers(i),bs.setScissor(0,0,0,0,!1),bs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),bs.submitSprites(t),bs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):bs.submitSpine(t),bs.flush(),this.executeDrawCallbacks(n,r),bs.end()}executeDrawCallbacks(e,t){const n=Qn;if(n.size>0){Gn.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)}Gn.end();for(const e of s)es(e)}}}const Rs="__scene_transition_overlay__";class Cs{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 As{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),Zn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=gs.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){gs.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 ks{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},Zn(Rs,()=>{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;Gn.setLayer(9999),Gn.setDepth(9999),Gn.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,es(Rs),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,es(Rs),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 Cs(t);this.scenes_.set(e,n);const s=new As(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Pn)?this.app_.getResource(Pn):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 Cs(t);this.scenes_.set(e,n);const s=new As(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Pn)?this.app_.getResource(Pn):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())es(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{gs.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(Pn)&&(i.assetServer=this.app_.getResource(Pn));const r=await nn(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=Fs(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(Pn)?this.app_.getResource(Pn):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)Bt.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{gs.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 Is=Me(null,"SceneManager");function Fs(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Is).getSceneStatus(t)&&n._fn(...s)}}}const Bs=pt([Te(Is),Pe(Ce)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),zs={name:"SceneManager",build(e){const t=new ks(e);e.insertResource(Is,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Is),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,Bs)}};class Us{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 Us}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(Is).register(e),this}setInitialScene(e){return this.getResource(Is).setInitial(e),this}tick(e){this.runner_||(this.runner_=new wt(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 wt(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,ts();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=[Ps,vs,fs,ls,It,jn];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 $s(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 Ds=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ls(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 Ws=[];function Os(e){if(e<Ws.length)return Ws[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 Ws.push(t),t}function Hs(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=Ls(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=h*o,a=Ys(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=Ns(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const u=Gs(r.position.x,r.position.y,r.position.z),f=Os(c.length);f.entity=e,f.viewProjection.set(Ks(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 Xs=new Float32Array(16);function Ys(e,t,n,s,i,r){const o=Xs;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 js=new Float32Array(16);function Ns(e,t,n,s){const i=js;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 Vs=new Float32Array(16);function Gs(e,t,n){const s=Vs;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 qs=new Float32Array(16);function Ks(e,t){const n=qs;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 Js={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 Zs=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 ei=null,ti=null;function ni(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 si(e,t){switch(e){case Js.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Js.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Js.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 ii(e,t){switch(e){case Js.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Js.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Js.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 ri(e,t,n,s){switch(e){case Js.BottomToTop:case Js.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function oi(e,t,n,s){if(!e.has(t,Zs))return;const i=e.get(t,Zs),r=si(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,Zs,i)}function ai(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function li(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function ci(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(li(o.charCodeAt(0))&&s.length>0&&li(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!li(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 di(e){let t=1;for(;t<e;)t*=2;return t}function hi(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 ui(e,t){if(ei&&ti){const e=ei.getUIRectComputedWidth(ti,t);if(e>0)return e}return e.size.x}function fi(e,t){if(ei&&ti){const e=ei.getUIRectComputedHeight(ti,t);if(e>0)return e}return e.size.y}function pi(e,t,n,s,i,r){if(!e.has(t,ae))return;const o=e.get(t,ae);let a,l;switch(n){case Js.BottomToTop:case Js.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 gi(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 yi(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function _i(e,t,n,s,i){if(!e.has(t,Zs))return;const r=e.get(t,Zs),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 mi(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 wi=.1,xi=30,vi={r:.3,g:.5,b:.8,a:1},bi={Left:0,Center:1,Right:2},Si={Top:0,Middle:1,Bottom:2},Mi={Visible:0,Clip:1,Ellipsis:2},Pi=Y("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:bi.Left,verticalAlign:Si.Top,wordWrap:!0,overflow:Mi.Visible,lineHeight:1.2});class Ti{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,di(this.frameMaxW_)),e.height=Math.max(e.height,di(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=di(this.frameMaxW_),e.height=di(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=ci(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===Mi.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,di(f)),s.height=Math.max(s.height,di(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===Mi.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 Si.Top:x=d;break;case Si.Middle:x=d+(p-2*d-w)/2;break;case Si.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 bi.Left:s=d;break;case bi.Center:s=f/2;break;case bi.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===Mi.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 bi.Left:return"left";case bi.Center:return"center";case bi.Right:return"right"}}}const Ei=mi({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?ui(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?fi(e.uiRect,e.entity):0});class Ri{build(e){Q("Text",Pi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ti(t),s=e.world,i=new Map;e.addSystemToSchedule(ht.PreUpdate,pt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Pi));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Pi)){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([Pi]);for(const t of e){const e=s.get(t,Pi),r=s.has(t,Zs)?s.get(t,Zs):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Ei.changed(a,o)){if(s.has(t,ae)&&s.get(t,ae).texture!==k)continue}ni(s,t);const l=r?{size:{x:ui(r,t),y:fi(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,Ei.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ci=new Ri,Ai=0,ki=1,Ii=ee("UIMask",{enabled:!0,mode:Ai});function Fi(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 Bi(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 zi(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 Ui(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 $i(e,t){return 2*Math.atan2(e,t)}function Di(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 Li(e,t,n,s,i,r,o,a,l,c){const d=$i(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 Wi(e,t,n,s,i,r,o){if(!e.has(t,Zs)||!e.has(t,ie))return null;const a=e.get(t,Zs),l=e.get(t,ie),c=ui(a,t)*l.worldScale.x,d=fi(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=$i(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]=Di(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 Oi(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ii]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,Ii);n.enabled&&(h.add(e),n.mode===ki?(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;gi(t,e,e=>{if(i.has(e)){if(t.get(e,Ii).mode===Ai)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,Ii).mode===Ai){const e=Wi(t,n,r,o,a,l,c);e&&(s=Fi(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=Wi(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;gi(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 Hi{build(e){if(Q("UIMask",Ii),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Oi(e.wasmModule,e.world))}}const Xi=new Hi,Yi=ee("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),ji=ee("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Ni={Normal:0,Hovered:1,Pressed:2,Disabled:3},Vi=Y("Button",{state:Ni.Normal,transition:null});class Gi{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 qi=Me(new Gi,"UIEvents");class Ki{build(e){Q("UIRect",Zs);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){ei=e,ti=t}(n,s);e.addSystemToSchedule(ht.PreUpdate,pt([Pe(Mt)],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,pt([Pe(Mt)],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,pt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ji=new Ki;let Qi=!1,Zi=!1;function er(e){Qi=e}function tr(){return Qi}function nr(){return!Qi}function sr(e){Zi=e}function ir(){return Zi}const rr=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&&(Bi(t,e),n=!1),e)}}();function or(e,t,n,s){t.emit(n,s,n),gi(e,n,i=>{if(!e.has(i,Yi))return!1;const r=e.get(i,Yi);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class ar{build(e){Q("Interactable",Yi),Q("Button",Vi);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new Gi;e.insertResource(qi,i);let r=null,o=null;e.addSystemToSchedule(ht.PreUpdate,pt([Pe(vt),Pe(Mt)],(e,a)=>{if(i.drain(),tr()&&!ir())return;const l=t.getEntitiesWithComponents([ji]);for(const e of l){const n=t.get(e,ji);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,ji,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;rr.update(a.viewProjection);const u=zi(d,h,rr.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,ji)){const e=t.get(r,ji);e.hovered=!1,t.insert(r,ji,e),i.emit(r,"hover_exit")}if(null!==m){yi(t,m,ji);const e=t.get(m,ji);e.hovered=!0,t.insert(m,ji,e),i.emit(m,"hover_enter")}r=m}if(g&&null!==m){const e=t.get(m,ji);e.pressed=!0,e.justPressed=!0,t.insert(m,ji,e),o=m,or(t,i,m,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,ji)){const e=t.get(o,ji);e.pressed=!1,e.justReleased=!0,t.insert(o,ji,e),or(t,i,o,"release"),o===r&&or(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(ht.Update,pt([],()=>{const e=t.getEntitiesWithComponents([Vi]);for(const n of e){if(yi(t,n,Yi,{enabled:!0}),!t.has(n,ji))continue;const e=t.get(n,ji),s=t.get(n,Vi),i=t.get(n,Yi),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=Ni.Pressed:e.hovered?s.state=Ni.Hovered:s.state=Ni.Normal:s.state=Ni.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,ae)){const r=t.get(n,ae);r.color=ai(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,ae,r)}}},{name:"ButtonSystem"}))}}const lr=new ar,cr=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}),dr=Y("Focusable",{tabIndex:0,isFocused:!1});class hr{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 ur=Me(new hr,"FocusManager");class fr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Q("TextInput",cr),tr()&&!ir())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(ur);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,cr)?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,cr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(qi).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,cr);s.focused=!1,s.dirty=!0;e.getResource(ur).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,cr);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(qi).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,cr);e.focused=!1,e.dirty=!0}e.getResource(ur).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=di(Math.max(i.width,d)),i.height=di(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=ci(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=ci(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,pt([Pe(ur)],e=>{const t=n.getEntitiesWithComponents([cr]);for(const e of t)yi(n,e,dr,{tabIndex:0,isFocused:!1}),yi(n,e,Yi,{enabled:!0,blockRaycast:!0});const s=g();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,cr)){const e=n.get(M,cr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,cr);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,pt([],()=>{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,cr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,cr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([cr,Zs]);for(const e of a){const t=n.get(e,cr);if(!t.dirty)continue;const s=n.get(e,Zs),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(ni(n,e),P(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const pr=new fr,gr={Simple:0,Sliced:1,Tiled:2,Filled:3},yr={Horizontal:0,Vertical:1},_r={Left:0,Right:1,Bottom:2,Top:3},mr=Y("Image",{texture:k,color:{r:1,g:1,b:1,a:1},imageType:gr.Simple,fillMethod:yr.Horizontal,fillOrigin:_r.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),wr=mi({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?ui(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?fi(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const xr=new class{build(e){Q("Image",mr);const t=e.world,n=new Map;e.addSystemToSchedule(ht.PreUpdate,pt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,mr)||n.delete(e);const e=t.getEntitiesWithComponents([mr]);for(const s of e){const e=t.get(s,mr),i=t.has(s,Zs)?t.get(s,Zs):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!wr.changed(o,r))continue;ni(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=ui(i,s),a.size.y=fi(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===gr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===yr.Horizontal?e.fillOrigin===_r.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===_r.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===gr.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(s,ae,a),n.set(s,wr.take(r))}else a.color.a=0,t.insert(s,ae,a),n.set(s,wr.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},vr=Y("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),br=Y("ToggleGroup",{allowSwitchOff:!1});const Sr=new class{build(e){Q("Toggle",vr),Q("ToggleGroup",br);const t=e.world,n=new Set;e.addSystemToSchedule(ht.Update,pt([Pe(qi)],e=>{const s=t.getEntitiesWithComponents([vr]);if(!tr()||ir()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,vr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,vr,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,vr);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(yi(t,n,Yi,{enabled:!0}),!t.has(n,ji))continue;const s=t.get(n,ji),i=t.get(n,vr),o=t.get(n,Yi);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,br);if(i.isOn&&o){if(!t.get(s,br).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,vr,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,vr);i.isOn&&(i.isOn=!1,t.insert(s,vr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,ae)){const e=t.get(n,ae);e.color=ai(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,ae,e)}}}for(const e of s){const n=t.get(e,vr);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"]})}},Mr=Js,Pr=Y("ProgressBar",{value:0,fillEntity:0,direction:Js.LeftToRight});function Tr(e,t,n,s){if(!e.has(t,Zs))return;const i=e.get(t,Zs),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 Er{build(e){Q("ProgressBar",Pr);const t=e.world;e.addSystemToSchedule(ht.PreUpdate,pt([],()=>{const e=t.getEntitiesWithComponents([Pr,Zs]);for(const n of e){const e=t.get(n,Pr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Zs),i=Math.max(0,Math.min(1,e.value));oi(t,e.fillEntity,e.direction,i);const r=ui(s,n),o=fi(s,n);Tr(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Rr=new Er,Cr=Y("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Ar=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 kr=new class{build(e){Q("Draggable",Cr),Q("DragState",Ar);const t=e.world,n=e.getResource(qi);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(ht.PreUpdate,pt([Pe(vt),Pe(Mt)],(e,o)=>{if(tr()&&!ir())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Cr,ji]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,Cr).enabled)continue;if(t.get(s,ji).hovered){let e=0;t.has(s,ae)&&(e=t.get(s,ae).layer);const i=hi(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,Ar)||t.insert(n,Ar);const e=t.get(n,Ar),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,Ar)){t.get(s,Ar).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,Cr);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,Ar).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,Ar))return void(r=null);const s=t.get(r,Ar),i=t.get(r,Cr),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=$i(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"}))}},Ir=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 Fr(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 Br(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 zr=new class{build(e){Q("ScrollView",Ir);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(ht.PostUpdate,pt([Pe(vt),Pe(Mt),Pe(Ce)],(e,i,r)=>{const o=tr()&&!ir(),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([Ir,Zs]);for(const r of l){yi(t,r,Ii,{enabled:!0,mode:Ai});const l=t.get(r,Ir),c=t.get(r,Zs);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=ui(c,r),u=fi(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,Zs)){const e=t.get(o,Zs);a=ui(e,o)||e.size.x,l=fi(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){yi(t,r,Yi,{enabled:!0,blockRaycast:!0});const n=t.has(r,ji)?t.get(r,ji):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=Fr(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=Fr(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=Fr(l.scrollY,0,y,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Fr(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=Br(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)<wi&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>wi?(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=Br(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)<wi&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>wi?(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"]})}},Ur=Js,$r=Y("Slider",{value:0,minValue:0,maxValue:1,direction:Js.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Dr(e,t,n,s,i,r){const o=ui(s,i)*n.worldScale.x,a=fi(s,i)*n.worldScale.y,l=$i(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 Js.LeftToRight:return o>0?(f-g)/o:0;case Js.RightToLeft:return o>0?1-(f-g)/o:0;case Js.BottomToTop:return a>0?(p-y)/a:0;case Js.TopToBottom:return a>0?1-(p-y)/a:0}}function Lr(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Js.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case Js.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case Js.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case Js.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class Wr{build(e){Q("Slider",$r);const t=e.world;let n=null;e.addSystemToSchedule(ht.PreUpdate,pt([Pe(vt),Pe(Mt),Pe(qi)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([$r,Zs]);for(const o of r){const r=t.get(o,$r),a=t.get(o,Zs);if(!tr()||ir()){if(t.has(o,ie)){yi(t,o,Yi,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&yi(t,r.handleEntity,Yi,{enabled:!0,blockRaycast:!1});const l=t.get(o,ie),c=t.has(o,ji)?t.get(o,ji):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,ji)&&(d=t.get(r.handleEntity,ji).justPressed),d&&(n=o),n===o&&e.isMouseButtonDown(0)){let e=Dr(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,$r,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=ui(a,o),h=fi(a,o),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(oi(t,r.fillEntity,r.direction,c),_i(t,r.fillEntity,u,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,Zs)){const e=t.get(r.handleEntity,Zs);Lr(e,r.direction,c),t.insert(r.handleEntity,Zs,e),_i(t,r.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Or=new Wr;const Hr=new class{build(e){Q("Focusable",dr);const t=e.world,n=new hr;e.insertResource(ur,n),e.addSystemToSchedule(ht.Update,pt([Pe(vt),Pe(qi)],(e,s)=>{if(tr()&&!ir())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([dr]);for(const e of i){if(!t.has(e,ji))continue;t.get(e,ji).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,Yi)){if(!t.get(n,Yi).enabled)continue}const s=t.get(n,dr);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,dr)){t.get(i,dr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,dr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},Xr=Y("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Yr(){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 jr=new class{build(e){Q("SafeArea",Xr);const t=e.world;let n=Yr(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Yr(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Yr(),s=!0});e.addSystemToSchedule(ht.PreUpdate,pt([Pe(Mt)],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([Xr,Zs]);for(const e of d){const s=t.get(e,Xr),i=t.get(e,Zs),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,Zs,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},Nr=Y("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Vr=null;function Gr(e,t){if(!Vr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Vr.get(e);n?n.renderer=t:Vr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const qr=new class{build(e){Q("ListView",Nr);const t=e.world,n=new Map;Vr=n,e.addSystemToSchedule(ht.PostUpdate,pt([Pe(vt)],e=>{const s=tr()&&!ir();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([Nr,Zs]);for(const r of i){yi(t,r,Yi,{enabled:!0,blockRaycast:!0}),yi(t,r,Ii,{enabled:!0,mode:Ai});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,Nr),a=t.get(r,Zs),l=fi(a,r),c=ui(a,r);if(!s){const n=t.has(r,ji)?t.get(r,ji):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,Zs,{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"]})}},Kr=Y("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Jr=new class{build(e){Q("Dropdown",Kr);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*xi;t.insert(i,Zs,{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)*xi;t.insert(r,ge,{value:`Option_${e}`}),t.insert(r,Zs,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*xi},offsetMax:{x:0,y:0},size:{x:o,y:xi},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:xi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,Yi,{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,Pi,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:bi.Left,verticalAlign:Si.Middle,wordWrap:!1,overflow:Mi.Clip,lineHeight:1.2}),t.insert(c,Zs,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:xi},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,Pi))return;const s=t.get(n,Pi);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,Pi,{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,Yi)&&t.insert(e,Yi,{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?{...vi}:{r:.95,g:.95,b:.95,a:1};t.insert(s,ae,{texture:k,color:i,size:{x:e.ddWidth,y:xi},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,ji))continue;if(t.get(n,ji).hovered)return!0}return!1}e.addSystemToSchedule(ht.Update,pt([Pe(vt),Pe(qi)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=tr()&&!ir(),p=t.getEntitiesWithComponents([Kr]);for(const g of p){const p=t.get(g,Kr);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;yi(t,g,Yi,{enabled:!0,blockRaycast:!0});const _=t.has(g,ji)?t.get(g,ji):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,ji))continue;if(t.get(n,ji).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,ji))continue;if(t.get(s,ji).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,Zr=0,eo=2,to=Y("LayoutGroup",{direction:Qr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Zr,reverseOrder:!1});const no=new class{build(e){Q("LayoutGroup",to);const t=e.world;e.addSystemToSchedule(ht.PreUpdate,pt([],()=>{const e=t.getEntitiesWithComponents([to,Zs,ue]);for(const n of e){const e=t.get(n,to),s=t.get(n,Zs),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,Zs)&&t.has(e,ie)&&r.push({entity:e,rect:t.get(e,Zs)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=ui(s,n),a=fi(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=ui(s.rect,s.entity),f=fi(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===Zr?(1-c)*a-d.top-(1-g)*f:e.childAlignment===eo?-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===Zr?-l*o+d.left+p*i:e.childAlignment===eo?(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 so{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(ht.PostUpdate,pt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const io=new so;async function ro(e,t,n){const s=e.getResource(Is);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function oo(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 ao=Me({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),lo=Me(null,"PhysicsAPI");function co(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 uo{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(ao,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=oo(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,pt([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=co(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),fo(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=co(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=co(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=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(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(ao,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(lo,po._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function fo(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 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 go={nearest:0,linear:1},yo={repeat:0,clamp:1,mirror:2};function _o(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=go[s.filterMode??"linear"]??1,a=yo[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 mo(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 wo(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 xo(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=Gt(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]=_o(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=qt(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"===fn(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=mo(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=_o(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 uo("",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=Gt(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=fn(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=_o(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=Gt(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=Bt.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=Bt.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=Gt(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=tn(e.world,n);if(l&&e.hasResource(Is))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=qt(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=wo(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(Pn);t&&t.setAddressableManifest(a)}}function vo(e,t,n){return{name:e,async setup(){await xo(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}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,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=qt(e.type);if(i){const s=e.data[i.skeletonField],r=e.data[i.atlasField];s&&("binary"===fn(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}const r=Gt(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=fn(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 So="__preview__";class Mo{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(Is);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 o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new bo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await xo(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,So)}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(Is).getScene(So),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(Is);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}`)}}}const Po={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=bs.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:bs.getTargetTexture(n),width:e.width,height:e.height}},release(e){bs.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(bs.releaseRenderTarget(e._handle),Po.create({width:t,height:n,depth:!0})),begin(e,t){bs.begin(t,e._handle)},end(){bs.end()},getDepthTexture:e=>bs.getTargetDepthTexture(e._handle)};var To;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(To||(To={}));class Eo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${To[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case To.Debug:console.debug(t,n);break;case To.Info:console.log(t,n);break;case To.Warn:console.warn(t,n);break;case To.Error:console.error(t,n)}}}class Ro{constructor(){this.handlers_=[],this.minLevel_=To.Info,this.addHandler(new Eo)}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(To.Debug,e,t,n)}info(e,t,n){this.log(To.Info,e,t,n)}warn(e,t,n){this.log(To.Warn,e,t,n)}error(e,t,n){this.log(To.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 Co=new Ro;function Ao(){return Co}function ko(e){Co.setMinLevel(e)}function Io(e,t,n){Co.debug(e,t,n)}function Fo(e,t,n){Co.info(e,t,n)}function Bo(e,t,n){Co.warn(e,t,n)}function zo(e,t,n){Co.error(e,t,n)}const Uo=[Ci,Xi,Ji,xr,Rr,lr,kr,zr,Or,Sr,pr,Hr,jr,qr,Jr,no,io];function $o(e,t){return function(e,t){const n=Us.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Yn(e),kt(e),as(e),us(e),xs(e),Ms(e);const i=new Es;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=Hs(e,s,t,i));const o=n.getResource(Mt);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(Mt,{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;bs.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-r)/1e3;let h;if(bs.resize(t,l),gs.isInitialized()&&gs.getPassCount()>0&&!gs.isBypassed()&&gs.resize(t,l),n.hasResource(Is)){const e=n.getResource(Is).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=Hs(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Ds,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})}bs.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(ht.First,l),n.addSystemToSchedule(ht.Last,c),n.addPlugin(En),n.addPlugin(Dn),n.addPlugin(St),n.addPlugin(zs),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Uo,...t})}e=p;export{je as Added,Us as App,Tn as AssetPlugin,Rn as AssetRefCounter,Mn as AssetServer,Pn as Assets,Xt as AsyncCache,fe as BitmapText,Pt as BlendMode,be as BodyType,we as BoxCollider,Vi as Button,Ni 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,ns as DataType,Ar as DragState,Cr as Draggable,Gn as Draw,Kr as Dropdown,nt as EntityCommands,lt as EventReader,dt as EventReaderInstance,ot as EventRegistry,at as EventWriter,ct as EventWriterInstance,Js as FillDirection,yr as FillMethod,_r as FillOrigin,ur as FocusManager,hr as FocusManagerState,dr as Focusable,Ts as GLDebug,ds as Geometry,ut as GetWorld,A as INVALID_ENTITY,I as INVALID_FONT,F as INVALID_MATERIAL,k as INVALID_TEXTURE,mr as Image,gr as ImageType,vt as Input,bt as InputPlugin,xt as InputState,Yi as Interactable,Nr as ListView,re as LocalTransform,To as LogLevel,Ro as Logger,Bt as Material,Yt as MaterialLoader,Xe as Mut,ge as Name,he as Parent,po as Physics,ao as PhysicsEvents,uo as PhysicsPlugin,gs as PostProcess,zn as PrefabServer,Un as Prefabs,$n as PrefabsPlugin,Mo as PreviewPlugin,Pr as ProgressBar,Mr as ProgressBarDirection,Er as ProgressBarPlugin,te as ProjectionType,Je as Query,Qe as QueryInstance,Ze as Removed,et as RemovedQueryInstance,Es as RenderPipeline,_s as RenderStage,Po as RenderTexture,bs as Renderer,Pe as Res,Te as ResMut,me as RigidBody,R as RuntimeConfig,Xr as SafeArea,se as ScaleMode,Is as SceneManager,ks as SceneManagerState,ye as SceneOwner,ht as Schedule,Ir as ScrollView,Ht as ShaderSources,$r as Slider,Ur as SliderDirection,Wr as SliderPlugin,pe as SpineAnimation,ae as Sprite,wt as SystemRunner,Pi as Text,bi as TextAlign,cr as TextInput,fr as TextInputPlugin,Mi as TextOverflow,Ri as TextPlugin,Ti as TextRenderer,Si as TextVerticalAlign,Ce as Time,vr as Toggle,ie as Transform,Mt as UICameraInfo,Gi as UIEventQueue,qi as UIEvents,ji as UIInteraction,ar as UIInteractionPlugin,Ki as UILayoutPlugin,Ii as UIMask,Hi as UIMaskPlugin,Zs as UIRect,so as UIRenderOrderPlugin,de as Velocity,bo as WebAssetProvider,He as World,oe as WorldTransform,_t as addStartupSystem,yt as addSystem,mt as addSystemToSchedule,oi as applyDirectionalFill,C as applyRuntimeConfig,En as assetPlugin,ts as clearDrawCallbacks,V as clearUserComponents,$ as color,si as computeFillAnchors,ri as computeFillSize,ii as computeHandleAnchors,Qs as computeUIRectLayout,Oi as createMaskProcessor,vo as createRuntimeSceneConfig,$o as createWebApp,Io as debug,Y as defineComponent,it as defineEvent,Me as defineResource,pt as defineSystem,j as defineTag,zo as error,an as findEntityByName,$s as flushPendingSystems,gn as getAddressableType,yn as getAddressableTypeByEditorType,mn as getAllAssetExtensions,bn as getAssetMimeType,fn as getAssetTypeEntry,Z as getComponent,Gt as getComponentAssetFieldDescriptors,Vt as getComponentAssetFields,_e as getComponentDefaults,Qt as getComponentEntityFields,qt as getComponentSpineFieldDescriptor,xn as getCustomExtensions,pn as getEditorType,Ao as getLogger,t as getPlatform,s as getPlatformType,N as getUserComponent,vn as getWeChatPackOptions,Fo as info,Yn as initDrawAPI,Ms as initGLDebugAPI,as as initGeometryAPI,kt as initMaterialAPI,us as initPostProcessAPI,xs as initRendererAPI,St as inputPlugin,An as instantiatePrefab,Fi as intersectRects,Bi as invertMatrix4,K as isBuiltinComponent,Sn as isCustomExtension,tr as isEditor,_n as isKnownAssetExtension,n as isPlatformInitialized,ir as isPlayMode,nr as isRuntime,Tt as isTextureRef,i as isWeChat,r as isWeb,rn as loadComponent,oo as loadPhysicsModule,xo as loadRuntimeScene,tn as loadSceneData,nn as loadSceneWithAssets,wn as looksLikeAssetPath,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Li as pointInOBB,Ui as pointInWorldRect,Dn as prefabsPlugin,Rr as progressBarPlugin,D as quat,Q as registerComponent,Nt as registerComponentAssetFields,Jt as registerComponentEntityFields,Zn as registerDrawCallback,Cn as registerEmbeddedAssets,Ot as registerMaterialCallback,Zt as remapEntityFields,zs as sceneManagerPlugin,zi as screenToWorld,er as setEditorMode,Gr as setListViewRenderer,ko as setLogLevel,sr as setPlayMode,Be as setWasmErrorHandler,jn as shutdownDrawAPI,Ps as shutdownGLDebugAPI,ls as shutdownGeometryAPI,It as shutdownMaterialAPI,fs as shutdownPostProcessAPI,vs as shutdownRendererAPI,Or as sliderPlugin,pi as syncFillSpriteSize,pr as textInputPlugin,Ci as textPlugin,ro as transitionTo,lr as uiInteractionPlugin,Ji as uiLayoutPlugin,Xi as uiMaskPlugin,Uo as uiPlugins,io as uiRenderOrderPlugin,G as unregisterComponent,es as unregisterDrawCallback,on as updateCameraAspectRatio,B as vec2,z as vec3,U as vec4,Bo as warn,Fs 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,P=1/60,M={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 Pe(e,t){const n=++Se;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Me(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=Pe({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.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw 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_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){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)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){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 ut(){return{_type:"get_world"}}!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(ht||(ht={}));let ft=0;function pt(e,t,n){const s=++ft;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function gt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function yt(e){gt().push({schedule:ht.Update,system:e})}function _t(e){gt().push({schedule:ht.Startup,system:e})}function mt(e,t){gt().push({schedule:e,system:t})}class wt{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_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class xt{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 vt=Pe(new xt,"Input");class bt{constructor(e){this.target_=e??null}build(e){const n=new xt;e.insertResource(vt,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,pt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const St=new bt,Pt=Pe({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 Tt(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 Et=null,Rt=null,Ct=1;const At=new Map;function kt(e){Et=e,Rt=e.getResourceManager(),Ot()}function It(){0!==Ut&&Et&&(Et._free(Ut),Ut=0),At.clear(),Ct=1,zt=!1,Dt.clear(),Lt=null,Rt=null,Et=null}function Ft(){if(!Rt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Rt}const Bt={createShader:(e,t)=>Ft().createShader(e,t),releaseShader(e){e>0&&Ft().releaseShader(e)},create(e){const t=Ct++,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 At.set(t,n),t},get:e=>At.get(e),setUniform(e,t,n){const s=At.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,Et?.invalidateMaterialCache(e))},getUniform(e,t){const n=At.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=At.get(e);n&&(n.blendMode=t,Et?.invalidateMaterialCache(e))},getBlendMode(e){const t=At.get(e);return t?.blendMode??Mt.Normal},setDepthTest(e,t){const n=At.get(e);n&&(n.depthTest=t,Et?.invalidateMaterialCache(e))},getShader(e){const t=At.get(e);return t?.shader??0},release(e){At.delete(e),Et?.invalidateMaterialCache(e)},isValid:e=>At.has(e),releaseAll(){At.clear(),Et?.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=At.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ct++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return At.set(n,s),n},toAssetData(e,t){const n=At.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=At.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let zt=!1,Ut=0;const $t=16384,Dt=new Map;let Lt=null;function Wt(e){const t=(0===Ut&&Et&&(Ut=Et._malloc($t)),Ut);if(0===t||!Et)return{ptr:0,count:0};let n=0,s=0;const i=Et.HEAPU8,r=Et.HEAPU32,o=Et.HEAPF32;for(const[a,l]of e){if(Tt(l))continue;let e=Dt.get(a);e||(Lt||(Lt=new TextEncoder),e=Lt.encode(a),Dt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>$t){console.warn(`[ESEngine] Material uniform buffer full (${n}/${$t} 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 Ot(){if(!Et||zt)return;Et.materialDataProvider=(e,t,n,s,i)=>{const r=At.get(e);if(!r)return Et.HEAPU32[t>>2]=0,Et.HEAPU32[n>>2]=0,Et.HEAPU32[s>>2]=0,void(Et.HEAPU32[i>>2]=0);Et.HEAPU32[t>>2]=r.shader,Et.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=Wt(r.uniforms);Et.HEAPU32[s>>2]=o,Et.HEAPU32[i>>2]=a},zt=!0}const Ht={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 Xt{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 Yt{constructor(e,t=""){this.cache_=new Xt,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&&(Bt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Bt.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:Bt.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 jt=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 Nt(e,t){jt.set(e,t)}function Vt(e){const t=jt.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 Gt(e){return jt.get(e)?.fields??[]}function qt(e){return jt.get(e)?.spine??null}const Kt=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Jt(e,t){Kt.set(e,t)}function Qt(e){return Kt.get(e)}function Zt(e,t){const n=Kt.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 en(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)Zt(i,n),rn(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 tn(e,t){return en(e,t)}async function nn(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,r=new Map;s&&await async function(e,t,n,s,i){const r=new Map;for(const e of sn.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=jt.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=[...sn.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=jt.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=en(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 sn=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 rn(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 on(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 an(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 ln=[{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}],cn={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"},dn=new Map,hn=new Set;for(const e of ln)for(const t of e.extensions)dn.set(t,e),hn.add(t);function un(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function fn(e){return dn.get(un(e))}function pn(e){return fn(e)?.editorType??"unknown"}function gn(e){return fn(e)?.addressableType??null}function yn(e){for(const t of ln)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function _n(e){return hn.has(e.toLowerCase())}function mn(){return hn}function wn(e){return"string"==typeof e&&(!!e.includes("/")&&_n(un(e)))}function xn(){const e=[];for(const t of ln)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function vn(){return xn().map(e=>({type:"suffix",value:e}))}function bn(e){return cn[e.toLowerCase()]}function Sn(e){const t=fn(e);return t?.wechatPackInclude??!1}class Pn{constructor(e){this.textureCache_=new Xt,this.shaderCache_=new Xt,this.jsonCache_=new Xt,this.textCache_=new Xt,this.binaryCache_=new Xt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Xt,this.prefabCache_=new Xt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=h(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 Yt(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(),Bt.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"===fn(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=fn(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const i=n?`${n}/${s}`:s;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],i=e.substring(0,e.lastIndexOf("/")),r=i?`${i}/${s}`:s,o=await this.loadTextureRaw(r);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of Vt(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=qt(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return nn(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,i){const r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=r;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const i=this.ctx_.getImageData(0,0,t,n),r=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(r);const o=this.module_.getResourceManager(),a=this.module_._malloc(r.length);this.module_.HEAPU8.set(r,a);const l=o.createTexture(t,n,a,r.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return Bt.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 Bt.createShader(i,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Mn=Pe(null,"Assets");class Tn{build(e){const t=e.wasmModule;t?e.insertResource(Mn,new Pn(t)):console.warn("AssetPlugin: No WASM module available")}}const En=new Tn;class Rn{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 Cn(e,t){const n=e.getResource(Mn);n&&n.registerEmbeddedAssets(t)}async function An(e,t,n){const{entities:s,rootId:i}=await In(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 nn(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 kn=10;async function In(e,t,n,s,i,r=0){if(r>kn)throw new Error(`Prefab nesting depth exceeded ${kn}. 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 In(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};Fn(h.components,o),Bn(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 Fn(e,t){for(const n of e){const e=Qt(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function Bn(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 zn{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 An(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Un=Pe(null,"Prefabs");class $n{constructor(){this.name="PrefabsPlugin",this.dependencies=[Mn]}build(e){const t=e.getResource(Mn);e.insertResource(Un,new zn(e.world,t))}}const Dn=new $n;let Ln=null,Wn=0,On=0,Hn=0;const Xn=new Float32Array(256);function Yn(e){Ln=e,Wn=Ln._malloc(64),On=Ln._malloc(64),Hn=Ln._malloc(1024)}function jn(){Ln&&(Wn&&(Ln._free(Wn),Wn=0),On&&(Ln._free(On),On=0),Hn&&(Ln._free(Hn),Hn=0)),Ln=null}function Nn(){if(!Ln)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ln}const Vn={r:1,g:1,b:1,a:1},Gn={begin(e){const t=Nn();try{t.HEAPF32.set(e,Wn/4),t.draw_begin(Wn)}catch(e){ze(e,"Draw.begin")}},end(){try{Nn().draw_end()}catch(e){ze(e,"Draw.end")}},line(e,t,n,s=1){try{Nn().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{Nn().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{Nn().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{Nn().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{Nn().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=Vn){try{Nn().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=Vn){try{Nn().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){Nn().draw_setLayer(e)},setDepth(e){Nn().draw_setDepth(e)},getDrawCallCount:()=>Ln?Ln.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ln?Ln.draw_getPrimitiveCount():0,setBlendMode(e){Nn().draw_setBlendMode(e)},setDepthTest(e){Nn().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=Nn();s.HEAPF32.set(n,On/4),s.draw_mesh(e,t,On)}catch(n){ze(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Nn(),i=Bt.get(t);if(!i)return;if(Gn.setBlendMode(i.blendMode),Gn.setDepthTest(i.depthTest),0===i.uniforms.size)return void Gn.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,On/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=Jn(t);if(!(s<0)){if(Tt(n))Xn[r++]=10,Xn[r++]=s,Xn[r++]=n.slot??e++,Xn[r++]=n.textureId;else if("number"==typeof n)Xn[r++]=1,Xn[r++]=s,Xn[r++]=n;else if(Array.isArray(n)){Xn[r++]=n.length,Xn[r++]=s;for(let e=0;e<n.length;e++)Xn[r++]=n[e]}else"w"in n?(Xn[r++]=4,Xn[r++]=s,Xn[r++]=n.x,Xn[r++]=n.y,Xn[r++]=n.z,Xn[r++]=n.w):"z"in n?(Xn[r++]=3,Xn[r++]=s,Xn[r++]=n.x,Xn[r++]=n.y,Xn[r++]=n.z):(Xn[r++]=2,Xn[r++]=s,Xn[r++]=n.x,Xn[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(Xn.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,On);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),Hn/4),s.draw_meshWithUniforms(e,i.shader,On,Hn,r)}catch(n){ze(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},qn={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},Kn=new Set;function Jn(e){const t=qn[e];return void 0!==t?t:(Kn.has(e)||(Kn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(qn).join(", ")}`)),-1)}const Qn=new Map;function Zn(e,t,n){Qn.set(e,{fn:t,scene:n??""})}function es(e){Qn.delete(e)}function ts(){Qn.clear()}var ns;!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"}(ns||(ns={}));let ss=null,is=0,rs=0,os=0;function as(e){ss=e,is=ss._malloc(262144),rs=ss._malloc(65536),os=ss._malloc(256)}function ls(){ss&&(is&&ss._free(is),rs&&ss._free(rs),os&&ss._free(os),is=0,rs=0,os=0),ss=null}function cs(){if(!ss)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ss}const ds={create(e){const t=cs(),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,is/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,os,i).set(r),t.geometry_init(n,is,s,os,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,rs,s).set(e.indices),t.geometry_setIndices16(n,rs,s)}else{new Uint32Array(t.HEAPU8.buffer,rs,s).set(e.indices),t.geometry_setIndices32(n,rs,s)}}return n},updateVertices(e,t,n=0){const s=cs(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,is/4),s.geometry_updateVertices(e,is,i,n)},release(e){e>0&&cs().geometry_release(e)},isValid:e=>!(!ss||e<=0)&&ss.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return ds.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:ns.Float2},{name:"a_texCoord",type:ns.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 ds.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:ns.Float2},{name:"a_texCoord",type:ns.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 ds.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:ns.Float2},{name:"a_texCoord",type:ns.Float2}],indices:new Uint16Array(o)})}};let hs=null;function us(e){hs=e}function fs(){hs&&gs.isInitialized()&&gs.shutdown(),hs=null}function ps(){if(!hs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return hs}const gs={init(e,t){try{return ps().postprocess_init(e,t)}catch(n){return ze(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{ps().postprocess_shutdown()}catch(e){ze(e,"PostProcess.shutdown")}},resize(e,t){try{ps().postprocess_resize(e,t)}catch(n){ze(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return ps().postprocess_addPass(e,t)}catch(t){return ze(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{ps().postprocess_removePass(e)}catch(t){ze(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{ps().postprocess_setPassEnabled(e,t)}catch(t){ze(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return ps().postprocess_isPassEnabled(e)}catch(t){return ze(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{ps().postprocess_setUniformFloat(e,t,n)}catch(n){ze(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){ze(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{ps().postprocess_begin()}catch(e){ze(e,"PostProcess.begin")}},end(){try{ps().postprocess_end()}catch(e){ze(e,"PostProcess.end")}},getPassCount(){try{return ps().postprocess_getPassCount()}catch(e){return ze(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!hs)return!1;try{return hs.postprocess_isInitialized()}catch(e){return ze(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{ps().postprocess_setBypass(e)}catch(e){ze(e,"PostProcess.setBypass")}},isBypassed(){if(!hs)return!0;try{return hs.postprocess_isBypassed()}catch(e){return ze(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Bt.createShader(ys,"#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:()=>Bt.createShader(ys,"#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:()=>Bt.createShader(ys,"#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:()=>Bt.createShader(ys,"#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")},ys="#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 _s;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(_s||(_s={}));let ms=null,ws=0;function xs(e){ms=e,ws=ms._malloc(64)}function vs(){ms&&ws&&(ms._free(ws),ws=0),ms=null}const bs={init(e,t){ms?.renderer_init(e,t)},resize(e,t){ms?.renderer_resize(e,t)},begin(e,t){if(ms&&ws)try{ms.HEAPF32.set(e,ws/4),ms.renderer_begin(ws,t??0)}catch(e){ze(e,"Renderer.begin")}},flush(){try{ms?.renderer_flush()}catch(e){ze(e,"Renderer.flush")}},end(){try{ms?.renderer_end()}catch(e){ze(e,"Renderer.end")}},submitSprites(e){if(ms)try{ms.renderer_submitSprites(e._cpp)}catch(e){ze(e,"Renderer.submitSprites")}},submitBitmapText(e){if(ms)try{ms.renderer_submitBitmapText(e._cpp)}catch(e){ze(e,"Renderer.submitBitmapText")}},submitSpine(e){if(ms)try{ms.renderer_submitSpine?.(e._cpp)}catch(e){ze(e,"Renderer.submitSpine")}},setStage(e){ms?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>ms?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){ms?.renderer_releaseTarget(e)},getTargetTexture:e=>ms?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>ms?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){ms?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){ms?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){ms?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){ms?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>ms?ms.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>ms?{drawCalls:ms.renderer_getDrawCalls(),triangles:ms.renderer_getTriangles(),sprites:ms.renderer_getSprites(),text:ms.renderer_getText(),spine:ms.renderer_getSpine?.()??0,meshes:ms.renderer_getMeshes(),culled:ms.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Ss=null;function Ps(e){Ss=e}function Ms(){Ss=null}const Ts={enable(){Ss?.gl_enableErrorCheck(!0)},disable(){Ss?.gl_enableErrorCheck(!1)},check:e=>Ss?.gl_checkErrors(e)??0,diagnose(){Ss?.renderer_diagnose()}};class Es{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_||(bs.resize(s,i),gs.isInitialized()&&gs.getPassCount()>0&&gs.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),bs.setViewport(0,0,s,i),bs.clearBuffers(3),bs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),bs.submitSprites(t),bs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):bs.submitSpine(t),bs.flush(),this.executeDrawCallbacks(n,r),bs.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;bs.setViewport(s.x,s.y,s.w,s.h),bs.setScissor(s.x,s.y,s.w,s.h,!0),bs.clearBuffers(i),bs.setScissor(0,0,0,0,!1),bs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),bs.submitSprites(t),bs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):bs.submitSpine(t),bs.flush(),this.executeDrawCallbacks(n,r),bs.end()}executeDrawCallbacks(e,t){const n=Qn;if(n.size>0){Gn.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)}Gn.end();for(const e of s)es(e)}}}const Rs="__scene_transition_overlay__";class Cs{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 As{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),Zn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=gs.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){gs.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 ks{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},Zn(Rs,()=>{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;Gn.setLayer(9999),Gn.setDepth(9999),Gn.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,es(Rs),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,es(Rs),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 Cs(t);this.scenes_.set(e,n);const s=new As(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Mn)?this.app_.getResource(Mn):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 Cs(t);this.scenes_.set(e,n);const s=new As(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Mn)?this.app_.getResource(Mn):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())es(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{gs.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(Mn)&&(i.assetServer=this.app_.getResource(Mn));const r=await nn(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=Fs(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(Mn)?this.app_.getResource(Mn):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)Bt.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{gs.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 Is=Pe(null,"SceneManager");function Fs(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Is).getSceneStatus(t)&&n._fn(...s)}}}const Bs=pt([Te(Is),Me(Ce)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),zs={name:"SceneManager",build(e){const t=new ks(e);e.insertResource(Is,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Is),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,Bs)}};class Us{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 Us}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)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return 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(Is).register(e),this}setInitialScene(e){return this.getResource(Is).setInitial(e),this}tick(e){this.runner_||(this.runner_=new wt(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 wt(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,ts();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=[Ms,vs,fs,ls,It,jn];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 $s(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 Ds=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ls(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 Ws=[];function Os(e){if(e<Ws.length)return Ws[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 Ws.push(t),t}function Hs(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=Ls(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=h*o,a=Ys(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=Ns(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const u=Gs(r.position.x,r.position.y,r.position.z),f=Os(c.length);f.entity=e,f.viewProjection.set(Ks(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 Xs=new Float32Array(16);function Ys(e,t,n,s,i,r){const o=Xs;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 js=new Float32Array(16);function Ns(e,t,n,s){const i=js;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 Vs=new Float32Array(16);function Gs(e,t,n){const s=Vs;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 qs=new Float32Array(16);function Ks(e,t){const n=qs;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 Js={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 Zs=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 ei=null,ti=null;function ni(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 si(e,t){switch(e){case Js.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Js.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Js.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 ii(e,t){switch(e){case Js.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Js.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Js.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 ri(e,t,n,s){switch(e){case Js.BottomToTop:case Js.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function oi(e,t,n,s){if(!e.has(t,Zs))return;const i=e.get(t,Zs),r=si(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,Zs,i)}function ai(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function li(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function ci(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(li(o.charCodeAt(0))&&s.length>0&&li(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!li(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 di(e){let t=1;for(;t<e;)t*=2;return t}function hi(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 ui(e,t){if(ei&&ti){const e=ei.getUIRectComputedWidth(ti,t);if(e>0)return e}return e.size.x}function fi(e,t){if(ei&&ti){const e=ei.getUIRectComputedHeight(ti,t);if(e>0)return e}return e.size.y}function pi(e,t,n,s,i,r){if(!e.has(t,ae))return;const o=e.get(t,ae);let a,l;switch(n){case Js.BottomToTop:case Js.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 gi(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 yi(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function _i(e,t,n,s,i){if(!e.has(t,Zs))return;const r=e.get(t,Zs),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 mi(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 wi=.1,xi=30,vi={r:.3,g:.5,b:.8,a:1},bi={Left:0,Center:1,Right:2},Si={Top:0,Middle:1,Bottom:2},Pi={Visible:0,Clip:1,Ellipsis:2},Mi=Y("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:bi.Left,verticalAlign:Si.Top,wordWrap:!0,overflow:Pi.Visible,lineHeight:1.2});class Ti{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,di(this.frameMaxW_)),e.height=Math.max(e.height,di(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=di(this.frameMaxW_),e.height=di(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=ci(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===Pi.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,di(f)),s.height=Math.max(s.height,di(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===Pi.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 Si.Top:x=d;break;case Si.Middle:x=d+(p-2*d-w)/2;break;case Si.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 bi.Left:s=d;break;case bi.Center:s=f/2;break;case bi.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===Pi.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const i=this.renderText(t,n);return this.cache.set(e,i),i}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case bi.Left:return"left";case bi.Center:return"center";case bi.Right:return"right"}}}const Ei=mi({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?ui(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?fi(e.uiRect,e.entity):0});class Ri{build(e){Q("Text",Mi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ti(t),s=e.world,i=new Map;e.addSystemToSchedule(ht.PreUpdate,pt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Mi));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Mi)){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([Mi]);for(const t of e){const e=s.get(t,Mi),r=s.has(t,Zs)?s.get(t,Zs):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Ei.changed(a,o)){if(s.has(t,ae)&&s.get(t,ae).texture!==k)continue}ni(s,t);const l=r?{size:{x:ui(r,t),y:fi(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,Ei.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ci=new Ri,Ai=0,ki=1,Ii=ee("UIMask",{enabled:!0,mode:Ai});function Fi(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 Bi(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,P=r*d-o*c,M=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+P*M;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*P-_*S+m*b)*k,n[3]=(f*S-u*P-p*b)*k,n[4]=(c*E-a*A-d*T)*k,n[5]=(s*A-r*E+o*T)*k,n[6]=(_*v-g*P-m*x)*k,n[7]=(h*P-f*v+p*x)*k,n[8]=(a*C-l*E+d*M)*k,n[9]=(i*E-s*C-o*M)*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*M)*k,n[13]=(s*R-i*T+r*M)*k,n[14]=(y*x-g*b-_*w)*k,n[15]=(h*b-u*x+f*w)*k),n}function zi(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 Ui(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 $i(e,t){return 2*Math.atan2(e,t)}function Di(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 Li(e,t,n,s,i,r,o,a,l,c){const d=$i(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 Wi(e,t,n,s,i,r,o){if(!e.has(t,Zs)||!e.has(t,ie))return null;const a=e.get(t,Zs),l=e.get(t,ie),c=ui(a,t)*l.worldScale.x,d=fi(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=$i(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,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=Di(e,t,n,s,i,r,o);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function Oi(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ii]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,Ii);n.enabled&&(h.add(e),n.mode===ki?(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;gi(t,e,e=>{if(i.has(e)){if(t.get(e,Ii).mode===Ai)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,Ii).mode===Ai){const e=Wi(t,n,r,o,a,l,c);e&&(s=Fi(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=Wi(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;gi(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 Hi{build(e){if(Q("UIMask",Ii),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Oi(e.wasmModule,e.world))}}const Xi=new Hi,Yi=ee("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),ji=ee("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Ni={Normal:0,Hovered:1,Pressed:2,Disabled:3},Vi=Y("Button",{state:Ni.Normal,transition:null});class Gi{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 qi=Pe(new Gi,"UIEvents");class Ki{build(e){Q("UIRect",Zs);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){ei=e,ti=t}(n,s);e.addSystemToSchedule(ht.PreUpdate,pt([Me(Pt)],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,pt([Me(Pt)],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,pt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ji=new Ki;let Qi=!1,Zi=!1;function er(e){Qi=e}function tr(){return Qi}function nr(){return!Qi}function sr(e){Zi=e}function ir(){return Zi}const rr=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&&(Bi(t,e),n=!1),e)}}();function or(e,t,n,s){t.emit(n,s,n),gi(e,n,i=>{if(!e.has(i,Yi))return!1;const r=e.get(i,Yi);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class ar{build(e){Q("Interactable",Yi),Q("Button",Vi);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new Gi;e.insertResource(qi,i);let r=null,o=null;e.addSystemToSchedule(ht.PreUpdate,pt([Me(vt),Me(Pt)],(e,a)=>{if(i.drain(),tr()&&!ir())return;const l=t.getEntitiesWithComponents([ji]);for(const e of l){const n=t.get(e,ji);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,ji,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;rr.update(a.viewProjection);const u=zi(d,h,rr.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,ji)){const e=t.get(r,ji);e.hovered=!1,t.insert(r,ji,e),i.emit(r,"hover_exit")}if(null!==m){yi(t,m,ji);const e=t.get(m,ji);e.hovered=!0,t.insert(m,ji,e),i.emit(m,"hover_enter")}r=m}if(g&&null!==m){const e=t.get(m,ji);e.pressed=!0,e.justPressed=!0,t.insert(m,ji,e),o=m,or(t,i,m,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,ji)){const e=t.get(o,ji);e.pressed=!1,e.justReleased=!0,t.insert(o,ji,e),or(t,i,o,"release"),o===r&&or(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(ht.Update,pt([],()=>{const e=t.getEntitiesWithComponents([Vi]);for(const n of e){if(yi(t,n,Yi,{enabled:!0}),!t.has(n,ji))continue;const e=t.get(n,ji),s=t.get(n,Vi),i=t.get(n,Yi),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=Ni.Pressed:e.hovered?s.state=Ni.Hovered:s.state=Ni.Normal:s.state=Ni.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,ae)){const r=t.get(n,ae);r.color=ai(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,ae,r)}}},{name:"ButtonSystem"}))}}const lr=new ar,cr=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}),dr=Y("Focusable",{tabIndex:0,isFocused:!1});class hr{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 ur=Pe(new hr,"FocusManager");class fr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Q("TextInput",cr),tr()&&!ir())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(ur);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,cr)?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,cr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(qi).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,cr);s.focused=!1,s.dirty=!0;e.getResource(ur).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,cr);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(qi).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,cr);e.focused=!1,e.dirty=!0}e.getResource(ur).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 P=null;function M(e,l,d,h){(i.width<d||i.height<h)&&(i.width=di(Math.max(i.width,d)),i.height=di(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=ci(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=ci(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,pt([Me(ur)],e=>{const t=n.getEntitiesWithComponents([cr]);for(const e of t)yi(n,e,dr,{tabIndex:0,isFocused:!1}),yi(n,e,Yi,{enabled:!0,blockRaycast:!0});const s=g();if(s!==P){if(null!==P&&n.valid(P)&&n.has(P,cr)){const e=n.get(P,cr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,cr);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(s),P=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(ht.PreUpdate,pt([],()=>{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,cr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,cr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([cr,Zs]);for(const e of a){const t=n.get(e,cr);if(!t.dirty)continue;const s=n.get(e,Zs),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(ni(n,e),M(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const pr=new fr,gr={Simple:0,Sliced:1,Tiled:2,Filled:3},yr={Horizontal:0,Vertical:1},_r={Left:0,Right:1,Bottom:2,Top:3},mr=Y("Image",{texture:k,color:{r:1,g:1,b:1,a:1},imageType:gr.Simple,fillMethod:yr.Horizontal,fillOrigin:_r.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),wr=mi({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?ui(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?fi(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const xr=new class{build(e){Q("Image",mr);const t=e.world,n=new Map;e.addSystemToSchedule(ht.PreUpdate,pt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,mr)||n.delete(e);const e=t.getEntitiesWithComponents([mr]);for(const s of e){const e=t.get(s,mr),i=t.has(s,Zs)?t.get(s,Zs):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!wr.changed(o,r))continue;ni(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=ui(i,s),a.size.y=fi(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===gr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===yr.Horizontal?e.fillOrigin===_r.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===_r.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===gr.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(s,ae,a),n.set(s,wr.take(r))}else a.color.a=0,t.insert(s,ae,a),n.set(s,wr.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},vr=Y("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),br=Y("ToggleGroup",{allowSwitchOff:!1});const Sr=new class{build(e){Q("Toggle",vr),Q("ToggleGroup",br);const t=e.world,n=new Set;e.addSystemToSchedule(ht.Update,pt([Me(qi)],e=>{const s=t.getEntitiesWithComponents([vr]);if(!tr()||ir()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,vr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,vr,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,vr);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(yi(t,n,Yi,{enabled:!0}),!t.has(n,ji))continue;const s=t.get(n,ji),i=t.get(n,vr),o=t.get(n,Yi);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,br);if(i.isOn&&o){if(!t.get(s,br).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,vr,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,vr);i.isOn&&(i.isOn=!1,t.insert(s,vr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,ae)){const e=t.get(n,ae);e.color=ai(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,ae,e)}}}for(const e of s){const n=t.get(e,vr);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"]})}},Pr=Js,Mr=Y("ProgressBar",{value:0,fillEntity:0,direction:Js.LeftToRight});function Tr(e,t,n,s){if(!e.has(t,Zs))return;const i=e.get(t,Zs),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 Er{build(e){Q("ProgressBar",Mr);const t=e.world;e.addSystemToSchedule(ht.PreUpdate,pt([],()=>{const e=t.getEntitiesWithComponents([Mr,Zs]);for(const n of e){const e=t.get(n,Mr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Zs),i=Math.max(0,Math.min(1,e.value));oi(t,e.fillEntity,e.direction,i);const r=ui(s,n),o=fi(s,n);Tr(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Rr=new Er,Cr=Y("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Ar=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 kr=new class{build(e){Q("Draggable",Cr),Q("DragState",Ar);const t=e.world,n=e.getResource(qi);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(ht.PreUpdate,pt([Me(vt),Me(Pt)],(e,o)=>{if(tr()&&!ir())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Cr,ji]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,Cr).enabled)continue;if(t.get(s,ji).hovered){let e=0;t.has(s,ae)&&(e=t.get(s,ae).layer);const i=hi(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,Ar)||t.insert(n,Ar);const e=t.get(n,Ar),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,Ar)){t.get(s,Ar).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,Cr);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,Ar).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,Ar))return void(r=null);const s=t.get(r,Ar),i=t.get(r,Cr),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=$i(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"}))}},Ir=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 Fr(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 Br(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 zr=new class{build(e){Q("ScrollView",Ir);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(ht.PostUpdate,pt([Me(vt),Me(Pt),Me(Ce)],(e,i,r)=>{const o=tr()&&!ir(),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([Ir,Zs]);for(const r of l){yi(t,r,Ii,{enabled:!0,mode:Ai});const l=t.get(r,Ir),c=t.get(r,Zs);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=ui(c,r),u=fi(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,Zs)){const e=t.get(o,Zs);a=ui(e,o)||e.size.x,l=fi(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){yi(t,r,Yi,{enabled:!0,blockRaycast:!0});const n=t.has(r,ji)?t.get(r,ji):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=Fr(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=Fr(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=Fr(l.scrollY,0,y,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Fr(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=Br(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)<wi&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>wi?(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=Br(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)<wi&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>wi?(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"]})}},Ur=Js,$r=Y("Slider",{value:0,minValue:0,maxValue:1,direction:Js.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Dr(e,t,n,s,i,r){const o=ui(s,i)*n.worldScale.x,a=fi(s,i)*n.worldScale.y,l=$i(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 Js.LeftToRight:return o>0?(f-g)/o:0;case Js.RightToLeft:return o>0?1-(f-g)/o:0;case Js.BottomToTop:return a>0?(p-y)/a:0;case Js.TopToBottom:return a>0?1-(p-y)/a:0}}function Lr(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Js.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case Js.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case Js.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case Js.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class Wr{build(e){Q("Slider",$r);const t=e.world;let n=null;e.addSystemToSchedule(ht.PreUpdate,pt([Me(vt),Me(Pt),Me(qi)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([$r,Zs]);for(const o of r){const r=t.get(o,$r),a=t.get(o,Zs);if(!tr()||ir()){if(t.has(o,ie)){yi(t,o,Yi,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&yi(t,r.handleEntity,Yi,{enabled:!0,blockRaycast:!1});const l=t.get(o,ie),c=t.has(o,ji)?t.get(o,ji):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,ji)&&(d=t.get(r.handleEntity,ji).justPressed),d&&(n=o),n===o&&e.isMouseButtonDown(0)){let e=Dr(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,$r,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=ui(a,o),h=fi(a,o),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(oi(t,r.fillEntity,r.direction,c),_i(t,r.fillEntity,u,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,Zs)){const e=t.get(r.handleEntity,Zs);Lr(e,r.direction,c),t.insert(r.handleEntity,Zs,e),_i(t,r.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Or=new Wr;const Hr=new class{build(e){Q("Focusable",dr);const t=e.world,n=new hr;e.insertResource(ur,n),e.addSystemToSchedule(ht.Update,pt([Me(vt),Me(qi)],(e,s)=>{if(tr()&&!ir())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([dr]);for(const e of i){if(!t.has(e,ji))continue;t.get(e,ji).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,Yi)){if(!t.get(n,Yi).enabled)continue}const s=t.get(n,dr);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,dr)){t.get(i,dr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,dr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},Xr=Y("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Yr(){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 jr=new class{build(e){Q("SafeArea",Xr);const t=e.world;let n=Yr(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Yr(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Yr(),s=!0});e.addSystemToSchedule(ht.PreUpdate,pt([Me(Pt)],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([Xr,Zs]);for(const e of d){const s=t.get(e,Xr),i=t.get(e,Zs),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,Zs,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},Nr=Y("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Vr=null;function Gr(e,t){if(!Vr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Vr.get(e);n?n.renderer=t:Vr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const qr=new class{build(e){Q("ListView",Nr);const t=e.world,n=new Map;Vr=n,e.addSystemToSchedule(ht.PostUpdate,pt([Me(vt)],e=>{const s=tr()&&!ir();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([Nr,Zs]);for(const r of i){yi(t,r,Yi,{enabled:!0,blockRaycast:!0}),yi(t,r,Ii,{enabled:!0,mode:Ai});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,Nr),a=t.get(r,Zs),l=fi(a,r),c=ui(a,r);if(!s){const n=t.has(r,ji)?t.get(r,ji):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,Zs,{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"]})}},Kr=Y("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Jr=new class{build(e){Q("Dropdown",Kr);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*xi;t.insert(i,Zs,{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)*xi;t.insert(r,ge,{value:`Option_${e}`}),t.insert(r,Zs,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*xi},offsetMax:{x:0,y:0},size:{x:o,y:xi},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:xi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,Yi,{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,Mi,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:bi.Left,verticalAlign:Si.Middle,wordWrap:!1,overflow:Pi.Clip,lineHeight:1.2}),t.insert(c,Zs,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:xi},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,Mi))return;const s=t.get(n,Mi);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,Mi,{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,Yi)&&t.insert(e,Yi,{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?{...vi}:{r:.95,g:.95,b:.95,a:1};t.insert(s,ae,{texture:k,color:i,size:{x:e.ddWidth,y:xi},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,ji))continue;if(t.get(n,ji).hovered)return!0}return!1}e.addSystemToSchedule(ht.Update,pt([Me(vt),Me(qi)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=tr()&&!ir(),p=t.getEntitiesWithComponents([Kr]);for(const g of p){const p=t.get(g,Kr);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;yi(t,g,Yi,{enabled:!0,blockRaycast:!0});const _=t.has(g,ji)?t.get(g,ji):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,ji))continue;if(t.get(n,ji).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,ji))continue;if(t.get(s,ji).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,Zr=0,eo=2,to=Y("LayoutGroup",{direction:Qr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Zr,reverseOrder:!1});const no=new class{build(e){Q("LayoutGroup",to);const t=e.world;e.addSystemToSchedule(ht.PreUpdate,pt([],()=>{const e=t.getEntitiesWithComponents([to,Zs,ue]);for(const n of e){const e=t.get(n,to),s=t.get(n,Zs),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,Zs)&&t.has(e,ie)&&r.push({entity:e,rect:t.get(e,Zs)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=ui(s,n),a=fi(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=ui(s.rect,s.entity),f=fi(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===Zr?(1-c)*a-d.top-(1-g)*f:e.childAlignment===eo?-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===Zr?-l*o+d.left+p*i:e.childAlignment===eo?(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 so{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(ht.PostUpdate,pt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const io=new so;async function ro(e,t,n){const s=e.getResource(Is);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function oo(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 ao=Pe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),lo=Pe(null,"PhysicsAPI");function co(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 uo{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(ao,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=oo(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,pt([Me(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=co(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),fo(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=co(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=co(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=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(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(ao,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(lo,po._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function fo(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 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 go={nearest:0,linear:1},yo={repeat:0,clamp:1,mirror:2};function _o(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=go[s.filterMode??"linear"]??1,a=yo[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 mo(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 wo(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 xo(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=Gt(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]=_o(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=qt(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"===fn(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=mo(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=_o(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??{...M},fixedTimestep:o?.fixedTimestep??T,subStepCount:o?.subStepCount??4};new uo("",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=Gt(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=fn(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=_o(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=Gt(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=Bt.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=Bt.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=Gt(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=tn(e.world,n);if(l&&e.hasResource(Is))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=qt(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=P);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=wo(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(Mn);t&&t.setAddressableManifest(a)}}function vo(e,t,n){return{name:e,async setup(){await xo(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}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,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=qt(e.type);if(i){const s=e.data[i.skeletonField],r=e.data[i.atlasField];s&&("binary"===fn(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}const r=Gt(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=fn(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 So="__preview__";class Po{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(Is);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 o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new bo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await xo(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,So)}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(Is).getScene(So),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(Is);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}`)}}}const Mo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=bs.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:bs.getTargetTexture(n),width:e.width,height:e.height}},release(e){bs.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(bs.releaseRenderTarget(e._handle),Mo.create({width:t,height:n,depth:!0})),begin(e,t){bs.begin(t,e._handle)},end(){bs.end()},getDepthTexture:e=>bs.getTargetDepthTexture(e._handle)};var To;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(To||(To={}));class Eo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${To[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case To.Debug:console.debug(t,n);break;case To.Info:console.log(t,n);break;case To.Warn:console.warn(t,n);break;case To.Error:console.error(t,n)}}}class Ro{constructor(){this.handlers_=[],this.minLevel_=To.Info,this.addHandler(new Eo)}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(To.Debug,e,t,n)}info(e,t,n){this.log(To.Info,e,t,n)}warn(e,t,n){this.log(To.Warn,e,t,n)}error(e,t,n){this.log(To.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 Co=new Ro;function Ao(){return Co}function ko(e){Co.setMinLevel(e)}function Io(e,t,n){Co.debug(e,t,n)}function Fo(e,t,n){Co.info(e,t,n)}function Bo(e,t,n){Co.warn(e,t,n)}function zo(e,t,n){Co.error(e,t,n)}const Uo=[Ci,Xi,Ji,xr,Rr,lr,kr,zr,Or,Sr,pr,Hr,jr,qr,Jr,no,io];function $o(e,t){return function(e,t){const n=Us.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Yn(e),kt(e),as(e),us(e),xs(e),Ps(e);const i=new Es;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=Hs(e,s,t,i));const o=n.getResource(Pt);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(Pt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});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;bs.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-r)/1e3;let h;if(bs.resize(t,l),gs.isInitialized()&&gs.getPassCount()>0&&!gs.isBypassed()&&gs.resize(t,l),n.hasResource(Is)){const e=n.getResource(Is).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=Hs(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Ds,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})}bs.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(ht.First,l),n.addSystemToSchedule(ht.Last,c),n.addPlugin(En),n.addPlugin(Dn),n.addPlugin(St),n.addPlugin(zs),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Uo,...t})}e=p;export{je as Added,Us as App,Tn as AssetPlugin,Rn as AssetRefCounter,Pn as AssetServer,Mn as Assets,Xt as AsyncCache,fe as BitmapText,Mt as BlendMode,be as BodyType,we as BoxCollider,Vi as Button,Ni 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,P as DEFAULT_FALLBACK_DT,T as DEFAULT_FIXED_TIMESTEP,x as DEFAULT_FONT_FAMILY,v as DEFAULT_FONT_SIZE,M 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,ns as DataType,Ar as DragState,Cr as Draggable,Gn as Draw,Kr as Dropdown,nt as EntityCommands,lt as EventReader,dt as EventReaderInstance,ot as EventRegistry,at as EventWriter,ct as EventWriterInstance,Js as FillDirection,yr as FillMethod,_r as FillOrigin,ur as FocusManager,hr as FocusManagerState,dr as Focusable,Ts as GLDebug,ds as Geometry,ut as GetWorld,A as INVALID_ENTITY,I as INVALID_FONT,F as INVALID_MATERIAL,k as INVALID_TEXTURE,mr as Image,gr as ImageType,vt as Input,bt as InputPlugin,xt as InputState,Yi as Interactable,Nr as ListView,re as LocalTransform,To as LogLevel,Ro as Logger,Bt as Material,Yt as MaterialLoader,Xe as Mut,ge as Name,he as Parent,po as Physics,ao as PhysicsEvents,uo as PhysicsPlugin,gs as PostProcess,zn as PrefabServer,Un as Prefabs,$n as PrefabsPlugin,Po as PreviewPlugin,Mr as ProgressBar,Pr as ProgressBarDirection,Er as ProgressBarPlugin,te as ProjectionType,Je as Query,Qe as QueryInstance,Ze as Removed,et as RemovedQueryInstance,Es as RenderPipeline,_s as RenderStage,Mo as RenderTexture,bs as Renderer,Me as Res,Te as ResMut,me as RigidBody,R as RuntimeConfig,Xr as SafeArea,se as ScaleMode,Is as SceneManager,ks as SceneManagerState,ye as SceneOwner,ht as Schedule,Ir as ScrollView,Ht as ShaderSources,$r as Slider,Ur as SliderDirection,Wr as SliderPlugin,pe as SpineAnimation,ae as Sprite,wt as SystemRunner,Mi as Text,bi as TextAlign,cr as TextInput,fr as TextInputPlugin,Pi as TextOverflow,Ri as TextPlugin,Ti as TextRenderer,Si as TextVerticalAlign,Ce as Time,vr as Toggle,ie as Transform,Pt as UICameraInfo,Gi as UIEventQueue,qi as UIEvents,ji as UIInteraction,ar as UIInteractionPlugin,Ki as UILayoutPlugin,Ii as UIMask,Hi as UIMaskPlugin,Zs as UIRect,so as UIRenderOrderPlugin,de as Velocity,bo as WebAssetProvider,He as World,oe as WorldTransform,_t as addStartupSystem,yt as addSystem,mt as addSystemToSchedule,oi as applyDirectionalFill,C as applyRuntimeConfig,En as assetPlugin,ts as clearDrawCallbacks,V as clearUserComponents,$ as color,si as computeFillAnchors,ri as computeFillSize,ii as computeHandleAnchors,Qs as computeUIRectLayout,Oi as createMaskProcessor,vo as createRuntimeSceneConfig,$o as createWebApp,Io as debug,Y as defineComponent,it as defineEvent,Pe as defineResource,pt as defineSystem,j as defineTag,zo as error,an as findEntityByName,$s as flushPendingSystems,gn as getAddressableType,yn as getAddressableTypeByEditorType,mn as getAllAssetExtensions,bn as getAssetMimeType,fn as getAssetTypeEntry,Z as getComponent,Gt as getComponentAssetFieldDescriptors,Vt as getComponentAssetFields,_e as getComponentDefaults,Qt as getComponentEntityFields,qt as getComponentSpineFieldDescriptor,xn as getCustomExtensions,pn as getEditorType,Ao as getLogger,t as getPlatform,s as getPlatformType,N as getUserComponent,vn as getWeChatPackOptions,Fo as info,Yn as initDrawAPI,Ps as initGLDebugAPI,as as initGeometryAPI,kt as initMaterialAPI,us as initPostProcessAPI,xs as initRendererAPI,St as inputPlugin,An as instantiatePrefab,Fi as intersectRects,Bi as invertMatrix4,K as isBuiltinComponent,Sn as isCustomExtension,tr as isEditor,_n as isKnownAssetExtension,n as isPlatformInitialized,ir as isPlayMode,nr as isRuntime,Tt as isTextureRef,i as isWeChat,r as isWeb,rn as loadComponent,oo as loadPhysicsModule,xo as loadRuntimeScene,tn as loadSceneData,nn as loadSceneWithAssets,wn as looksLikeAssetPath,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Li as pointInOBB,Ui as pointInWorldRect,Dn as prefabsPlugin,Rr as progressBarPlugin,D as quat,Q as registerComponent,Nt as registerComponentAssetFields,Jt as registerComponentEntityFields,Zn as registerDrawCallback,Cn as registerEmbeddedAssets,Ot as registerMaterialCallback,Zt as remapEntityFields,zs as sceneManagerPlugin,zi as screenToWorld,er as setEditorMode,Gr as setListViewRenderer,ko as setLogLevel,sr as setPlayMode,Be as setWasmErrorHandler,jn as shutdownDrawAPI,Ms as shutdownGLDebugAPI,ls as shutdownGeometryAPI,It as shutdownMaterialAPI,fs as shutdownPostProcessAPI,vs as shutdownRendererAPI,Or as sliderPlugin,pi as syncFillSpriteSize,pr as textInputPlugin,Ci as textPlugin,ro as transitionTo,lr as uiInteractionPlugin,Ji as uiLayoutPlugin,Xi as uiMaskPlugin,Uo as uiPlugins,io as uiRenderOrderPlugin,G as unregisterComponent,es as unregisterDrawCallback,on as updateCameraAspectRatio,B as vec2,z as vec3,U as vec4,Bo as warn,Fs as wrapSceneSystem};//# sourceMappingURL=index.js.mapdiff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.tsindex a0e1c5c17..40a36a16c 100644--- a/sdk/src/asset/AssetServer.ts+++ b/sdk/src/asset/AssetServer.ts@@ -16,6 +16,7 @@ import { AsyncCache } from './AsyncCache';import type { PrefabData } from '../prefab';import type { SpineModuleController } from '../spine/SpineController';import { type AddressableAssetType, getAssetTypeEntry } from '../assetTypes';+import { getComponentAssetFields, getComponentSpineFieldDescriptor } from '../scene';// =============================================================================// Types@@ -128,6 +129,7 @@ export class AssetServer {private spineController_: SpineModuleController | null = null;private spineSkeletons_ = new Map<string, number>();private textureRefCounts_ = new Map<string, number>();+ private assetRefResolver_: ((ref: string) => string | null) | null = null;constructor(module: ESEngineModule) {this.module_ = module;@@ -427,15 +429,57 @@ export class AssetServer {return rm.loadBitmapFont(fntContent, texInfo.handle, texInfo.width, texInfo.height) as FontHandle;}+ // =========================================================================+ // Asset Ref Resolver+ // =========================================================================++ setAssetRefResolver(resolver: (ref: string) => string | null): void {+ this.assetRefResolver_ = resolver;+ }+// =========================================================================// Prefab// =========================================================================async loadPrefab(path: string, baseUrl?: string): Promise<PrefabData> {const url = this.resolveUrl(path, baseUrl);- return this.prefabCache_.getOrLoad(url, () =>- this.fetchJson(url) as Promise<PrefabData>- );+ return this.prefabCache_.getOrLoad(url, async () => {+ const data = await this.fetchJson(url) as PrefabData;+ if (this.assetRefResolver_) {+ this.resolvePrefabRefs_(data);+ }+ return data;+ });+ }++ private resolvePrefabRefs_(prefab: PrefabData): void {+ const resolve = this.assetRefResolver_!;+ for (const entity of prefab.entities) {+ for (const comp of entity.components) {+ if (!comp.data) continue;+ for (const field of getComponentAssetFields(comp.type)) {+ const value = comp.data[field];+ if (typeof value === 'string' && value) {+ const resolved = resolve(value);+ if (resolved) comp.data[field] = resolved;+ }+ }+ const spine = getComponentSpineFieldDescriptor(comp.type);+ if (spine) {+ for (const field of [spine.skeletonField, spine.atlasField]) {+ const value = comp.data[field];+ if (typeof value === 'string' && value) {+ const resolved = resolve(value);+ if (resolved) comp.data[field] = resolved;+ }+ }+ }+ }+ if (entity.nestedPrefab?.prefabPath) {+ const resolved = resolve(entity.nestedPrefab.prefabPath);+ if (resolved) entity.nestedPrefab.prefabPath = resolved;+ }+ }}// =========================================================================@@ -688,12 +732,25 @@ export class AssetServer {}private async loadImage(source: string): Promise<HTMLImageElement | ImageBitmap> {- const localPath = this.isLocalPath(source) ? this.toLocalPath(source) : source;- const embedded = this.embedded_.get(localPath);- if (this.embeddedOnly_ && !embedded) {+ const localPath = this.isLocalPath(source) ? this.toLocalPath(source) : null;+ if (localPath) {+ const embedded = this.embedded_.get(localPath);+ if (embedded) {+ return this.loadImageFromSrc(embedded);+ }+ if (this.embeddedOnly_) {+ throw new Error(`Asset not embedded: ${source}`);+ }+ const imgSrc = this.baseUrl ? `${this.baseUrl}/${localPath}` : localPath;+ return this.loadImageFromSrc(imgSrc);+ }+ if (this.embeddedOnly_) {throw new Error(`Asset not embedded: ${source}`);}- const imgSrc = embedded ?? localPath;+ return this.loadImageFromSrc(source);+ }++ private loadImageFromSrc(imgSrc: string): Promise<HTMLImageElement | ImageBitmap> {return new Promise((resolve, reject) => {const img = platformCreateImage();img.crossOrigin = 'anonymous';@@ -712,7 +769,7 @@ export class AssetServer {}resolve(img);};- img.onerror = () => reject(new Error(`Failed to load image: ${source}`));+ img.onerror = () => reject(new Error(`Failed to load image: ${imgSrc}`));img.src = imgSrc;});}@@ -881,7 +938,7 @@ export class AssetServer {}private isLocalPath(url: string): boolean {- return !url.startsWith('http://') && !url.startsWith('https://');+ return !url.startsWith('http://') && !url.startsWith('https://') && !url.startsWith('asset://');}private toLocalPath(url: string): string {