Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat: reuse hierarchy and inspector panels in play mode (Unity-style)

esengine4805f9eac412
diff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.ts
index 481a98451..0a018505e 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -695,6 +695,8 @@ declare class World {
private removeScript;
private getStorage;
resetQueryPool(): void;
+ getComponentTypes(entity: Entity): string[];
+ private findScriptName;
getEntitiesWithComponents(components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]): Entity[];
}
@@ -1600,6 +1602,9 @@ declare class App {
private error_handler_;
private system_error_handler_;
private frame_paused_;
+ private user_paused_;
+ private step_pending_;
+ private play_speed_;
private constructor();
static new(): App;
addPlugin(plugin: Plugin): this;
@@ -1627,6 +1632,11 @@ declare class App {
onError(handler: (error: unknown, systemName: string) => void): this;
onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;
onWasmError(handler: (error: unknown, context: string) => void): this;
+ setPaused(paused: boolean): void;
+ isPaused(): boolean;
+ stepFrame(): void;
+ setPlaySpeed(speed: number): void;
+ getPlaySpeed(): number;
insertResource<T>(resource: ResourceDef<T>, value: T): this;
getResource<T>(resource: ResourceDef<T>): T;
hasResource<T>(resource: ResourceDef<T>): boolean;
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index d9d3c413d..149cfd310 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return null!==e}function n(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function h(e,s){return t().instantiateWasm(e,s)}function u(e,s){return t().createCanvas(e,s)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const s=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),n={};return s.headers.forEach((e,t)=>{n[t]=e}),{ok:s.ok,status:s.status,statusText:s.statusText,headers:n,json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let s;s="string"==typeof e?await this.readFile(e):e;const n=await WebAssembly.instantiate(s,t);return{instance:n.instance,module:n.module}}createImage(){return new Image}createCanvas(e,t){let s;return s="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),s.width=e,s.height=t,s}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t??document.querySelector("canvas")??document.body,n=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),i=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},o=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},h=()=>{e.onPointerUp(0)},u=t=>{const s=t;e.onWheel(s.deltaX,s.deltaY)};document.addEventListener("keydown",n),document.addEventListener("keyup",r),s.addEventListener("mousemove",i),s.addEventListener("mousedown",o),s.addEventListener("mouseup",a),s.addEventListener("touchstart",c),s.addEventListener("touchmove",l),s.addEventListener("touchend",h),s.addEventListener("wheel",u),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",r),s.removeEventListener("mousemove",i),s.removeEventListener("mousedown",o),s.removeEventListener("mouseup",a),s.removeEventListener("touchstart",c),s.removeEventListener("touchmove",l),s.removeEventListener("touchend",h),s.removeEventListener("wheel",u)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,_=1080,m=100,g=512,y={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function w(e){e.Text&&(e.Text._default.fontFamily=y.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=y.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=y.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=y.canvasMatchWidthOrHeight)}const x=0,v=4294967295,b=4294967295,S=(e=0,t=0)=>({x:e,y:t}),P=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),C=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),T=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),E=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function M(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(M);const t={};for(const s in e)t[s]=M(e[s]);return t}let R=0;function A(e,t){const s=++R;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...M(t),...e}:M(t)}}function I(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const s=I(),n=s.get(e);if(n)return n;const r=A(e,t);return s.set(e,r),U(e,t,!1),r}function $(e){const t=I(),s=t.get(e);if(s)return s;const n=A(e,{});return t.set(e,n),U(e,{},!0),n}function k(e){return I().get(e)}function B(){I().clear()}function U(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function D(e){return!0===e._builtin}const z=new Map;function L(e,t){z.set(e,t)}function O(e){return z.get(e)??k(e)}function H(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return z.set(e,s),s}const W={Perspective:0,Orthographic:1},j={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},N={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},V=H("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),X=H("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Y=H("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),q=H("Camera",{projectionType:W.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:j.ColorAndDepth}),G=H("Canvas",{designResolution:{x:p,y:_},pixelsPerUnit:100,scaleMode:N.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),J=H("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),K=H("Parent",{entity:0}),Q=H("Children",{entities:[]}),Z=H("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:b}),ee=H("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}),te={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},se=F("SceneOwner",{scene:"",persistent:!1});function ne(e){const t=O(e);return t?M(t._default):null}L("Name",te);const re=H("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ie=H("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),oe=H("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ae=H("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ce={Static:0,Kinematic:1,Dynamic:2};let le=0;function he(e,t){const s=++le;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ue(e){return{_type:"res",_resource:e}}function de(e){return{_type:"res_mut",_resource:e}}class fe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class pe{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new fe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const _e=he({delta:0,elapsed:0,frameCount:0},"Time");function me(e){return{_type:"mut",_component:e}}function ge(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function ye(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{ge(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class we{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ge(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let h=null;this.world_.beginIteration();try{for(const u of n){if(null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(u,t[s])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];h=u}yield a}}finally{if(this.world_.endIteration(),null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function xe(){return{_type:"commands"}}class ve{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class be{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ve(this,null);return this.spawned_.push(e),e}entity(e){return new ve(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Se;!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"}(Se||(Se={}));let Pe=0;function Ce(e,t,s){const n=++Pe;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Te(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ee(e){Te().push({schedule:Se.Update,system:e})}function Me(e){Te().push({schedule:Se.Startup,system:e})}function Re(e,t){Te().push({schedule:e,system:t})}class Ae{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof be&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new we(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new be(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{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 Fe=he(new Ie,"Input");class $e{constructor(e){this.target_=e??null}build(e){const s=new Ie;e.insertResource(Fe,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Se.Last,Ce([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ke=new $e;function Be(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=Ue(t[e]),i=Ue(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function Ue(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function De(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let ze=null;function Le(e){ze=e}function Oe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ze&&ze(e,t)}function He(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="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}:He(e)}}return t}class We{constructor(){this.cppRegistry_=null,this.entities_=new Set,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}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Oe(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),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.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Oe(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}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&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Oe(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Oe(t,`removeParent(entity=${e})`)}}insert(e,t,s){return D(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(D(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Oe(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Be(t._name,t._default,n);if(e.length>0)throw new Error(De(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(r))}catch(s){Oe(s,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(s){return Oe(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return Oe(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Oe(s,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Be(t._name,t._default,e);if(r.length>0)throw new Error(De(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!D(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=i?i.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const je=he({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Ne;function Ve(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"}(Ne||(Ne={}));let Xe=null,Ye=null,qe=1;const Ge=new Map;function Je(e){Xe=e,Ye=e.getResourceManager(),ot()}function Ke(){0!==tt&&Xe&&(Xe._free(tt),tt=0),Ge.clear(),qe=1,et=!1,nt.clear(),rt=null,Ye=null,Xe=null}function Qe(){if(!Ye)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ye}const Ze={createShader:(e,t)=>Qe().createShader(e,t),releaseShader(e){e>0&&Qe().releaseShader(e)},create(e){const t=qe++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ne.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Ge.set(t,s),t},get:e=>Ge.get(e),setUniform(e,t,s){const n=Ge.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ge.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ge.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ge.get(e);return t?.blendMode??Ne.Normal},setDepthTest(e,t){const s=Ge.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ge.get(e);return t?.shader??0},release(e){Ge.delete(e)},isValid:e=>Ge.has(e),releaseAll(){Ge.clear()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??Ne.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ge.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=qe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ge.set(s,n),s},toAssetData(e,t){const s=Ge.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=Ge.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let et=!1,tt=0;const st=4096,nt=new Map;let rt=null;function it(e){const t=(0===tt&&Xe&&(tt=Xe._malloc(st)),tt);if(0===t||!Xe)return{ptr:0,count:0};let s=0,n=0;const r=Xe.HEAPU8,i=Xe.HEAPU32,o=Xe.HEAPF32;for(const[a,c]of e){if(s+128>st)break;let e=nt.get(a);e||(rt||(rt=new TextEncoder),e=rt.encode(a),nt.set(a,e));const l=e.length,h=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=h;let u=0,d=[0,0,0,0];if("number"==typeof c)u=0,d[0]=c;else if(Array.isArray(c)){u=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(u=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(u=2,d=[c.x,c.y,c.z,0]):"y"in c&&(u=1,d=[c.x,c.y,0,0]);i[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function ot(){if(!Xe||et)return;Xe.materialDataProvider=(e,t,s,n,r)=>{const i=Ge.get(e);if(!i)return Xe.HEAPU32[t>>2]=0,Xe.HEAPU32[s>>2]=0,Xe.HEAPU32[n>>2]=0,void(Xe.HEAPU32[r>>2]=0);Xe.HEAPU32[t>>2]=i.shader,Xe.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=it(i.uniforms);Xe.HEAPU32[n>>2]=o,Xe.HEAPU32[r>>2]=a},et=!0}const at={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 ct{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.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 lt{constructor(e,t=""){this.cache_=new ct,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&&(Ze.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ze.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const s=await c(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:Ze.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const ht=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"}]}]]);function ut(e,t){ht.set(e,t)}function dt(e){const t=ht.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function ft(e){return ht.get(e)?.fields??[]}function pt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,te,{value:n.name}),!1!==n.visible)for(const s of n.components)mt(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function _t(e,t,s){const n=new Map,r=s?.assetServer,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ht.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const l=new Map,h=new Map,u=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);l.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);h.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);u.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ht.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=h.get(t)??0;break;case"font":s[e.field]=u.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,te,{value:s.name}),!1!==s.visible)for(const n of s.components)mt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function mt(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=O(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function gt(e,t){const s=e.getEntitiesWithComponents([q]);for(const n of s){const s=e.get(n,q);s&&(s.aspectRatio=t,e.insert(n,q,s))}}function yt(e,t){const s=e.getEntitiesWithComponents([te]);for(const n of s){const s=e.get(n,te);if(s&&s.value===t)return n}return null}const wt=[{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}],xt={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"},vt=new Map,bt=new Set;for(const e of wt)for(const t of e.extensions)vt.set(t,e),bt.add(t);function St(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Pt(e){return vt.get(St(e))}function Ct(e){return Pt(e)?.editorType??"unknown"}function Tt(e){return Pt(e)?.addressableType??null}function Et(e){for(const t of wt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Mt(e){return bt.has(e.toLowerCase())}function Rt(){return bt}function At(e){return"string"==typeof e&&(!!e.includes("/")&&Mt(St(e)))}function It(){const e=[];for(const t of wt)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function Ft(){return It().map(e=>({type:"suffix",value:e}))}function $t(e){return xt[e.toLowerCase()]}function kt(e){const t=Pt(e);return t?.wechatPackInclude??!1}class Bt{constructor(e){this.textureCache_=new ct,this.shaderCache_=new ct,this.jsonCache_=new ct,this.textCache_=new ct,this.binaryCache_=new ct,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new ct,this.prefabCache_=new ct,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_=u(y.textCanvasSize,y.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 lt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,i)}}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(),Ze.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),c=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),h="binary"===Pt(e)?.contentType,u=h?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,i,h);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=Pt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return _t(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,s,a,i.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ze.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return Ze.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await c(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return c(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ut=he(null,"Assets");class Dt{build(e){const t=e.wasmModule;t?e.insertResource(Ut,new Bt(t)):console.warn("AssetPlugin: No WASM module available")}}const zt=new Dt;class Lt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Ot(e,t){const s=e.getResource(Ut);s&&s.registerEmbeddedAssets(t)}async function Ht(e,t,s){const{entities:n,rootId:r}=await jt(t,s?.overrides??[],s,void 0,new Set),i={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await _t(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const Wt=10;async function jt(e,t,s,n,r,i=0){if(i>Wt)throw new Error(`Prefab nesting depth exceeded ${Wt}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){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=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await jt(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),c.push(...t.entities);continue}const l=o.get(n.prefabEntityId),h=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:h?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Nt(u,t),c.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function Nt(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class Vt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Ht(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Xt=he(null,"Prefabs");class Yt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ut]}build(e){const t=e.getResource(Ut);e.insertResource(Xt,new Vt(e.world,t))}}const qt=new Yt;let Gt=null,Jt=0,Kt=0,Qt=0;const Zt=new Float32Array(256);function es(e){Gt=e,Jt=Gt._malloc(64),Kt=Gt._malloc(64),Qt=Gt._malloc(1024)}function ts(){Gt&&(Jt&&(Gt._free(Jt),Jt=0),Kt&&(Gt._free(Kt),Kt=0),Qt&&(Gt._free(Qt),Qt=0)),Gt=null}function ss(){if(!Gt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Gt}const ns={r:1,g:1,b:1,a:1},rs={begin(e){const t=ss();try{t.HEAPF32.set(e,Jt/4),t.draw_begin(Jt)}catch(e){Oe(e,"Draw.begin")}},end(){try{ss().draw_end()}catch(e){Oe(e,"Draw.end")}},line(e,t,s,n=1){try{ss().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.line")}},rect(e,t,s,n=!0){try{ss().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{ss().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{ss().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Oe(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{ss().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Oe(e,"Draw.circleOutline")}},texture(e,t,s,n=ns){try{ss().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Oe(e,"Draw.texture")}},textureRotated(e,t,s,n,r=ns){try{ss().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Oe(e,"Draw.textureRotated")}},setLayer(e){ss().draw_setLayer(e)},setDepth(e){ss().draw_setDepth(e)},getDrawCallCount:()=>Gt?Gt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Gt?Gt.draw_getPrimitiveCount():0,setBlendMode(e){ss().draw_setBlendMode(e)},setDepthTest(e){ss().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ss();n.HEAPF32.set(s,Kt/4),n.draw_mesh(e,t,Kt)}catch(s){Oe(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ss(),r=Ze.get(t);if(!r)return;if(rs.setBlendMode(r.blendMode),rs.setDepthTest(r.depthTest),0===r.uniforms.size)return void rs.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,Kt/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=as(t);if(!(n<0)){if(Ve(s))Zt[i++]=10,Zt[i++]=n,Zt[i++]=s.slot??e++,Zt[i++]=s.textureId;else if("number"==typeof s)Zt[i++]=1,Zt[i++]=n,Zt[i++]=s;else if(Array.isArray(s)){Zt[i++]=s.length,Zt[i++]=n;for(let e=0;e<s.length;e++)Zt[i++]=s[e]}else"w"in s?(Zt[i++]=4,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.y,Zt[i++]=s.z,Zt[i++]=s.w):"z"in s?(Zt[i++]=3,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.y,Zt[i++]=s.z):(Zt[i++]=2,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<i)&&(r.cachedBuffer_=new Float32Array(i)),r.cachedBuffer_.set(Zt.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}if(0===i)return void n.draw_mesh(e,r.shader,Kt);n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),Qt/4),n.draw_meshWithUniforms(e,r.shader,Kt,Qt,i)}catch(s){Oe(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},is={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},os=new Set;function as(e){const t=is[e];return void 0!==t?t:(os.has(e)||(os.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(is).join(", ")}`)),-1)}const cs=new Map;function ls(e,t,s){cs.set(e,{fn:t,scene:s??""})}function hs(e){cs.delete(e)}function us(){cs.clear()}var ds;!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"}(ds||(ds={}));let fs=null,ps=0,_s=0,ms=0;function gs(e){fs=e,ps=fs._malloc(262144),_s=fs._malloc(65536),ms=fs._malloc(256)}function ys(){fs&&(ps&&fs._free(ps),_s&&fs._free(_s),ms&&fs._free(ms),ps=0,_s=0,ms=0),fs=null}function ws(){if(!fs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return fs}const xs={create(e){const t=ws(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,ps/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ms,r).set(i),t.geometry_init(s,ps,n,ms,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices16(s,_s,n)}else{new Uint32Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices32(s,_s,n)}}return s},updateVertices(e,t,s=0){const n=ws(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,ps/4),n.geometry_updateVertices(e,ps,r,s)},release(e){e>0&&ws().geometry_release(e)},isValid:e=>!(!fs||e<=0)&&fs.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return xs.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return xs.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.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 xs.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array(o)})}};let vs=null;function bs(e){vs=e}function Ss(){vs&&Cs.isInitialized()&&Cs.shutdown(),vs=null}function Ps(){if(!vs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return vs}const Cs={init(e,t){try{return Ps().postprocess_init(e,t)}catch(s){return Oe(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ps().postprocess_shutdown()}catch(e){Oe(e,"PostProcess.shutdown")}},resize(e,t){try{Ps().postprocess_resize(e,t)}catch(s){Oe(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ps().postprocess_addPass(e,t)}catch(t){return Oe(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ps().postprocess_removePass(e)}catch(t){Oe(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ps().postprocess_setPassEnabled(e,t)}catch(t){Oe(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ps().postprocess_isPassEnabled(e)}catch(t){return Oe(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Ps().postprocess_setUniformFloat(e,t,s)}catch(s){Oe(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Ps().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Oe(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ps().postprocess_begin()}catch(e){Oe(e,"PostProcess.begin")}},end(){try{Ps().postprocess_end()}catch(e){Oe(e,"PostProcess.end")}},getPassCount(){try{return Ps().postprocess_getPassCount()}catch(e){return Oe(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!vs)return!1;try{return vs.postprocess_isInitialized()}catch(e){return Oe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ps().postprocess_setBypass(e)}catch(e){Oe(e,"PostProcess.setBypass")}},isBypassed(){if(!vs)return!0;try{return vs.postprocess_isBypassed()}catch(e){return Oe(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ze.createShader(Ts,"#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:()=>Ze.createShader(Ts,"#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:()=>Ze.createShader(Ts,"#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:()=>Ze.createShader(Ts,"#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")},Ts="#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 Es;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Es||(Es={}));let Ms=null,Rs=0;function As(e){Ms=e,Rs=Ms._malloc(64)}function Is(){Ms&&Rs&&(Ms._free(Rs),Rs=0),Ms=null}const Fs={init(e,t){Ms?.renderer_init(e,t)},resize(e,t){Ms?.renderer_resize(e,t)},begin(e,t){if(Ms&&Rs)try{Ms.HEAPF32.set(e,Rs/4),Ms.renderer_begin(Rs,t??0)}catch(e){Oe(e,"Renderer.begin")}},flush(){try{Ms?.renderer_flush()}catch(e){Oe(e,"Renderer.flush")}},end(){try{Ms?.renderer_end()}catch(e){Oe(e,"Renderer.end")}},submitSprites(e){if(Ms)try{Ms.renderer_submitSprites(e._cpp)}catch(e){Oe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Ms)try{Ms.renderer_submitBitmapText(e._cpp)}catch(e){Oe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Ms)try{Ms.renderer_submitSpine?.(e._cpp)}catch(e){Oe(e,"Renderer.submitSpine")}},setStage(e){Ms?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Ms?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Ms?.renderer_releaseTarget(e)},getTargetTexture:e=>Ms?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ms?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Ms?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Ms?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Ms?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Ms?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Ms?Ms.getResourceManager().measureBitmapText(e,t,s,n):{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 $s=null;function ks(e){$s=e}function Bs(){$s=null}const Us={enable(){$s?.gl_enableErrorCheck(!0)},disable(){$s?.gl_enableErrorCheck(!1)},check:e=>$s?.gl_checkErrors(e)??0,diagnose(){$s?.renderer_diagnose()}};class Ds{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Fs.resize(n,r),Cs.isInitialized()&&Cs.getPassCount()>0&&Cs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Fs.setViewport(0,0,n,r),Fs.clearBuffers(3),Fs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(s,i),Fs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Fs.setViewport(n.x,n.y,n.w,n.h),Fs.setScissor(n.x,n.y,n.w,n.h,!0),Fs.clearBuffers(r),Fs.setScissor(0,0,0,0,!1),Fs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(s,i),Fs.end()}executeDrawCallbacks(e,t){const s=cs;if(s.size>0){rs.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}rs.end();for(const e of n)hs(e)}}}const zs="__scene_transition_overlay__";class Ls{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Os{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,se,{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),ls(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Cs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Cs.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,se)){const s=this.app_.world.get(e,se);s.persistent=t,this.app_.world.insert(e,se,s)}}}class Hs{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.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_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??y.sceneTransitionDuration,r=t.color??{...y.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},ls(zs,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;rs.setLayer(9999),rs.setDepth(9999),rs.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,hs(zs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,hs(zs),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Ls(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const n=await _t(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=js(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Ls(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const n=await _t(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=js(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,se)){if(this.app_.world.get(e,se).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())hs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Cs.removePass(e)}catch{}s.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Y,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Y,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Cs.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Ws=he(null,"SceneManager");function js(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Ws).getSceneStatus(t)&&s._fn(...n)}}}const Ns=Ce([de(Ws),ue(_e)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Vs={name:"SceneManager",build(e){const t=new Hs(e);e.insertResource(Ws,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ws),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Se.Startup,s),e.addSystemToSchedule(Se.Last,Ns)}};class Xs{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_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Se.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Se.FixedPreUpdate),this.runSchedule(Se.FixedUpdate),this.runSchedule(Se.FixedPostUpdate),n++;n>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Se.PreUpdate),this.runSchedule(Se.Update),this.runSchedule(Se.PostUpdate),this.runSchedule(Se.Last),requestAnimationFrame(this.mainLoop)},this.world_=new We,this.resources_=new pe;for(const e of Object.values(Se))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Xs}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Se.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Se.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),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 Le(e),this}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(Ws).register(e),this}setInitialScene(e){return this.getResource(Ws).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ae(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Se.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,us();const e=[Bs,Is,Ss,ys,Ke,ts];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}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}function Ys(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const qs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Gs(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case N.FixedWidth:return i;case N.FixedHeight:return o;case N.Expand:return Math.max(i,o);case N.Shrink:return Math.min(i,o);case N.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function Js(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,se);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let h,u=0,d=0;if(r.projectionType===W.Orthographic){if(d=r.orthoSize,c){d=Gs(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}u=d*a,h=Qs(-u,u,-d,d,-r.farPlane,r.farPlane)}else h=en(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=sn(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(rn(h,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const Ks=new Float32Array(16);function Qs(e,t,s,n,r,i){const o=Ks;o.fill(0);const a=t-e,c=n-s,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+s)/c,o[14]=-(i+r)/l,o[15]=1,o}const Zs=new Float32Array(16);function en(e,t,s,n){const r=Zs;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const tn=new Float32Array(16);function sn(e,t,s){const n=tn;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const nn=new Float32Array(16);function rn(e,t){const s=nn;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var on,an,cn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(on||(on={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(an||(an={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(cn||(cn={}));const ln=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:on.Left,verticalAlign:an.Top,wordWrap:!0,overflow:cn.Visible,lineHeight:1.2}),hn=F("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}});class un{constructor(e){this.cache=new Map,this.module=e,this.canvas=u(y.textCanvasSize,y.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):u+2*h,p=r?Math.ceil(o):d+2*h;if(r&&e.overflow===cn.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,r&&e.overflow===cn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case an.Top:x=h;break;case an.Middle:x=(p-w)/2;break;case an.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of c){let n;switch(e.align){case on.Left:n=h;break;case on.Center:n=f/2;break;case on.Right:n=f-h;break;default:n=h}s.fillText(t,n,v),v+=l}r&&e.overflow===cn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case on.Left:return"left";case on.Center:return"center";case on.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function dn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function fn(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class pn{build(e){L("Text",ln);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new un(t),n=e.world,r=new Map;e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,ln));for(const e of r.keys())n.valid(e)&&n.has(e,ln)||r.delete(e);const e=n.getEntitiesWithComponents([ln]);for(const t of e){const e=n.get(t,ln),i=n.has(t,hn)?n.get(t,hn):null,o=r.get(t);if(o&&!fn(o,e,i))continue;n.has(t,Y)||n.insert(t,Y,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,i),c=n.get(t,Y);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,Y,c),r.set(t,dn(e,i))}}))}}const _n=new pn,mn=F("UIMask",{enabled:!0});function gn(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function yn(e,t,s,n,r,i,o,a,c,l,h){const u=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*h]}const[m,g]=_(u,f),[y,w]=_(d,p),x=Math.min(m,y),v=Math.max(m,y),b=Math.min(g,w),S=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function wn(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],c=e[5],l=e[6],h=e[7],u=e[8],d=e[9],f=e[10],p=e[11],_=e[12],m=e[13],g=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*h-o*a,b=r*l-i*c,S=r*h-o*c,P=i*h-o*l,C=u*m-d*_,T=u*g-f*_,E=u*y-p*_,M=d*g-f*m,R=d*y-p*m,A=f*y-p*g;let I=w*A-x*R+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*A-l*R+h*M)*I,s[1]=(i*R-r*A-o*M)*I,s[2]=(m*P-g*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*A-h*T)*I,s[5]=(n*A-i*E+o*T)*I,s[6]=(g*v-_*P-y*x)*I,s[7]=(u*P-f*v+p*x)*I,s[8]=(a*R-c*E+h*C)*I,s[9]=(r*E-n*R-o*C)*I,s[10]=(_*S-m*v+y*w)*I,s[11]=(d*v-u*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(m*x-_*b-g*w)*I,s[15]=(u*b-d*x+f*w)*I),s}function xn(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,c=(t-r)/o*2-1,l=s[0]*a+s[4]*c+s[12],h=s[1]*a+s[5]*c+s[13],u=s[3]*a+s[7]*c+s[15];return{x:l/u,y:h/u}}function vn(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function bn(e,t,s,n,r,i,o){if(!e.has(t,hn)||!e.has(t,X))return null;const a=e.get(t,hn),c=e.get(t,X),l=a.size.x*c.scale.x,h=a.size.y*c.scale.y;return yn(c.position.x,c.position.y,l,h,a.pivot.x,a.pivot.y,s,n,r,i,o)}function Sn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([mn]);if(0!==c.length)try{!function(e,t,s,n,r,i,o,a,c){const l=new Set;for(const e of n){t.get(e,mn).enabled&&l.add(e)}const h=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,K);){const e=t.get(n,K);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&h.push(e)}function u(n,h){const d=e.getChildEntities(s,n);for(const s of d){let n=h;if(l.has(s)){const e=bn(t,s,r,i,o,a,c);e&&(n=gn(h,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of h){const s=bn(t,e,r,i,o,a,c);s&&u(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class Pn{build(e){if(L("UIMask",mn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Sn(e.wasmModule,e.world))}}const Cn=new Pn,Tn=F("Interactable",{enabled:!0}),En=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Mn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Mn||(Mn={}));const Rn=F("Button",{state:Mn.Normal,transition:null});class An{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const In=he(new An,"UIEvents"),Fn=$("ScreenSpace");function $n(e,t,s,n,r,i){const o=i.right-i.left,a=i.top-i.bottom,c=i.left+e.x*o,l=i.left+t.x*o,h=i.bottom+e.y*a,u=i.bottom+t.y*a;let d,f,p,_;if(c===l&&h===u){const e=c+s.x,t=h+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=c+s.x,f=h+s.y,p=l+n.x,_=u+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function kn(e,t,s,n,r,i){if(!e.has(t,hn))return;const o=e.get(t,hn),a=$n(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const c=e.get(t,V);if(i?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,V,c),!e.has(t,Q))return;const l=e.get(t,Q);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&kn(e,t,a.rect,a.centerX,a.centerY,!1)}class Bn{build(e){L("UIRect",hn);const t=e.world;e.addSystemToSchedule(Se.PreUpdate,Ce([ue(je)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([Fn,hn,V]);for(const e of i)kn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Un=new Bn,Dn=new Float32Array(16),zn=new Float32Array(16);let Ln=!0,On=1;class Hn{build(e){L("Interactable",Tn),L("Button",Rn);const t=e.world,s=new An;e.insertResource(In,s);let n=null,r=null;On="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Se.PreUpdate,Ce([ue(Fe),ue(je)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([En]);for(const e of o){const s=t.get(e,En);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*On,c=i.screenH-e.mouseY*On;!function(e){let t=!1;for(let s=0;s<16;s++)if(zn[s]!==e[s]){t=!0;break}t&&(zn.set(e),Ln=!0)}(i.viewProjection),Ln&&(wn(i.viewProjection,Dn),Ln=!1);const l=xn(a,c,Dn,i.vpX,i.vpY,i.vpW,i.vpH),h=t.getEntitiesWithComponents([Tn,hn,X]);let u=null,d=-1/0;for(const e of h){t.has(e,En)||t.insert(e,En);if(!t.get(e,Tn).enabled)continue;const s=t.get(e,X),n=t.get(e,hn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(vn(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Y)&&(s=t.get(e,Y).layer),s>=d&&(d=s,u=e)}}if(n!==u){if(null!==n&&t.valid(n)&&t.has(n,En)){t.get(n,En).hovered=!1,s.emit(n,"hover_exit")}if(null!==u){t.get(u,En).hovered=!0,s.emit(u,"hover_enter")}n=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,En);e.pressed=!0,e.justPressed=!0,r=u,s.emit(u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,En)){const e=t.get(r,En);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Se.Update,Ce([],()=>{const e=t.getEntitiesWithComponents([Rn]);for(const s of e){if(t.has(s,Tn)||t.insert(s,Tn,{enabled:!0}),!t.has(s,En))continue;const e=t.get(s,En),n=t.get(s,Rn),r=t.get(s,Tn),i=n.state;if(r.enabled?e.pressed?n.state=Mn.Pressed:e.hovered?n.state=Mn.Hovered:n.state=Mn.Normal:n.state=Mn.Disabled,i!==n.state&&n.transition&&t.has(s,Y)){const e=t.get(s,Y),r=n.transition;switch(n.state){case Mn.Normal:e.color={...r.normalColor};break;case Mn.Hovered:e.color={...r.hoveredColor};break;case Mn.Pressed:e.color={...r.pressedColor};break;case Mn.Disabled:e.color={...r.disabledColor}}t.insert(s,Y,e)}}},{name:"ButtonSystem"}))}}const Wn=new Hn,jn=F("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});class Nn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){L("TextInput",jn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=u(y.textCanvasSize,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,h=0;const d=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(!d)return;const f=d,p=()=>{a||null===o||x()},_=()=>{a=!0},m=()=>{a=!1,x()},g=t=>{if(null===o)return;if("Escape"===t.key)return void S();const n=s.get(o,jn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(In).emit(o,"submit"),void S()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,P())},w=()=>{if(null!==o&&s.valid(o)&&s.has(o,jn)){const e=s.get(o,jn);e.focused=!1,e.dirty=!0}o=null};function x(){if(null===o||!s.valid(o))return;const t=s.get(o,jn);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(In).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,P()}function b(e){if(o===e)return;S();const t=s.get(e,jn);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),P())}function S(){if(null!==o&&s.valid(o)&&s.has(o,jn)){const e=s.get(o,jn);e.focused=!1,e.dirty=!0}o=null,f.blur()}function P(){c=!0,l=0}function C(e,o,a,l){(r.width<a||r.height<l)&&(r.width=Xn(Math.max(r.width,a)),r.height=Xn(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const h=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,i.fillRect(0,0,a,l),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,l),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const u=0===o.value.length,d=u?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=u?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=Vn(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&c){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=Vn(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(l-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const m=i.getImageData(0,0,a,l),g=new Uint8Array(m.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,g.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,Y);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,Y,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",m),f.addEventListener("keydown",g),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",m),f.removeEventListener("keydown",g),f.removeEventListener("blur",w),f.remove()},e.addSystemToSchedule(Se.PreUpdate,Ce([ue(In)],e=>{const t=s.getEntitiesWithComponents([jn,Tn]);for(const e of t){if(!s.has(e,En))continue;if(s.get(e,En).justPressed)return void b(e)}if(null!==o){const e=s.getEntitiesWithComponents([Tn]);for(const t of e){if(s.has(t,jn))continue;if(!s.has(t,En))continue;if(s.get(t,En).justPressed)return void S()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,jn)))){s.get(o,jn).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,jn)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([jn,hn]);for(const e of a){const t=s.get(e,jn);if(!t.dirty)continue;const n=s.get(e,hn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,Y)||s.insert(e,Y,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:r,y:i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),C(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Vn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function Xn(e){let t=1;for(;t<e;)t*=2;return t}const Yn=new Nn;async function qn(e,t,s){const n=e.getResource(Ws);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Gn(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 Jn=he({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Kn=he(null,"PhysicsAPI");function Qn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Zn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class er{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Jn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Gn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([G]);for(const s of t){const t=e.world.get(s,G);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Se.PostUpdate,Ce([ue(_e)],a=>{const c=o.getEntitiesWithComponents([re,V,X]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,re),c=o.get(r,X);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=Qn(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),tr(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ce.Kinematic){const e=Qn(c.rotation);n._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const h=e.world.get(o,V);if(!h)continue;let u=a,d=c,f=l;if(e.world.has(o,K)){const t=e.world.get(o,K);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,X)){const s=e.world.get(t.entity,X),n=Qn(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),h=Math.sin(-n);u=(r*o-i*h)/(0!==s.scale.x?s.scale.x:1),d=(r*h+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}h.position.x=u,h.position.y=d;const p=Zn(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(o,V,h)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<o;s++){const n=e+2*s;i.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<c;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const l=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<h;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Jn,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Kn,sr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function tr(e,t,s){const n=e.world;if(n.has(s,ie)){const e=n.get(s,ie);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,oe)){const e=n.get(s,oe);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ae)){const e=n.get(s,ae);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class sr{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(sr.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)}}function nr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function rr(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function ir(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,h=e.rotation.w,u=a+a,d=c+c,f=l+l,p=a*u,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=h*u,v=h*d,b=h*f;return new Float32Array([(1-(g+w))*r,(_+b)*r,(m-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function or(e,t,s,n,r,i,o,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=nr(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let h={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const n=await r.readText(a),h="binary"===Pt(c)?.contentType;let u,d;if(h){const e=await r.readBinary(o);d=e.length,u=t._malloc(d),t.HEAPU8.set(e,u)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,u=t._malloc(d+1),t.HEAPU8.set(s,u),t.HEAPU8[u+d]=0}const f=s.loadSkeleton(u,d,n,n.length,h);if(t._free(u),f<0)continue;i[o]=f;const p=rr(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=nr(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,u,s,n)),i){new er("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=Pt(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${o}`:o;t=await s.readText(c),i=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=i?`${i}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),h=nr(e,l,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,h,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=Ze.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=Ze.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=ft(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,d,f);const p=pt(e.world,s);if(c&&e.hasResource(Ws))for(const t of p.values())e.world.insert(t,se,{scene:c,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=n.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,h,p);!function(e,t,s,n,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,ee)?l.get(i,ee):null,h=!1!==a?.playing,u=a?.timeScale??1;h&&n.update(o,c*u);let d=0;if(l.has(i,X)){const e=ir(l.get(i,X),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=s._malloc(a),h=s._malloc(c),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,h,u,f);const p=s.HEAPU32[u>>2],_=s.HEAPU32[f>>2],m=new Float32Array(s.HEAPF32.buffer,l,8*r),g=new Uint16Array(s.HEAPU8.buffer,h,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(h),s._free(u),s._free(f)}d&&t._free(d)}})}(e,t,r,u,n)}if(a){const t=e.getResource(Ut);t&&t.setAddressableManifest(a)}}function ar(e,t,s){return{name:e,data:t,async setup(){await or(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class cr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===Pt(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=Pt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||i.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}i.length>0&&await Promise.all(i)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.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 lr="__preview__";class hr{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(Ws);t.register({name:lr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(lr),this.loadPromise_=t.load(lr).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(),s=new cr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await or(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,lr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([q]);for(const n of s){if(e.get(n,q).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([G]);for(const r of n){const n=e.get(r,G);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(Ws).getScene(lr),i=r?r.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}};e.insert(i,V,o);const a={isActive:!0,projectionType:W.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:j.ColorAndDepth};e.insert(i,q,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(Ws);await e.switchTo(lr),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 ur={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Fs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Fs.getTargetTexture(s),width:e.width,height:e.height}},release(e){Fs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Fs.releaseRenderTarget(e._handle),ur.create({width:t,height:s,depth:!0})),begin(e,t){Fs.begin(t,e._handle)},end(){Fs.end()},getDepthTexture:e=>Fs.getTargetDepthTexture(e._handle)};let dr=!1;function fr(e){dr=e}function pr(){return dr}function _r(){return!dr}var mr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(mr||(mr={}));class gr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${mr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case mr.Debug:console.debug(t,s);break;case mr.Info:console.log(t,s);break;case mr.Warn:console.warn(t,s);break;case mr.Error:console.error(t,s)}}}class yr{constructor(){this.handlers_=[],this.minLevel_=mr.Info,this.addHandler(new gr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(mr.Debug,e,t,s)}info(e,t,s){this.log(mr.Info,e,t,s)}warn(e,t,s){this.log(mr.Warn,e,t,s)}error(e,t,s){this.log(mr.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const wr=new yr;function xr(){return wr}function vr(e){wr.setMinLevel(e)}function br(e,t,s){wr.debug(e,t,s)}function Sr(e,t,s){wr.info(e,t,s)}function Pr(e,t,s){wr.warn(e,t,s)}function Cr(e,t,s){wr.error(e,t,s)}const Tr=[_n,Cn,Un,Wn,Yn];function Er(e,t){return function(e,t){const s=Xs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),es(e),Je(e),gs(e),bs(e),As(e),ks(e);const r=new Ds;s.setPipeline(r);let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=Js(e,n,t,r));const o=s.getResource(je);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,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}s.insertResource(je,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=o();if(0===t||0===c)return;const l=e.registry_getCanvasEntity(n);if(l>=0){const e=n.getCanvas(l).backgroundColor;Fs.setClearColor(e.x,e.y,e.z,e.w)}const h=(d()-i)/1e3;let u;if(Fs.resize(t,c),Cs.isInitialized()&&Cs.getPassCount()>0&&!Cs.isBypassed()&&Cs.resize(t,c),s.hasResource(Ws)){const e=s.getResource(Ws).getActiveScenes();e.length>0&&(u=new Set(e))}r.setActiveScenes(u??null);const f=Js(e,n,t,c,s.world,u);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:qs,width:t,height:c,elapsed:h});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:l},clearFlags:e.clearFlags,elapsed:h})}Fs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Se.First,c),s.addSystemToSchedule(Se.Last,l),s.addPlugin(zt),s.addPlugin(qt),s.addPlugin(ke),s.addPlugin(Vs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Tr,...t})}e=f;export{Xs as App,Dt as AssetPlugin,Lt as AssetRefCounter,Bt as AssetServer,Ut as Assets,ct as AsyncCache,Z as BitmapText,Ne as BlendMode,ce as BodyType,ie as BoxCollider,Rn as Button,Mn as ButtonState,q as Camera,G as Canvas,ae as CapsuleCollider,Q as Children,oe as CircleCollider,j as ClearFlags,xe as Commands,be as CommandsInstance,_ as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,m as DEFAULT_PIXELS_PER_UNIT,g as DEFAULT_TEXT_CANVAS_SIZE,ds as DataType,rs as Draw,ve as EntityCommands,Us as GLDebug,xs as Geometry,x as INVALID_ENTITY,b as INVALID_FONT,v as INVALID_TEXTURE,Fe as Input,$e as InputPlugin,Ie as InputState,Tn as Interactable,V as LocalTransform,mr as LogLevel,yr as Logger,Ze as Material,lt as MaterialLoader,me as Mut,te as Name,K as Parent,sr as Physics,Jn as PhysicsEvents,er as PhysicsPlugin,Cs as PostProcess,Vt as PrefabServer,Xt as Prefabs,Yt as PrefabsPlugin,hr as PreviewPlugin,W as ProjectionType,ye as Query,we as QueryInstance,Ds as RenderPipeline,Es as RenderStage,ur as RenderTexture,Fs as Renderer,ue as Res,de as ResMut,re as RigidBody,y as RuntimeConfig,N as ScaleMode,Ws as SceneManager,Hs as SceneManagerState,se as SceneOwner,Se as Schedule,Fn as ScreenSpace,at as ShaderSources,ee as SpineAnimation,Y as Sprite,Ae as SystemRunner,ln as Text,on as TextAlign,jn as TextInput,Nn as TextInputPlugin,cn as TextOverflow,pn as TextPlugin,un as TextRenderer,an as TextVerticalAlign,_e as Time,je as UICameraInfo,An as UIEventQueue,In as UIEvents,En as UIInteraction,Hn as UIInteractionPlugin,Bn as UILayoutPlugin,mn as UIMask,Pn as UIMaskPlugin,hn as UIRect,J as Velocity,cr as WebAssetProvider,We as World,X as WorldTransform,Me as addStartupSystem,Ee as addSystem,Re as addSystemToSchedule,w as applyRuntimeConfig,zt as assetPlugin,us as clearDrawCallbacks,B as clearUserComponents,T as color,$n as computeUIRectLayout,Sn as createMaskProcessor,ar as createRuntimeSceneConfig,Er as createWebApp,br as debug,F as defineComponent,he as defineResource,Ce as defineSystem,$ as defineTag,Cr as error,yt as findEntityByName,Ys as flushPendingSystems,Tt as getAddressableType,Et as getAddressableTypeByEditorType,Rt as getAllAssetExtensions,$t as getAssetMimeType,Pt as getAssetTypeEntry,O as getComponent,dt as getComponentAssetFields,ne as getComponentDefaults,It as getCustomExtensions,Ct as getEditorType,xr as getLogger,t as getPlatform,n as getPlatformType,k as getUserComponent,Ft as getWeChatPackOptions,Sr as info,es as initDrawAPI,ks as initGLDebugAPI,gs as initGeometryAPI,Je as initMaterialAPI,bs as initPostProcessAPI,As as initRendererAPI,ke as inputPlugin,Ht as instantiatePrefab,gn as intersectRects,wn as invertMatrix4,D as isBuiltinComponent,kt as isCustomExtension,pr as isEditor,Mt as isKnownAssetExtension,s as isPlatformInitialized,_r as isRuntime,Ve as isTextureRef,r as isWeChat,i as isWeb,mt as loadComponent,Gn as loadPhysicsModule,or as loadRuntimeScene,pt as loadSceneData,_t as loadSceneWithAssets,At as looksLikeAssetPath,o as platformFetch,l as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,vn as pointInWorldRect,qt as prefabsPlugin,E as quat,L as registerComponent,ut as registerComponentAssetFields,ls as registerDrawCallback,Ot as registerEmbeddedAssets,ot as registerMaterialCallback,Vs as sceneManagerPlugin,xn as screenToWorld,fr as setEditorMode,vr as setLogLevel,Le as setWasmErrorHandler,ts as shutdownDrawAPI,Bs as shutdownGLDebugAPI,ys as shutdownGeometryAPI,Ke as shutdownMaterialAPI,Ss as shutdownPostProcessAPI,Is as shutdownRendererAPI,Yn as textInputPlugin,_n as textPlugin,qn as transitionTo,Wn as uiInteractionPlugin,Un as uiLayoutPlugin,Cn as uiMaskPlugin,Tr as uiPlugins,hs as unregisterDrawCallback,gt as updateCameraAspectRatio,S as vec2,P as vec3,C as vec4,Pr as warn,yn as worldRectToScreen,js as wrapSceneSystem};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return null!==e}function n(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function h(e,s){return t().instantiateWasm(e,s)}function u(e,s){return t().createCanvas(e,s)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const s=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),n={};return s.headers.forEach((e,t)=>{n[t]=e}),{ok:s.ok,status:s.status,statusText:s.statusText,headers:n,json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let s;s="string"==typeof e?await this.readFile(e):e;const n=await WebAssembly.instantiate(s,t);return{instance:n.instance,module:n.module}}createImage(){return new Image}createCanvas(e,t){let s;return s="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),s.width=e,s.height=t,s}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t??document.querySelector("canvas")??document.body,n=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),i=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},o=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},h=()=>{e.onPointerUp(0)},u=t=>{const s=t;e.onWheel(s.deltaX,s.deltaY)};document.addEventListener("keydown",n),document.addEventListener("keyup",r),s.addEventListener("mousemove",i),s.addEventListener("mousedown",o),s.addEventListener("mouseup",a),s.addEventListener("touchstart",c),s.addEventListener("touchmove",l),s.addEventListener("touchend",h),s.addEventListener("wheel",u),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",r),s.removeEventListener("mousemove",i),s.removeEventListener("mousedown",o),s.removeEventListener("mouseup",a),s.removeEventListener("touchstart",c),s.removeEventListener("touchmove",l),s.removeEventListener("touchend",h),s.removeEventListener("wheel",u)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,_=1080,m=100,g=512,y={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function w(e){e.Text&&(e.Text._default.fontFamily=y.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=y.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=y.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=y.canvasMatchWidthOrHeight)}const x=0,v=4294967295,b=4294967295,S=(e=0,t=0)=>({x:e,y:t}),P=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),C=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),T=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),E=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function M(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(M);const t={};for(const s in e)t[s]=M(e[s]);return t}let R=0;function A(e,t){const s=++R;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...M(t),...e}:M(t)}}function I(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const s=I(),n=s.get(e);if(n)return n;const r=A(e,t);return s.set(e,r),U(e,t,!1),r}function $(e){const t=I(),s=t.get(e);if(s)return s;const n=A(e,{});return t.set(e,n),U(e,{},!0),n}function k(e){return I().get(e)}function B(){I().clear()}function U(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function D(e){return!0===e._builtin}const L=new Map;function z(e,t){L.set(e,t)}function O(e){return L.get(e)??k(e)}function H(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return L.set(e,s),s}const W={Perspective:0,Orthographic:1},j={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},N={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},V=H("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),X=H("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Y=H("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),q=H("Camera",{projectionType:W.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:j.ColorAndDepth}),G=H("Canvas",{designResolution:{x:p,y:_},pixelsPerUnit:100,scaleMode:N.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),J=H("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),K=H("Parent",{entity:0}),Q=H("Children",{entities:[]}),Z=H("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:b}),ee=H("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}),te={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},se=F("SceneOwner",{scene:"",persistent:!1});function ne(e){const t=O(e);return t?M(t._default):null}z("Name",te);const re=H("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ie=H("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),oe=H("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ae=H("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ce={Static:0,Kinematic:1,Dynamic:2};let le=0;function he(e,t){const s=++le;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ue(e){return{_type:"res",_resource:e}}function de(e){return{_type:"res_mut",_resource:e}}class fe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class pe{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new fe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const _e=he({delta:0,elapsed:0,frameCount:0},"Time");function me(e){return{_type:"mut",_component:e}}function ge(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function ye(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{ge(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class we{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ge(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let h=null;this.world_.beginIteration();try{for(const u of n){if(null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(u,t[s])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];h=u}yield a}}finally{if(this.world_.endIteration(),null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function xe(){return{_type:"commands"}}class ve{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class be{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ve(this,null);return this.spawned_.push(e),e}entity(e){return new ve(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Se;!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"}(Se||(Se={}));let Pe=0;function Ce(e,t,s){const n=++Pe;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Te(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ee(e){Te().push({schedule:Se.Update,system:e})}function Me(e){Te().push({schedule:Se.Startup,system:e})}function Re(e,t){Te().push({schedule:e,system:t})}class Ae{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof be&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new we(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new be(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{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 Fe=he(new Ie,"Input");class $e{constructor(e){this.target_=e??null}build(e){const s=new Ie;e.insertResource(Fe,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Se.Last,Ce([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ke=new $e;function Be(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=Ue(t[e]),i=Ue(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function Ue(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function De(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let Le=null;function ze(e){Le=e}function Oe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Le&&Le(e,t)}function He(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="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}:He(e)}}return t}class We{constructor(){this.cppRegistry_=null,this.entities_=new Set,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}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Oe(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),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.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Oe(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t)this.tsStorage_.get(s)?.delete(e);this.entityComponents_.delete(e)}}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&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Oe(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Oe(t,`removeParent(entity=${e})`)}}insert(e,t,s){return D(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(D(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Oe(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Be(t._name,t._default,n);if(e.length>0)throw new Error(De(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(r))}catch(s){Oe(s,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(s){return Oe(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return Oe(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Oe(s,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Be(t._name,t._default,e);if(r.length>0)throw new Error(De(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.push(s)}catch{}if(this.cppRegistry_){const s=["LocalTransform","GlobalTransform","Sprite","Camera","Text","Velocity","Parent","Children","BitmapText","SpineAnimation","Canvas","UIRect","Interaction","Mask","LayoutGroup","LayoutElement","TextInput","RigidBody","BoxCollider","CircleCollider","CapsuleCollider"];for(const n of s){if(t.includes(n))continue;const s=O(n);if(s&&D(s))try{this.getBuiltinMethods(s._cppName).has(e)&&t.push(n)}catch{}}}const s=this.entityComponents_.get(e);if(s)for(const n of s)for(const[,s]of this.tsStorage_)if(s.has(e)&&s===this.tsStorage_.get(n))for(const[e,s]of this.findScriptName(n))t.includes(e)||t.push(e);return t}findScriptName(e){const t=[];if("undefined"!=typeof window&&window.__esengine_componentRegistry){const s=window.__esengine_componentRegistry;for(const[n,r]of s)if(r._id===e){t.push([n,r]);break}}return t}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!D(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=i?i.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const je=he({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Ne;function Ve(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"}(Ne||(Ne={}));let Xe=null,Ye=null,qe=1;const Ge=new Map;function Je(e){Xe=e,Ye=e.getResourceManager(),ot()}function Ke(){0!==tt&&Xe&&(Xe._free(tt),tt=0),Ge.clear(),qe=1,et=!1,nt.clear(),rt=null,Ye=null,Xe=null}function Qe(){if(!Ye)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ye}const Ze={createShader:(e,t)=>Qe().createShader(e,t),releaseShader(e){e>0&&Qe().releaseShader(e)},create(e){const t=qe++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ne.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Ge.set(t,s),t},get:e=>Ge.get(e),setUniform(e,t,s){const n=Ge.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ge.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ge.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ge.get(e);return t?.blendMode??Ne.Normal},setDepthTest(e,t){const s=Ge.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ge.get(e);return t?.shader??0},release(e){Ge.delete(e)},isValid:e=>Ge.has(e),releaseAll(){Ge.clear()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??Ne.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ge.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=qe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ge.set(s,n),s},toAssetData(e,t){const s=Ge.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=Ge.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let et=!1,tt=0;const st=4096,nt=new Map;let rt=null;function it(e){const t=(0===tt&&Xe&&(tt=Xe._malloc(st)),tt);if(0===t||!Xe)return{ptr:0,count:0};let s=0,n=0;const r=Xe.HEAPU8,i=Xe.HEAPU32,o=Xe.HEAPF32;for(const[a,c]of e){if(s+128>st)break;let e=nt.get(a);e||(rt||(rt=new TextEncoder),e=rt.encode(a),nt.set(a,e));const l=e.length,h=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=h;let u=0,d=[0,0,0,0];if("number"==typeof c)u=0,d[0]=c;else if(Array.isArray(c)){u=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(u=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(u=2,d=[c.x,c.y,c.z,0]):"y"in c&&(u=1,d=[c.x,c.y,0,0]);i[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function ot(){if(!Xe||et)return;Xe.materialDataProvider=(e,t,s,n,r)=>{const i=Ge.get(e);if(!i)return Xe.HEAPU32[t>>2]=0,Xe.HEAPU32[s>>2]=0,Xe.HEAPU32[n>>2]=0,void(Xe.HEAPU32[r>>2]=0);Xe.HEAPU32[t>>2]=i.shader,Xe.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=it(i.uniforms);Xe.HEAPU32[n>>2]=o,Xe.HEAPU32[r>>2]=a},et=!0}const at={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 ct{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.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 lt{constructor(e,t=""){this.cache_=new ct,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&&(Ze.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ze.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const s=await c(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:Ze.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const ht=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"}]}]]);function ut(e,t){ht.set(e,t)}function dt(e){const t=ht.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function ft(e){return ht.get(e)?.fields??[]}function pt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,te,{value:n.name}),!1!==n.visible)for(const s of n.components)mt(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function _t(e,t,s){const n=new Map,r=s?.assetServer,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ht.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const l=new Map,h=new Map,u=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);l.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);h.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);u.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ht.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=h.get(t)??0;break;case"font":s[e.field]=u.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,te,{value:s.name}),!1!==s.visible)for(const n of s.components)mt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function mt(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=O(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function gt(e,t){const s=e.getEntitiesWithComponents([q]);for(const n of s){const s=e.get(n,q);s&&(s.aspectRatio=t,e.insert(n,q,s))}}function yt(e,t){const s=e.getEntitiesWithComponents([te]);for(const n of s){const s=e.get(n,te);if(s&&s.value===t)return n}return null}const wt=[{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}],xt={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"},vt=new Map,bt=new Set;for(const e of wt)for(const t of e.extensions)vt.set(t,e),bt.add(t);function St(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Pt(e){return vt.get(St(e))}function Ct(e){return Pt(e)?.editorType??"unknown"}function Tt(e){return Pt(e)?.addressableType??null}function Et(e){for(const t of wt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Mt(e){return bt.has(e.toLowerCase())}function Rt(){return bt}function At(e){return"string"==typeof e&&(!!e.includes("/")&&Mt(St(e)))}function It(){const e=[];for(const t of wt)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function Ft(){return It().map(e=>({type:"suffix",value:e}))}function $t(e){return xt[e.toLowerCase()]}function kt(e){const t=Pt(e);return t?.wechatPackInclude??!1}class Bt{constructor(e){this.textureCache_=new ct,this.shaderCache_=new ct,this.jsonCache_=new ct,this.textCache_=new ct,this.binaryCache_=new ct,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new ct,this.prefabCache_=new ct,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_=u(y.textCanvasSize,y.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 lt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,i)}}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(),Ze.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),c=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),h="binary"===Pt(e)?.contentType,u=h?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,i,h);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=Pt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return _t(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,s,a,i.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ze.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return Ze.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await c(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return c(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ut=he(null,"Assets");class Dt{build(e){const t=e.wasmModule;t?e.insertResource(Ut,new Bt(t)):console.warn("AssetPlugin: No WASM module available")}}const Lt=new Dt;class zt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Ot(e,t){const s=e.getResource(Ut);s&&s.registerEmbeddedAssets(t)}async function Ht(e,t,s){const{entities:n,rootId:r}=await jt(t,s?.overrides??[],s,void 0,new Set),i={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await _t(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const Wt=10;async function jt(e,t,s,n,r,i=0){if(i>Wt)throw new Error(`Prefab nesting depth exceeded ${Wt}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){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=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await jt(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),c.push(...t.entities);continue}const l=o.get(n.prefabEntityId),h=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:h?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Nt(u,t),c.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function Nt(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class Vt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Ht(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Xt=he(null,"Prefabs");class Yt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ut]}build(e){const t=e.getResource(Ut);e.insertResource(Xt,new Vt(e.world,t))}}const qt=new Yt;let Gt=null,Jt=0,Kt=0,Qt=0;const Zt=new Float32Array(256);function es(e){Gt=e,Jt=Gt._malloc(64),Kt=Gt._malloc(64),Qt=Gt._malloc(1024)}function ts(){Gt&&(Jt&&(Gt._free(Jt),Jt=0),Kt&&(Gt._free(Kt),Kt=0),Qt&&(Gt._free(Qt),Qt=0)),Gt=null}function ss(){if(!Gt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Gt}const ns={r:1,g:1,b:1,a:1},rs={begin(e){const t=ss();try{t.HEAPF32.set(e,Jt/4),t.draw_begin(Jt)}catch(e){Oe(e,"Draw.begin")}},end(){try{ss().draw_end()}catch(e){Oe(e,"Draw.end")}},line(e,t,s,n=1){try{ss().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.line")}},rect(e,t,s,n=!0){try{ss().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{ss().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{ss().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Oe(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{ss().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Oe(e,"Draw.circleOutline")}},texture(e,t,s,n=ns){try{ss().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Oe(e,"Draw.texture")}},textureRotated(e,t,s,n,r=ns){try{ss().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Oe(e,"Draw.textureRotated")}},setLayer(e){ss().draw_setLayer(e)},setDepth(e){ss().draw_setDepth(e)},getDrawCallCount:()=>Gt?Gt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Gt?Gt.draw_getPrimitiveCount():0,setBlendMode(e){ss().draw_setBlendMode(e)},setDepthTest(e){ss().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ss();n.HEAPF32.set(s,Kt/4),n.draw_mesh(e,t,Kt)}catch(s){Oe(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ss(),r=Ze.get(t);if(!r)return;if(rs.setBlendMode(r.blendMode),rs.setDepthTest(r.depthTest),0===r.uniforms.size)return void rs.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,Kt/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=as(t);if(!(n<0)){if(Ve(s))Zt[i++]=10,Zt[i++]=n,Zt[i++]=s.slot??e++,Zt[i++]=s.textureId;else if("number"==typeof s)Zt[i++]=1,Zt[i++]=n,Zt[i++]=s;else if(Array.isArray(s)){Zt[i++]=s.length,Zt[i++]=n;for(let e=0;e<s.length;e++)Zt[i++]=s[e]}else"w"in s?(Zt[i++]=4,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.y,Zt[i++]=s.z,Zt[i++]=s.w):"z"in s?(Zt[i++]=3,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.y,Zt[i++]=s.z):(Zt[i++]=2,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<i)&&(r.cachedBuffer_=new Float32Array(i)),r.cachedBuffer_.set(Zt.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}if(0===i)return void n.draw_mesh(e,r.shader,Kt);n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),Qt/4),n.draw_meshWithUniforms(e,r.shader,Kt,Qt,i)}catch(s){Oe(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},is={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},os=new Set;function as(e){const t=is[e];return void 0!==t?t:(os.has(e)||(os.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(is).join(", ")}`)),-1)}const cs=new Map;function ls(e,t,s){cs.set(e,{fn:t,scene:s??""})}function hs(e){cs.delete(e)}function us(){cs.clear()}var ds;!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"}(ds||(ds={}));let fs=null,ps=0,_s=0,ms=0;function gs(e){fs=e,ps=fs._malloc(262144),_s=fs._malloc(65536),ms=fs._malloc(256)}function ys(){fs&&(ps&&fs._free(ps),_s&&fs._free(_s),ms&&fs._free(ms),ps=0,_s=0,ms=0),fs=null}function ws(){if(!fs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return fs}const xs={create(e){const t=ws(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,ps/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ms,r).set(i),t.geometry_init(s,ps,n,ms,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices16(s,_s,n)}else{new Uint32Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices32(s,_s,n)}}return s},updateVertices(e,t,s=0){const n=ws(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,ps/4),n.geometry_updateVertices(e,ps,r,s)},release(e){e>0&&ws().geometry_release(e)},isValid:e=>!(!fs||e<=0)&&fs.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return xs.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return xs.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.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 xs.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array(o)})}};let vs=null;function bs(e){vs=e}function Ss(){vs&&Cs.isInitialized()&&Cs.shutdown(),vs=null}function Ps(){if(!vs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return vs}const Cs={init(e,t){try{return Ps().postprocess_init(e,t)}catch(s){return Oe(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ps().postprocess_shutdown()}catch(e){Oe(e,"PostProcess.shutdown")}},resize(e,t){try{Ps().postprocess_resize(e,t)}catch(s){Oe(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ps().postprocess_addPass(e,t)}catch(t){return Oe(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ps().postprocess_removePass(e)}catch(t){Oe(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ps().postprocess_setPassEnabled(e,t)}catch(t){Oe(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ps().postprocess_isPassEnabled(e)}catch(t){return Oe(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Ps().postprocess_setUniformFloat(e,t,s)}catch(s){Oe(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Ps().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Oe(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ps().postprocess_begin()}catch(e){Oe(e,"PostProcess.begin")}},end(){try{Ps().postprocess_end()}catch(e){Oe(e,"PostProcess.end")}},getPassCount(){try{return Ps().postprocess_getPassCount()}catch(e){return Oe(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!vs)return!1;try{return vs.postprocess_isInitialized()}catch(e){return Oe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ps().postprocess_setBypass(e)}catch(e){Oe(e,"PostProcess.setBypass")}},isBypassed(){if(!vs)return!0;try{return vs.postprocess_isBypassed()}catch(e){return Oe(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ze.createShader(Ts,"#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:()=>Ze.createShader(Ts,"#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:()=>Ze.createShader(Ts,"#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:()=>Ze.createShader(Ts,"#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")},Ts="#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 Es;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Es||(Es={}));let Ms=null,Rs=0;function As(e){Ms=e,Rs=Ms._malloc(64)}function Is(){Ms&&Rs&&(Ms._free(Rs),Rs=0),Ms=null}const Fs={init(e,t){Ms?.renderer_init(e,t)},resize(e,t){Ms?.renderer_resize(e,t)},begin(e,t){if(Ms&&Rs)try{Ms.HEAPF32.set(e,Rs/4),Ms.renderer_begin(Rs,t??0)}catch(e){Oe(e,"Renderer.begin")}},flush(){try{Ms?.renderer_flush()}catch(e){Oe(e,"Renderer.flush")}},end(){try{Ms?.renderer_end()}catch(e){Oe(e,"Renderer.end")}},submitSprites(e){if(Ms)try{Ms.renderer_submitSprites(e._cpp)}catch(e){Oe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Ms)try{Ms.renderer_submitBitmapText(e._cpp)}catch(e){Oe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Ms)try{Ms.renderer_submitSpine?.(e._cpp)}catch(e){Oe(e,"Renderer.submitSpine")}},setStage(e){Ms?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Ms?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Ms?.renderer_releaseTarget(e)},getTargetTexture:e=>Ms?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ms?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Ms?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Ms?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Ms?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Ms?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Ms?Ms.getResourceManager().measureBitmapText(e,t,s,n):{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 $s=null;function ks(e){$s=e}function Bs(){$s=null}const Us={enable(){$s?.gl_enableErrorCheck(!0)},disable(){$s?.gl_enableErrorCheck(!1)},check:e=>$s?.gl_checkErrors(e)??0,diagnose(){$s?.renderer_diagnose()}};class Ds{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Fs.resize(n,r),Cs.isInitialized()&&Cs.getPassCount()>0&&Cs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Fs.setViewport(0,0,n,r),Fs.clearBuffers(3),Fs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(s,i),Fs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Fs.setViewport(n.x,n.y,n.w,n.h),Fs.setScissor(n.x,n.y,n.w,n.h,!0),Fs.clearBuffers(r),Fs.setScissor(0,0,0,0,!1),Fs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(s,i),Fs.end()}executeDrawCallbacks(e,t){const s=cs;if(s.size>0){rs.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}rs.end();for(const e of n)hs(e)}}}const Ls="__scene_transition_overlay__";class zs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Os{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,se,{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),ls(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Cs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Cs.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,se)){const s=this.app_.world.get(e,se);s.persistent=t,this.app_.world.insert(e,se,s)}}}class Hs{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.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_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??y.sceneTransitionDuration,r=t.color??{...y.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},ls(Ls,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;rs.setLayer(9999),rs.setDepth(9999),rs.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,hs(Ls)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,hs(Ls),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new zs(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const n=await _t(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=js(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new zs(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const n=await _t(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=js(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,se)){if(this.app_.world.get(e,se).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())hs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Cs.removePass(e)}catch{}s.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Y,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Y,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Cs.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Ws=he(null,"SceneManager");function js(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Ws).getSceneStatus(t)&&s._fn(...n)}}}const Ns=Ce([de(Ws),ue(_e)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Vs={name:"SceneManager",build(e){const t=new Hs(e);e.insertResource(Ws,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ws),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Se.Startup,s),e.addSystemToSchedule(Se.Last,Ns)}};class Xs{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_=new Set,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=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Se.Last);else{this.runSchedule(Se.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Se.FixedPreUpdate),this.runSchedule(Se.FixedUpdate),this.runSchedule(Se.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Se.PreUpdate),this.runSchedule(Se.Update),this.runSchedule(Se.PostUpdate),this.runSchedule(Se.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new We,this.resources_=new pe;for(const e of Object.values(Se))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Xs}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Se.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Se.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),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 ze(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(Ws).register(e),this}setInitialScene(e){return this.getResource(Ws).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ae(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Se.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,us();const e=[Bs,Is,Ss,ys,Ke,ts];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}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}function Ys(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const qs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Gs(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case N.FixedWidth:return i;case N.FixedHeight:return o;case N.Expand:return Math.max(i,o);case N.Shrink:return Math.min(i,o);case N.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function Js(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,se);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let h,u=0,d=0;if(r.projectionType===W.Orthographic){if(d=r.orthoSize,c){d=Gs(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}u=d*a,h=Qs(-u,u,-d,d,-r.farPlane,r.farPlane)}else h=en(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=sn(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(rn(h,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const Ks=new Float32Array(16);function Qs(e,t,s,n,r,i){const o=Ks;o.fill(0);const a=t-e,c=n-s,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+s)/c,o[14]=-(i+r)/l,o[15]=1,o}const Zs=new Float32Array(16);function en(e,t,s,n){const r=Zs;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const tn=new Float32Array(16);function sn(e,t,s){const n=tn;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const nn=new Float32Array(16);function rn(e,t){const s=nn;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var on,an,cn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(on||(on={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(an||(an={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(cn||(cn={}));const ln=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:on.Left,verticalAlign:an.Top,wordWrap:!0,overflow:cn.Visible,lineHeight:1.2}),hn=F("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}});class un{constructor(e){this.cache=new Map,this.module=e,this.canvas=u(y.textCanvasSize,y.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):u+2*h,p=r?Math.ceil(o):d+2*h;if(r&&e.overflow===cn.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,r&&e.overflow===cn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case an.Top:x=h;break;case an.Middle:x=(p-w)/2;break;case an.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of c){let n;switch(e.align){case on.Left:n=h;break;case on.Center:n=f/2;break;case on.Right:n=f-h;break;default:n=h}s.fillText(t,n,v),v+=l}r&&e.overflow===cn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case on.Left:return"left";case on.Center:return"center";case on.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function dn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function fn(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class pn{build(e){z("Text",ln);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new un(t),n=e.world,r=new Map;e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,ln));for(const e of r.keys())n.valid(e)&&n.has(e,ln)||r.delete(e);const e=n.getEntitiesWithComponents([ln]);for(const t of e){const e=n.get(t,ln),i=n.has(t,hn)?n.get(t,hn):null,o=r.get(t);if(o&&!fn(o,e,i))continue;n.has(t,Y)||n.insert(t,Y,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,i),c=n.get(t,Y);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,Y,c),r.set(t,dn(e,i))}}))}}const _n=new pn,mn=F("UIMask",{enabled:!0});function gn(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function yn(e,t,s,n,r,i,o,a,c,l,h){const u=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*h]}const[m,g]=_(u,f),[y,w]=_(d,p),x=Math.min(m,y),v=Math.max(m,y),b=Math.min(g,w),S=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function wn(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],c=e[5],l=e[6],h=e[7],u=e[8],d=e[9],f=e[10],p=e[11],_=e[12],m=e[13],g=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*h-o*a,b=r*l-i*c,S=r*h-o*c,P=i*h-o*l,C=u*m-d*_,T=u*g-f*_,E=u*y-p*_,M=d*g-f*m,R=d*y-p*m,A=f*y-p*g;let I=w*A-x*R+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*A-l*R+h*M)*I,s[1]=(i*R-r*A-o*M)*I,s[2]=(m*P-g*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*A-h*T)*I,s[5]=(n*A-i*E+o*T)*I,s[6]=(g*v-_*P-y*x)*I,s[7]=(u*P-f*v+p*x)*I,s[8]=(a*R-c*E+h*C)*I,s[9]=(r*E-n*R-o*C)*I,s[10]=(_*S-m*v+y*w)*I,s[11]=(d*v-u*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(m*x-_*b-g*w)*I,s[15]=(u*b-d*x+f*w)*I),s}function xn(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,c=(t-r)/o*2-1,l=s[0]*a+s[4]*c+s[12],h=s[1]*a+s[5]*c+s[13],u=s[3]*a+s[7]*c+s[15];return{x:l/u,y:h/u}}function vn(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function bn(e,t,s,n,r,i,o){if(!e.has(t,hn)||!e.has(t,X))return null;const a=e.get(t,hn),c=e.get(t,X),l=a.size.x*c.scale.x,h=a.size.y*c.scale.y;return yn(c.position.x,c.position.y,l,h,a.pivot.x,a.pivot.y,s,n,r,i,o)}function Sn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([mn]);if(0!==c.length)try{!function(e,t,s,n,r,i,o,a,c){const l=new Set;for(const e of n){t.get(e,mn).enabled&&l.add(e)}const h=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,K);){const e=t.get(n,K);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&h.push(e)}function u(n,h){const d=e.getChildEntities(s,n);for(const s of d){let n=h;if(l.has(s)){const e=bn(t,s,r,i,o,a,c);e&&(n=gn(h,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of h){const s=bn(t,e,r,i,o,a,c);s&&u(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class Pn{build(e){if(z("UIMask",mn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Sn(e.wasmModule,e.world))}}const Cn=new Pn,Tn=F("Interactable",{enabled:!0}),En=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Mn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Mn||(Mn={}));const Rn=F("Button",{state:Mn.Normal,transition:null});class An{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const In=he(new An,"UIEvents"),Fn=$("ScreenSpace");function $n(e,t,s,n,r,i){const o=i.right-i.left,a=i.top-i.bottom,c=i.left+e.x*o,l=i.left+t.x*o,h=i.bottom+e.y*a,u=i.bottom+t.y*a;let d,f,p,_;if(c===l&&h===u){const e=c+s.x,t=h+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=c+s.x,f=h+s.y,p=l+n.x,_=u+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function kn(e,t,s,n,r,i){if(!e.has(t,hn))return;const o=e.get(t,hn),a=$n(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const c=e.get(t,V);if(i?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,V,c),!e.has(t,Q))return;const l=e.get(t,Q);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&kn(e,t,a.rect,a.centerX,a.centerY,!1)}class Bn{build(e){z("UIRect",hn);const t=e.world;e.addSystemToSchedule(Se.PreUpdate,Ce([ue(je)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([Fn,hn,V]);for(const e of i)kn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Un=new Bn,Dn=new Float32Array(16),Ln=new Float32Array(16);let zn=!0,On=1;class Hn{build(e){z("Interactable",Tn),z("Button",Rn);const t=e.world,s=new An;e.insertResource(In,s);let n=null,r=null;On="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Se.PreUpdate,Ce([ue(Fe),ue(je)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([En]);for(const e of o){const s=t.get(e,En);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*On,c=i.screenH-e.mouseY*On;!function(e){let t=!1;for(let s=0;s<16;s++)if(Ln[s]!==e[s]){t=!0;break}t&&(Ln.set(e),zn=!0)}(i.viewProjection),zn&&(wn(i.viewProjection,Dn),zn=!1);const l=xn(a,c,Dn,i.vpX,i.vpY,i.vpW,i.vpH),h=t.getEntitiesWithComponents([Tn,hn,X]);let u=null,d=-1/0;for(const e of h){t.has(e,En)||t.insert(e,En);if(!t.get(e,Tn).enabled)continue;const s=t.get(e,X),n=t.get(e,hn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(vn(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Y)&&(s=t.get(e,Y).layer),s>=d&&(d=s,u=e)}}if(n!==u){if(null!==n&&t.valid(n)&&t.has(n,En)){t.get(n,En).hovered=!1,s.emit(n,"hover_exit")}if(null!==u){t.get(u,En).hovered=!0,s.emit(u,"hover_enter")}n=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,En);e.pressed=!0,e.justPressed=!0,r=u,s.emit(u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,En)){const e=t.get(r,En);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Se.Update,Ce([],()=>{const e=t.getEntitiesWithComponents([Rn]);for(const s of e){if(t.has(s,Tn)||t.insert(s,Tn,{enabled:!0}),!t.has(s,En))continue;const e=t.get(s,En),n=t.get(s,Rn),r=t.get(s,Tn),i=n.state;if(r.enabled?e.pressed?n.state=Mn.Pressed:e.hovered?n.state=Mn.Hovered:n.state=Mn.Normal:n.state=Mn.Disabled,i!==n.state&&n.transition&&t.has(s,Y)){const e=t.get(s,Y),r=n.transition;switch(n.state){case Mn.Normal:e.color={...r.normalColor};break;case Mn.Hovered:e.color={...r.hoveredColor};break;case Mn.Pressed:e.color={...r.pressedColor};break;case Mn.Disabled:e.color={...r.disabledColor}}t.insert(s,Y,e)}}},{name:"ButtonSystem"}))}}const Wn=new Hn,jn=F("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});class Nn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){z("TextInput",jn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=u(y.textCanvasSize,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,h=0;const d=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(!d)return;const f=d,p=()=>{a||null===o||x()},_=()=>{a=!0},m=()=>{a=!1,x()},g=t=>{if(null===o)return;if("Escape"===t.key)return void S();const n=s.get(o,jn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(In).emit(o,"submit"),void S()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,P())},w=()=>{if(null!==o&&s.valid(o)&&s.has(o,jn)){const e=s.get(o,jn);e.focused=!1,e.dirty=!0}o=null};function x(){if(null===o||!s.valid(o))return;const t=s.get(o,jn);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(In).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,P()}function b(e){if(o===e)return;S();const t=s.get(e,jn);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),P())}function S(){if(null!==o&&s.valid(o)&&s.has(o,jn)){const e=s.get(o,jn);e.focused=!1,e.dirty=!0}o=null,f.blur()}function P(){c=!0,l=0}function C(e,o,a,l){(r.width<a||r.height<l)&&(r.width=Xn(Math.max(r.width,a)),r.height=Xn(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const h=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,i.fillRect(0,0,a,l),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,l),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const u=0===o.value.length,d=u?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=u?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=Vn(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&c){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=Vn(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(l-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const m=i.getImageData(0,0,a,l),g=new Uint8Array(m.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,g.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,Y);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,Y,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",m),f.addEventListener("keydown",g),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",m),f.removeEventListener("keydown",g),f.removeEventListener("blur",w),f.remove()},e.addSystemToSchedule(Se.PreUpdate,Ce([ue(In)],e=>{const t=s.getEntitiesWithComponents([jn,Tn]);for(const e of t){if(!s.has(e,En))continue;if(s.get(e,En).justPressed)return void b(e)}if(null!==o){const e=s.getEntitiesWithComponents([Tn]);for(const t of e){if(s.has(t,jn))continue;if(!s.has(t,En))continue;if(s.get(t,En).justPressed)return void S()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,jn)))){s.get(o,jn).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,jn)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([jn,hn]);for(const e of a){const t=s.get(e,jn);if(!t.dirty)continue;const n=s.get(e,hn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,Y)||s.insert(e,Y,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:r,y:i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),C(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Vn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function Xn(e){let t=1;for(;t<e;)t*=2;return t}const Yn=new Nn;async function qn(e,t,s){const n=e.getResource(Ws);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Gn(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 Jn=he({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Kn=he(null,"PhysicsAPI");function Qn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Zn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class er{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Jn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Gn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([G]);for(const s of t){const t=e.world.get(s,G);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Se.PostUpdate,Ce([ue(_e)],a=>{const c=o.getEntitiesWithComponents([re,V,X]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,re),c=o.get(r,X);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=Qn(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),tr(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ce.Kinematic){const e=Qn(c.rotation);n._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const h=e.world.get(o,V);if(!h)continue;let u=a,d=c,f=l;if(e.world.has(o,K)){const t=e.world.get(o,K);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,X)){const s=e.world.get(t.entity,X),n=Qn(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),h=Math.sin(-n);u=(r*o-i*h)/(0!==s.scale.x?s.scale.x:1),d=(r*h+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}h.position.x=u,h.position.y=d;const p=Zn(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(o,V,h)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<o;s++){const n=e+2*s;i.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<c;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const l=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<h;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Jn,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Kn,sr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function tr(e,t,s){const n=e.world;if(n.has(s,ie)){const e=n.get(s,ie);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,oe)){const e=n.get(s,oe);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ae)){const e=n.get(s,ae);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class sr{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(sr.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)}}function nr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function rr(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function ir(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,h=e.rotation.w,u=a+a,d=c+c,f=l+l,p=a*u,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=h*u,v=h*d,b=h*f;return new Float32Array([(1-(g+w))*r,(_+b)*r,(m-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function or(e,t,s,n,r,i,o,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=nr(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let h={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const n=await r.readText(a),h="binary"===Pt(c)?.contentType;let u,d;if(h){const e=await r.readBinary(o);d=e.length,u=t._malloc(d),t.HEAPU8.set(e,u)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,u=t._malloc(d+1),t.HEAPU8.set(s,u),t.HEAPU8[u+d]=0}const f=s.loadSkeleton(u,d,n,n.length,h);if(t._free(u),f<0)continue;i[o]=f;const p=rr(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=nr(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,u,s,n)),i){new er("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=Pt(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${o}`:o;t=await s.readText(c),i=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=i?`${i}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),h=nr(e,l,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,h,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=Ze.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=Ze.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=ft(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,d,f);const p=pt(e.world,s);if(c&&e.hasResource(Ws))for(const t of p.values())e.world.insert(t,se,{scene:c,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=n.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,h,p);!function(e,t,s,n,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,ee)?l.get(i,ee):null,h=!1!==a?.playing,u=a?.timeScale??1;h&&n.update(o,c*u);let d=0;if(l.has(i,X)){const e=ir(l.get(i,X),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=s._malloc(a),h=s._malloc(c),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,h,u,f);const p=s.HEAPU32[u>>2],_=s.HEAPU32[f>>2],m=new Float32Array(s.HEAPF32.buffer,l,8*r),g=new Uint16Array(s.HEAPU8.buffer,h,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(h),s._free(u),s._free(f)}d&&t._free(d)}})}(e,t,r,u,n)}if(a){const t=e.getResource(Ut);t&&t.setAddressableManifest(a)}}function ar(e,t,s){return{name:e,data:t,async setup(){await or(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class cr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===Pt(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=Pt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||i.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}i.length>0&&await Promise.all(i)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.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 lr="__preview__";class hr{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(Ws);t.register({name:lr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(lr),this.loadPromise_=t.load(lr).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(),s=new cr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await or(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,lr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([q]);for(const n of s){if(e.get(n,q).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([G]);for(const r of n){const n=e.get(r,G);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(Ws).getScene(lr),i=r?r.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}};e.insert(i,V,o);const a={isActive:!0,projectionType:W.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:j.ColorAndDepth};e.insert(i,q,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(Ws);await e.switchTo(lr),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 ur={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Fs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Fs.getTargetTexture(s),width:e.width,height:e.height}},release(e){Fs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Fs.releaseRenderTarget(e._handle),ur.create({width:t,height:s,depth:!0})),begin(e,t){Fs.begin(t,e._handle)},end(){Fs.end()},getDepthTexture:e=>Fs.getTargetDepthTexture(e._handle)};let dr=!1;function fr(e){dr=e}function pr(){return dr}function _r(){return!dr}var mr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(mr||(mr={}));class gr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${mr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case mr.Debug:console.debug(t,s);break;case mr.Info:console.log(t,s);break;case mr.Warn:console.warn(t,s);break;case mr.Error:console.error(t,s)}}}class yr{constructor(){this.handlers_=[],this.minLevel_=mr.Info,this.addHandler(new gr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(mr.Debug,e,t,s)}info(e,t,s){this.log(mr.Info,e,t,s)}warn(e,t,s){this.log(mr.Warn,e,t,s)}error(e,t,s){this.log(mr.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const wr=new yr;function xr(){return wr}function vr(e){wr.setMinLevel(e)}function br(e,t,s){wr.debug(e,t,s)}function Sr(e,t,s){wr.info(e,t,s)}function Pr(e,t,s){wr.warn(e,t,s)}function Cr(e,t,s){wr.error(e,t,s)}const Tr=[_n,Cn,Un,Wn,Yn];function Er(e,t){return function(e,t){const s=Xs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),es(e),Je(e),gs(e),bs(e),As(e),ks(e);const r=new Ds;s.setPipeline(r);let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=Js(e,n,t,r));const o=s.getResource(je);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,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}s.insertResource(je,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=o();if(0===t||0===c)return;const l=e.registry_getCanvasEntity(n);if(l>=0){const e=n.getCanvas(l).backgroundColor;Fs.setClearColor(e.x,e.y,e.z,e.w)}const h=(d()-i)/1e3;let u;if(Fs.resize(t,c),Cs.isInitialized()&&Cs.getPassCount()>0&&!Cs.isBypassed()&&Cs.resize(t,c),s.hasResource(Ws)){const e=s.getResource(Ws).getActiveScenes();e.length>0&&(u=new Set(e))}r.setActiveScenes(u??null);const f=Js(e,n,t,c,s.world,u);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:qs,width:t,height:c,elapsed:h});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:l},clearFlags:e.clearFlags,elapsed:h})}Fs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Se.First,c),s.addSystemToSchedule(Se.Last,l),s.addPlugin(Lt),s.addPlugin(qt),s.addPlugin(ke),s.addPlugin(Vs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Tr,...t})}e=f;export{Xs as App,Dt as AssetPlugin,zt as AssetRefCounter,Bt as AssetServer,Ut as Assets,ct as AsyncCache,Z as BitmapText,Ne as BlendMode,ce as BodyType,ie as BoxCollider,Rn as Button,Mn as ButtonState,q as Camera,G as Canvas,ae as CapsuleCollider,Q as Children,oe as CircleCollider,j as ClearFlags,xe as Commands,be as CommandsInstance,_ as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,m as DEFAULT_PIXELS_PER_UNIT,g as DEFAULT_TEXT_CANVAS_SIZE,ds as DataType,rs as Draw,ve as EntityCommands,Us as GLDebug,xs as Geometry,x as INVALID_ENTITY,b as INVALID_FONT,v as INVALID_TEXTURE,Fe as Input,$e as InputPlugin,Ie as InputState,Tn as Interactable,V as LocalTransform,mr as LogLevel,yr as Logger,Ze as Material,lt as MaterialLoader,me as Mut,te as Name,K as Parent,sr as Physics,Jn as PhysicsEvents,er as PhysicsPlugin,Cs as PostProcess,Vt as PrefabServer,Xt as Prefabs,Yt as PrefabsPlugin,hr as PreviewPlugin,W as ProjectionType,ye as Query,we as QueryInstance,Ds as RenderPipeline,Es as RenderStage,ur as RenderTexture,Fs as Renderer,ue as Res,de as ResMut,re as RigidBody,y as RuntimeConfig,N as ScaleMode,Ws as SceneManager,Hs as SceneManagerState,se as SceneOwner,Se as Schedule,Fn as ScreenSpace,at as ShaderSources,ee as SpineAnimation,Y as Sprite,Ae as SystemRunner,ln as Text,on as TextAlign,jn as TextInput,Nn as TextInputPlugin,cn as TextOverflow,pn as TextPlugin,un as TextRenderer,an as TextVerticalAlign,_e as Time,je as UICameraInfo,An as UIEventQueue,In as UIEvents,En as UIInteraction,Hn as UIInteractionPlugin,Bn as UILayoutPlugin,mn as UIMask,Pn as UIMaskPlugin,hn as UIRect,J as Velocity,cr as WebAssetProvider,We as World,X as WorldTransform,Me as addStartupSystem,Ee as addSystem,Re as addSystemToSchedule,w as applyRuntimeConfig,Lt as assetPlugin,us as clearDrawCallbacks,B as clearUserComponents,T as color,$n as computeUIRectLayout,Sn as createMaskProcessor,ar as createRuntimeSceneConfig,Er as createWebApp,br as debug,F as defineComponent,he as defineResource,Ce as defineSystem,$ as defineTag,Cr as error,yt as findEntityByName,Ys as flushPendingSystems,Tt as getAddressableType,Et as getAddressableTypeByEditorType,Rt as getAllAssetExtensions,$t as getAssetMimeType,Pt as getAssetTypeEntry,O as getComponent,dt as getComponentAssetFields,ne as getComponentDefaults,It as getCustomExtensions,Ct as getEditorType,xr as getLogger,t as getPlatform,n as getPlatformType,k as getUserComponent,Ft as getWeChatPackOptions,Sr as info,es as initDrawAPI,ks as initGLDebugAPI,gs as initGeometryAPI,Je as initMaterialAPI,bs as initPostProcessAPI,As as initRendererAPI,ke as inputPlugin,Ht as instantiatePrefab,gn as intersectRects,wn as invertMatrix4,D as isBuiltinComponent,kt as isCustomExtension,pr as isEditor,Mt as isKnownAssetExtension,s as isPlatformInitialized,_r as isRuntime,Ve as isTextureRef,r as isWeChat,i as isWeb,mt as loadComponent,Gn as loadPhysicsModule,or as loadRuntimeScene,pt as loadSceneData,_t as loadSceneWithAssets,At as looksLikeAssetPath,o as platformFetch,l as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,vn as pointInWorldRect,qt as prefabsPlugin,E as quat,z as registerComponent,ut as registerComponentAssetFields,ls as registerDrawCallback,Ot as registerEmbeddedAssets,ot as registerMaterialCallback,Vs as sceneManagerPlugin,xn as screenToWorld,fr as setEditorMode,vr as setLogLevel,ze as setWasmErrorHandler,ts as shutdownDrawAPI,Bs as shutdownGLDebugAPI,ys as shutdownGeometryAPI,Ke as shutdownMaterialAPI,Ss as shutdownPostProcessAPI,Is as shutdownRendererAPI,Yn as textInputPlugin,_n as textPlugin,qn as transitionTo,Wn as uiInteractionPlugin,Un as uiLayoutPlugin,Cn as uiMaskPlugin,Tr as uiPlugins,hs as unregisterDrawCallback,gt as updateCameraAspectRatio,S as vec2,P as vec3,C as vec4,Pr as warn,yn as worldRectToScreen,js as wrapSceneSystem};
//# sourceMappingURL=index.js.map
diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.html
index f62a758f4..811fb8fe4 100644
--- a/desktop/src-tauri/src/preview_template.html
+++ b/desktop/src-tauri/src/preview_template.html
@@ -49,6 +49,224 @@
const loading = document.getElementById('loading');
const errorDiv = document.getElementById('error');
+ let gameApp = null;
+
+ function sendToEditor(type, data) {
+ try {
+ window.parent.postMessage({ type, data }, '*');
+ } catch (e) { /* ignore */ }
+ }
+
+ const _origLog = console.log;
+ const _origWarn = console.warn;
+ const _origError = console.error;
+ function formatArgs(args) {
+ return args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ');
+ }
+ console.log = (...args) => {
+ _origLog.apply(console, args);
+ sendToEditor('console:log', { message: formatArgs(args) });
+ };
+ console.warn = (...args) => {
+ _origWarn.apply(console, args);
+ sendToEditor('console:warn', { message: formatArgs(args) });
+ };
+ console.error = (...args) => {
+ _origError.apply(console, args);
+ sendToEditor('console:error', { message: formatArgs(args) });
+ };
+
+ let _frameCount = 0;
+ let _lastStatsTime = performance.now();
+ function reportStats() {
+ _frameCount++;
+ const now = performance.now();
+ if (now - _lastStatsTime >= 1000) {
+ const fps = Math.round(_frameCount * 1000 / (now - _lastStatsTime));
+ const entityCount = gameApp?.world?.getAllEntities()?.length ?? 0;
+ sendToEditor('stats', { fps, entityCount });
+ _frameCount = 0;
+ _lastStatsTime = now;
+ }
+ requestAnimationFrame(reportStats);
+ }
+
+ window.addEventListener('message', (event) => {
+ if (event.source !== window.parent) return;
+ const msg = event.data;
+ if (!msg || typeof msg !== 'object' || !msg.type) return;
+
+ const { type, requestId } = msg;
+ let response = null;
+
+ try {
+ switch (type) {
+ case 'pause':
+ gameApp?.setPaused(true);
+ response = { success: true };
+ break;
+ case 'resume':
+ gameApp?.setPaused(false);
+ response = { success: true };
+ break;
+ case 'step':
+ gameApp?.stepFrame();
+ response = { success: true };
+ break;
+ case 'set-speed':
+ gameApp?.setPlaySpeed(msg.speed ?? 1);
+ response = { success: true };
+ break;
+ case 'query-entity-list':
+ response = getEntityList();
+ break;
+ case 'query-entity':
+ response = getEntityData(msg.entityId);
+ break;
+ case 'set-entity-property':
+ setEntityProperty(msg.entityId, msg.component, msg.property, msg.value);
+ response = { success: true };
+ break;
+ case 'query-stats': {
+ const entities = gameApp?.world?.getAllEntities() ?? [];
+ response = { entityCount: entities.length, paused: gameApp?.isPaused() ?? false };
+ break;
+ }
+ }
+ } catch (e) {
+ response = { error: e.message || String(e) };
+ }
+
+ if (requestId !== undefined) {
+ window.parent.postMessage({ type, requestId, data: response }, '*');
+ }
+ });
+
+ function getEntityList() {
+ if (!gameApp) return [];
+ const world = gameApp.world;
+ const sdk = window.__esSdk;
+ const entities = world.getAllEntities();
+ return entities.map(entityId => {
+ const name = getEntityName(world, entityId);
+ const componentTypes = getComponentTypes(world, entityId);
+ const parentId = getEntityParentId(world, sdk, entityId);
+ const children = getEntityChildren(world, sdk, entityId);
+ return { entityId, name, parentId, children, components: componentTypes.map(t => ({ type: t, data: {} })) };
+ });
+ }
+
+ function getEntityData(entityId) {
+ if (!gameApp) return null;
+ const world = gameApp.world;
+ const sdk = window.__esSdk;
+ const name = getEntityName(world, entityId);
+ const componentTypes = getComponentTypes(world, entityId);
+ const parentId = getEntityParentId(world, sdk, entityId);
+ const children = getEntityChildren(world, sdk, entityId);
+ const components = componentTypes.map(typeName => {
+ try {
+ const data = getComponentData(world, entityId, typeName);
+ return { type: typeName, data: data || {} };
+ } catch {
+ return { type: typeName, data: {} };
+ }
+ });
+ return { entityId, name, parentId, children, components };
+ }
+
+ function getEntityName(world, entityId) {
+ const sdk = window.__esSdk;
+ if (sdk) {
+ try {
+ const nameDef = sdk.getComponent('Name');
+ if (nameDef) {
+ const nameData = world.tryGet(entityId, nameDef);
+ if (nameData && nameData.value) return nameData.value;
+ }
+ } catch {}
+ }
+ return 'Entity ' + entityId;
+ }
+
+ function getComponentTypes(world, entityId) {
+ try {
+ if (world.getComponentTypes) {
+ return world.getComponentTypes(entityId);
+ }
+ } catch {}
+ return [];
+ }
+
+ function getEntityParentId(world, sdk, entityId) {
+ if (!sdk) return null;
+ try {
+ const parent = world.tryGet(entityId, sdk.Parent);
+ if (parent && parent.entity !== undefined && parent.entity !== 0) return parent.entity;
+ } catch {}
+ return null;
+ }
+
+ function getEntityChildren(world, sdk, entityId) {
+ if (!sdk) return [];
+ try {
+ const children = world.tryGet(entityId, sdk.Children);
+ if (children && Array.isArray(children.entities)) return children.entities;
+ } catch {}
+ return [];
+ }
+
+ function serializeValue(val) {
+ if (val === null || val === undefined) return val;
+ if (typeof val === 'number' || typeof val === 'boolean' || typeof val === 'string') return val;
+ if (Array.isArray(val)) return val.map(serializeValue);
+ if (typeof val === 'object') {
+ const out = {};
+ for (const k of Object.keys(val)) {
+ const v = val[k];
+ if (typeof v === 'function') continue;
+ out[k] = serializeValue(v);
+ }
+ return out;
+ }
+ return String(val);
+ }
+
+ function getComponentData(world, entityId, typeName) {
+ const sdk = window.__esSdk;
+ if (!sdk) return {};
+ try {
+ const compDef = sdk.getComponent(typeName);
+ if (!compDef) return {};
+ const data = world.tryGet(entityId, compDef);
+ if (!data) return {};
+ return serializeValue(data);
+ } catch { return {}; }
+ }
+
+ function setEntityProperty(entityId, component, property, value) {
+ if (!gameApp) return;
+ const sdk = window.__esSdk;
+ if (!sdk) return;
+ const world = gameApp.world;
+ try {
+ const compDef = sdk.getComponent(component);
+ if (!compDef) return;
+ const current = world.tryGet(entityId, compDef);
+ if (!current) return;
+
+ if (compDef._builtin) {
+ const snapshot = serializeValue(current);
+ snapshot[property] = value;
+ world.insert(entityId, compDef, snapshot);
+ } else {
+ current[property] = value;
+ }
+ } catch (e) {
+ _origWarn.call(console, 'setEntityProperty failed:', e);
+ }
+ }
+
function updateLoading(message) {
loading.textContent = message;
}
@@ -132,6 +350,7 @@
step = 'load SDK';
updateLoading('Loading SDK...');
const sdk = await withTimeout(import('/sdk/index.js'), 30000, 'SDK import');
+ window.__esSdk = sdk;
let spinePlugin = null;
let physicsPlugin = null;
@@ -232,6 +451,10 @@
step = 'app.run';
loading.style.display = 'none';
app.run();
+
+ gameApp = app;
+ sendToEditor('ready', {});
+ reportStats();
} catch (err) {
showError('[' + step + '] ' + (err.message || String(err)), err);
}
@@ -239,10 +462,12 @@
window.addEventListener('error', (e) => {
showError('[runtime error] ' + (e.message || String(e)), e.error);
+ sendToEditor('error', { message: e.message || String(e), stack: e.error?.stack });
});
window.addEventListener('unhandledrejection', (e) => {
const err = e.reason;
showError('[unhandled rejection] ' + (err?.message || String(err)), err);
+ sendToEditor('error', { message: err?.message || String(err), stack: err?.stack });
});
function connectLiveReload() {
diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.ts
index 1aeb2ca28..8946cb1f9 100644
--- a/editor/src/panels/InspectorPanel.ts
+++ b/editor/src/panels/InspectorPanel.ts
@@ -18,6 +18,8 @@ import { renderMaterialInspector } from './inspector/MaterialInspector';
import { renderBitmapFontInspector } from './inspector/BitmapFontInspector';
import { renderFolderInspector } from './inspector/FolderInspector';
import { renderScriptInspector, renderSceneInspector, renderFileInspector } from './inspector/FileInspector';
+import { getPlayModeService } from '../services/PlayModeService';
+import { renderRuntimeEntity, updateRuntimeEntityValues } from './inspector/RuntimeEntityRenderer';
// =============================================================================
// InspectorPanel
@@ -42,6 +44,10 @@ export class InspectorPanel {
private locked_: boolean = false;
private materialPreviewState_: MaterialPreviewState;
private extensionSections_: InspectorSectionInstance[] = [];
+ private playMode_: boolean = false;
+ private playModeCleanups_: (() => void)[] = [];
+ private runtimeEntityId_: number | null = null;
+ private runtimeRefreshTimer_: ReturnType<typeof setInterval> | null = null;
constructor(container: HTMLElement, store: EditorStore) {
this.container_ = container;
@@ -69,6 +75,31 @@ export class InspectorPanel {
this.unsubscribe_ = store.subscribe(() => this.render());
this.unsubPropertyChange_ = store.subscribeToPropertyChanges(() => this.updateEditors());
this.render();
+
+ const pms = getPlayModeService();
+ this.playModeCleanups_.push(
+ pms.onStateChange((state) => {
+ this.playMode_ = state === 'playing';
+ if (this.playMode_) {
+ this.container_.classList.add('es-play-mode');
+ hideMaterialPreview(this.materialPreviewState_);
+ } else {
+ this.container_.classList.remove('es-play-mode');
+ this.stopRuntimeRefresh();
+ this.runtimeEntityId_ = null;
+ this.render();
+ }
+ }),
+ pms.onSelectionChange((entityId) => {
+ if (!this.playMode_) return;
+ this.runtimeEntityId_ = entityId;
+ if (entityId !== null) {
+ this.renderRuntimeEntity(entityId);
+ } else {
+ this.renderPlayModeEmpty();
+ }
+ }),
+ );
}
private setupLockButton(): void {
@@ -93,6 +124,9 @@ export class InspectorPanel {
}
dispose(): void {
+ for (const cleanup of this.playModeCleanups_) cleanup();
+ this.playModeCleanups_ = [];
+ this.stopRuntimeRefresh();
this.disposeEditors();
this.cleanupImageUrl();
if (this.unsubscribe_) {
@@ -110,6 +144,7 @@ export class InspectorPanel {
// =========================================================================
private render(): void {
+ if (this.playMode_) return;
if (this.locked_) {
if (this.currentEntity_ !== null) {
this.updateEditors();
@@ -322,6 +357,56 @@ export class InspectorPanel {
this.updateFooter(getAssetTypeName(asset.type));
}
+ // =========================================================================
+ // Play Mode (Runtime Inspector)
+ // =========================================================================
+
+ private async renderRuntimeEntity(entityId: number): Promise<void> {
+ this.stopRuntimeRefresh();
+ this.disposeEditors();
+ this.cleanupImageUrl();
+ this.currentEntity_ = null;
+ this.currentAssetPath_ = null;
+ hideMaterialPreview(this.materialPreviewState_);
+
+ const pms = getPlayModeService();
+ const data = await pms.querySelectedEntity();
+ if (!data || this.runtimeEntityId_ !== entityId) return;
+
+ this.contentContainer_.innerHTML = '';
+ renderRuntimeEntity(this.contentContainer_, data, pms.bridge);
+ this.updateFooter(`${data.components.length} components (Runtime)`);
+
+ this.runtimeRefreshTimer_ = setInterval(async () => {
+ if (this.runtimeEntityId_ !== entityId) {
+ this.stopRuntimeRefresh();
+ return;
+ }
+ const fresh = await pms.querySelectedEntity();
+ if (fresh && this.runtimeEntityId_ === entityId) {
+ updateRuntimeEntityValues(this.contentContainer_, fresh);
+ }
+ }, 500);
+ }
+
+ private renderPlayModeEmpty(): void {
+ this.stopRuntimeRefresh();
+ this.disposeEditors();
+ this.cleanupImageUrl();
+ this.currentEntity_ = null;
+ this.currentAssetPath_ = null;
+ this.contentContainer_.innerHTML = '<div class="es-inspector-empty">Select a runtime entity</div>';
+ hideMaterialPreview(this.materialPreviewState_);
+ this.updateFooter('Runtime mode');
+ }
+
+ private stopRuntimeRefresh(): void {
+ if (this.runtimeRefreshTimer_) {
+ clearInterval(this.runtimeRefreshTimer_);
+ this.runtimeRefreshTimer_ = null;
+ }
+ }
+
// =========================================================================
// Editors
// =========================================================================
diff --git a/editor/src/panels/game-view/GameViewBridge.ts b/editor/src/panels/game-view/GameViewBridge.ts
new file mode 100644
index 000000000..12218ca1d
--- /dev/null
+++ b/editor/src/panels/game-view/GameViewBridge.ts
@@ -0,0 +1,143 @@
+export interface EntityComponentData {
+ type: string;
+ data: Record<string, unknown>;
+}
+
+export interface RuntimeEntityData {
+ entityId: number;
+ name: string;
+ parentId: number | null;
+ children: number[];
+ components: EntityComponentData[];
+}
+
+export interface RuntimeStats {
+ fps: number;
+ entityCount: number;
+}
+
+type EventHandler = (data: any) => void;
+
+export class GameViewBridge {
+ private iframe_: HTMLIFrameElement;
+ private messageId_ = 0;
+ private pendingRequests_ = new Map<number, { resolve: (v: any) => void; timer: ReturnType<typeof setTimeout> }>();
+ private listeners_ = new Map<string, Set<EventHandler>>();
+ private boundHandler_: (e: MessageEvent) => void;
+ private ready_ = false;
+
+ constructor(iframe: HTMLIFrameElement) {
+ this.iframe_ = iframe;
+ this.boundHandler_ = (e: MessageEvent) => this.handleMessage(e);
+ window.addEventListener('message', this.boundHandler_);
+ }
+
+ get isReady(): boolean {
+ return this.ready_;
+ }
+
+ request<T = any>(type: string, payload?: Record<string, unknown>, timeout = 5000): Promise<T> {
+ return new Promise((resolve, reject) => {
+ const requestId = ++this.messageId_;
+ const timer = setTimeout(() => {
+ this.pendingRequests_.delete(requestId);
+ reject(new Error(`GameViewBridge: '${type}' timed out`));
+ }, timeout);
+ this.pendingRequests_.set(requestId, { resolve, timer });
+ this.postCommand({ type, requestId, ...payload });
+ });
+ }
+
+ send(type: string, payload?: Record<string, unknown>): void {
+ this.postCommand({ type, ...payload });
+ }
+
+ async pause(): Promise<void> {
+ await this.request('pause');
+ }
+
+ async resume(): Promise<void> {
+ await this.request('resume');
+ }
+
+ async step(): Promise<void> {
+ await this.request('step');
+ }
+
+ setSpeed(speed: number): void {
+ this.send('set-speed', { speed });
+ }
+
+ async queryEntityList(): Promise<RuntimeEntityData[]> {
+ return this.request('query-entity-list');
+ }
+
+ async queryEntity(entityId: number): Promise<RuntimeEntityData> {
+ return this.request('query-entity', { entityId });
+ }
+
+ async setEntityProperty(
+ entityId: number,
+ component: string,
+ property: string,
+ value: unknown,
+ ): Promise<void> {
+ return this.request('set-entity-property', { entityId, component, property, value });
+ }
+
+ async queryStats(): Promise<RuntimeStats> {
+ return this.request('query-stats');
+ }
+
+ on(event: string, handler: EventHandler): () => void {
+ if (!this.listeners_.has(event)) {
+ this.listeners_.set(event, new Set());
+ }
+ this.listeners_.get(event)!.add(handler);
+ return () => {
+ this.listeners_.get(event)?.delete(handler);
+ };
+ }
+
+ dispose(): void {
+ window.removeEventListener('message', this.boundHandler_);
+ for (const { timer } of this.pendingRequests_.values()) {
+ clearTimeout(timer);
+ }
+ this.pendingRequests_.clear();
+ this.listeners_.clear();
+ this.ready_ = false;
+ }
+
+ private postCommand(data: Record<string, unknown>): void {
+ this.iframe_.contentWindow?.postMessage(data, '*');
+ }
+
+ private handleMessage(e: MessageEvent): void {
+ if (e.source !== this.iframe_.contentWindow) return;
+
+ const msg = e.data;
+ if (!msg || typeof msg !== 'object' || !msg.type) return;
+
+ if (msg.type === 'ready') {
+ this.ready_ = true;
+ }
+
+ if (msg.requestId !== undefined) {
+ const pending = this.pendingRequests_.get(msg.requestId);
+ if (pending) {
+ clearTimeout(pending.timer);
+ pending.resolve(msg.data);
+ this.pendingRequests_.delete(msg.requestId);
+ return;
+ }
+ }
+
+ const handlers = this.listeners_.get(msg.type);
+ if (handlers) {
+ for (const handler of handlers) {
+ handler(msg.data);
+ }
+ }
+ }
+}
diff --git a/editor/src/panels/game-view/GameViewPanel.ts b/editor/src/panels/game-view/GameViewPanel.ts
index 118a4dbda..f106ebcd7 100644
--- a/editor/src/panels/game-view/GameViewPanel.ts
+++ b/editor/src/panels/game-view/GameViewPanel.ts
@@ -2,6 +2,8 @@ import type { EditorStore } from '../../store/EditorStore';
import type { PanelInstance, Resizable } from '../PanelRegistry';
import { GameInstanceManager, type GameState } from './GameInstanceManager';
import { GameViewToolbar } from './GameViewToolbar';
+import { GameViewBridge } from './GameViewBridge';
+import { getPlayModeService } from '../../services/PlayModeService';
export interface GameViewPanelOptions {
projectPath?: string;
@@ -12,8 +14,10 @@ export class GameViewPanel implements PanelInstance, Resizable {
private iframe_: HTMLIFrameElement | null = null;
private toolbar_: GameViewToolbar;
private gameManager_: GameInstanceManager;
- private viewport_: HTMLElement | null = null;
+ private bridge_: GameViewBridge | null = null;
+ private canvasArea_: HTMLElement | null = null;
private placeholder_: HTMLElement | null = null;
+ private eventCleanups_: (() => void)[] = [];
constructor(container: HTMLElement, _store: EditorStore, _options?: GameViewPanelOptions) {
this.container_ = container;
@@ -26,6 +30,10 @@ export class GameViewPanel implements PanelInstance, Resizable {
this.toolbar_ = new GameViewToolbar(container, {
onPlay: () => this.play(),
onStop: () => this.stop(),
+ onPause: () => this.pause(),
+ onResume: () => this.resume(),
+ onStepFrame: () => this.stepFrame(),
+ onSpeedChange: (speed) => this.bridge_?.setSpeed(speed),
onResolutionChange: () => this.updateIframeSize(),
});
@@ -37,6 +45,7 @@ export class GameViewPanel implements PanelInstance, Resizable {
}
dispose(): void {
+ this.disposeBridge();
this.gameManager_.dispose();
this.toolbar_.dispose();
}
@@ -50,15 +59,17 @@ export class GameViewPanel implements PanelInstance, Resizable {
</div>
</div>
<div class="es-gameview-viewport">
- <iframe class="es-gameview-iframe"></iframe>
- <div class="es-gameview-placeholder">
- <span>Click Play to start</span>
+ <div class="es-gameview-canvas-area">
+ <iframe class="es-gameview-iframe"></iframe>
+ <div class="es-gameview-placeholder">
+ <span>Click Play to start</span>
+ </div>
</div>
</div>
`;
this.iframe_ = this.container_.querySelector('.es-gameview-iframe')!;
- this.viewport_ = this.container_.querySelector('.es-gameview-viewport')!;
+ this.canvasArea_ = this.container_.querySelector('.es-gameview-canvas-area')!;
this.placeholder_ = this.container_.querySelector('.es-gameview-placeholder')!;
this.toolbar_.setup();
@@ -69,16 +80,78 @@ export class GameViewPanel implements PanelInstance, Resizable {
const url = await this.gameManager_.play();
if (url && this.iframe_) {
this.iframe_.src = url + '?t=' + Date.now();
+ this.createBridge();
}
}
+ private async pause(): Promise<void> {
+ if (!this.bridge_?.isReady) return;
+ try {
+ await this.bridge_.pause();
+ this.gameManager_.pause();
+ } catch { /* ignore timeout */ }
+ }
+
+ private async resume(): Promise<void> {
+ if (!this.bridge_?.isReady) return;
+ try {
+ await this.bridge_.resume();
+ this.gameManager_.resume();
+ } catch { /* ignore timeout */ }
+ }
+
+ private async stepFrame(): Promise<void> {
+ if (!this.bridge_?.isReady) return;
+ try {
+ await this.bridge_.step();
+ } catch { /* ignore timeout */ }
+ }
+
private async stop(): Promise<void> {
+ this.disposeBridge();
if (this.iframe_) {
this.iframe_.src = 'about:blank';
}
await this.gameManager_.stop();
}
+ private createBridge(): void {
+ if (!this.iframe_) return;
+ this.disposeBridge();
+
+ this.bridge_ = new GameViewBridge(this.iframe_);
+
+ this.eventCleanups_.push(
+ this.bridge_.on('stats', (data) => {
+ this.toolbar_.updateFps(data.fps ?? 0);
+ }),
+ this.bridge_.on('console:log', (data) => {
+ console.log('[Preview]', data.message);
+ }),
+ this.bridge_.on('console:warn', (data) => {
+ console.warn('[Preview]', data.message);
+ }),
+ this.bridge_.on('console:error', (data) => {
+ console.error('[Preview]', data.message);
+ }),
+ this.bridge_.on('error', (data) => {
+ console.error('[Preview Error]', data.message);
+ }),
+ this.bridge_.on('ready', () => {
+ getPlayModeService().enter(this.bridge_!);
+ }),
+ );
+ }
+
+ private disposeBridge(): void {
+ for (const cleanup of this.eventCleanups_) cleanup();
+ this.eventCleanups_ = [];
+ getPlayModeService().exit();
+ this.bridge_?.dispose();
+ this.bridge_ = null;
+ this.toolbar_.updateFps(0);
+ }
+
private onStateChange(state: GameState): void {
this.toolbar_.updateState(state);
@@ -91,9 +164,9 @@ export class GameViewPanel implements PanelInstance, Resizable {
}
private updateIframeSize(): void {
- if (!this.iframe_ || !this.viewport_) return;
+ if (!this.iframe_ || !this.canvasArea_) return;
- const rect = this.viewport_.getBoundingClientRect();
+ const rect = this.canvasArea_.getBoundingClientRect();
const preset = this.toolbar_.currentPreset;
if (preset.width > 0 && preset.height > 0) {
diff --git a/editor/src/panels/game-view/index.ts b/editor/src/panels/game-view/index.ts
index 8b898a914..c95cd514d 100644
--- a/editor/src/panels/game-view/index.ts
+++ b/editor/src/panels/game-view/index.ts
@@ -1,3 +1,4 @@
export { GameViewPanel, type GameViewPanelOptions } from './GameViewPanel';
export { GameInstanceManager, type GameState, type GameInstanceCallbacks } from './GameInstanceManager';
export { GameViewToolbar, type ResolutionPreset, type GameViewToolbarCallbacks } from './GameViewToolbar';
+export { GameViewBridge, type RuntimeEntityData, type RuntimeStats, type EntityComponentData } from './GameViewBridge';
diff --git a/editor/src/panels/hierarchy/HierarchyPanel.ts b/editor/src/panels/hierarchy/HierarchyPanel.ts
index 7b8830381..4e5e901b6 100644
--- a/editor/src/panels/hierarchy/HierarchyPanel.ts
+++ b/editor/src/panels/hierarchy/HierarchyPanel.ts
@@ -11,6 +11,9 @@ import { performSearch, selectNextResult, selectPreviousResult, focusSelectedRes
import { setupKeyboard, selectRange } from './HierarchyKeyboard';
import { setupDragAndDrop } from './HierarchyDragDrop';
import { showEntityContextMenu, duplicateEntity, createEntityFromAsset } from './HierarchyContextMenu';
+import { getPlayModeService } from '../../services/PlayModeService';
+import type { RuntimeEntityData } from '../game-view/GameViewBridge';
+import type { EntityData } from '../../types/SceneTypes';
export class HierarchyPanel implements HierarchyState {
private container_: HTMLElement;
@@ -38,6 +41,9 @@ export class HierarchyPanel implements HierarchyState {
renamingEntityId: number | null = null;
lastClickEntityId: number | null = null;
lastClickTime: number = 0;
+ playMode: boolean = false;
+ private playModeCleanups_: (() => void)[] = [];
+ private toolbar_: HTMLElement | null = null;
constructor(container: HTMLElement, store: EditorStore) {
this.container_ = container;
@@ -85,12 +91,37 @@ export class HierarchyPanel implements HierarchyState {
this.store.exitPrefabEditMode();
});
+ this.toolbar_ = this.container_.querySelector('.es-hierarchy-toolbar');
+
this.setupEvents();
this.unsubscribe_ = store.subscribe((_state, dirtyFlags) => this.onStoreNotify(dirtyFlags));
this.render();
+
+ const pms = getPlayModeService();
+ this.playModeCleanups_.push(
+ pms.onStateChange((state) => {
+ this.playMode = state === 'playing';
+ if (this.playMode) {
+ this.container_.classList.add('es-play-mode');
+ this.setToolbarDisabled(true);
+ } else {
+ this.container_.classList.remove('es-play-mode');
+ this.setToolbarDisabled(false);
+ }
+ this.render();
+ }),
+ pms.onEntityListUpdate(() => {
+ if (this.playMode) this.render();
+ }),
+ pms.onSelectionChange(() => {
+ if (this.playMode) this.renderVisibleRows();
+ }),
+ );
}
dispose(): void {
+ for (const cleanup of this.playModeCleanups_) cleanup();
+ this.playModeCleanups_ = [];
if (this.unsubscribe_) {
this.unsubscribe_();
this.unsubscribe_ = null;
@@ -106,6 +137,7 @@ export class HierarchyPanel implements HierarchyState {
}
private onStoreNotify(dirtyFlags?: ReadonlySet<DirtyFlag>): void {
+ if (this.playMode) return;
if (dirtyFlags && !dirtyFlags.has('scene') && !dirtyFlags.has('hierarchy') && !dirtyFlags.has('selection')) {
return;
}
@@ -177,17 +209,6 @@ export class HierarchyPanel implements HierarchyState {
if (target.closest('.es-hierarchy-rename-input')) return;
- const visibilityBtn = target.closest('.es-hierarchy-visibility') as HTMLElement;
- if (visibilityBtn) {
- e.stopPropagation();
- const item = visibilityBtn.closest('.es-hierarchy-item') as HTMLElement;
- const entityId = parseInt(item?.dataset.entityId ?? '', 10);
- if (!isNaN(entityId)) {
- this.store.toggleVisibility(entityId);
- }
- return;
- }
-
const expandBtn = target.closest('.es-hierarchy-expand') as HTMLElement;
if (expandBtn) {
e.stopPropagation();
@@ -205,6 +226,28 @@ export class HierarchyPanel implements HierarchyState {
return;
}
+ if (this.playMode) {
+ const row = target.closest('.es-hierarchy-row');
+ const item = row?.parentElement as HTMLElement;
+ if (!item?.classList.contains('es-hierarchy-item')) return;
+ const entityId = parseInt(item.dataset.entityId ?? '', 10);
+ if (!isNaN(entityId)) {
+ getPlayModeService().selectEntity(entityId);
+ }
+ return;
+ }
+
+ const visibilityBtn = target.closest('.es-hierarchy-visibility') as HTMLElement;
+ if (visibilityBtn) {
+ e.stopPropagation();
+ const item = visibilityBtn.closest('.es-hierarchy-item') as HTMLElement;
+ const entityId = parseInt(item?.dataset.entityId ?? '', 10);
+ if (!isNaN(entityId)) {
+ this.store.toggleVisibility(entityId);
+ }
+ return;
+ }
+
const row = target.closest('.es-hierarchy-row');
const item = row?.parentElement as HTMLElement;
if (!item?.classList.contains('es-hierarchy-item')) return;
@@ -239,6 +282,7 @@ export class HierarchyPanel implements HierarchyState {
});
this.treeContainer.addEventListener('dblclick', (e) => {
+ if (this.playMode) return;
const target = e.target as HTMLElement;
if (target.closest('.es-hierarchy-rename-input')) return;
const item = target.closest('.es-hierarchy-item') as HTMLElement;
@@ -253,6 +297,7 @@ export class HierarchyPanel implements HierarchyState {
});
this.treeContainer.addEventListener('contextmenu', (e) => {
+ if (this.playMode) { e.preventDefault(); return; }
e.preventDefault();
const target = e.target as HTMLElement;
const item = target.closest('.es-hierarchy-item') as HTMLElement;
@@ -323,6 +368,11 @@ export class HierarchyPanel implements HierarchyState {
}
render(): void {
+ if (this.playMode) {
+ this.renderPlayMode();
+ return;
+ }
+
const scene = this.store.scene;
const selectedEntity = this.store.selectedEntity;
@@ -363,6 +413,12 @@ export class HierarchyPanel implements HierarchyState {
private updateFooter(): void {
if (!this.footerContainer_) return;
+ if (this.playMode) {
+ const count = getPlayModeService().runtimeEntities.length;
+ this.footerContainer_.textContent = `${count} ${count === 1 ? 'entity' : 'entities'} (Runtime)`;
+ return;
+ }
+
if (this.searchFilter) {
const count = this.searchResults.length;
this.footerContainer_.textContent = `${count} ${count === 1 ? 'match' : 'matches'}`;
@@ -422,6 +478,49 @@ export class HierarchyPanel implements HierarchyState {
}
}
+ private renderPlayMode(): void {
+ if (this.prefabEditBar_) {
+ this.prefabEditBar_.style.display = 'none';
+ }
+
+ const entities = getPlayModeService().runtimeEntities;
+ const entityMap = new Map<number, RuntimeEntityData>();
+ for (const e of entities) entityMap.set(e.entityId, e);
+
+ const rows: FlattenedRow[] = [];
+ const visited = new Set<number>();
+ const buildRows = (parentId: number | null, depth: number) => {
+ for (const e of entities) {
+ if (visited.has(e.entityId)) continue;
+ if ((e.parentId ?? null) !== parentId) continue;
+ visited.add(e.entityId);
+ const adapted = runtimeToEntityData(e);
+ const hasChildren = (e.children?.length ?? 0) > 0;
+ const isExpanded = this.expandedIds.has(e.entityId);
+ rows.push({ entity: adapted, depth, hasChildren, isExpanded });
+ if (hasChildren && isExpanded) {
+ buildRows(e.entityId, depth + 1);
+ }
+ }
+ };
+ buildRows(null, 0);
+
+ this.flatRows = rows;
+ this.scrollContent.style.height = `${rows.length * ROW_HEIGHT}px`;
+ this.lastVisibleStart_ = -1;
+ this.lastVisibleEnd_ = -1;
+ this.renderVisibleRows();
+ this.updateFooter();
+ }
+
+ private setToolbarDisabled(disabled: boolean): void {
+ if (!this.toolbar_) return;
+ const buttons = this.toolbar_.querySelectorAll('[data-action="add"], [data-action="duplicate"]');
+ for (const btn of buttons) {
+ (btn as HTMLButtonElement).disabled = disabled;
+ }
+ }
+
private onScroll(): void {
if (this.scrollRafId_) return;
this.scrollRafId_ = requestAnimationFrame(() => {
@@ -433,3 +532,14 @@ export class HierarchyPanel implements HierarchyState {
});
}
}
+
+function runtimeToEntityData(r: RuntimeEntityData): EntityData {
+ return {
+ id: r.entityId,
+ name: r.name,
+ parent: r.parentId ?? null,
+ children: r.children ?? [],
+ components: r.components.map(c => ({ type: c.type, data: c.data })),
+ visible: true,
+ };
+}
diff --git a/editor/src/panels/hierarchy/HierarchyTree.ts b/editor/src/panels/hierarchy/HierarchyTree.ts
index b358d5098..e3b8f9c8b 100644
--- a/editor/src/panels/hierarchy/HierarchyTree.ts
+++ b/editor/src/panels/hierarchy/HierarchyTree.ts
@@ -4,6 +4,7 @@ import type { FuzzyMatch } from '../../utils/fuzzy';
import { icons } from '../../utils/icons';
import { escapeHtml } from '../../utils/html';
import type { FlattenedRow, HierarchyState } from './HierarchyTypes';
+import { getPlayModeService } from '../../services/PlayModeService';
export function buildFlatRows(state: HierarchyState): FlattenedRow[] {
const rows: FlattenedRow[] = [];
@@ -84,18 +85,26 @@ export function renderSingleRow(state: HierarchyState, row: FlattenedRow, select
const icon = getEntityIcon(entity);
const type = getEntityType(entity);
const expandIcon = isExpanded ? icons.chevronDown(10) : icons.chevronRight(10);
- const isVisible = state.store.isEntityVisible(entity.id);
+ const inPlayMode = state.playMode;
+
+ const isVisible = inPlayMode ? true : state.store.isEntityVisible(entity.id);
const visibilityIcon = isVisible ? icons.eye(10) : icons.eyeOff(10);
let itemClass = 'es-hierarchy-item';
- if (state.store.selectedEntities.has(entity.id)) itemClass += ' es-selected';
+ if (inPlayMode) {
+ if (entity.id === getPlayModeService().selectedEntityId) itemClass += ' es-selected';
+ } else {
+ if (state.store.selectedEntities.has(entity.id)) itemClass += ' es-selected';
+ }
if (!isVisible) itemClass += ' es-entity-hidden';
- if (entity.prefab?.isRoot) itemClass += ' es-prefab-root';
- else if (entity.prefab) itemClass += ' es-prefab-child';
+ if (!inPlayMode) {
+ if (entity.prefab?.isRoot) itemClass += ' es-prefab-root';
+ else if (entity.prefab) itemClass += ' es-prefab-child';
+ }
if (hasChildren) itemClass += ' es-has-children';
if (isExpanded) itemClass += ' es-expanded';
- if (entity.id === state.draggingEntityId) itemClass += ' es-dragging';
- if (entity.id === state.dragOverEntityId) {
+ if (!inPlayMode && entity.id === state.draggingEntityId) itemClass += ' es-dragging';
+ if (!inPlayMode && entity.id === state.dragOverEntityId) {
if (state.dropPosition) {
itemClass += ` es-drop-${state.dropPosition}`;
} else {
@@ -112,13 +121,13 @@ export function renderSingleRow(state: HierarchyState, row: FlattenedRow, select
}
const nameHtml = renderEntityName(entity.name, match);
-
const ariaExpanded = hasChildren ? ` aria-expanded="${isExpanded}"` : '';
+ const draggable = inPlayMode ? 'false' : 'true';
return `<div class="${itemClass}" data-entity-id="${entity.id}" role="treeitem"${ariaExpanded}>
- <div class="es-hierarchy-row" draggable="true" style="padding-left: ${8 + depth * 16}px">
+ <div class="es-hierarchy-row" draggable="${draggable}" style="padding-left: ${8 + depth * 16}px">
${hasChildren ? `<span class="es-hierarchy-expand">${expandIcon}</span>` : '<span class="es-hierarchy-spacer"></span>'}
- <span class="es-hierarchy-visibility">${visibilityIcon}</span>
+ ${inPlayMode ? '' : `<span class="es-hierarchy-visibility">${visibilityIcon}</span>`}
<span class="es-hierarchy-icon">${icon}</span>
<span class="es-hierarchy-name">${nameHtml}</span>
<span class="es-hierarchy-type">${type}</span>
diff --git a/editor/src/panels/hierarchy/HierarchyTypes.ts b/editor/src/panels/hierarchy/HierarchyTypes.ts
index d88297ba4..f0fb5cd43 100644
--- a/editor/src/panels/hierarchy/HierarchyTypes.ts
+++ b/editor/src/panels/hierarchy/HierarchyTypes.ts
@@ -35,6 +35,7 @@ export interface HierarchyState {
renamingEntityId: number | null;
lastClickEntityId: number | null;
lastClickTime: number;
+ playMode: boolean;
render(): void;
renderVisibleRows(): void;
}
diff --git a/editor/src/panels/inspector/RuntimeEntityRenderer.ts b/editor/src/panels/inspector/RuntimeEntityRenderer.ts
new file mode 100644
index 000000000..b060c19db
--- /dev/null
+++ b/editor/src/panels/inspector/RuntimeEntityRenderer.ts
@@ -0,0 +1,149 @@
+import type { RuntimeEntityData, GameViewBridge } from '../game-view/GameViewBridge';
+import { icons } from '../../utils/icons';
+
+export function renderRuntimeEntity(
+ container: HTMLElement,
+ data: RuntimeEntityData,
+ bridge: GameViewBridge | null,
+): void {
+ container.innerHTML = '';
+
+ const header = document.createElement('div');
+ header.className = 'es-inspector-entity-header';
+ header.innerHTML = `
+ <span class="es-entity-icon">${icons.box(16)}</span>
+ <span class="es-entity-name">${data.name || 'Entity ' + data.entityId}</span>
+ <span class="es-entity-id">#${data.entityId}</span>
+ `;
+ container.appendChild(header);
+
+ for (const comp of data.components) {
+ const section = document.createElement('div');
+ section.className = 'es-component-section es-collapsible es-expanded';
+
+ const compHeader = document.createElement('div');
+ compHeader.className = 'es-component-header es-collapsible-header';
+ compHeader.innerHTML = `
+ <span class="es-collapse-icon">${icons.chevronDown(12)}</span>
+ <span class="es-component-title">${comp.type}</span>
+ `;
+ compHeader.addEventListener('click', () => section.classList.toggle('es-expanded'));
+ section.appendChild(compHeader);
+
+ const props = document.createElement('div');
+ props.className = 'es-component-properties es-collapsible-content';
+
+ for (const [key, value] of Object.entries(comp.data)) {
+ const row = document.createElement('div');
+ row.className = 'es-property-row';
+
+ const label = document.createElement('label');
+ label.className = 'es-property-label';
+ label.textContent = key;
+
+ const editor = document.createElement('div');
+ editor.className = 'es-property-editor';
+ createRuntimePropertyEditor(editor, data.entityId, comp.type, key, value, bridge);
+
+ row.appendChild(label);
+ row.appendChild(editor);
+ props.appendChild(row);
+ }
+
+ section.appendChild(props);
+ container.appendChild(section);
+ }
+}
+
+export function updateRuntimeEntityValues(
+ container: HTMLElement,
+ data: RuntimeEntityData,
+): void {
+ for (const comp of data.components) {
+ for (const [key, value] of Object.entries(comp.data)) {
+ const input = container.querySelector(
+ `[data-rt-comp="${comp.type}"][data-rt-prop="${key}"]`
+ ) as HTMLInputElement | null;
+ if (!input) continue;
+ if (document.activeElement === input) continue;
+
+ if (input.type === 'checkbox') {
+ input.checked = Boolean(value);
+ } else if (input.type === 'number') {
+ input.value = String(Math.round((value as number) * 1000) / 1000);
+ } else {
+ input.value = String(value ?? '');
+ }
+ }
+ }
+}
+
+function createRuntimePropertyEditor(
+ container: HTMLElement,
+ entityId: number,
+ componentType: string,
+ property: string,
+ value: unknown,
+ bridge: GameViewBridge | null,
+): void {
+ if (typeof value === 'number') {
+ const input = document.createElement('input');
+ input.type = 'number';
+ input.className = 'es-input es-runtime-input';
+ input.value = String(Math.round(value * 1000) / 1000);
+ input.step = 'any';
+ input.dataset.rtComp = componentType;
+ input.dataset.rtProp = property;
+ input.addEventListener('change', () => {
+ bridge?.setEntityProperty(entityId, componentType, property, parseFloat(input.value));
+ });
+ container.appendChild(input);
+ } else if (typeof value === 'boolean') {
+ const input = document.createElement('input');
+ input.type = 'checkbox';
+ input.checked = value;
+ input.dataset.rtComp = componentType;
+ input.dataset.rtProp = property;
+ input.addEventListener('change', () => {
+ bridge?.setEntityProperty(entityId, componentType, property, input.checked);
+ });
+ container.appendChild(input);
+ } else if (typeof value === 'string') {
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'es-input es-runtime-input';
+ input.value = value;
+ input.dataset.rtComp = componentType;
+ input.dataset.rtProp = property;
+ input.addEventListener('change', () => {
+ bridge?.setEntityProperty(entityId, componentType, property, input.value);
+ });
+ container.appendChild(input);
+ } else if (value && typeof value === 'object' && !Array.isArray(value)) {
+ const obj = value as Record<string, number>;
+ for (const k of Object.keys(obj)) {
+ const wrapper = document.createElement('span');
+ wrapper.className = 'es-runtime-vec-field';
+ const lbl = document.createElement('span');
+ lbl.className = 'es-runtime-vec-label';
+ lbl.textContent = k;
+ const inp = document.createElement('input');
+ inp.type = 'number';
+ inp.className = 'es-input es-runtime-vec-input';
+ inp.value = String(Math.round(obj[k] * 1000) / 1000);
+ inp.step = 'any';
+ inp.addEventListener('change', () => {
+ const newObj = { ...obj, [k]: parseFloat(inp.value) };
+ bridge?.setEntityProperty(entityId, componentType, property, newObj);
+ });
+ wrapper.appendChild(lbl);
+ wrapper.appendChild(inp);
+ container.appendChild(wrapper);
+ }
+ } else {
+ const span = document.createElement('span');
+ span.className = 'es-runtime-readonly';
+ span.textContent = JSON.stringify(value);
+ container.appendChild(span);
+ }
+}
diff --git a/editor/src/services/PlayModeService.ts b/editor/src/services/PlayModeService.ts
new file mode 100644
index 000000000..495bdb9e5
--- /dev/null
+++ b/editor/src/services/PlayModeService.ts
@@ -0,0 +1,130 @@
+import type { GameViewBridge, RuntimeEntityData } from '../panels/game-view/GameViewBridge';
+
+export type PlayState = 'stopped' | 'playing';
+
+type StateChangeCallback = (state: PlayState) => void;
+type EntityListCallback = (entities: RuntimeEntityData[]) => void;
+type SelectionCallback = (entityId: number | null) => void;
+
+class PlayModeService {
+ private state_: PlayState = 'stopped';
+ private bridge_: GameViewBridge | null = null;
+ private selectedEntityId_: number | null = null;
+ private cachedEntities_: RuntimeEntityData[] = [];
+ private pollTimer_: ReturnType<typeof setInterval> | null = null;
+ private detailTimer_: ReturnType<typeof setInterval> | null = null;
+ private stateListeners_ = new Set<StateChangeCallback>();
+ private entityListListeners_ = new Set<EntityListCallback>();
+ private selectionListeners_ = new Set<SelectionCallback>();
+
+ get state(): PlayState { return this.state_; }
+ get bridge(): GameViewBridge | null { return this.bridge_; }
+ get runtimeEntities(): RuntimeEntityData[] { return this.cachedEntities_; }
+ get selectedEntityId(): number | null { return this.selectedEntityId_; }
+
+ enter(bridge: GameViewBridge): void {
+ this.bridge_ = bridge;
+ this.state_ = 'playing';
+ this.cachedEntities_ = [];
+ this.selectedEntityId_ = null;
+ this.startPolling();
+ this.emitStateChange();
+ }
+
+ exit(): void {
+ this.stopPolling();
+ this.stopDetailPolling();
+ this.bridge_ = null;
+ this.state_ = 'stopped';
+ this.cachedEntities_ = [];
+ this.selectedEntityId_ = null;
+ this.emitStateChange();
+ this.emitSelectionChange();
+ }
+
+ selectEntity(id: number | null): void {
+ this.selectedEntityId_ = id;
+ this.emitSelectionChange();
+ if (id !== null) {
+ this.startDetailPolling();
+ } else {
+ this.stopDetailPolling();
+ }
+ }
+
+ onStateChange(cb: StateChangeCallback): () => void {
+ this.stateListeners_.add(cb);
+ return () => { this.stateListeners_.delete(cb); };
+ }
+
+ onEntityListUpdate(cb: EntityListCallback): () => void {
+ this.entityListListeners_.add(cb);
+ return () => { this.entityListListeners_.delete(cb); };
+ }
+
+ onSelectionChange(cb: SelectionCallback): () => void {
+ this.selectionListeners_.add(cb);
+ return () => { this.selectionListeners_.delete(cb); };
+ }
+
+ async refreshEntityList(): Promise<void> {
+ if (!this.bridge_?.isReady) return;
+ try {
+ this.cachedEntities_ = await this.bridge_.queryEntityList();
+ this.emitEntityListUpdate();
+ } catch {}
+ }
+
+ async querySelectedEntity(): Promise<RuntimeEntityData | null> {
+ if (this.selectedEntityId_ === null || !this.bridge_?.isReady) return null;
+ try {
+ return await this.bridge_.queryEntity(this.selectedEntityId_);
+ } catch { return null; }
+ }
+
+ private startPolling(): void {
+ this.stopPolling();
+ this.refreshEntityList();
+ this.pollTimer_ = setInterval(() => this.refreshEntityList(), 1000);
+ }
+
+ private stopPolling(): void {
+ if (this.pollTimer_) {
+ clearInterval(this.pollTimer_);
+ this.pollTimer_ = null;
+ }
+ }
+
+ private startDetailPolling(): void {
+ this.stopDetailPolling();
+ this.detailTimer_ = setInterval(() => {
+ this.emitSelectionChange();
+ }, 500);
+ }
+
+ private stopDetailPolling(): void {
+ if (this.detailTimer_) {
+ clearInterval(this.detailTimer_);
+ this.detailTimer_ = null;
+ }
+ }
+
+ private emitStateChange(): void {
+ for (const cb of this.stateListeners_) cb(this.state_);
+ }
+
+ private emitEntityListUpdate(): void {
+ for (const cb of this.entityListListeners_) cb(this.cachedEntities_);
+ }
+
+ private emitSelectionChange(): void {
+ for (const cb of this.selectionListeners_) cb(this.selectedEntityId_);
+ }
+}
+
+let instance: PlayModeService | null = null;
+
+export function getPlayModeService(): PlayModeService {
+ if (!instance) instance = new PlayModeService();
+ return instance;
+}
diff --git a/editor/src/styles/game-view.css b/editor/src/styles/game-view.css
index ae7e33cf4..618a52e1a 100644
--- a/editor/src/styles/game-view.css
+++ b/editor/src/styles/game-view.css
@@ -100,12 +100,9 @@
.es-gameview-viewport {
flex: 1;
- position: relative;
overflow: hidden;
background: #1a1a1a;
display: flex;
- align-items: center;
- justify-content: center;
}
.es-gameview-iframe {
@@ -124,3 +121,64 @@
font-size: 14px;
user-select: none;
}
+
+/* Speed select */
+.es-gameview-speed {
+ background: var(--es-input-bg);
+ color: var(--es-text-primary);
+ border: 1px solid var(--es-border);
+ border-radius: 3px;
+ font-size: 11px;
+ padding: 2px 4px;
+ height: 22px;
+ outline: none;
+}
+
+.es-gameview-speed:focus {
+ border-color: var(--es-accent);
+}
+
+/* Runtime property editors (used by InspectorPanel in play mode) */
+.es-runtime-input {
+ width: 100%;
+ height: 20px;
+ padding: 1px 4px;
+ font-size: 11px;
+}
+
+.es-runtime-vec-field {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ margin-right: 4px;
+}
+
+.es-runtime-vec-label {
+ font-size: 10px;
+ color: var(--es-text-secondary);
+ text-transform: uppercase;
+ min-width: 8px;
+}
+
+.es-runtime-vec-input {
+ width: 52px;
+ height: 20px;
+ padding: 1px 3px;
+ font-size: 11px;
+}
+
+.es-runtime-readonly {
+ font-size: 11px;
+ color: var(--es-text-secondary);
+ word-break: break-all;
+}
+
+/* Viewport layout */
+.es-gameview-canvas-area {
+ flex: 1;
+ position: relative;
+ overflow: hidden;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
diff --git a/editor/src/styles/hierarchy.css b/editor/src/styles/hierarchy.css
index b7e441576..098c7c1cc 100644
--- a/editor/src/styles/hierarchy.css
+++ b/editor/src/styles/hierarchy.css
@@ -296,6 +296,31 @@
border-left: 2px solid var(--es-drag);
}
+/* Play mode indicator */
+.es-hierarchy-panel.es-play-mode {
+ border-top: 2px solid #4a9eff;
+}
+
+.es-hierarchy-panel.es-play-mode .es-hierarchy-toolbar::after {
+ content: 'RUNTIME';
+ font-size: 9px;
+ font-weight: 600;
+ color: #4a9eff;
+ padding: 1px 5px;
+ border-radius: 2px;
+ background: rgba(74, 158, 255, 0.12);
+ margin-left: auto;
+}
+
+.es-hierarchy-panel.es-play-mode .es-hierarchy-item.es-selected > .es-hierarchy-row {
+ background: rgba(74, 158, 255, 0.3);
+ border-left-color: #4a9eff;
+}
+
+.es-hierarchy-panel.es-play-mode .es-hierarchy-item.es-selected > .es-hierarchy-row .es-hierarchy-name {
+ color: #4a9eff;
+}
+
.es-hierarchy-footer {
padding: 6px 12px;
font-size: 11px;
diff --git a/editor/src/styles/inspector.css b/editor/src/styles/inspector.css
index 115f05e3f..9d59cad6f 100644
--- a/editor/src/styles/inspector.css
+++ b/editor/src/styles/inspector.css
@@ -1146,3 +1146,19 @@
.es-property-row-top {
align-items: flex-start;
}
+
+/* Play mode indicator */
+.es-inspector-panel.es-play-mode {
+ border-top: 2px solid #4a9eff;
+}
+
+.es-inspector-panel.es-play-mode .es-inspector-toolbar::after {
+ content: 'RUNTIME';
+ font-size: 9px;
+ font-weight: 600;
+ color: #4a9eff;
+ padding: 1px 5px;
+ border-radius: 2px;
+ background: rgba(74, 158, 255, 0.12);
+ margin-left: auto;
+}
diff --git a/sdk/src/world.ts b/sdk/src/world.ts
index e7993e6c2..53295b208 100644
--- a/sdk/src/world.ts
+++ b/sdk/src/world.ts
@@ -4,7 +4,7 @@
*/
import { Entity } from './types';
-import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent } from './component';
+import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getComponent } from './component';
import type { CppRegistry } from './wasm';
import { validateComponentData, formatValidationErrors } from './validation';
import { handleWasmError } from './wasmError';
@@ -401,6 +401,58 @@ export class World {
this.queryCache_.clear();
}
+ getComponentTypes(entity: Entity): string[] {
+ const types: string[] = [];
+ for (const [name, methods] of this.builtinMethodCache_) {
+ try { if (methods.has(entity)) types.push(name); } catch {}
+ }
+ if (this.cppRegistry_) {
+ const knownBuiltins = [
+ 'LocalTransform', 'GlobalTransform', 'Sprite', 'Camera', 'Text',
+ 'Velocity', 'Parent', 'Children', 'BitmapText', 'SpineAnimation',
+ 'Canvas', 'UIRect', 'Interaction', 'Mask', 'LayoutGroup', 'LayoutElement',
+ 'TextInput', 'RigidBody', 'BoxCollider', 'CircleCollider', 'CapsuleCollider',
+ ];
+ for (const name of knownBuiltins) {
+ if (types.includes(name)) continue;
+ const comp = getComponent(name);
+ if (comp && isBuiltinComponent(comp)) {
+ try {
+ const m = this.getBuiltinMethods(comp._cppName);
+ if (m.has(entity)) types.push(name);
+ } catch {}
+ }
+ }
+ }
+ const ids = this.entityComponents_.get(entity);
+ if (ids) {
+ for (const id of ids) {
+ for (const [, storage] of this.tsStorage_) {
+ if (storage.has(entity) && storage === this.tsStorage_.get(id)) {
+ for (const [name, def] of this.findScriptName(id)) {
+ if (!types.includes(name)) types.push(name);
+ }
+ }
+ }
+ }
+ }
+ return types;
+ }
+
+ private findScriptName(id: symbol): [string, ComponentDef<any>][] {
+ const results: [string, ComponentDef<any>][] = [];
+ if (typeof window !== 'undefined' && (window as any).__esengine_componentRegistry) {
+ const registry = (window as any).__esengine_componentRegistry as Map<string, ComponentDef<any>>;
+ for (const [name, def] of registry) {
+ if (def._id === id) {
+ results.push([name, def]);
+ break;
+ }
+ }
+ }
+ return results;
+ }
+
getEntitiesWithComponents(
components: AnyComponentDef[],
withFilters: AnyComponentDef[] = [],