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.

chore: sync SDK build artifacts

esengine84dde2756de0
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index 7449c5d59..2f67fc6a0 100644
--- a/desktop/public/sdk/cjs/esengine.wechat.js
+++ b/desktop/public/sdk/cjs/esengine.wechat.js
@@ -1,2 +1,2 @@
-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function s(e,s){return t().fetch(e,s)}async function n(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function l(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const d=[{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}],u={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"},h=new Map,p=new Set;for(const e of d)for(const t of e.extensions)h.set(t,e),p.add(t);function f(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function g(e){return h.get(f(e))}function m(e){return p.has(e.toLowerCase())}function y(){const e=[];for(const t of d)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function x(e){const t=g(e);return t?.wechatPackInclude??!1}let _=null;function w(){return _||(_=wx.getFileSystemManager()),_}function v(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(x(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return s.includes("no such file")||s.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function b(e){return new Promise((t,s)=>{w().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(v(e,t.errMsg)))}})})}function S(e,t="utf-8"){return new Promise((s,n)=>{w().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(v(e,t.errMsg)))}})})}function P(e){return new Promise(t=>{w().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function T(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function M(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let E=!1;const C=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return b(e)}async readTextFile(e){return S(e)}async fileExists(e){return P(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},A=1920,R=1080,I={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const F=4294967295,B=4294967295;function D(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(D);const t={};for(const s in e)t[s]=D(e[s]);return t}let k=0;function L(e,t){const s=++k;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...D(t),...e}:D(t)}}function W(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function U(e,t){const s=W(),n=s.get(e);if(n)return n;const r=L(e,t);return s.set(e,r),O(e,t,!1),r}function $(e){const t=W(),s=t.get(e);if(s)return s;const n=L(e,{});return t.set(e,n),O(e,{},!0),n}function z(e){return W().get(e)}function O(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function H(e){return!0===e._builtin}const j=new Map;function X(e,t){j.set(e,t)}function N(e){return j.get(e)??z(e)}function V(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return j.set(e,s),s}const Y={Perspective:0,Orthographic:1},G={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},q={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},J=V("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),K=V("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Q=V("Sprite",{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Z=V("Camera",{projectionType:Y.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:G.ColorAndDepth}),ee=V("Canvas",{designResolution:{x:A,y:R},pixelsPerUnit:100,scaleMode:q.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),te=V("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=V("Parent",{entity:0}),ne=V("Children",{entities:[]}),re=V("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B,enabled:!0}),oe=V("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ae=U("SceneOwner",{scene:"",persistent:!1});X("Name",ie);const le=V("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ce=V("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),de=V("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ue=V("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),he={Static:0,Kinematic:1,Dynamic:2};let pe=0;function fe(e,t){const s=++pe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ge(e){return{_type:"res",_resource:e}}function me(e){return{_type:"res_mut",_resource:e}}class ye{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 xe{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 ye(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const _e=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>we(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,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let d=null;this.world_.beginIteration();try{for(const u of n){if(null!==d&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(d,t.component,t.data)}if(i){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(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];d=u}yield a}}finally{if(this.world_.endIteration(),null!==d&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(d,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}}class be{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=H(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 Se{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new be(this,null);return this.spawned_.push(e),e}entity(e){return new be(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 Pe;exports.Schedule=void 0,(Pe=exports.Schedule||(exports.Schedule={}))[Pe.Startup=0]="Startup",Pe[Pe.First=1]="First",Pe[Pe.PreUpdate=2]="PreUpdate",Pe[Pe.Update=3]="Update",Pe[Pe.PostUpdate=4]="PostUpdate",Pe[Pe.Last=5]="Last",Pe[Pe.FixedPreUpdate=10]="FixedPreUpdate",Pe[Pe.FixedUpdate=11]="FixedUpdate",Pe[Pe.FixedPostUpdate=12]="FixedPostUpdate";let Te=0;function Me(e,t,s){const n=++Te;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Ee(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Ce{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 Se&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ae{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 Re=fe(new Ae,"Input");class Ie{constructor(e){this.target_=e??null}build(e){const s=new Ae;e.insertResource(Re,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,Me([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Fe=new Ie;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=De(t[e]),o=De(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function De(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ke(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 We(e){Le=e}function Ue(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Le&&Le(e,t)}function $e(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}:$e(e)}}return t}class ze{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 Ue(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){Ue(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){Ue(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ue(t,`removeParent(entity=${e})`)}}insert(e,t,s){return H(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return H(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return H(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(H(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Ue(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.");H(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(ke(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,$e(r))}catch(s){Ue(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 Ue(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 Ue(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ue(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(ke(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.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_)for(const[s,n]of j)if(H(n)&&!t.includes(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.push(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const n of s)for(const[s,r]of e)if(r._id===n){t.push(s);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 o=null,i=1/0;for(const t of e)if(!H(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<i&&(i=s,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=o?o.keys():this.entities_;for(const t of l){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 Oe=fe({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 He;function je(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(He=exports.BlendMode||(exports.BlendMode={}))[He.Normal=0]="Normal",He[He.Additive=1]="Additive",He[He.Multiply=2]="Multiply",He[He.Screen=3]="Screen",He[He.PremultipliedAlpha=4]="PremultipliedAlpha";let Xe=null,Ne=null,Ve=1;const Ye=new Map;function Ge(e){Xe=e,Ne=e.getResourceManager(),rt()}function qe(){0!==Ze&&Xe&&(Xe._free(Ze),Ze=0),Ye.clear(),Ve=1,Qe=!1,tt.clear(),st=null,Ne=null,Xe=null}function Je(){if(!Ne)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ne}const Ke={createShader:(e,t)=>Je().createShader(e,t),releaseShader(e){e>0&&Je().releaseShader(e)},create(e){const t=Ve++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Ye.set(t,s),t},get:e=>Ye.get(e),setUniform(e,t,s){const n=Ye.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ye.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ye.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ye.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ye.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ye.get(e);return t?.shader??0},release(e){Ye.delete(e)},isValid:e=>Ye.has(e),releaseAll(){Ye.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??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ye.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Ve++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ye.set(s,n),s},toAssetData(e,t){const s=Ye.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=Ye.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Qe=!1,Ze=0;const et=4096,tt=new Map;let st=null;function nt(e){const t=(0===Ze&&Xe&&(Ze=Xe._malloc(et)),Ze);if(0===t||!Xe)return{ptr:0,count:0};let s=0,n=0;const r=Xe.HEAPU8,o=Xe.HEAPU32,i=Xe.HEAPF32;for(const[a,l]of e){if(s+128>et)break;let e=tt.get(a);e||(st||(st=new TextEncoder),e=st.encode(a),tt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=d;let u=0,h=[0,0,0,0];if("number"==typeof l)u=0,h[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(u=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,h=[l.x,l.y,l.z,0]):"y"in l&&(u=1,h=[l.x,l.y,0,0]);o[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function rt(){if(!Xe||Qe)return;Xe.materialDataProvider=(e,t,s,n,r)=>{const o=Ye.get(e);if(!o)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]=o.shader,Xe.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=nt(o.uniforms);Xe.HEAPU32[n>>2]=i,Xe.HEAPU32[r>>2]=a},Qe=!0}const ot={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class it{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class at{constructor(e,t=""){this.cache_=new it,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&&(Ke.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ke.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await r(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:Ke.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const lt=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}]]);function ct(e){return lt.get(e)?.fields??[]}function dt(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,ie,{value:n.name}),!1!==n.visible)for(const s of n.components)ht(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 ut(e,t,s){const n=new Map,r=s?.assetServer,o=s?.assetBaseUrl,i=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=lt.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}`;l.has(t)||(l.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":o.add(t);break;case"font":i.add(t)}}}const c=new Map,d=new Map,u=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const n=await t.loadMaterial(e,s);d.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),d.set(e,0)}})());for(const e of i)h.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)h.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(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=lt.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]=c.get(t)??0;break;case"material":s[e.field]=d.get(t)??0;break;case"font":s[e.field]=u.get(t)??0}}}}(t,r,o,i);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ie,{value:s.name}),!1!==s.visible)for(const n of s.components)ht(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=i.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function ht(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=N(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}class pt{constructor(e){this.textureCache_=new it,this.shaderCache_=new it,this.jsonCache_=new it,this.textCache_=new it,this.binaryCache_=new it,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new it,this.prefabCache_=new it,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_=i(I.textCanvasSize,I.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 at(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Ke.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),d="binary"===g(e)?.contentType,u=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,d);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=g(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return ut(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}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 r(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.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 ft=fe(null,"Assets");class gt{build(e){const t=e.wasmModule;t?e.insertResource(ft,new pt(t)):console.warn("AssetPlugin: No WASM module available")}}const mt=new gt;async function yt(e,t,s){const{entities:n,rootId:r}=await _t(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await ut(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const xt=10;async function _t(e,t,s,n,r,o=0){if(o>xt)throw new Error(`Prefab nesting depth exceeded ${xt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){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 _t(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),l.push(...t.entities);continue}const c=i.get(n.prefabEntityId),d=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:d?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};wt(u,t),l.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function wt(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 yt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const bt=fe(null,"Prefabs");class St{constructor(){this.name="PrefabsPlugin",this.dependencies=[ft]}build(e){const t=e.getResource(ft);e.insertResource(bt,new vt(e.world,t))}}const Pt=new St;let Tt=null,Mt=0,Et=0,Ct=0;const At=new Float32Array(256);function Rt(e){Tt=e,Mt=Tt._malloc(64),Et=Tt._malloc(64),Ct=Tt._malloc(1024)}function It(){Tt&&(Mt&&(Tt._free(Mt),Mt=0),Et&&(Tt._free(Et),Et=0),Ct&&(Tt._free(Ct),Ct=0)),Tt=null}function Ft(){if(!Tt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Tt}const Bt={r:1,g:1,b:1,a:1},Dt={begin(e){const t=Ft();try{t.HEAPF32.set(e,Mt/4),t.draw_begin(Mt)}catch(e){Ue(e,"Draw.begin")}},end(){try{Ft().draw_end()}catch(e){Ue(e,"Draw.end")}},line(e,t,s,n=1){try{Ft().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.line")}},rect(e,t,s,n=!0){try{Ft().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Ft().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{Ft().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ue(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{Ft().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ue(e,"Draw.circleOutline")}},texture(e,t,s,n=Bt){try{Ft().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ue(e,"Draw.texture")}},textureRotated(e,t,s,n,r=Bt){try{Ft().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Ue(e,"Draw.textureRotated")}},setLayer(e){Ft().draw_setLayer(e)},setDepth(e){Ft().draw_setDepth(e)},getDrawCallCount:()=>Tt?Tt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Tt?Tt.draw_getPrimitiveCount():0,setBlendMode(e){Ft().draw_setBlendMode(e)},setDepthTest(e){Ft().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Ft();n.HEAPF32.set(s,Et/4),n.draw_mesh(e,t,Et)}catch(s){Ue(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Ft(),r=Ke.get(t);if(!r)return;if(Dt.setBlendMode(r.blendMode),Dt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Dt.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,Et/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Wt(t);if(!(n<0)){if(je(s))At[o++]=10,At[o++]=n,At[o++]=s.slot??e++,At[o++]=s.textureId;else if("number"==typeof s)At[o++]=1,At[o++]=n,At[o++]=s;else if(Array.isArray(s)){At[o++]=s.length,At[o++]=n;for(let e=0;e<s.length;e++)At[o++]=s[e]}else"w"in s?(At[o++]=4,At[o++]=n,At[o++]=s.x,At[o++]=s.y,At[o++]=s.z,At[o++]=s.w):"z"in s?(At[o++]=3,At[o++]=n,At[o++]=s.x,At[o++]=s.y,At[o++]=s.z):(At[o++]=2,At[o++]=n,At[o++]=s.x,At[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(At.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,Et);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Ct/4),n.draw_meshWithUniforms(e,r.shader,Et,Ct,o)}catch(s){Ue(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},kt={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},Lt=new Set;function Wt(e){const t=kt[e];return void 0!==t?t:(Lt.has(e)||(Lt.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(kt).join(", ")}`)),-1)}const Ut=new Map;function $t(e,t,s){Ut.set(e,{fn:t,scene:s??""})}function zt(e){Ut.delete(e)}function Ot(){Ut.clear()}var Ht;exports.DataType=void 0,(Ht=exports.DataType||(exports.DataType={}))[Ht.Float=1]="Float",Ht[Ht.Float2=2]="Float2",Ht[Ht.Float3=3]="Float3",Ht[Ht.Float4=4]="Float4",Ht[Ht.Int=5]="Int",Ht[Ht.Int2=6]="Int2",Ht[Ht.Int3=7]="Int3",Ht[Ht.Int4=8]="Int4";let jt=null,Xt=0,Nt=0,Vt=0;function Yt(e){jt=e,Xt=jt._malloc(262144),Nt=jt._malloc(65536),Vt=jt._malloc(256)}function Gt(){jt&&(Xt&&jt._free(Xt),Nt&&jt._free(Nt),Vt&&jt._free(Vt),Xt=0,Nt=0,Vt=0),jt=null}function qt(){if(!jt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return jt}const Jt={create(e){const t=qt(),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,Xt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Vt,r).set(o),t.geometry_init(s,Xt,n,Vt,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,Nt,n).set(e.indices),t.geometry_setIndices16(s,Nt,n)}else{new Uint32Array(t.HEAPU8.buffer,Nt,n).set(e.indices),t.geometry_setIndices32(s,Nt,n)}}return s},updateVertices(e,t,s=0){const n=qt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Xt/4),n.geometry_updateVertices(e,Xt,r,s)},release(e){e>0&&qt().geometry_release(e)},isValid:e=>!(!jt||e<=0)&&jt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Jt.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Jt.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Jt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let Kt=null;function Qt(e){Kt=e}function Zt(){Kt&&ts.isInitialized()&&ts.shutdown(),Kt=null}function es(){if(!Kt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Kt}const ts={init(e,t){try{return es().postprocess_init(e,t)}catch(s){return Ue(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{es().postprocess_shutdown()}catch(e){Ue(e,"PostProcess.shutdown")}},resize(e,t){try{es().postprocess_resize(e,t)}catch(s){Ue(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return es().postprocess_addPass(e,t)}catch(t){return Ue(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{es().postprocess_removePass(e)}catch(t){Ue(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{es().postprocess_setPassEnabled(e,t)}catch(t){Ue(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return es().postprocess_isPassEnabled(e)}catch(t){return Ue(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{es().postprocess_setUniformFloat(e,t,s)}catch(s){Ue(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{es().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Ue(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{es().postprocess_begin()}catch(e){Ue(e,"PostProcess.begin")}},end(){try{es().postprocess_end()}catch(e){Ue(e,"PostProcess.end")}},getPassCount(){try{return es().postprocess_getPassCount()}catch(e){return Ue(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Kt)return!1;try{return Kt.postprocess_isInitialized()}catch(e){return Ue(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{es().postprocess_setBypass(e)}catch(e){Ue(e,"PostProcess.setBypass")}},isBypassed(){if(!Kt)return!0;try{return Kt.postprocess_isBypassed()}catch(e){return Ue(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ke.createShader(ss,"#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:()=>Ke.createShader(ss,"#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:()=>Ke.createShader(ss,"#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:()=>Ke.createShader(ss,"#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")},ss="#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 ns;exports.RenderStage=void 0,(ns=exports.RenderStage||(exports.RenderStage={}))[ns.Background=0]="Background",ns[ns.Opaque=1]="Opaque",ns[ns.Transparent=2]="Transparent",ns[ns.Overlay=3]="Overlay";let rs=null,os=0;function is(e){rs=e,os=rs._malloc(64)}function as(){rs&&os&&(rs._free(os),os=0),rs=null}const ls={init(e,t){rs?.renderer_init(e,t)},resize(e,t){rs?.renderer_resize(e,t)},begin(e,t){if(rs&&os)try{rs.HEAPF32.set(e,os/4),rs.renderer_begin(os,t??0)}catch(e){Ue(e,"Renderer.begin")}},flush(){try{rs?.renderer_flush()}catch(e){Ue(e,"Renderer.flush")}},end(){try{rs?.renderer_end()}catch(e){Ue(e,"Renderer.end")}},submitSprites(e){if(rs)try{rs.renderer_submitSprites(e._cpp)}catch(e){Ue(e,"Renderer.submitSprites")}},submitBitmapText(e){if(rs)try{rs.renderer_submitBitmapText(e._cpp)}catch(e){Ue(e,"Renderer.submitBitmapText")}},submitSpine(e){if(rs)try{rs.renderer_submitSpine?.(e._cpp)}catch(e){Ue(e,"Renderer.submitSpine")}},setStage(e){rs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>rs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){rs?.renderer_releaseTarget(e)},getTargetTexture:e=>rs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>rs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){rs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){rs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){rs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){rs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>rs?rs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>rs?{drawCalls:rs.renderer_getDrawCalls(),triangles:rs.renderer_getTriangles(),sprites:rs.renderer_getSprites(),text:rs.renderer_getText(),spine:rs.renderer_getSpine?.()??0,meshes:rs.renderer_getMeshes(),culled:rs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let cs=null;function ds(e){cs=e}function us(){cs=null}const hs={enable(){cs?.gl_enableErrorCheck(!0)},disable(){cs?.gl_enableErrorCheck(!1)},check:e=>cs?.gl_checkErrors(e)??0,diagnose(){cs?.renderer_diagnose()}};class ps{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(ls.resize(n,r),ts.isInitialized()&&ts.getPassCount()>0&&ts.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),ls.setViewport(0,0,n,r),ls.clearBuffers(3),ls.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),ls.submitSprites(t),ls.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ls.submitSpine(t),ls.flush(),this.executeDrawCallbacks(s,o),ls.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;ls.setViewport(n.x,n.y,n.w,n.h),ls.setScissor(n.x,n.y,n.w,n.h,!0),ls.clearBuffers(r),ls.setScissor(0,0,0,0,!1),ls.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),ls.submitSprites(t),ls.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ls.submitSpine(t),ls.flush(),this.executeDrawCallbacks(s,o),ls.end()}executeDrawCallbacks(e,t){const s=Ut;if(s.size>0){Dt.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)}Dt.end();for(const e of n)zt(e)}}}const fs="__scene_transition_overlay__";class gs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class ms{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,ae,{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),$t(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=ts.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){ts.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,ae)){const s=this.app_.world.get(e,ae);s.persistent=t,this.app_.world.insert(e,ae,s)}}}class ys{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.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??I.sceneTransitionDuration,r=t.color??{...I.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},$t(fs,()=>{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;Dt.setLayer(9999),Dt.setDepth(9999),Dt.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,zt(fs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,zt(fs),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 gs(t);this.scenes_.set(e,s);const n=new ms(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):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(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await ut(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=_s(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 gs(t);this.scenes_.set(e,s);const n=new ms(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):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(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await ut(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=_s(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,ae)){if(this.app_.world.get(e,ae).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())zt(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{ts.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 o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,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,Q)){const s=this.app_.world.get(e,Q);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Q,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,Q)){const s=this.app_.world.get(e,Q),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Q,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{ts.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const xs=fe(null,"SceneManager");function _s(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(xs).getSceneStatus(t)&&s._fn(...n)}}}const ws=Me([me(xs),ge(_e)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),vs={name:"SceneManager",build(e){const t=new ys(e);e.insertResource(xs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(xs),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,ws)}};class bs{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=a(),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(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new ze,this.resources_=new xe;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new bs}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(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.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 We(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(xs).register(e),this}setInitialScene(e){return this.getResource(xs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ce(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Ot();const e=[us,as,Zt,Gt,qe,It];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,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}const Ss=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ps(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case q.FixedWidth:return o;case q.FixedHeight:return i;case q.Expand:return Math.max(o,i);case q.Shrink:return Math.min(o,i);case q.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Ts(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,ae);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*s/(i.h*n);let d,u=0,h=0;if(r.projectionType===Y.Orthographic){if(h=r.orthoSize,l){h=Ps(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}u=h*a,d=Es(-u,u,-h,h,-r.farPlane,r.farPlane)}else d=As(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=Is(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(Bs(d,p)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Ms=new Float32Array(16);function Es(e,t,s,n,r,o){const i=Ms;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const Cs=new Float32Array(16);function As(e,t,s,n){const r=Cs;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const Rs=new Float32Array(16);function Is(e,t,s){const n=Rs;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 Fs=new Float32Array(16);function Bs(e,t){const s=Fs;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 Ds,ks,Ls;exports.TextAlign=void 0,(Ds=exports.TextAlign||(exports.TextAlign={}))[Ds.Left=0]="Left",Ds[Ds.Center=1]="Center",Ds[Ds.Right=2]="Right",exports.TextVerticalAlign=void 0,(ks=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ks.Top=0]="Top",ks[ks.Middle=1]="Middle",ks[ks.Bottom=2]="Bottom",exports.TextOverflow=void 0,(Ls=exports.TextOverflow||(exports.TextOverflow={}))[Ls.Visible=0]="Visible",Ls[Ls.Clip=1]="Clip",Ls[Ls.Ellipsis=2]="Ellipsis";const Ws=U("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2}),Us=U("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 $s{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(I.textCanvasSize,I.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,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=r?Math.ceil(o):u+2*d,f=r?Math.ceil(i):h+2*d;if(r&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const g=Math.round(255*e.color.r),m=Math.round(255*e.color.g),y=Math.round(255*e.color.b),x=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${m}, ${y}, ${x})`,r&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const _=l.length*c;let w;if(r)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=d;break;case exports.TextVerticalAlign.Middle:w=(f-_)/2;break;case exports.TextVerticalAlign.Bottom:w=f-_-d;break;default:w=d}else w=d;let v=w;for(const t of l){let n;switch(e.align){case exports.TextAlign.Left:n=d;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-d;break;default:n=d}s.fillText(t,n,v),v+=c}r&&e.overflow===exports.TextOverflow.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),T=this.module._malloc(S.length);this.module.HEAPU8.set(S,T);const M=P.createTexture(p,f,T,S.length,1,!0);return this.module._free(T),{textureHandle:M,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const 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 exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function zs(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 Os(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 Hs{build(e){X("Text",Ws);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new $s(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Ws));for(const e of r.keys())n.valid(e)&&n.has(e,Ws)||r.delete(e);const e=n.getEntitiesWithComponents([Ws]);for(const t of e){const e=n.get(t,Ws),o=n.has(t,Us)?n.get(t,Us):null,i=r.get(t);if(i&&!Os(i,e,o))continue;n.has(t,Q)||n.insert(t,Q,{texture:F,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,o),l=n.get(t,Q);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,n.insert(t,Q,l),r.set(t,zs(e,o))}}))}}const js=new Hs,Xs=U("UIMask",{enabled:!0,mode:"scissor"});function Ns(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function Vs(e,t,s,n,r,o,i,a,l,c,d){const u=e-s*r,h=e+s*(1-r),p=t-n*o,f=t+n*(1-o);function g(e,t){const s=i[0]*e+i[4]*t+i[12],n=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/r)+.5)*c,l+(.5*(n/r)+.5)*d]}const[m,y]=g(u,p),[x,_]=g(h,f),w=Math.min(m,x),v=Math.max(m,x),b=Math.min(y,_),S=Math.max(y,_);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function Ys(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],d=e[7],u=e[8],h=e[9],p=e[10],f=e[11],g=e[12],m=e[13],y=e[14],x=e[15],_=n*l-r*a,w=n*c-o*a,v=n*d-i*a,b=r*c-o*l,S=r*d-i*l,P=o*d-i*c,T=u*m-h*g,M=u*y-p*g,E=u*x-f*g,C=h*y-p*m,A=h*x-f*m,R=p*x-f*y;let I=_*R-w*A+v*C+b*E-S*M+P*T;return 0===I||(I=1/I,s[0]=(l*R-c*A+d*C)*I,s[1]=(o*A-r*R-i*C)*I,s[2]=(m*P-y*S+x*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*E-a*R-d*M)*I,s[5]=(n*R-o*E+i*M)*I,s[6]=(y*v-g*P-x*w)*I,s[7]=(u*P-p*v+f*w)*I,s[8]=(a*A-l*E+d*T)*I,s[9]=(r*E-n*A-i*T)*I,s[10]=(g*S-m*v+x*_)*I,s[11]=(h*v-u*S-f*_)*I,s[12]=(l*M-a*C-c*T)*I,s[13]=(n*C-r*M+o*T)*I,s[14]=(m*w-g*b-y*_)*I,s[15]=(u*b-h*w+p*_)*I),s}function Gs(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],d=s[1]*a+s[5]*l+s[13],u=s[3]*a+s[7]*l+s[15];return{x:c/u,y:d/u}}function qs(e,t,s,n,r,o,i,a,l,c){const d=2*Math.atan2(l,c),u=Math.sin(-d),h=Math.cos(-d),p=e-s,f=t-n,g=p*h-f*u+s,m=p*u+f*h+n;return g>=s-r*i&&g<=s+r*(1-i)&&m>=n-o*a&&m<=n+o*(1-a)}function Js(e,t,s,n,r,o,i){if(!e.has(t,Us)||!e.has(t,K))return null;const a=e.get(t,Us),l=e.get(t,K),c=a.size.x*l.scale.x,d=a.size.y*l.scale.y;return Vs(l.position.x,l.position.y,c,d,a.pivot.x,a.pivot.y,s,n,r,o,i)}function Ks(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Xs]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,Xs);s.enabled&&(u.add(e),"stencil"===s.mode?(d.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,r,o,i,a,l,c){const d=[];for(const e of n){let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(r.has(e.entity)){if("scissor"===t.get(e.entity,Xs).mode){s=!1;break}}n=e.entity}s&&d.push(e)}function u(n,d){const h=e.getChildEntities(s,n);for(const s of h){let n=d;if(r.has(s)){if("scissor"===t.get(s,Xs).mode){const e=Js(t,s,o,i,a,l,c);e&&(n=Ns(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=Js(t,e,o,i,a,l,c);s&&u(e,s)}}(e,t,s,c,u,n,r,o,i,a),d.length>0&&function(e,t,s,n,r){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(r.has(e.entity)){s=!1;break}n=e.entity}s&&o.push(e)}let i=1;function a(t,n){e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,n),l(t,n)}function l(t,n){const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,n),l(t,n)}for(const e of o){a(e,i++)}}(e,t,s,d,h)}catch(t){e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Qs{build(e){if(X("UIMask",Xs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Ks(e.wasmModule,e.world))}}const Zs=new Qs,en=U("Interactable",{enabled:!0,blockRaycast:!0}),tn=U("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var sn;exports.ButtonState=void 0,(sn=exports.ButtonState||(exports.ButtonState={}))[sn.Normal=0]="Normal",sn[sn.Hovered=1]="Hovered",sn[sn.Pressed=2]="Pressed",sn[sn.Disabled=3]="Disabled";const nn=U("Button",{state:exports.ButtonState.Normal,transition:null,enabled:!0});class rn{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const on=fe(new rn,"UIEvents"),an=$("ScreenSpace");function ln(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,d=o.bottom+e.y*a,u=o.bottom+t.y*a;let h,p,f,g;if(e.x===t.x){const e=l+s.x,t=.5*r.x;h=e-t,f=e+t}else h=l+s.x,f=c+n.x;if(e.y===t.y){const e=d+s.y,t=.5*r.y;p=e-t,g=e+t}else p=d+s.y,g=u+n.y;return{centerX:.5*(h+f),centerY:.5*(p+g),width:f-h,height:g-p,rect:{left:h,bottom:p,right:f,top:g}}}function cn(e){return{anchorMinX:e.anchorMin.x,anchorMinY:e.anchorMin.y,anchorMaxX:e.anchorMax.x,anchorMaxY:e.anchorMax.y,offsetMinX:e.offsetMin.x,offsetMinY:e.offsetMin.y,offsetMaxX:e.offsetMax.x,offsetMaxY:e.offsetMax.y,sizeX:e.size.x,sizeY:e.size.y}}function dn(e,t){return e.anchorMinX!==t.anchorMin.x||e.anchorMinY!==t.anchorMin.y||e.anchorMaxX!==t.anchorMax.x||e.anchorMaxY!==t.anchorMax.y||e.offsetMinX!==t.offsetMin.x||e.offsetMinY!==t.offsetMin.y||e.offsetMaxX!==t.offsetMax.x||e.offsetMaxY!==t.offsetMax.y||e.sizeX!==t.size.x||e.sizeY!==t.size.y}function un(e,t){let s=t;for(;;){if(e.has(s,an))return s;if(!e.has(s,se))return null;const t=e.get(s,se);if(!e.valid(t.entity))return null;s=t.entity}}function hn(e,t,s,n,r,o){if(!e.has(t,Us))return;const i=e.get(t,Us),a=ln(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,J);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-n,l.position.y=a.centerY-r),e.insert(t,J,l),!e.has(t,ne))return;const c=e.get(t,ne);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&hn(e,t,a.rect,a.centerX,a.centerY,!1)}class pn{build(e){X("UIRect",Us);const t=e.world,s=new Map;let n=NaN,r=NaN,o=NaN,i=NaN;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Oe)],e=>{if(!e.valid)return;const a={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},l=.5*(a.left+a.right),c=.5*(a.bottom+a.top),d=n!==e.worldLeft||r!==e.worldBottom||o!==e.worldRight||i!==e.worldTop;n=e.worldLeft,r=e.worldBottom,o=e.worldRight,i=e.worldTop;const u=new Set;if(d){const e=t.getEntitiesWithComponents([an,Us,J]);for(const t of e)u.add(t)}const h=t.getEntitiesWithComponents([Us]);for(const e of h){const n=t.get(e,Us),r=s.get(e);if(!r||dn(r,n)){const s=un(t,e);null!==s&&u.add(s)}}for(const e of s.keys())if(!t.valid(e)||!t.has(e,Us)){s.delete(e);const n=un(t,e);null!==n&&u.add(n)}for(const e of u)hn(t,e,a,l,c,!0);for(const e of h){const n=t.get(e,Us);s.set(e,cn(n))}},{name:"UILayoutSystem"}))}}const fn=new pn,gn=new Float32Array(16),mn=new Float32Array(16);let yn=!0,xn=1;function _n(e,t,s,n){t.emit(s,n,s);let r=s;for(;e.has(r,se);){const o=e.get(r,se).entity;if(!e.valid(o))break;if(!e.has(o,en)){r=o;continue}const i=e.get(o,en);if(i.enabled&&t.emit(o,n,s),i.blockRaycast)break;r=o}}class wn{build(e){X("Interactable",en),X("Button",nn);const t=e.world,s=new rn;e.insertResource(on,s);let n=null,r=null;xn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re),ge(Oe)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([tn]);for(const e of i){const s=t.get(e,tn);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*xn,l=o.screenH-e.mouseY*xn;!function(e){let t=!1;for(let s=0;s<16;s++)if(mn[s]!==e[s]){t=!0;break}t&&(mn.set(e),yn=!0)}(o.viewProjection),yn&&(Ys(o.viewProjection,gn),yn=!1);const c=Gs(a,l,gn,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([en,Us,K]);let u=null,h=-1/0;for(const e of d){t.has(e,tn)||t.insert(e,tn);if(!t.get(e,en).enabled)continue;const s=t.get(e,K),n=t.get(e,Us),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(qs(c.x,c.y,s.position.x,s.position.y,r,o,n.pivot.x,n.pivot.y,s.rotation.z,s.rotation.w)){let s=0;t.has(e,Q)&&(s=t.get(e,Q).layer),s>=h&&(h=s,u=e)}}if(n!==u){if(null!==n&&t.valid(n)&&t.has(n,tn)){t.get(n,tn).hovered=!1,s.emit(n,"hover_exit")}if(null!==u){t.get(u,tn).hovered=!0,s.emit(u,"hover_enter")}n=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,tn);e.pressed=!0,e.justPressed=!0,r=u,_n(t,s,u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,tn)){const e=t.get(r,tn);e.pressed=!1,e.justReleased=!0,_n(t,s,r,"release"),r===n&&_n(t,s,r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,Me([],()=>{const e=t.getEntitiesWithComponents([nn]);for(const s of e){if(t.has(s,en)||t.insert(s,en,{enabled:!0}),!t.has(s,tn))continue;const e=t.get(s,tn),n=t.get(s,nn),r=t.get(s,en),o=n.state;if(r.enabled?e.pressed?n.state=exports.ButtonState.Pressed:e.hovered?n.state=exports.ButtonState.Hovered:n.state=exports.ButtonState.Normal:n.state=exports.ButtonState.Disabled,o!==n.state&&n.transition&&t.has(s,Q)){const e=t.get(s,Q),r=n.transition;switch(n.state){case exports.ButtonState.Normal:e.color={...r.normalColor};break;case exports.ButtonState.Hovered:e.color={...r.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...r.pressedColor};break;case exports.ButtonState.Disabled:e.color={...r.disabledColor}}t.insert(s,Q,e)}}},{name:"ButtonSystem"}))}}const vn=new wn,bn=U("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 Sn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){X("TextInput",bn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=i(I.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,d=0,u=0;const h=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(!h)return;const p=h,f=()=>{l||null===a||_()},g=()=>{l=!0},m=()=>{l=!1,_()},y=t=>{if(null===a)return;if("Escape"===t.key)return void v();const n=s.get(a,bn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(on).emit(a,"submit"),void v()}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,p.selectionStart=r,p.selectionEnd=r,n.dirty=!0,b())},x=()=>{if(null!==a&&s.valid(a)&&s.has(a,bn)){const e=s.get(a,bn);e.focused=!1,e.dirty=!0}a=null};function _(){if(null===a||!s.valid(a))return;const t=s.get(a,bn);if(t.readOnly)return;let n=p.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),p.value=n),n!==t.value){t.value=n;e.getResource(on).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,b()}function w(e){if(a===e)return;v();const t=s.get(e,bn);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),b())}function v(){if(null!==a&&s.valid(a)&&s.has(a,bn)){const e=s.get(a,bn);e.focused=!1,e.dirty=!0}a=null,p.blur()}function b(){c=!0,d=0}function S(e,i,a,l){(r.width<a||r.height<l)&&(r.width=Tn(Math.max(r.width,a)),r.height=Tn(Math.max(r.height,l))),o.clearRect(0,0,r.width,r.height);const d=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,o.fillRect(0,0,a,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const u=0===i.value.length,h=u?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=u?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=Pn(o,h,a-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,g,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=Pn(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,s=g+(e.length-1)*f,n=f}else t=g+o.measureText(e).width,s=(l-i.fontSize)/2,n=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,n)}o.restore();const m=o.getImageData(0,0,a,l),y=new Uint8Array(m.data.buffer),x=t.getResourceManager(),_=t._malloc(y.length);t.HEAPU8.set(y,_);const w=n.get(e);void 0!==w&&x.releaseTexture(w);const v=x.createTexture(a,l,_,y.length,1,!0);n.set(e,v),t._free(_);const b=s.get(e,Q);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,Q,b)}p.addEventListener("input",f),p.addEventListener("compositionstart",g),p.addEventListener("compositionend",m),p.addEventListener("keydown",y),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",f),p.removeEventListener("compositionstart",g),p.removeEventListener("compositionend",m),p.removeEventListener("keydown",y),p.removeEventListener("blur",x),p.remove()},e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(on)],e=>{const t=s.getEntitiesWithComponents([bn,en]);for(const e of t){if(!s.has(e,tn))continue;if(s.get(e,tn).justPressed)return void w(e)}if(null!==a){const e=s.getEntitiesWithComponents([en]);for(const t of e){if(s.has(t,bn))continue;if(!s.has(t,tn))continue;if(s.get(t,tn).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==a&&(d+=r,d>=.5&&(d-=.5,c=!c,null!==a&&s.valid(a)&&s.has(a,bn)))){s.get(a,bn).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,bn)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([bn,Us]);for(const e of i){const t=s.get(e,bn);if(!t.dirty)continue;const n=s.get(e,Us),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(s.has(e,Q)||s.insert(e,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Pn(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 o of t){const t=n+o;e.measureText(t).width>s&&n?(r.push(n),n=o):n=t}n&&r.push(n)}return r.length>0?r:[""]}function Tn(e){let t=1;for(;t<e;)t*=2;return t}const Mn=new Sn,En={Simple:0,Sliced:1,Tiled:2,Filled:3},Cn={Horizontal:0,Vertical:1},An={Left:0,Right:1,Bottom:2,Top:3},Rn=U("Image",{texture:F,color:{r:1,g:1,b:1,a:1},imageType:En.Simple,fillMethod:Cn.Horizontal,fillOrigin:An.Left,fillAmount:1,preserveAspect:!1,layer:0,material:0,enabled:!0});const In=new class{build(e){X("Image",Rn);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{const e=t.getEntitiesWithComponents([Rn]);for(const s of e){const e=t.get(s,Rn);t.has(s,Q)||t.insert(s,Q,{texture:F,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 n=t.get(s,Q);if(n.texture=e.texture,n.color.r=e.color.r,n.color.g=e.color.g,n.color.b=e.color.b,n.color.a=e.color.a,n.layer=e.layer,n.material=e.material,t.has(s,Us)){const e=t.get(s,Us);n.size.x=e.size.x,n.size.y=e.size.y}if(n.uvOffset.x=0,n.uvOffset.y=0,n.uvScale.x=1,n.uvScale.y=1,e.imageType===En.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));e.fillMethod===Cn.Horizontal?e.fillOrigin===An.Left?(n.uvScale.x=t,n.size.x*=t):(n.uvOffset.x=1-t,n.uvScale.x=t,n.size.x*=t):e.fillOrigin===An.Bottom?(n.uvScale.y=t,n.size.y*=t):(n.uvOffset.y=1-t,n.uvScale.y=t,n.size.y*=t)}t.insert(s,Q,n)}},{name:"ImageSystem"}))}},Fn=U("Toggle",{isOn:!0,graphicEntity:0,transition:null,enabled:!0});const Bn=new class{build(e){X("Toggle",Fn);const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,Me([ge(on)],e=>{const s=t.getEntitiesWithComponents([Fn]);for(const n of s){if(t.has(n,en)||t.insert(n,en,{enabled:!0}),!t.has(n,tn))continue;const s=t.get(n,tn),r=t.get(n,Fn),o=t.get(n,en);if(s.justPressed&&o.enabled&&(r.isOn=!r.isOn,e.emit(n,"change")),r.graphicEntity&&t.valid(r.graphicEntity)){const e=r.graphicEntity;if(t.has(e,Q)){const s=t.get(e,Q);s.color.a=r.isOn?1:0,t.insert(e,Q,s)}}if(r.transition&&t.has(n,Q)){const e=t.get(n,Q),i=r.transition;o.enabled?s.pressed?e.color={...i.pressedColor}:s.hovered?e.color={...i.hoveredColor}:e.color={...i.normalColor}:e.color={...i.disabledColor},t.insert(n,Q,e)}}},{name:"ToggleSystem"}))}};var Dn;exports.ProgressBarDirection=void 0,(Dn=exports.ProgressBarDirection||(exports.ProgressBarDirection={}))[Dn.LeftToRight=0]="LeftToRight",Dn[Dn.RightToLeft=1]="RightToLeft",Dn[Dn.BottomToTop=2]="BottomToTop",Dn[Dn.TopToBottom=3]="TopToBottom";const kn=U("ProgressBar",{value:0,fillEntity:0,direction:exports.ProgressBarDirection.LeftToRight});const Ln=new class{build(e){X("ProgressBar",kn);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{const e=t.getEntitiesWithComponents([kn,Us]);for(const s of e){const e=t.get(s,kn);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=e.fillEntity;if(!t.has(n,Us))continue;const r=t.get(n,Us),o=Math.max(0,Math.min(1,e.value));switch(e.direction){case exports.ProgressBarDirection.LeftToRight:r.anchorMin={x:0,y:0},r.anchorMax={x:o,y:1};break;case exports.ProgressBarDirection.RightToLeft:r.anchorMin={x:1-o,y:0},r.anchorMax={x:1,y:1};break;case exports.ProgressBarDirection.BottomToTop:r.anchorMin={x:0,y:0},r.anchorMax={x:1,y:o};break;case exports.ProgressBarDirection.TopToBottom:r.anchorMin={x:0,y:1-o},r.anchorMax={x:1,y:1}}r.offsetMin={x:0,y:0},r.offsetMax={x:0,y:0},t.insert(n,Us,r)}},{name:"ProgressBarSystem"}))}},Wn=U("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Un=U("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}}),$n=new Float32Array(16),zn=new Float32Array(16);let On=!0;function Hn(e,t,s){const n=e.mouseX*s,r=t.screenH-e.mouseY*s;return function(e){let t=!1;for(let s=0;s<16;s++)if(zn[s]!==e[s]){t=!0;break}t&&(zn.set(e),On=!0)}(t.viewProjection),On&&(Ys(t.viewProjection,$n),On=!1),Gs(n,r,$n,t.vpX,t.vpY,t.vpW,t.vpH)}const jn=new class{build(e){X("Draggable",Wn),X("DragState",Un);const t=e.world,s=e.getResource(on);let n=null,r={x:0,y:0},o=null;const i="undefined"!=typeof window&&window.devicePixelRatio||1;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re),ge(Oe)],(e,a)=>{if(!a.valid)return;const l=Hn(e,a,i);if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Wn,tn]);let s=null;for(const n of e){if(!t.get(n,Wn).enabled)continue;t.get(n,tn).hovered&&(s=n)}if(null!==s){n=s,r={x:l.x,y:l.y},t.has(s,Un)||t.insert(s,Un);const e=t.get(s,Un),o=t.get(s,K);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:l.x,y:l.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,Un)){t.get(n,Un).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=l.x-r.x,i=l.y-r.y,c=Math.sqrt(e*e+i*i),d=t.get(n,Wn);if(c*(a.vpW/(a.worldRight-a.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,Un).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Un))return void(o=null);const n=t.get(o,Un),r=t.get(o,Wn),i=l.x-n.pointerStartWorld.x,a=l.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+i,d=n.startWorldPos.y+a;const u=function(e,t,s,n){let r=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,n,c,d);c=u.x,d=u.y;const h=n.currentWorldPos.x,p=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:d-p},n.currentWorldPos={x:c,y:d},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:d-n.startWorldPos.y},t.has(o,J)){const e=function(e,t,s,n){if(!e.has(t,se))return{x:s,y:n};const r=e.get(t,se).entity;if(!e.valid(r)||!e.has(r,K))return{x:s,y:n};const o=e.get(r,K),i=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=2*Math.atan2(o.rotation.z,o.rotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(s*d-n*c)/i,y:(s*c+n*d)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,J);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,J,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Xn=U("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const Nn=new class{build(e){X("ScrollView",Xn);const t=e.world,s=new Map,n=new Float32Array(16),r="undefined"!=typeof window&&window.devicePixelRatio||1;let o=0;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re),ge(Oe)],(e,i)=>{const a=performance.now()/1e3,l=o>0?Math.min(a-o,.05):0;if(o=a,!i.valid)return;const c=e.mouseX*r,d=i.screenH-e.mouseY*r;Ys(i.viewProjection,n);const u=Gs(c,d,n,i.vpX,i.vpY,i.vpW,i.vpH),h=t.getEntitiesWithComponents([Xn,Us]);for(const n of h){t.has(n,en)||t.insert(n,en,{enabled:!0,blockRaycast:!0}),t.has(n,Xs)||t.insert(n,Xs,{enabled:!0,mode:"scissor"});const r=t.get(n,Xn),o=t.get(n,Us);let i=s.get(n);i||(i={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},s.set(n,i));const a=t.has(n,tn)?t.get(n,tn):null;if(a?.justPressed&&(i.isDragging=!0,i.lastWorldX=u.x,i.lastWorldY=u.y,i.velocityX=0,i.velocityY=0),i.isDragging&&e.isMouseButtonDown(0)){const e=u.x-i.lastWorldX,t=u.y-i.lastWorldY;r.horizontalEnabled&&(r.scrollX-=e,i.velocityX=l>0?-e/l:0),r.verticalEnabled&&(r.scrollY-=t,i.velocityY=l>0?-t/l:0),i.lastWorldX=u.x,i.lastWorldY=u.y}if(i.isDragging&&e.isMouseButtonReleased(0)&&(i.isDragging=!1),a?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,i.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,i.velocityX=0)}if(!i.isDragging&&r.inertia&&l>0){const e=Math.pow(r.decelerationRate,l);r.horizontalEnabled&&Math.abs(i.velocityX)>.1?(r.scrollX+=i.velocityX*l,i.velocityX*=e):i.velocityX=0,r.verticalEnabled&&Math.abs(i.velocityY)>.1?(r.scrollY+=i.velocityY*l,i.velocityY*=e):i.velocityY=0}const c=o.size.x,d=o.size.y,h=Math.max(0,r.contentWidth-c),p=Math.max(0,r.contentHeight-d);if(r.scrollX=Math.max(0,Math.min(r.scrollX,h)),r.scrollY=Math.max(0,Math.min(r.scrollY,p)),0!==r.contentEntity&&t.valid(r.contentEntity)){const e=r.contentEntity;if(t.has(e,J)){const s=t.get(e,J);s.position.x=-r.scrollX,s.position.y=r.scrollY,t.insert(e,J,s)}}}},{name:"ScrollViewSystem"}))}};var Vn;exports.SliderDirection=void 0,(Vn=exports.SliderDirection||(exports.SliderDirection={}))[Vn.LeftToRight=0]="LeftToRight",Vn[Vn.RightToLeft=1]="RightToLeft",Vn[Vn.BottomToTop=2]="BottomToTop",Vn[Vn.TopToBottom=3]="TopToBottom";const Yn=U("Slider",{value:0,minValue:0,maxValue:1,direction:exports.SliderDirection.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1,enabled:!0});const Gn=new class{build(e){X("Slider",Yn);const t=e.world,s=new Float32Array(16),n="undefined"!=typeof window&&window.devicePixelRatio||1;let r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re),ge(Oe)],(e,o)=>{if(!o.valid)return;const i=e.mouseX*n,a=o.screenH-e.mouseY*n;Ys(o.viewProjection,s);const l=Gs(i,a,s,o.vpX,o.vpY,o.vpW,o.vpH),c=t.getEntitiesWithComponents([Yn,Us,K]);for(const s of c){t.has(s,en)||t.insert(s,en,{enabled:!0,blockRaycast:!0});const n=t.get(s,Yn),o=t.get(s,Us),i=t.get(s,K),a=t.has(s,tn)?t.get(s,tn):null;if(a?.justPressed&&(r=s),r===s&&e.isMouseButtonDown(0)){const e=o.size.x*i.scale.x,t=o.size.y*i.scale.y,s=i.position.x-o.pivot.x*e,r=i.position.y-o.pivot.y*t;let a;switch(n.direction){case exports.SliderDirection.LeftToRight:a=e>0?(l.x-s)/e:0;break;case exports.SliderDirection.RightToLeft:a=e>0?1-(l.x-s)/e:0;break;case exports.SliderDirection.BottomToTop:a=t>0?(l.y-r)/t:0;break;case exports.SliderDirection.TopToBottom:a=t>0?1-(l.y-r)/t:0}a=Math.max(0,Math.min(1,a));let c=n.minValue+a*(n.maxValue-n.minValue);n.wholeNumbers&&(c=Math.round(c)),n.value=Math.max(n.minValue,Math.min(n.maxValue,c))}r===s&&e.isMouseButtonReleased(0)&&(r=null);const c=n.maxValue-n.minValue,d=c>0?(n.value-n.minValue)/c:0;if(0!==n.fillEntity&&t.valid(n.fillEntity)){const e=n.fillEntity;if(t.has(e,Us)){const s=t.get(e,Us);switch(n.direction){case exports.SliderDirection.LeftToRight:s.anchorMin={x:0,y:0},s.anchorMax={x:d,y:1};break;case exports.SliderDirection.RightToLeft:s.anchorMin={x:1-d,y:0},s.anchorMax={x:1,y:1};break;case exports.SliderDirection.BottomToTop:s.anchorMin={x:0,y:0},s.anchorMax={x:1,y:d};break;case exports.SliderDirection.TopToBottom:s.anchorMin={x:0,y:1-d},s.anchorMax={x:1,y:1}}t.insert(e,Us,s)}}if(0!==n.handleEntity&&t.valid(n.handleEntity)){const e=n.handleEntity;if(t.has(e,Us)){const s=t.get(e,Us);switch(n.direction){case exports.SliderDirection.LeftToRight:s.anchorMin={x:d,y:0},s.anchorMax={x:d,y:1};break;case exports.SliderDirection.RightToLeft:s.anchorMin={x:1-d,y:0},s.anchorMax={x:1-d,y:1};break;case exports.SliderDirection.BottomToTop:s.anchorMin={x:0,y:d},s.anchorMax={x:1,y:d};break;case exports.SliderDirection.TopToBottom:s.anchorMin={x:0,y:1-d},s.anchorMax={x:1,y:1-d}}t.insert(e,Us,s)}}}},{name:"SliderSystem"}))}},qn=U("Focusable",{tabIndex:0,isFocused:!1});class Jn{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Kn=fe(new Jn,"FocusManager");const Qn=new class{build(e){X("Focusable",qn);const t=e.world,s=new Jn;e.insertResource(Kn,s),e.addSystemToSchedule(exports.Schedule.Update,Me([ge(Re),ge(on)],(e,n)=>{const r=t.getEntitiesWithComponents([qn]);for(const e of r){if(!t.has(e,tn))continue;t.get(e,tn).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of r){const n=t.get(s,qn);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const i=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?n.length-1:0:a?(i-1+n.length)%n.length:(i+1)%n.length,o(n[l])}function o(e){const r=s.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,qn)){t.get(r,qn).isFocused=!1,n.emit(r,"hover_exit",r)}s.focus(e);t.get(e,qn).isFocused=!0,n.emit(e,"hover_enter",e)}},{name:"FocusSystem"}))}},Zn=U("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});const er=new class{build(e){X("SafeArea",Zn);const t=e.world;let s={top:0,bottom:0,left:0,right:0},n=0;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([],()=>{n++%60==0&&(s=function(){if("undefined"==typeof document)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}());const e=t.getEntitiesWithComponents([Zn,Us]);for(const n of e){const e=t.get(n,Zn),r=t.get(n,Us);let o=!1;const i=e.applyTop?s.top:0,a=e.applyBottom?s.bottom:0,l=e.applyLeft?s.left:0,c=e.applyRight?s.right:0;r.offsetMin.x===l&&r.offsetMin.y===a||(r.offsetMin={x:l,y:a},o=!0),r.offsetMax.x===-c&&r.offsetMax.y===-i||(r.offsetMax={x:-c,y:-i},o=!0),o&&t.insert(n,Us,r)}},{name:"SafeAreaSystem"}))}},tr=U("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2}),sr=new Map;const nr=new class{build(e){X("ListView",tr);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Me([ge(Re)],e=>{const s=t.getEntitiesWithComponents([tr,Us]);for(const n of s){t.has(n,en)||t.insert(n,en,{enabled:!0,blockRaycast:!0}),t.has(n,Xs)||t.insert(n,Xs,{enabled:!0,mode:"scissor"});let s=sr.get(n);s||(s={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},sr.set(n,s));const r=t.get(n,tr),o=t.get(n,Us),i=o.size.y,a=t.has(n,tn)?t.get(n,tn):null;if(a?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}const l=Math.max(0,r.itemCount*r.itemHeight-i);r.scrollY=Math.max(0,Math.min(r.scrollY,l));const c=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+i)/r.itemHeight)+r.overscan);for(const[e,n]of s.itemEntities)(e<c||e>=d)&&(t.valid(n)&&t.despawn(n),s.itemEntities.delete(e));for(let e=c;e<d;e++){let i=s.itemEntities.get(e);if(i&&t.valid(i)||(i=t.spawn(),t.insert(i,ie,{value:`ListItem_${e}`}),t.insert(i,Us,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o.size.x,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(i,n),s.itemEntities.set(e,i),s.renderer&&s.renderer(e,i)),t.has(i,J)){const s=t.get(i,J);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(i,J,s)}}s.visibleStart=c,s.visibleEnd=d}},{name:"ListViewSystem"}))}},rr=U("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const or=new class{build(e){X("Dropdown",rr);const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,Me([ge(Re),ge(on)],(e,s)=>{const n=t.getEntitiesWithComponents([rr]);for(const o of n){t.has(o,en)||t.insert(o,en,{enabled:!0,blockRaycast:!0});const n=t.get(o,rr),i=t.has(o,tn)?t.get(o,tn):null;if(i?.justPressed&&(n.isOpen=!n.isOpen,r(n.listEntity,n.isOpen),s.emit(o,"change",o)),n.isOpen&&e.isMouseButtonPressed(0)&&!i?.hovered){0!==n.listEntity&&t.valid(n.listEntity)&&t.has(n.listEntity,tn)&&t.get(n.listEntity,tn).hovered||(n.isOpen=!1,r(n.listEntity,!1))}}function r(e,s){if(0===e)return;const n=e;if(!t.valid(n)||!t.has(n,J))return;const r=t.get(n,J),o=s?1:0;r.scale={x:o,y:o,z:o},t.insert(n,J,r)}},{name:"DropdownSystem"}))}};async function ir(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const ar=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),lr=fe(null,"PhysicsAPI");function cr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function dr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ur{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(ar,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=ir(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([ee]);for(const s of t){const t=e.world.get(s,ee);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Me([ge(_e)],a=>{const l=i.getEntitiesWithComponents([le,J,K]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,le),l=i.get(r,K);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=cr(l.rotation);n._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),hr(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===he.Kinematic){const e=cr(l.rotation);n._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const d=e.world.get(i,J);if(!d)continue;let u=a,h=l,p=c;if(e.world.has(i,se)){const t=e.world.get(i,se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,K)){const s=e.world.get(t.entity,K),n=cr(s.rotation),r=a-s.position.x,o=l-s.position.y,i=Math.cos(-n),d=Math.sin(-n);u=(r*i-o*d)/(0!==s.scale.x?s.scale.x:1),h=(r*d+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-n}}d.position.x=u,d.position.y=h;const f=dr(p);d.rotation.w=f.w,d.rotation.x=f.x,d.rotation.y=f.y,d.rotation.z=f.z,e.world.insert(i,J,d)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<d;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(ar,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(lr,pr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function hr(e,t,s){const n=e.world;if(n.has(s,ce)){const e=n.get(s,ce);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,de)){const e=n.get(s,de);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,ue)){const e=n.get(s,ue);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 pr{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(pr.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 fr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),o}function gr(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 mr(e,t,s,n){const r=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,d=e.rotation.w,u=a+a,h=l+l,p=c+c,f=a*u,g=a*h,m=a*p,y=l*h,x=l*p,_=c*p,w=d*u,v=d*h,b=d*p;return new Float32Array([(1-(y+_))*r,(g+b)*r,(m-v)*r,0,(g-b)*o,(1-(f+_))*o,(x+w)*o,0,(m+v)*i,(x-w)*i,(1-(f+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function yr(e,t,s,n,r,o,i,a,l){const c=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]=fr(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,c);let d={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),d=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const n=await r.readText(a),d="binary"===g(l)?.contentType;let u,h;if(d){const e=await r.readBinary(i);h=e.length,u=t._malloc(h),t.HEAPU8.set(e,u)}else{const e=await r.readText(i),s=(new TextEncoder).encode(e);h=s.length,u=t._malloc(h+1),t.HEAPU8.set(s,u),t.HEAPU8[u+h]=0}const p=s.loadSkeleton(u,h,n,n.length,d);if(t._free(u),p<0)continue;o[i]=p;const f=gr(n),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=fr(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){new ur("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){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,o;const i=g(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=fr(e,c,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,d,c.width,c.height)}catch{n[r]=0}}return n}(t,s,n),p=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 o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Ke.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=Ke.createFromAsset(e,i)}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=ct(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,c,h,p);const f=dt(e.world,s);if(l&&e.hasResource(xs))for(const t of f.values())e.world.insert(t,ae,{scene:l,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=n.get(o.id);void 0!==l&&(r[l]=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,d,f);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,oe)?c.get(o,oe):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&n.update(i,l*u);let h=0;if(c.has(o,K)){const e=mr(c.get(o,K),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),d=s._malloc(l),u=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,d,u,p);const f=s.HEAPU32[u>>2],g=s.HEAPU32[p>>2],m=new Float32Array(s.HEAPF32.buffer,c,8*r),y=new Uint16Array(s.HEAPU8.buffer,d,o),x=t._malloc(a),_=t._malloc(l);t.HEAPF32.set(m,x>>2),new Uint16Array(t.HEAPU8.buffer,_,o).set(y),t.renderer_submitTriangles(x,r,_,o,f,g,h),t._free(x),t._free(_),s._free(c),s._free(d),s._free(u),s._free(p)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource(ft);t&&t.setAddressableManifest(a)}}class xr{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"===g(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 o=[];for(const e of n){const t=g(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const _r="__preview__";const wr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=ls.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:ls.getTargetTexture(s),width:e.width,height:e.height}},release(e){ls.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(ls.releaseRenderTarget(e._handle),wr.create({width:t,height:s,depth:!0})),begin(e,t){ls.begin(t,e._handle)},end(){ls.end()},getDepthTexture:e=>ls.getTargetDepthTexture(e._handle)};let vr=!1;var br;exports.LogLevel=void 0,(br=exports.LogLevel||(exports.LogLevel={}))[br.Debug=0]="Debug",br[br.Info=1]="Info",br[br.Warn=2]="Warn",br[br.Error=3]="Error";class Sr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,s);break;case exports.LogLevel.Info:console.log(t,s);break;case exports.LogLevel.Warn:console.warn(t,s);break;case exports.LogLevel.Error:console.error(t,s)}}}class Pr{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Sr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Tr=new Pr;const Mr=[js,Zs,fn,In,Ln,vn,jn,Nn,Gn,Bn,Mn,Qn,er,nr,or];E||(E=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await l(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=C,exports.App=bs,exports.AssetPlugin=gt,exports.AssetRefCounter=class{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}},exports.AssetServer=pt,exports.Assets=ft,exports.AsyncCache=it,exports.BitmapText=re,exports.BodyType=he,exports.BoxCollider=ce,exports.Button=nn,exports.Camera=Z,exports.Canvas=ee,exports.CapsuleCollider=ue,exports.Children=ne,exports.CircleCollider=de,exports.ClearFlags=G,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Se,exports.DEFAULT_DESIGN_HEIGHT=R,exports.DEFAULT_DESIGN_WIDTH=A,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragState=Un,exports.Draggable=Wn,exports.Draw=Dt,exports.Dropdown=rr,exports.EntityCommands=be,exports.FillMethod=Cn,exports.FillOrigin=An,exports.FocusManager=Kn,exports.FocusManagerState=Jn,exports.Focusable=qn,exports.GLDebug=hs,exports.Geometry=Jt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Image=Rn,exports.ImageType=En,exports.Input=Re,exports.InputPlugin=Ie,exports.InputState=Ae,exports.Interactable=en,exports.ListView=tr,exports.LocalTransform=J,exports.Logger=Pr,exports.Material=Ke,exports.MaterialLoader=at,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=pr,exports.PhysicsEvents=ar,exports.PhysicsPlugin=ur,exports.PostProcess=ts,exports.PrefabServer=vt,exports.Prefabs=bt,exports.PrefabsPlugin=St,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(xs);t.register({name:_r,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(_r),this.loadPromise_=t.load(_r).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await s(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new xr(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await yr(this.app_,this.app_.wasmModule,t,n,r,null,void 0,null,_r)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Z]);for(const n of s){if(e.get(n,Z).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([ee]);for(const r of n){const n=e.get(r,ee);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(xs).getScene(_r),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,J,i);const a={isActive:!0,projectionType:Y.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:G.ColorAndDepth};e.insert(o,Z,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(xs);await e.switchTo(_r),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}},exports.ProgressBar=kn,exports.ProjectionType=Y,exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{we(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=ve,exports.RenderPipeline=ps,exports.RenderTexture=wr,exports.Renderer=ls,exports.Res=ge,exports.ResMut=me,exports.RigidBody=le,exports.RuntimeConfig=I,exports.SafeArea=Zn,exports.ScaleMode=q,exports.SceneManager=xs,exports.SceneManagerState=ys,exports.SceneOwner=ae,exports.ScreenSpace=an,exports.ScrollView=Xn,exports.ShaderSources=ot,exports.Slider=Yn,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ce,exports.Text=Ws,exports.TextInput=bn,exports.TextInputPlugin=Sn,exports.TextPlugin=Hs,exports.TextRenderer=$s,exports.Time=_e,exports.Toggle=Fn,exports.UICameraInfo=Oe,exports.UIEventQueue=rn,exports.UIEvents=on,exports.UIInteraction=tn,exports.UIInteractionPlugin=wn,exports.UILayoutPlugin=pn,exports.UIMask=Xs,exports.UIMaskPlugin=Qs,exports.UIRect=Us,exports.Velocity=te,exports.WebAssetProvider=xr,exports.World=ze,exports.WorldTransform=K,exports.addStartupSystem=function(e){Ee().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Ee().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Ee().push({schedule:e,system:t})},exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=I.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=I.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=I.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=I.canvasMatchWidthOrHeight)},exports.assetPlugin=mt,exports.clearDrawCallbacks=Ot,exports.clearUserComponents=function(){W().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=ln,exports.createMaskProcessor=Ks,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await yr(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}},exports.createWebApp=function(e,t){return function(e,t){const s=bs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Rt(e),Ge(e),Yt(e),Qt(e),is(e),ds(e);const r=new ps;s.setPipeline(r);let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,r,o){o||(o=Ts(e,n,t,r));const i=s.getResource(Oe);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(Oe,{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}=i();l(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const d=e.registry_getCanvasEntity(n);if(d>=0){const e=n.getCanvas(d).backgroundColor;ls.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;let h;if(ls.resize(t,c),ts.isInitialized()&&ts.getPassCount()>0&&!ts.isBypassed()&&ts.resize(t,c),s.hasResource(xs)){const e=s.getResource(xs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=Ts(e,n,t,c,s.world,h);if(l(t,c,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:Ss,width:t,height:c,elapsed:u});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:l},clearFlags:e.clearFlags,elapsed:u})}ls.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(mt),s.addPlugin(Pt),s.addPlugin(Fe),s.addPlugin(vs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Mr,...t})},exports.debug=function(e,t,s){Tr.debug(e,t,s)},exports.defineComponent=U,exports.defineResource=fe,exports.defineSystem=Me,exports.defineTag=$,exports.error=function(e,t,s){Tr.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ie]);for(const n of s){const s=e.get(n,ie);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return g(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of d)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return p},exports.getAssetMimeType=function(e){return u[e.toLowerCase()]},exports.getAssetTypeEntry=g,exports.getComponent=N,exports.getComponentAssetFields=function(e){const t=lt.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s},exports.getComponentDefaults=function(e){const t=N(e);return t?D(t._default):null},exports.getCustomExtensions=y,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return Tr},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=z,exports.getWeChatPackOptions=function(){return y().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Tr.info(e,t,s)},exports.initDrawAPI=Rt,exports.initGLDebugAPI=ds,exports.initGeometryAPI=Yt,exports.initMaterialAPI=Ge,exports.initPostProcessAPI=Qt,exports.initRendererAPI=is,exports.inputPlugin=Fe,exports.instantiatePrefab=yt,exports.intersectRects=Ns,exports.invertMatrix4=Ys,exports.isBuiltinComponent=H,exports.isCustomExtension=x,exports.isEditor=function(){return vr},exports.isKnownAssetExtension=m,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!vr},exports.isTextureRef=je,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=ht,exports.loadPhysicsModule=ir,exports.loadRuntimeScene=yr,exports.loadSceneData=dt,exports.loadSceneWithAssets=ut,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&m(f(e)))},exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=n,exports.platformReadTextFile=r,exports.pointInOBB=qs,exports.pointInWorldRect=function(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)},exports.prefabsPlugin=Pt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=X,exports.registerComponentAssetFields=function(e,t){lt.set(e,t)},exports.registerDrawCallback=$t,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ft);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=rt,exports.sceneManagerPlugin=vs,exports.screenToWorld=Gs,exports.setEditorMode=function(e){vr=e},exports.setListViewRenderer=function(e,t){const s=sr.get(e);s&&(s.renderer=t)},exports.setLogLevel=function(e){Tr.setMinLevel(e)},exports.setWasmErrorHandler=We,exports.shutdownDrawAPI=It,exports.shutdownGLDebugAPI=us,exports.shutdownGeometryAPI=Gt,exports.shutdownMaterialAPI=qe,exports.shutdownPostProcessAPI=Zt,exports.shutdownRendererAPI=as,exports.textInputPlugin=Mn,exports.textPlugin=js,exports.transitionTo=async function(e,t,s){const n=e.getResource(xs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=vn,exports.uiLayoutPlugin=fn,exports.uiMaskPlugin=Zs,exports.uiPlugins=Mr,exports.unregisterComponent=function(e){W().delete(e)},exports.unregisterDrawCallback=zt,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([Z]);for(const n of s){const s=e.get(n,Z);s&&(s.aspectRatio=t,e.insert(n,Z,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){Tr.warn(e,t,s)},exports.worldRectToScreen=Vs,exports.wrapSceneSystem=_s,exports.wxFileExists=P,exports.wxFileExistsSync=function(e){const t=w();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=M,exports.wxLoadImage=T,exports.wxLoadImagePixels=async function(e){return M(await T(e))},exports.wxReadFile=b,exports.wxReadTextFile=S,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{w().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function s(e,s){return t().fetch(e,s)}async function n(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function l(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const d=[{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}],u={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"},h=new Map,p=new Set;for(const e of d)for(const t of e.extensions)h.set(t,e),p.add(t);function f(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function g(e){return h.get(f(e))}function y(e){return p.has(e.toLowerCase())}function m(){const e=[];for(const t of d)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function _(e){const t=g(e);return t?.wechatPackInclude??!1}let x=null;function w(){return x||(x=wx.getFileSystemManager()),x}function v(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(_(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return s.includes("no such file")||s.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function b(e){return new Promise((t,s)=>{w().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(v(e,t.errMsg)))}})})}function S(e,t="utf-8"){return new Promise((s,n)=>{w().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(v(e,t.errMsg)))}})})}function P(e){return new Promise(t=>{w().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function M(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function T(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let E=!1;const C=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return b(e)}async readTextFile(e){return S(e)}async fileExists(e){return P(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},A=1920,R=1080,I={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const F=4294967295,B=4294967295;function k(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(k);const t={};for(const s in e)t[s]=k(e[s]);return t}let D=0;function U(e,t){const s=++D;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...k(t),...e}:k(t)}}function L(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function W(e,t){const s=L(),n=s.get(e);if(n)return n;const r=U(e,t);return s.set(e,r),O(e,t,!1),r}function z(e){const t=L(),s=t.get(e);if(s)return s;const n=U(e,{});return t.set(e,n),O(e,{},!0),n}function $(e){return L().get(e)}function O(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function H(e){return!0===e._builtin}const j=new Map;function X(e,t){j.set(e,t)}function N(e){return j.get(e)??$(e)}function Y(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return j.set(e,s),s}const V={Perspective:0,Orthographic:1},G={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},q={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},J=Y("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),K=Y("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Q=Y("Sprite",{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Z=Y("Camera",{projectionType:V.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:G.ColorAndDepth}),ee=Y("Canvas",{designResolution:{x:A,y:R},pixelsPerUnit:100,scaleMode:q.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),te=Y("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=Y("Parent",{entity:0}),ne=Y("Children",{entities:[]}),re=Y("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B,enabled:!0}),oe=Y("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ae=W("SceneOwner",{scene:"",persistent:!1});X("Name",ie);const le=Y("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ce=Y("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),de=Y("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ue=Y("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),he={Static:0,Kinematic:1,Dynamic:2};let pe=0;function fe(e,t){const s=++pe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ge(e){return{_type:"res",_resource:e}}function ye(e){return{_type:"res_mut",_resource:e}}class me{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 _e{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 me(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const xe=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>we(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,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let d=null;this.world_.beginIteration();try{for(const u of n){if(null!==d&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(d,t.component,t.data)}if(i){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(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];d=u}yield a}}finally{if(this.world_.endIteration(),null!==d&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(d,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}}class be{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=H(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 Se{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new be(this,null);return this.spawned_.push(e),e}entity(e){return new be(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 Pe;exports.Schedule=void 0,(Pe=exports.Schedule||(exports.Schedule={}))[Pe.Startup=0]="Startup",Pe[Pe.First=1]="First",Pe[Pe.PreUpdate=2]="PreUpdate",Pe[Pe.Update=3]="Update",Pe[Pe.PostUpdate=4]="PostUpdate",Pe[Pe.Last=5]="Last",Pe[Pe.FixedPreUpdate=10]="FixedPreUpdate",Pe[Pe.FixedUpdate=11]="FixedUpdate",Pe[Pe.FixedPostUpdate=12]="FixedPostUpdate";let Me=0;function Te(e,t,s){const n=++Me;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Ee(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Ce{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 Se&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ae{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 Re=fe(new Ae,"Input");class Ie{constructor(e){this.target_=e??null}build(e){const s=new Ae;e.insertResource(Re,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,Te([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Fe=new Ie;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=ke(t[e]),o=ke(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function ke(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 Ue=null;function Le(e){Ue=e}function We(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Ue&&Ue(e,t)}function ze(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}:ze(e)}}return t}class $e{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 We(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){We(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){We(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){We(t,`removeParent(entity=${e})`)}}insert(e,t,s){return H(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return H(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return H(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(H(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return We(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.");H(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,ze(r))}catch(s){We(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 We(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 We(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){We(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 o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.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_)for(const[s,n]of j)if(H(n)&&!t.includes(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.push(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const n of s)for(const[s,r]of e)if(r._id===n){t.push(s);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 o=null,i=1/0;for(const t of e)if(!H(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<i&&(i=s,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=o?o.keys():this.entities_;for(const t of l){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 Oe=fe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var He;function je(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(He=exports.BlendMode||(exports.BlendMode={}))[He.Normal=0]="Normal",He[He.Additive=1]="Additive",He[He.Multiply=2]="Multiply",He[He.Screen=3]="Screen",He[He.PremultipliedAlpha=4]="PremultipliedAlpha";let Xe=null,Ne=null,Ye=1;const Ve=new Map;function Ge(e){Xe=e,Ne=e.getResourceManager(),rt()}function qe(){0!==Ze&&Xe&&(Xe._free(Ze),Ze=0),Ve.clear(),Ye=1,Qe=!1,tt.clear(),st=null,Ne=null,Xe=null}function Je(){if(!Ne)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ne}const Ke={createShader:(e,t)=>Je().createShader(e,t),releaseShader(e){e>0&&Je().releaseShader(e)},create(e){const t=Ye++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return Ve.set(t,s),t},get:e=>Ve.get(e),setUniform(e,t,s){const n=Ve.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ve.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ve.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ve.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ve.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ve.get(e);return t?.shader??0},release(e){Ve.delete(e)},isValid:e=>Ve.has(e),releaseAll(){Ve.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??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ve.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Ye++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ve.set(s,n),s},toAssetData(e,t){const s=Ve.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=Ve.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Qe=!1,Ze=0;const et=4096,tt=new Map;let st=null;function nt(e){const t=(0===Ze&&Xe&&(Ze=Xe._malloc(et)),Ze);if(0===t||!Xe)return{ptr:0,count:0};let s=0,n=0;const r=Xe.HEAPU8,o=Xe.HEAPU32,i=Xe.HEAPF32;for(const[a,l]of e){if(s+128>et)break;let e=tt.get(a);e||(st||(st=new TextEncoder),e=st.encode(a),tt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=d;let u=0,h=[0,0,0,0];if("number"==typeof l)u=0,h[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(u=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,h=[l.x,l.y,l.z,0]):"y"in l&&(u=1,h=[l.x,l.y,0,0]);o[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function rt(){if(!Xe||Qe)return;Xe.materialDataProvider=(e,t,s,n,r)=>{const o=Ve.get(e);if(!o)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]=o.shader,Xe.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=nt(o.uniforms);Xe.HEAPU32[n>>2]=i,Xe.HEAPU32[r>>2]=a},Qe=!0}const ot={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class it{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class at{constructor(e,t=""){this.cache_=new it,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&&(Ke.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ke.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await r(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:Ke.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const lt=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}]]);function ct(e){return lt.get(e)?.fields??[]}function dt(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,ie,{value:n.name}),!1!==n.visible)for(const s of n.components)ht(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 ut(e,t,s){const n=new Map,r=s?.assetServer,o=s?.assetBaseUrl,i=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=lt.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}`;l.has(t)||(l.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":o.add(t);break;case"font":i.add(t)}}}const c=new Map,d=new Map,u=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const n=await t.loadMaterial(e,s);d.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),d.set(e,0)}})());for(const e of i)h.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)h.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(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=lt.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]=c.get(t)??0;break;case"material":s[e.field]=d.get(t)??0;break;case"font":s[e.field]=u.get(t)??0}}}}(t,r,o,i);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ie,{value:s.name}),!1!==s.visible)for(const n of s.components)ht(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=i.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function ht(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=N(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}class pt{constructor(e){this.textureCache_=new it,this.shaderCache_=new it,this.jsonCache_=new it,this.textCache_=new it,this.binaryCache_=new it,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new it,this.prefabCache_=new it,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_=i(I.textCanvasSize,I.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 at(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Ke.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),d="binary"===g(e)?.contentType,u=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,d);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=g(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return ut(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}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 r(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.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 ft=fe(null,"Assets");class gt{build(e){const t=e.wasmModule;t?e.insertResource(ft,new pt(t)):console.warn("AssetPlugin: No WASM module available")}}const yt=new gt;async function mt(e,t,s){const{entities:n,rootId:r}=await xt(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await ut(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const _t=10;async function xt(e,t,s,n,r,o=0){if(o>_t)throw new Error(`Prefab nesting depth exceeded ${_t}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){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 xt(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),l.push(...t.entities);continue}const c=i.get(n.prefabEntityId),d=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:d?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};wt(u,t),l.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function wt(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 mt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const bt=fe(null,"Prefabs");class St{constructor(){this.name="PrefabsPlugin",this.dependencies=[ft]}build(e){const t=e.getResource(ft);e.insertResource(bt,new vt(e.world,t))}}const Pt=new St;let Mt=null,Tt=0,Et=0,Ct=0;const At=new Float32Array(256);function Rt(e){Mt=e,Tt=Mt._malloc(64),Et=Mt._malloc(64),Ct=Mt._malloc(1024)}function It(){Mt&&(Tt&&(Mt._free(Tt),Tt=0),Et&&(Mt._free(Et),Et=0),Ct&&(Mt._free(Ct),Ct=0)),Mt=null}function Ft(){if(!Mt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Mt}const Bt={r:1,g:1,b:1,a:1},kt={begin(e){const t=Ft();try{t.HEAPF32.set(e,Tt/4),t.draw_begin(Tt)}catch(e){We(e,"Draw.begin")}},end(){try{Ft().draw_end()}catch(e){We(e,"Draw.end")}},line(e,t,s,n=1){try{Ft().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.line")}},rect(e,t,s,n=!0){try{Ft().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Ft().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){We(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{Ft().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){We(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{Ft().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){We(e,"Draw.circleOutline")}},texture(e,t,s,n=Bt){try{Ft().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){We(e,"Draw.texture")}},textureRotated(e,t,s,n,r=Bt){try{Ft().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){We(e,"Draw.textureRotated")}},setLayer(e){Ft().draw_setLayer(e)},setDepth(e){Ft().draw_setDepth(e)},getDrawCallCount:()=>Mt?Mt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Mt?Mt.draw_getPrimitiveCount():0,setBlendMode(e){Ft().draw_setBlendMode(e)},setDepthTest(e){Ft().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Ft();n.HEAPF32.set(s,Et/4),n.draw_mesh(e,t,Et)}catch(s){We(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Ft(),r=Ke.get(t);if(!r)return;if(kt.setBlendMode(r.blendMode),kt.setDepthTest(r.depthTest),0===r.uniforms.size)return void kt.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,Et/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Lt(t);if(!(n<0)){if(je(s))At[o++]=10,At[o++]=n,At[o++]=s.slot??e++,At[o++]=s.textureId;else if("number"==typeof s)At[o++]=1,At[o++]=n,At[o++]=s;else if(Array.isArray(s)){At[o++]=s.length,At[o++]=n;for(let e=0;e<s.length;e++)At[o++]=s[e]}else"w"in s?(At[o++]=4,At[o++]=n,At[o++]=s.x,At[o++]=s.y,At[o++]=s.z,At[o++]=s.w):"z"in s?(At[o++]=3,At[o++]=n,At[o++]=s.x,At[o++]=s.y,At[o++]=s.z):(At[o++]=2,At[o++]=n,At[o++]=s.x,At[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(At.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,Et);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Ct/4),n.draw_meshWithUniforms(e,r.shader,Et,Ct,o)}catch(s){We(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Dt={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},Ut=new Set;function Lt(e){const t=Dt[e];return void 0!==t?t:(Ut.has(e)||(Ut.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Dt).join(", ")}`)),-1)}const Wt=new Map;function zt(e,t,s){Wt.set(e,{fn:t,scene:s??""})}function $t(e){Wt.delete(e)}function Ot(){Wt.clear()}var Ht;exports.DataType=void 0,(Ht=exports.DataType||(exports.DataType={}))[Ht.Float=1]="Float",Ht[Ht.Float2=2]="Float2",Ht[Ht.Float3=3]="Float3",Ht[Ht.Float4=4]="Float4",Ht[Ht.Int=5]="Int",Ht[Ht.Int2=6]="Int2",Ht[Ht.Int3=7]="Int3",Ht[Ht.Int4=8]="Int4";let jt=null,Xt=0,Nt=0,Yt=0;function Vt(e){jt=e,Xt=jt._malloc(262144),Nt=jt._malloc(65536),Yt=jt._malloc(256)}function Gt(){jt&&(Xt&&jt._free(Xt),Nt&&jt._free(Nt),Yt&&jt._free(Yt),Xt=0,Nt=0,Yt=0),jt=null}function qt(){if(!jt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return jt}const Jt={create(e){const t=qt(),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,Xt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Yt,r).set(o),t.geometry_init(s,Xt,n,Yt,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,Nt,n).set(e.indices),t.geometry_setIndices16(s,Nt,n)}else{new Uint32Array(t.HEAPU8.buffer,Nt,n).set(e.indices),t.geometry_setIndices32(s,Nt,n)}}return s},updateVertices(e,t,s=0){const n=qt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Xt/4),n.geometry_updateVertices(e,Xt,r,s)},release(e){e>0&&qt().geometry_release(e)},isValid:e=>!(!jt||e<=0)&&jt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Jt.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Jt.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Jt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let Kt=null;function Qt(e){Kt=e}function Zt(){Kt&&ts.isInitialized()&&ts.shutdown(),Kt=null}function es(){if(!Kt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Kt}const ts={init(e,t){try{return es().postprocess_init(e,t)}catch(s){return We(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{es().postprocess_shutdown()}catch(e){We(e,"PostProcess.shutdown")}},resize(e,t){try{es().postprocess_resize(e,t)}catch(s){We(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return es().postprocess_addPass(e,t)}catch(t){return We(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{es().postprocess_removePass(e)}catch(t){We(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{es().postprocess_setPassEnabled(e,t)}catch(t){We(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return es().postprocess_isPassEnabled(e)}catch(t){return We(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{es().postprocess_setUniformFloat(e,t,s)}catch(s){We(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{es().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){We(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{es().postprocess_begin()}catch(e){We(e,"PostProcess.begin")}},end(){try{es().postprocess_end()}catch(e){We(e,"PostProcess.end")}},getPassCount(){try{return es().postprocess_getPassCount()}catch(e){return We(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Kt)return!1;try{return Kt.postprocess_isInitialized()}catch(e){return We(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{es().postprocess_setBypass(e)}catch(e){We(e,"PostProcess.setBypass")}},isBypassed(){if(!Kt)return!0;try{return Kt.postprocess_isBypassed()}catch(e){return We(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ke.createShader(ss,"#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:()=>Ke.createShader(ss,"#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:()=>Ke.createShader(ss,"#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:()=>Ke.createShader(ss,"#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")},ss="#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 ns;exports.RenderStage=void 0,(ns=exports.RenderStage||(exports.RenderStage={}))[ns.Background=0]="Background",ns[ns.Opaque=1]="Opaque",ns[ns.Transparent=2]="Transparent",ns[ns.Overlay=3]="Overlay";let rs=null,os=0;function is(e){rs=e,os=rs._malloc(64)}function as(){rs&&os&&(rs._free(os),os=0),rs=null}const ls={init(e,t){rs?.renderer_init(e,t)},resize(e,t){rs?.renderer_resize(e,t)},begin(e,t){if(rs&&os)try{rs.HEAPF32.set(e,os/4),rs.renderer_begin(os,t??0)}catch(e){We(e,"Renderer.begin")}},flush(){try{rs?.renderer_flush()}catch(e){We(e,"Renderer.flush")}},end(){try{rs?.renderer_end()}catch(e){We(e,"Renderer.end")}},submitSprites(e){if(rs)try{rs.renderer_submitSprites(e._cpp)}catch(e){We(e,"Renderer.submitSprites")}},submitBitmapText(e){if(rs)try{rs.renderer_submitBitmapText(e._cpp)}catch(e){We(e,"Renderer.submitBitmapText")}},submitSpine(e){if(rs)try{rs.renderer_submitSpine?.(e._cpp)}catch(e){We(e,"Renderer.submitSpine")}},setStage(e){rs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>rs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){rs?.renderer_releaseTarget(e)},getTargetTexture:e=>rs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>rs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){rs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){rs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){rs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){rs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>rs?rs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>rs?{drawCalls:rs.renderer_getDrawCalls(),triangles:rs.renderer_getTriangles(),sprites:rs.renderer_getSprites(),text:rs.renderer_getText(),spine:rs.renderer_getSpine?.()??0,meshes:rs.renderer_getMeshes(),culled:rs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let cs=null;function ds(e){cs=e}function us(){cs=null}const hs={enable(){cs?.gl_enableErrorCheck(!0)},disable(){cs?.gl_enableErrorCheck(!1)},check:e=>cs?.gl_checkErrors(e)??0,diagnose(){cs?.renderer_diagnose()}};class ps{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(ls.resize(n,r),ts.isInitialized()&&ts.getPassCount()>0&&ts.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),ls.setViewport(0,0,n,r),ls.clearBuffers(3),ls.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),ls.submitSprites(t),ls.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ls.submitSpine(t),ls.flush(),this.executeDrawCallbacks(s,o),ls.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;ls.setViewport(n.x,n.y,n.w,n.h),ls.setScissor(n.x,n.y,n.w,n.h,!0),ls.clearBuffers(r),ls.setScissor(0,0,0,0,!1),ls.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),ls.submitSprites(t),ls.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ls.submitSpine(t),ls.flush(),this.executeDrawCallbacks(s,o),ls.end()}executeDrawCallbacks(e,t){const s=Wt;if(s.size>0){kt.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)}kt.end();for(const e of n)$t(e)}}}const fs="__scene_transition_overlay__";class gs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class ys{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,ae,{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),zt(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=ts.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){ts.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,ae)){const s=this.app_.world.get(e,ae);s.persistent=t,this.app_.world.insert(e,ae,s)}}}class ms{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??I.sceneTransitionDuration,r=t.color??{...I.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},zt(fs,()=>{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;kt.setLayer(9999),kt.setDepth(9999),kt.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,$t(fs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,$t(fs),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 gs(t);this.scenes_.set(e,s);const n=new ys(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):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(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await ut(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=xs(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 gs(t);this.scenes_.set(e,s);const n=new ys(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):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(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await ut(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=xs(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,ae)){if(this.app_.world.get(e,ae).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())$t(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{ts.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 o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,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,Q)){const s=this.app_.world.get(e,Q);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Q,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,Q)){const s=this.app_.world.get(e,Q),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Q,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{ts.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const _s=fe(null,"SceneManager");function xs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(_s).getSceneStatus(t)&&s._fn(...n)}}}const ws=Te([ye(_s),ge(xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),vs={name:"SceneManager",build(e){const t=new ms(e);e.insertResource(_s,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(_s),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,ws)}};class bs{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=a(),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(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new $e,this.resources_=new _e;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new bs}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(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.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}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(_s).register(e),this}setInitialScene(e){return this.getResource(_s).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ce(this.world_,this.resources_),this.resources_.insert(xe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Ot();const e=[us,as,Zt,Gt,qe,It];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,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(xe);t.delta=e,t.elapsed+=e,t.frameCount++}}const Ss=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ps(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case q.FixedWidth:return o;case q.FixedHeight:return i;case q.Expand:return Math.max(o,i);case q.Shrink:return Math.min(o,i);case q.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Ms(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,ae);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*s/(i.h*n);let d,u=0,h=0;if(r.projectionType===V.Orthographic){if(h=r.orthoSize,l){h=Ps(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}u=h*a,d=Es(-u,u,-h,h,-r.farPlane,r.farPlane)}else d=As(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=Is(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(Bs(d,p)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Ts=new Float32Array(16);function Es(e,t,s,n,r,o){const i=Ts;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const Cs=new Float32Array(16);function As(e,t,s,n){const r=Cs;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const Rs=new Float32Array(16);function Is(e,t,s){const n=Rs;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 Fs=new Float32Array(16);function Bs(e,t){const s=Fs;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}const ks={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3},Ds=W("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},_dirty:!0});function Us(e,t){e.has(t,Q)||e.insert(t,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function Ls(e,t,s,n){if(!e.has(t,Ds))return;const r=e.get(t,Ds);switch(s){case 0:r.anchorMin={x:0,y:0},r.anchorMax={x:n,y:1};break;case 1:r.anchorMin={x:1-n,y:0},r.anchorMax={x:1,y:1};break;case 2:r.anchorMin={x:0,y:0},r.anchorMax={x:1,y:n};break;case 3:r.anchorMin={x:0,y:1-n},r.anchorMax={x:1,y:1}}r.offsetMin={x:0,y:0},r.offsetMax={x:0,y:0},e.insert(t,Ds,r)}function Ws(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function zs(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function $s(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(let o=0;o<t.length;o++){const i=t[o],a=n+i;if(e.measureText(a).width>s&&n){if(zs(i.charCodeAt(0))&&n.length>0&&zs(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!zs(n.charCodeAt(t))){e=t;break}e>=0?(r.push(n.substring(0,e+1)),n=n.substring(e+1)+i):(r.push(n),n=i)}else r.push(n),n=i}else n=a}n&&r.push(n)}return r.length>0?r:[""]}function Os(e){let t=1;for(;t<e;)t*=2;return t}const Hs={Left:0,Center:1,Right:2},js={Top:0,Middle:1,Bottom:2},Xs={Visible:0,Clip:1,Ellipsis:2},Ns=W("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Hs.Left,verticalAlign:js.Top,wordWrap:!0,overflow:Xs.Visible,lineHeight:1.2});class Ys{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(I.textCanvasSize,I.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,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=$s(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=r?Math.ceil(o):u+2*d,f=r?Math.ceil(i):h+2*d;if(r&&e.overflow===Xs.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<p||n.height<f){const e=Math.max(n.width,Os(p)),t=Math.max(n.height,Os(f));n.width=e,n.height=t}const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=Math.round(255*e.color.b),_=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${y}, ${m}, ${_})`,r&&e.overflow===Xs.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(r)switch(e.verticalAlign){case js.Top:w=d;break;case js.Middle:w=(f-x)/2;break;case js.Bottom:w=f-x-d;break;default:w=d}else w=d;let v=w;for(const t of l){let n;switch(e.align){case Hs.Left:n=d;break;case Hs.Center:n=p/2;break;case Hs.Right:n=p-d;break;default:n=d}s.fillText(t,n,v),v+=c}r&&e.overflow===Xs.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(p,f,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const s of e){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 Hs.Left:return"left";case Hs.Center:return"center";case Hs.Right:return"right"}}}function Vs(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 Gs(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 qs{build(e){X("Text",Ns);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Ys(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Ns));for(const e of r.keys())n.valid(e)&&n.has(e,Ns)||r.delete(e);const e=n.getEntitiesWithComponents([Ns]);for(const t of e){const e=n.get(t,Ns),o=n.has(t,Ds)?n.get(t,Ds):null,i=r.get(t);if(i&&!Gs(i,e,o))continue;Us(n,t);const a=s.renderForEntity(t,e,o),l=n.get(t,Q);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,n.insert(t,Q,l),r.set(t,Vs(e,o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Js=new qs,Ks=W("UIMask",{enabled:!0,mode:"scissor"});function Qs(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function Zs(e,t,s,n,r,o,i,a,l,c,d){const u=e-s*r,h=e+s*(1-r),p=t-n*o,f=t+n*(1-o);function g(e,t){const s=i[0]*e+i[4]*t+i[12],n=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/r)+.5)*c,l+(.5*(n/r)+.5)*d]}const[y,m]=g(u,p),[_,x]=g(h,f),w=Math.min(y,_),v=Math.max(y,_),b=Math.min(m,x),S=Math.max(m,x);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function en(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],d=e[7],u=e[8],h=e[9],p=e[10],f=e[11],g=e[12],y=e[13],m=e[14],_=e[15],x=n*l-r*a,w=n*c-o*a,v=n*d-i*a,b=r*c-o*l,S=r*d-i*l,P=o*d-i*c,M=u*y-h*g,T=u*m-p*g,E=u*_-f*g,C=h*m-p*y,A=h*_-f*y,R=p*_-f*m;let I=x*R-w*A+v*C+b*E-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*R-c*A+d*C)*I,s[1]=(o*A-r*R-i*C)*I,s[2]=(y*P-m*S+_*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*E-a*R-d*T)*I,s[5]=(n*R-o*E+i*T)*I,s[6]=(m*v-g*P-_*w)*I,s[7]=(u*P-p*v+f*w)*I,s[8]=(a*A-l*E+d*M)*I,s[9]=(r*E-n*A-i*M)*I,s[10]=(g*S-y*v+_*x)*I,s[11]=(h*v-u*S-f*x)*I,s[12]=(l*T-a*C-c*M)*I,s[13]=(n*C-r*T+o*M)*I,s[14]=(y*w-g*b-m*x)*I,s[15]=(u*b-h*w+p*x)*I),s}function tn(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],d=s[1]*a+s[5]*l+s[13],u=s[3]*a+s[7]*l+s[15];return{x:c/u,y:d/u}}function sn(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)}function nn(e,t,s,n,r,o,i,a,l,c){const d=2*Math.atan2(l,c),u=Math.sin(-d),h=Math.cos(-d),p=e-s,f=t-n,g=p*h-f*u+s,y=p*u+f*h+n;return g>=s-r*i&&g<=s+r*(1-i)&&y>=n-o*a&&y<=n+o*(1-a)}function rn(e,t,s,n,r,o,i){if(!e.has(t,Ds)||!e.has(t,K))return null;const a=e.get(t,Ds),l=e.get(t,K),c=a.size.x*l.scale.x,d=a.size.y*l.scale.y;return Zs(l.position.x,l.position.y,c,d,a.pivot.x,a.pivot.y,s,n,r,o,i)}function on(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ks]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,Ks);s.enabled&&(u.add(e),"stencil"===s.mode?(d.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,r,o,i,a,l,c){const d=[];for(const e of n){let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(r.has(e.entity)){if("scissor"===t.get(e.entity,Ks).mode){s=!1;break}}n=e.entity}s&&d.push(e)}function u(n,d){const h=e.getChildEntities(s,n);for(const s of h){let n=d;if(r.has(s)){if("scissor"===t.get(s,Ks).mode){const e=rn(t,s,o,i,a,l,c);e&&(n=Qs(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=rn(t,e,o,i,a,l,c);s&&u(e,s)}}(e,t,s,c,u,n,r,o,i,a),d.length>0&&function(e,t,s,n,r){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(r.has(e.entity)){s=!1;break}n=e.entity}s&&o.push(e)}let i=1;function a(t,n){e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,n),l(t,n)}function l(t,n){const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,n),l(t,n)}for(const e of o){a(e,i++)}}(e,t,s,d,h)}catch(t){e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class an{build(e){if(X("UIMask",Ks),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(on(e.wasmModule,e.world))}}const ln=new an,cn=W("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),dn=W("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),un={Normal:0,Hovered:1,Pressed:2,Disabled:3},hn=W("Button",{state:un.Normal,transition:null});class pn{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const fn=fe(new pn,"UIEvents"),gn=z("ScreenSpace");function yn(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,d=o.bottom+e.y*a,u=o.bottom+t.y*a;let h,p,f,g;if(e.x===t.x){const e=l+s.x,t=.5*r.x;h=e-t,f=e+t}else h=l+s.x,f=c+n.x;if(e.y===t.y){const e=d+s.y,t=.5*r.y;p=e-t,g=e+t}else p=d+s.y,g=u+n.y;return{centerX:.5*(h+f),centerY:.5*(p+g),width:f-h,height:g-p,rect:{left:h,bottom:p,right:f,top:g}}}function mn(e,t){e.anchorMinX=t.anchorMin.x,e.anchorMinY=t.anchorMin.y,e.anchorMaxX=t.anchorMax.x,e.anchorMaxY=t.anchorMax.y,e.offsetMinX=t.offsetMin.x,e.offsetMinY=t.offsetMin.y,e.offsetMaxX=t.offsetMax.x,e.offsetMaxY=t.offsetMax.y,e.sizeX=t.size.x,e.sizeY=t.size.y}function _n(e){return{anchorMinX:e.anchorMin.x,anchorMinY:e.anchorMin.y,anchorMaxX:e.anchorMax.x,anchorMaxY:e.anchorMax.y,offsetMinX:e.offsetMin.x,offsetMinY:e.offsetMin.y,offsetMaxX:e.offsetMax.x,offsetMaxY:e.offsetMax.y,sizeX:e.size.x,sizeY:e.size.y}}function xn(e,t){return e.anchorMinX!==t.anchorMin.x||e.anchorMinY!==t.anchorMin.y||e.anchorMaxX!==t.anchorMax.x||e.anchorMaxY!==t.anchorMax.y||e.offsetMinX!==t.offsetMin.x||e.offsetMinY!==t.offsetMin.y||e.offsetMaxX!==t.offsetMax.x||e.offsetMaxY!==t.offsetMax.y||e.sizeX!==t.size.x||e.sizeY!==t.size.y}function wn(e,t,s,n,r,o){if(!e.has(t,Ds))return;const i=e.get(t,Ds),a=yn(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,J);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-n,l.position.y=a.centerY-r),e.insert(t,J,l),!e.has(t,ne))return;const c=e.get(t,ne);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&wn(e,t,a.rect,a.centerX,a.centerY,!1)}class vn{build(e){X("UIRect",Ds);const t=e.world,s=new Map,n=new Map;let r=NaN,o=NaN,i=NaN,a=NaN;function l(e){let s=n.get(e);return void 0!==s||(s=function(e,t){let s=t;for(;;){if(e.has(s,gn))return s;if(!e.has(s,se))return null;const t=e.get(s,se);if(!e.valid(t.entity))return null;s=t.entity}}(t,e),n.set(e,s)),s}e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([ge(Oe)],e=>{if(!e.valid)return;const c={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},d=.5*(c.left+c.right),u=.5*(c.bottom+c.top),h=r!==e.worldLeft||o!==e.worldBottom||i!==e.worldRight||a!==e.worldTop;r=e.worldLeft,o=e.worldBottom,i=e.worldRight,a=e.worldTop;const p=new Set;if(h){n.clear();const e=t.getEntitiesWithComponents([gn,Ds,J]);for(const t of e)p.add(t)}for(const e of s.keys())t.valid(e)&&t.has(e,Ds)||(s.delete(e),n.delete(e));const f=t.getEntitiesWithComponents([Ds]);for(const e of f){const r=t.get(e,Ds),o=s.get(e);if(r._dirty||!o||xn(o,r)){r._dirty=!1,n.delete(e);const t=l(e);null!==t&&p.add(t)}}for(const e of p)wn(t,e,c,d,u,!0);for(const e of f){const n=t.get(e,Ds),r=s.get(e);r?mn(r,n):s.set(e,_n(n))}},{name:"UILayoutSystem"}))}}const bn=new vn,Sn=new Float32Array(16),Pn=new Float32Array(16);let Mn=!0,Tn=1;function En(e,t,s,n){let r=t;for(;e.has(r,se);){const t=e.get(r,se).entity;if(!e.valid(t))break;if(e.has(t,Ks)){if(e.get(t,Ks).enabled&&e.has(t,Ds)&&e.has(t,K)){const r=e.get(t,K),o=e.get(t,Ds),i=o.size.x*r.scale.x,a=o.size.y*r.scale.y;if(!sn(s,n,r.position.x,r.position.y,i,a,o.pivot.x,o.pivot.y))return!0}}r=t}return!1}function Cn(e,t,s,n){t.emit(s,n,s);let r=s;for(;e.has(r,se);){const o=e.get(r,se).entity;if(!e.valid(o))break;if(!e.has(o,cn)){r=o;continue}const i=e.get(o,cn);if(i.enabled&&t.emit(o,n,s),i.blockRaycast)break;r=o}}class An{build(e){X("Interactable",cn),X("Button",hn);const t=e.world,s=new pn;e.insertResource(fn,s);let n=null,r=null;Tn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([ge(Re),ge(Oe)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([dn]);for(const e of i){const s=t.get(e,dn);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Tn,l=o.screenH-e.mouseY*Tn;!function(e){let t=!1;for(let s=0;s<16;s++)if(Pn[s]!==e[s]){t=!0;break}t&&(Pn.set(e),Mn=!0)}(o.viewProjection),Mn&&(en(o.viewProjection,Sn),Mn=!1);const c=tn(a,l,Sn,o.vpX,o.vpY,o.vpW,o.vpH);o.worldMouseX=c.x,o.worldMouseY=c.y;const d=t.getEntitiesWithComponents([cn,Ds,K]);let u=null,h=-1/0;for(const e of d){t.has(e,dn)||t.insert(e,dn);const s=t.get(e,cn);if(!s.enabled)continue;if(!s.raycastTarget)continue;const n=t.get(e,K),r=t.get(e,Ds),o=r.size.x*n.scale.x,i=r.size.y*n.scale.y;if(nn(c.x,c.y,n.position.x,n.position.y,o,i,r.pivot.x,r.pivot.y,n.rotation.z,n.rotation.w)){if(En(t,e,c.x,c.y))continue;let s=0;t.has(e,Q)&&(s=t.get(e,Q).layer),s>=h&&(h=s,u=e)}}if(n!==u){if(null!==n&&t.valid(n)&&t.has(n,dn)){t.get(n,dn).hovered=!1,s.emit(n,"hover_exit")}if(null!==u){t.get(u,dn).hovered=!0,s.emit(u,"hover_enter")}n=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,dn);e.pressed=!0,e.justPressed=!0,r=u,Cn(t,s,u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,dn)){const e=t.get(r,dn);e.pressed=!1,e.justReleased=!0,Cn(t,s,r,"release"),r===n&&Cn(t,s,r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,Te([],()=>{const e=t.getEntitiesWithComponents([hn]);for(const s of e){if(t.has(s,cn)||t.insert(s,cn,{enabled:!0}),!t.has(s,dn))continue;const e=t.get(s,dn),n=t.get(s,hn),r=t.get(s,cn),o=n.state;if(r.enabled?e.pressed?n.state=un.Pressed:e.hovered?n.state=un.Hovered:n.state=un.Normal:n.state=un.Disabled,o!==n.state&&n.transition&&t.has(s,Q)){const o=t.get(s,Q);o.color=Ws(n.transition,r.enabled,e.pressed,e.hovered),t.insert(s,Q,o)}}},{name:"ButtonSystem"}))}}const Rn=new An,In=W("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 Fn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){X("TextInput",In);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=i(I.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,d=0,u=0;const h=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(!h)return;const p=h,f=()=>{l||null===a||x()},g=()=>{l=!0},y=()=>{l=!1,x()},m=t=>{if(null===a)return;if("Escape"===t.key)return void v();const n=s.get(a,In);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(fn).emit(a,"submit"),void v()}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,p.selectionStart=r,p.selectionEnd=r,n.dirty=!0,b())},_=()=>{if(null!==a&&s.valid(a)&&s.has(a,In)){const e=s.get(a,In);e.focused=!1,e.dirty=!0}a=null};function x(){if(null===a||!s.valid(a))return;const t=s.get(a,In);if(t.readOnly)return;let n=p.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),p.value=n),n!==t.value){t.value=n;e.getResource(fn).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,b()}function w(e){if(a===e)return;v();const t=s.get(e,In);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),b())}function v(){if(null!==a&&s.valid(a)&&s.has(a,In)){const e=s.get(a,In);e.focused=!1,e.dirty=!0}a=null,p.blur()}function b(){c=!0,d=0}function S(e,i,a,l){(r.width<a||r.height<l)&&(r.width=Os(Math.max(r.width,a)),r.height=Os(Math.max(r.height,l))),o.clearRect(0,0,r.width,r.height);const d=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,o.fillRect(0,0,a,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const u=0===i.value.length,h=u?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=u?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=$s(o,h,a-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,g,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=$s(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,s=g+(e.length-1)*f,n=f}else t=g+o.measureText(e).width,s=(l-i.fontSize)/2,n=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,n)}o.restore();const y=o.getImageData(0,0,a,l),m=new Uint8Array(y.data.buffer),_=t.getResourceManager(),x=t._malloc(m.length);t.HEAPU8.set(m,x);const w=n.get(e);void 0!==w&&_.releaseTexture(w);const v=_.createTexture(a,l,x,m.length,1,!0);n.set(e,v),t._free(x);const b=s.get(e,Q);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,Q,b)}p.addEventListener("input",f),p.addEventListener("compositionstart",g),p.addEventListener("compositionend",y),p.addEventListener("keydown",m),p.addEventListener("blur",_),this.cleanupListeners_=()=>{p.removeEventListener("input",f),p.removeEventListener("compositionstart",g),p.removeEventListener("compositionend",y),p.removeEventListener("keydown",m),p.removeEventListener("blur",_),p.remove()},e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([ge(fn)],e=>{const t=s.getEntitiesWithComponents([In,cn]);for(const e of t){if(!s.has(e,dn))continue;if(s.get(e,dn).justPressed)return void w(e)}if(null!==a){const e=s.getEntitiesWithComponents([cn]);for(const t of e){if(s.has(t,In))continue;if(!s.has(t,dn))continue;if(s.get(t,dn).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==a&&(d+=r,d>=.5&&(d-=.5,c=!c,null!==a&&s.valid(a)&&s.has(a,In)))){s.get(a,In).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,In)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([In,Ds]);for(const e of i){const t=s.get(e,In);if(!t.dirty)continue;const n=s.get(e,Ds),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(Us(s,e),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Bn=new Fn,kn={Simple:0,Sliced:1,Tiled:2,Filled:3},Dn={Horizontal:0,Vertical:1},Un={Left:0,Right:1,Bottom:2,Top:3},Ln=W("Image",{texture:F,color:{r:1,g:1,b:1,a:1},imageType:kn.Simple,fillMethod:Dn.Horizontal,fillOrigin:Un.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0});const Wn=new class{build(e){X("Image",Ln);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([],()=>{const e=t.getEntitiesWithComponents([Ln]);for(const s of e){const e=t.get(s,Ln);Us(t,s);const n=t.get(s,Q);if(n.texture=e.texture,n.color.r=e.color.r,n.color.g=e.color.g,n.color.b=e.color.b,n.color.a=e.color.a,n.layer=e.layer,n.material=e.material,t.has(s,Ds)){const e=t.get(s,Ds);n.size.x=e.size.x,n.size.y=e.size.y}if(n.uvOffset.x=0,n.uvOffset.y=0,n.uvScale.x=1,n.uvScale.y=1,e.imageType===kn.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));e.fillMethod===Dn.Horizontal?e.fillOrigin===Un.Left?(n.uvScale.x=t,n.size.x*=t):(n.uvOffset.x=1-t,n.uvScale.x=t,n.size.x*=t):e.fillOrigin===Un.Bottom?(n.uvScale.y=t,n.size.y*=t):(n.uvOffset.y=1-t,n.uvScale.y=t,n.size.y*=t)}else e.imageType===kn.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(n.uvScale.x=n.size.x/e.tileSize.x,n.uvScale.y=n.size.y/e.tileSize.y);t.insert(s,Q,n)}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},zn=W("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),$n=W("ToggleGroup",{allowSwitchOff:!1});const On=new class{build(e){X("Toggle",zn),X("ToggleGroup",$n);const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,Te([ge(fn)],e=>{const s=t.getEntitiesWithComponents([zn]);for(const n of s){if(t.has(n,cn)||t.insert(n,cn,{enabled:!0}),!t.has(n,dn))continue;const r=t.get(n,dn),o=t.get(n,zn),i=t.get(n,cn);if(r.justPressed&&i.enabled){const r=o.group,i=0!==r&&t.valid(r)&&t.has(r,$n);if(o.isOn&&i){if(!t.get(r,$n).allowSwitchOff)continue}if(o.isOn=!o.isOn,o.isOn&&i)for(const o of s){if(o===n)continue;const s=t.get(o,zn);s.group===r&&s.isOn&&(s.isOn=!1,e.emit(o,"change"))}e.emit(n,"change")}if(o.graphicEntity&&t.valid(o.graphicEntity)&&t.has(o.graphicEntity,Q)){const e=t.get(o.graphicEntity,Q);e.color.a=o.isOn?1:0,t.insert(o.graphicEntity,Q,e)}if(o.transition&&t.has(n,Q)){const e=t.get(n,Q);e.color=Ws(o.transition,i.enabled,r.pressed,r.hovered),t.insert(n,Q,e)}}},{name:"ToggleSystem"}))}},Hn=ks,jn=W("ProgressBar",{value:0,fillEntity:0,direction:ks.LeftToRight});const Xn=new class{build(e){X("ProgressBar",jn);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([],()=>{const e=t.getEntitiesWithComponents([jn,Ds]);for(const s of e){const e=t.get(s,jn);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=Math.max(0,Math.min(1,e.value));Ls(t,e.fillEntity,e.direction,n)}},{name:"ProgressBarSystem"}))}},Nn=W("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Yn=W("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}}),Vn=new Float32Array(16),Gn=new Float32Array(16);let qn=!0;function Jn(e,t,s){const n=e.mouseX*s,r=t.screenH-e.mouseY*s;return function(e){let t=!1;for(let s=0;s<16;s++)if(Gn[s]!==e[s]){t=!0;break}t&&(Gn.set(e),qn=!0)}(t.viewProjection),qn&&(en(t.viewProjection,Vn),qn=!1),tn(n,r,Vn,t.vpX,t.vpY,t.vpW,t.vpH)}const Kn=new class{build(e){X("Draggable",Nn),X("DragState",Yn);const t=e.world,s=e.getResource(fn);let n=null,r={x:0,y:0},o=null;const i="undefined"!=typeof window&&window.devicePixelRatio||1;e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([ge(Re),ge(Oe)],(e,a)=>{if(!a.valid)return;const l=Jn(e,a,i);if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Nn,dn]);let s=null;for(const n of e){if(!t.get(n,Nn).enabled)continue;t.get(n,dn).hovered&&(s=n)}if(null!==s){n=s,r={x:l.x,y:l.y},t.has(s,Yn)||t.insert(s,Yn);const e=t.get(s,Yn),o=t.get(s,K);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:l.x,y:l.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,Yn)){t.get(n,Yn).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=l.x-r.x,i=l.y-r.y,c=Math.sqrt(e*e+i*i),d=t.get(n,Nn);if(c*(a.vpW/(a.worldRight-a.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,Yn).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Yn))return void(o=null);const n=t.get(o,Yn),r=t.get(o,Nn),i=l.x-n.pointerStartWorld.x,a=l.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+i,d=n.startWorldPos.y+a;const u=function(e,t,s,n){let r=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,n,c,d);c=u.x,d=u.y;const h=n.currentWorldPos.x,p=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:d-p},n.currentWorldPos={x:c,y:d},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:d-n.startWorldPos.y},t.has(o,J)){const e=function(e,t,s,n){if(!e.has(t,se))return{x:s,y:n};const r=e.get(t,se).entity;if(!e.valid(r)||!e.has(r,K))return{x:s,y:n};const o=e.get(r,K),i=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=2*Math.atan2(o.rotation.z,o.rotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(s*d-n*c)/i,y:(s*c+n*d)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,J);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,J,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Qn=W("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const Zn=new class{build(e){X("ScrollView",Qn);const t=e.world,s=new Map;let n=0;e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([ge(Re),ge(Oe)],(e,r)=>{const o=performance.now()/1e3,i=n>0?Math.min(o-n,.05):0;if(n=o,!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY},l=t.getEntitiesWithComponents([Qn,Ds]);for(const n of l){t.has(n,cn)||t.insert(n,cn,{enabled:!0,blockRaycast:!0}),t.has(n,Ks)||t.insert(n,Ks,{enabled:!0,mode:"scissor"});const r=t.get(n,Qn),o=t.get(n,Ds);let l=s.get(n);l||(l={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},s.set(n,l));const c=t.has(n,dn)?t.get(n,dn):null;if(c?.justPressed&&(l.isDragging=!0,l.lastWorldX=a.x,l.lastWorldY=a.y,l.velocityX=0,l.velocityY=0),l.isDragging&&e.isMouseButtonDown(0)){const e=a.x-l.lastWorldX,t=a.y-l.lastWorldY;r.horizontalEnabled&&(r.scrollX-=e,l.velocityX=i>0?-e/i:0),r.verticalEnabled&&(r.scrollY-=t,l.velocityY=i>0?-t/i:0),l.lastWorldX=a.x,l.lastWorldY=a.y}if(l.isDragging&&e.isMouseButtonReleased(0)&&(l.isDragging=!1),c?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,l.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,l.velocityX=0)}if(!l.isDragging&&r.inertia&&i>0){const e=Math.pow(r.decelerationRate,i);r.horizontalEnabled&&Math.abs(l.velocityX)>.1?(r.scrollX+=l.velocityX*i,l.velocityX*=e):l.velocityX=0,r.verticalEnabled&&Math.abs(l.velocityY)>.1?(r.scrollY+=l.velocityY*i,l.velocityY*=e):l.velocityY=0}const d=o.size.x,u=o.size.y,h=Math.max(0,r.contentWidth-d),p=Math.max(0,r.contentHeight-u);if(r.scrollX=Math.max(0,Math.min(r.scrollX,h)),r.scrollY=Math.max(0,Math.min(r.scrollY,p)),0!==r.contentEntity&&t.valid(r.contentEntity)&&t.has(r.contentEntity,J)){const e=t.get(r.contentEntity,J);e.position.x=-r.scrollX,e.position.y=r.scrollY,t.insert(r.contentEntity,J,e)}}},{name:"ScrollViewSystem"}))}},er=ks,tr=W("Slider",{value:0,minValue:0,maxValue:1,direction:ks.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});const sr=new class{build(e){X("Slider",tr);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([ge(Re),ge(Oe)],(e,n)=>{if(!n.valid)return;const r=n.worldMouseX,o=n.worldMouseY,i=t.getEntitiesWithComponents([tr,Ds,K]);for(const n of i){t.has(n,cn)||t.insert(n,cn,{enabled:!0,blockRaycast:!0});const i=t.get(n,tr),a=t.get(n,Ds),l=t.get(n,K),c=t.has(n,dn)?t.get(n,dn):null;if(c?.justPressed&&(s=n),s===n&&e.isMouseButtonDown(0)){const e=a.size.x*l.scale.x,t=a.size.y*l.scale.y,s=l.position.x-a.pivot.x*e,n=l.position.y-a.pivot.y*t;let c;switch(i.direction){case ks.LeftToRight:c=e>0?(r-s)/e:0;break;case ks.RightToLeft:c=e>0?1-(r-s)/e:0;break;case ks.BottomToTop:c=t>0?(o-n)/t:0;break;case ks.TopToBottom:c=t>0?1-(o-n)/t:0}c=Math.max(0,Math.min(1,c));let d=i.minValue+c*(i.maxValue-i.minValue);i.wholeNumbers&&(d=Math.round(d)),i.value=Math.max(i.minValue,Math.min(i.maxValue,d))}s===n&&e.isMouseButtonReleased(0)&&(s=null);const d=i.maxValue-i.minValue,u=d>0?(i.value-i.minValue)/d:0;if(0!==i.fillEntity&&t.valid(i.fillEntity)&&Ls(t,i.fillEntity,i.direction,u),0!==i.handleEntity&&t.valid(i.handleEntity)&&t.has(i.handleEntity,Ds)){const e=t.get(i.handleEntity,Ds);switch(i.direction){case ks.LeftToRight:e.anchorMin={x:u,y:0},e.anchorMax={x:u,y:1};break;case ks.RightToLeft:e.anchorMin={x:1-u,y:0},e.anchorMax={x:1-u,y:1};break;case ks.BottomToTop:e.anchorMin={x:0,y:u},e.anchorMax={x:1,y:u};break;case ks.TopToBottom:e.anchorMin={x:0,y:1-u},e.anchorMax={x:1,y:1-u}}t.insert(i.handleEntity,Ds,e)}}},{name:"SliderSystem"}))}},nr=W("Focusable",{tabIndex:0,isFocused:!1});class rr{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const or=fe(new rr,"FocusManager");const ir=new class{build(e){X("Focusable",nr);const t=e.world,s=new rr;e.insertResource(or,s),e.addSystemToSchedule(exports.Schedule.Update,Te([ge(Re),ge(fn)],(e,n)=>{const r=t.getEntitiesWithComponents([nr]);for(const e of r){if(!t.has(e,dn))continue;t.get(e,dn).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of r){const n=t.get(s,nr);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const i=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?n.length-1:0:a?(i-1+n.length)%n.length:(i+1)%n.length,o(n[l])}function o(e){const r=s.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,nr)){t.get(r,nr).isFocused=!1,n.emit(r,"blur",r)}s.focus(e);t.get(e,nr).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},ar=W("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});const lr=new class{build(e){X("SafeArea",ar);const t=e.world;let s={top:0,bottom:0,left:0,right:0},n=0;e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([],()=>{n++%60==0&&(s=function(){if("undefined"==typeof document)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}());const e=t.getEntitiesWithComponents([ar,Ds]);for(const n of e){const e=t.get(n,ar),r=t.get(n,Ds);let o=!1;const i=e.applyTop?s.top:0,a=e.applyBottom?s.bottom:0,l=e.applyLeft?s.left:0,c=e.applyRight?s.right:0;r.offsetMin.x===l&&r.offsetMin.y===a||(r.offsetMin={x:l,y:a},o=!0),r.offsetMax.x===-c&&r.offsetMax.y===-i||(r.offsetMax={x:-c,y:-i},o=!0),o&&t.insert(n,Ds,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},cr=W("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2}),dr=new Map;const ur=new class{build(e){X("ListView",cr);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([ge(Re)],e=>{const s=t.getEntitiesWithComponents([cr,Ds]);for(const n of s){t.has(n,cn)||t.insert(n,cn,{enabled:!0,blockRaycast:!0}),t.has(n,Ks)||t.insert(n,Ks,{enabled:!0,mode:"scissor"});let s=dr.get(n);s||(s={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},dr.set(n,s));const r=t.get(n,cr),o=t.get(n,Ds),i=o.size.y,a=t.has(n,dn)?t.get(n,dn):null;if(a?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}const l=Math.max(0,r.itemCount*r.itemHeight-i);r.scrollY=Math.max(0,Math.min(r.scrollY,l));const c=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+i)/r.itemHeight)+r.overscan);for(const[e,n]of s.itemEntities)(e<c||e>=d)&&(t.valid(n)&&t.despawn(n),s.itemEntities.delete(e));for(let e=c;e<d;e++){let i=s.itemEntities.get(e);if(i&&t.valid(i)||(i=t.spawn(),t.insert(i,ie,{value:`ListItem_${e}`}),t.insert(i,Ds,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o.size.x,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(i,n),s.itemEntities.set(e,i),s.renderer&&s.renderer(e,i)),t.has(i,J)){const s=t.get(i,J);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(i,J,s)}}s.visibleStart=c,s.visibleEnd=d}},{name:"ListViewSystem"}))}},hr=W("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0}),pr=new Map;const fr=new class{build(e){X("Dropdown",hr);const t=e.world;function s(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const r=s.listEntity;if(0===r||!t.valid(r))return;a(r,!0),i(n);const o=t.has(r,Ds)?t.get(r,Ds):null,c=o?o.size.x:160;for(let e=0;e<s.options.length;e++){const o=t.spawn();t.insert(o,ie,{value:`Option_${e}`}),t.insert(o,Ds,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:30},pivot:{x:.5,y:1}}),t.insert(o,J,{position:{x:0,y:-30*e,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,Ns,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:1,g:1,b:1,a:1},align:0,verticalAlign:1,wordWrap:!1,overflow:1,lineHeight:1.2}),t.insert(o,cn,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,r),n.optionEntities.push(o)}o&&(o.size.y=30*s.options.length,t.insert(r,Ds,o)),l(n)}function n(e,t,s){t.isOpen=!1,i(s),a(t.listEntity,!1)}function r(e,t,s,r,o){t.selectedIndex=r,n(0,t,s),o.emit(e,"change")}function o(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Ns))return;const n=t.get(s,Ns),r=e.selectedIndex>=0&&e.selectedIndex<e.options.length?e.options[e.selectedIndex]:"";n.content!==r&&(n.content=r,t.insert(s,Ns,n))}function i(e){for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[]}function a(e,s){if(0===e||!t.valid(e))return;if(!t.has(e,J))return;const n=t.get(e,J),r=s?1:0;n.scale={x:r,y:r,z:r},t.insert(e,J,n)}function l(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,Q))continue;const r=t.get(n,Q);s===e.highlightIndex?r.color={r:.3,g:.5,b:.8,a:1}:r.color={r:1,g:1,b:1,a:1},t.insert(n,Q,r)}}function c(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,dn))continue;if(t.get(s,dn).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,Te([ge(Re),ge(fn)],(e,i)=>{const a=t.getEntitiesWithComponents([hr]);for(const d of a){t.has(d,cn)||t.insert(d,cn,{enabled:!0,blockRaycast:!0});const a=t.get(d,hr),u=t.has(d,dn)?t.get(d,dn):null;let h=pr.get(d);if(h||(h={optionEntities:[],highlightIndex:-1},pr.set(d,h)),u?.justPressed&&(a.isOpen?n(d,a,h):s(d,a,h)),a.isOpen){for(let e=0;e<h.optionEntities.length;e++){const s=h.optionEntities[e];if(!t.valid(s)||!t.has(s,dn))continue;if(t.get(s,dn).justPressed){r(d,a,h,e,i);break}}e.isKeyPressed("ArrowDown")?(h.highlightIndex=Math.min(h.highlightIndex+1,a.options.length-1),l(h)):e.isKeyPressed("ArrowUp")?(h.highlightIndex=Math.max(h.highlightIndex-1,0),l(h)):e.isKeyPressed("Enter")&&h.highlightIndex>=0?r(d,a,h,h.highlightIndex,i):e.isKeyPressed("Escape")&&n(d,a,h),e.isMouseButtonPressed(0)&&(u?.hovered||c(h)||n(d,a,h))}o(a)}},{name:"DropdownSystem"}))}},gr=0,yr=0,mr=2,_r=W("LayoutGroup",{direction:gr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:yr,reverseOrder:!1});const xr=new class{build(e){X("LayoutGroup",_r);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([],()=>{const e=t.getEntitiesWithComponents([_r,Ds,ne]);for(const s of e){const e=t.get(s,_r),n=t.get(s,Ds),r=t.get(s,ne);if(!r.entities||0===r.entities.length)continue;const o=[];for(const e of r.entities)t.valid(e)&&t.has(e,Ds)&&t.has(e,J)&&o.push({entity:e,rect:t.get(e,Ds)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const i=n.size.x,a=n.size.y,l=e.padding;l.left,l.right,l.top,l.bottom;const c=e.direction===gr;let d=0;for(const s of o){const n=s.rect.size.x,r=s.rect.size.y;let o,u;c?(o=.5*-i+l.left+d+.5*n,u=e.childAlignment===yr?.5*a-l.top-.5*r:e.childAlignment===mr?.5*-a+l.bottom+.5*r:.5*(l.bottom-l.top),d+=n+e.spacing):(o=e.childAlignment===yr?.5*-i+l.left+.5*n:e.childAlignment===mr?.5*i-l.right-.5*n:.5*(l.left-l.right),u=.5*a-l.top-d-.5*r,d+=r+e.spacing),s.rect.anchorMin.x=.5,s.rect.anchorMin.y=.5,s.rect.anchorMax.x=.5,s.rect.anchorMax.y=.5,s.rect.offsetMin.x=o,s.rect.offsetMin.y=u;const h=t.get(s.entity,J);h.position.x=o,h.position.y=u,t.insert(s.entity,J,h)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};async function wr(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 vr=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),br=fe(null,"PhysicsAPI");function Sr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Pr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Mr{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(vr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=wr(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([ee]);for(const s of t){const t=e.world.get(s,ee);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Te([ge(xe)],a=>{const l=i.getEntitiesWithComponents([le,J,K]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,le),l=i.get(r,K);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Sr(l.rotation);n._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,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===he.Kinematic){const e=Sr(l.rotation);n._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const d=e.world.get(i,J);if(!d)continue;let u=a,h=l,p=c;if(e.world.has(i,se)){const t=e.world.get(i,se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,K)){const s=e.world.get(t.entity,K),n=Sr(s.rotation),r=a-s.position.x,o=l-s.position.y,i=Math.cos(-n),d=Math.sin(-n);u=(r*i-o*d)/(0!==s.scale.x?s.scale.x:1),h=(r*d+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-n}}d.position.x=u,d.position.y=h;const f=Pr(p);d.rotation.w=f.w,d.rotation.x=f.x,d.rotation.y=f.y,d.rotation.z=f.z,e.world.insert(i,J,d)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<d;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(vr,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(br,Er._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,ce)){const e=n.get(s,ce);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,de)){const e=n.get(s,de);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,ue)){const e=n.get(s,ue);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 Er{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(Er.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 Cr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),o}function Ar(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 Rr(e,t,s,n){const r=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,d=e.rotation.w,u=a+a,h=l+l,p=c+c,f=a*u,g=a*h,y=a*p,m=l*h,_=l*p,x=c*p,w=d*u,v=d*h,b=d*p;return new Float32Array([(1-(m+x))*r,(g+b)*r,(y-v)*r,0,(g-b)*o,(1-(f+x))*o,(_+w)*o,0,(y+v)*i,(_-w)*i,(1-(f+m))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Ir(e,t,s,n,r,o,i,a,l){const c=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]=Cr(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,c);let d={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),d=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const n=await r.readText(a),d="binary"===g(l)?.contentType;let u,h;if(d){const e=await r.readBinary(i);h=e.length,u=t._malloc(h),t.HEAPU8.set(e,u)}else{const e=await r.readText(i),s=(new TextEncoder).encode(e);h=s.length,u=t._malloc(h+1),t.HEAPU8.set(s,u),t.HEAPU8[u+h]=0}const p=s.loadSkeleton(u,h,n,n.length,d);if(t._free(u),p<0)continue;o[i]=p;const f=Ar(n),y=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=y+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=Cr(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){new Mr("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){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,o;const i=g(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=Cr(e,c,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,d,c.width,c.height)}catch{n[r]=0}}return n}(t,s,n),p=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 o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Ke.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=Ke.createFromAsset(e,i)}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=ct(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,c,h,p);const f=dt(e.world,s);if(l&&e.hasResource(_s))for(const t of f.values())e.world.insert(t,ae,{scene:l,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=n.get(o.id);void 0!==l&&(r[l]=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,d,f);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,oe)?c.get(o,oe):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&n.update(i,l*u);let h=0;if(c.has(o,K)){const e=Rr(c.get(o,K),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),d=s._malloc(l),u=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,d,u,p);const f=s.HEAPU32[u>>2],g=s.HEAPU32[p>>2],y=new Float32Array(s.HEAPF32.buffer,c,8*r),m=new Uint16Array(s.HEAPU8.buffer,d,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(_,r,x,o,f,g,h),t._free(_),t._free(x),s._free(c),s._free(d),s._free(u),s._free(p)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource(ft);t&&t.setAddressableManifest(a)}}class Fr{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"===g(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 o=[];for(const e of n){const t=g(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Br="__preview__";const kr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=ls.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:ls.getTargetTexture(s),width:e.width,height:e.height}},release(e){ls.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(ls.releaseRenderTarget(e._handle),kr.create({width:t,height:s,depth:!0})),begin(e,t){ls.begin(t,e._handle)},end(){ls.end()},getDepthTexture:e=>ls.getTargetDepthTexture(e._handle)};let Dr=!1;var Ur;exports.LogLevel=void 0,(Ur=exports.LogLevel||(exports.LogLevel={}))[Ur.Debug=0]="Debug",Ur[Ur.Info=1]="Info",Ur[Ur.Warn=2]="Warn",Ur[Ur.Error=3]="Error";class Lr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,s);break;case exports.LogLevel.Info:console.log(t,s);break;case exports.LogLevel.Warn:console.warn(t,s);break;case exports.LogLevel.Error:console.error(t,s)}}}class Wr{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Lr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const zr=new Wr;const $r=[Js,ln,bn,Wn,Xn,Rn,Kn,Zn,sr,On,Bn,ir,lr,ur,fr,xr];E||(E=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await l(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=C,exports.App=bs,exports.AssetPlugin=gt,exports.AssetRefCounter=class{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}},exports.AssetServer=pt,exports.Assets=ft,exports.AsyncCache=it,exports.BitmapText=re,exports.BodyType=he,exports.BoxCollider=ce,exports.Button=hn,exports.ButtonState=un,exports.Camera=Z,exports.Canvas=ee,exports.CapsuleCollider=ue,exports.Children=ne,exports.CircleCollider=de,exports.ClearFlags=G,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Se,exports.DEFAULT_DESIGN_HEIGHT=R,exports.DEFAULT_DESIGN_WIDTH=A,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragState=Yn,exports.Draggable=Nn,exports.Draw=kt,exports.Dropdown=hr,exports.EntityCommands=be,exports.FillMethod=Dn,exports.FillOrigin=Un,exports.FocusManager=or,exports.FocusManagerState=rr,exports.Focusable=nr,exports.GLDebug=hs,exports.Geometry=Jt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Image=Ln,exports.ImageType=kn,exports.Input=Re,exports.InputPlugin=Ie,exports.InputState=Ae,exports.Interactable=cn,exports.ListView=cr,exports.LocalTransform=J,exports.Logger=Wr,exports.Material=Ke,exports.MaterialLoader=at,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=Er,exports.PhysicsEvents=vr,exports.PhysicsPlugin=Mr,exports.PostProcess=ts,exports.PrefabServer=vt,exports.Prefabs=bt,exports.PrefabsPlugin=St,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(_s);t.register({name:Br,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Br),this.loadPromise_=t.load(Br).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await s(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Fr(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await Ir(this.app_,this.app_.wasmModule,t,n,r,null,void 0,null,Br)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Z]);for(const n of s){if(e.get(n,Z).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([ee]);for(const r of n){const n=e.get(r,ee);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(_s).getScene(Br),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,J,i);const a={isActive:!0,projectionType:V.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:G.ColorAndDepth};e.insert(o,Z,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(_s);await e.switchTo(Br),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}},exports.ProgressBar=jn,exports.ProgressBarDirection=Hn,exports.ProjectionType=V,exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{we(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=ve,exports.RenderPipeline=ps,exports.RenderTexture=kr,exports.Renderer=ls,exports.Res=ge,exports.ResMut=ye,exports.RigidBody=le,exports.RuntimeConfig=I,exports.SafeArea=ar,exports.ScaleMode=q,exports.SceneManager=_s,exports.SceneManagerState=ms,exports.SceneOwner=ae,exports.ScreenSpace=gn,exports.ScrollView=Qn,exports.ShaderSources=ot,exports.Slider=tr,exports.SliderDirection=er,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ce,exports.Text=Ns,exports.TextAlign=Hs,exports.TextInput=In,exports.TextInputPlugin=Fn,exports.TextOverflow=Xs,exports.TextPlugin=qs,exports.TextRenderer=Ys,exports.TextVerticalAlign=js,exports.Time=xe,exports.Toggle=zn,exports.UICameraInfo=Oe,exports.UIEventQueue=pn,exports.UIEvents=fn,exports.UIInteraction=dn,exports.UIInteractionPlugin=An,exports.UILayoutPlugin=vn,exports.UIMask=Ks,exports.UIMaskPlugin=an,exports.UIRect=Ds,exports.Velocity=te,exports.WebAssetProvider=Fr,exports.World=$e,exports.WorldTransform=K,exports.addStartupSystem=function(e){Ee().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Ee().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Ee().push({schedule:e,system:t})},exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=I.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=I.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=I.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=I.canvasMatchWidthOrHeight)},exports.assetPlugin=yt,exports.clearDrawCallbacks=Ot,exports.clearUserComponents=function(){L().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=yn,exports.createMaskProcessor=on,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await Ir(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}},exports.createWebApp=function(e,t){return function(e,t){const s=bs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Rt(e),Ge(e),Vt(e),Qt(e),is(e),ds(e);const r=new ps;s.setPipeline(r);let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,r,o){o||(o=Ms(e,n,t,r));const i=s.getResource(Oe);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(Oe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();l(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const d=e.registry_getCanvasEntity(n);if(d>=0){const e=n.getCanvas(d).backgroundColor;ls.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;let h;if(ls.resize(t,c),ts.isInitialized()&&ts.getPassCount()>0&&!ts.isBypassed()&&ts.resize(t,c),s.hasResource(_s)){const e=s.getResource(_s).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=Ms(e,n,t,c,s.world,h);if(l(t,c,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:Ss,width:t,height:c,elapsed:u});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:l},clearFlags:e.clearFlags,elapsed:u})}ls.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(yt),s.addPlugin(Pt),s.addPlugin(Fe),s.addPlugin(vs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:$r,...t})},exports.debug=function(e,t,s){zr.debug(e,t,s)},exports.defineComponent=W,exports.defineResource=fe,exports.defineSystem=Te,exports.defineTag=z,exports.error=function(e,t,s){zr.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ie]);for(const n of s){const s=e.get(n,ie);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return g(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of d)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return p},exports.getAssetMimeType=function(e){return u[e.toLowerCase()]},exports.getAssetTypeEntry=g,exports.getComponent=N,exports.getComponentAssetFields=function(e){const t=lt.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s},exports.getComponentDefaults=function(e){const t=N(e);return t?k(t._default):null},exports.getCustomExtensions=m,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return zr},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=$,exports.getWeChatPackOptions=function(){return m().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){zr.info(e,t,s)},exports.initDrawAPI=Rt,exports.initGLDebugAPI=ds,exports.initGeometryAPI=Vt,exports.initMaterialAPI=Ge,exports.initPostProcessAPI=Qt,exports.initRendererAPI=is,exports.inputPlugin=Fe,exports.instantiatePrefab=mt,exports.intersectRects=Qs,exports.invertMatrix4=en,exports.isBuiltinComponent=H,exports.isCustomExtension=_,exports.isEditor=function(){return Dr},exports.isKnownAssetExtension=y,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Dr},exports.isTextureRef=je,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=ht,exports.loadPhysicsModule=wr,exports.loadRuntimeScene=Ir,exports.loadSceneData=dt,exports.loadSceneWithAssets=ut,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&y(f(e)))},exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=n,exports.platformReadTextFile=r,exports.pointInOBB=nn,exports.pointInWorldRect=sn,exports.prefabsPlugin=Pt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=X,exports.registerComponentAssetFields=function(e,t){lt.set(e,t)},exports.registerDrawCallback=zt,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ft);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=rt,exports.sceneManagerPlugin=vs,exports.screenToWorld=tn,exports.setEditorMode=function(e){Dr=e},exports.setListViewRenderer=function(e,t){const s=dr.get(e);s&&(s.renderer=t)},exports.setLogLevel=function(e){zr.setMinLevel(e)},exports.setWasmErrorHandler=Le,exports.shutdownDrawAPI=It,exports.shutdownGLDebugAPI=us,exports.shutdownGeometryAPI=Gt,exports.shutdownMaterialAPI=qe,exports.shutdownPostProcessAPI=Zt,exports.shutdownRendererAPI=as,exports.textInputPlugin=Bn,exports.textPlugin=Js,exports.transitionTo=async function(e,t,s){const n=e.getResource(_s);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=Rn,exports.uiLayoutPlugin=bn,exports.uiMaskPlugin=ln,exports.uiPlugins=$r,exports.unregisterComponent=function(e){L().delete(e)},exports.unregisterDrawCallback=$t,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([Z]);for(const n of s){const s=e.get(n,Z);s&&(s.aspectRatio=t,e.insert(n,Z,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){zr.warn(e,t,s)},exports.worldRectToScreen=Zs,exports.wrapSceneSystem=xs,exports.wxFileExists=P,exports.wxFileExistsSync=function(e){const t=w();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=T,exports.wxLoadImage=M,exports.wxLoadImagePixels=async function(e){return T(await M(e))},exports.wxReadFile=b,exports.wxReadTextFile=S,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{w().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
//# sourceMappingURL=index.wechat.cjs.js.map
diff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.js
index 40982b3ee..6351fc268 100644
--- a/desktop/public/sdk/cjs/index.wechat.js
+++ b/desktop/public/sdk/cjs/index.wechat.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function h(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function u(){return t().now()}function f(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const g=[{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}],y={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",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"},m=new Map,_=new Set;for(const e of g)for(const t of e.extensions)m.set(t,e),_.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function x(e){return m.get(w(e))}function v(e){return x(e)?.editorType??"unknown"}function b(e){return x(e)?.addressableType??null}function S(e){for(const t of g)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return _.has(e.toLowerCase())}function M(){return _}function T(e){return"string"==typeof e&&(!!e.includes("/")&&P(w(e)))}function E(){const e=[];for(const t of g)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function C(){return E().map(e=>({type:"suffix",value:e}))}function R(e){return y[e.toLowerCase()]}function A(e){const t=x(e);return t?.wechatPackInclude??!1}let F=null;function I(){return F||(F=wx.getFileSystemManager()),F}function B(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(A(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function k(e){return new Promise((t,n)=>{I().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(B(e,t.errMsg)))}})})}function $(e,t="utf-8"){return new Promise((n,s)=>{I().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(B(e,t.errMsg)))}})})}function W(e){return new Promise(t=>{I().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function D(e){const t=I();try{return t.accessSync(e),!0}catch{return!1}}function U(e,t){return new Promise((n,s)=>{I().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function z(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function L(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}async function O(e){return L(await z(e))}let H=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return k(e)}async readTextFile(e){return $(e)}async fileExists(e){return W(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:n}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX*n,s.clientY*n)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX*n,s.clientY*n)}),wx.onTouchEnd(t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)})}},X=1920,Y=1080,N=100,V=512,q={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function G(e){e.Text&&(e.Text._default.fontFamily=q.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=q.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=q.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=q.canvasMatchWidthOrHeight)}const J=0,K=4294967295,Q=4294967295,Z=(e=0,t=0)=>({x:e,y:t}),ee=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),te=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),ne=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),se=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function re(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(re);const t={};for(const n in e)t[n]=re(e[n]);return t}let oe=0;function ie(e,t){const n=++oe;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...re(t),...e}:re(t)}}function ae(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function le(e,t){const n=ae(),s=n.get(e);if(s)return s;const r=ie(e,t);return n.set(e,r),fe(e,t,!1),r}function ce(e){const t=ae(),n=t.get(e);if(n)return n;const s=ie(e,{});return t.set(e,s),fe(e,{},!0),s}function he(e){return ae().get(e)}function de(){ae().clear()}function ue(e){ae().delete(e)}function fe(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function pe(e){return!0===e._builtin}const ge=new Map;function ye(e,t){ge.set(e,t)}function me(e){return ge.get(e)??he(e)}function _e(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return ge.set(e,n),n}const we={Perspective:0,Orthographic:1},xe={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ve={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},be=_e("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Se=_e("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Pe=_e("Sprite",{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Me=_e("Camera",{projectionType:we.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:xe.ColorAndDepth}),Te=_e("Canvas",{designResolution:{x:X,y:Y},pixelsPerUnit:100,scaleMode:ve.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Ee=_e("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ce=_e("Parent",{entity:0}),Re=_e("Children",{entities:[]}),Ae=_e("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:Q,enabled:!0}),Fe=_e("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),Ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Be=le("SceneOwner",{scene:"",persistent:!1});function ke(e){const t=me(e);return t?re(t._default):null}ye("Name",Ie);const $e=_e("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),We=_e("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),De=_e("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ue=_e("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ze={Static:0,Kinematic:1,Dynamic:2};let Le=0;function Oe(e,t){const n=++Le;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function He(e){return{_type:"res",_resource:e}}function je(e){return{_type:"res_mut",_resource:e}}class Xe{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 Ye{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 Xe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ne=Oe({delta:0,elapsed:0,frameCount:0},"Time");function Ve(e){return{_type:"mut",_component:e}}function qe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ge(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{qe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class Je{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>qe(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_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let h=null;this.world_.beginIteration();try{for(const d of s){if(null!==h&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];h=d}yield a}}finally{if(this.world_.endIteration(),null!==h&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){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 Ke(){return{_type:"commands"}}class Qe{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=pe(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Ze{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Qe(this,null);return this.spawned_.push(e),e}entity(e){return new Qe(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var et;!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"}(et||(et={}));let tt=0;function nt(e,t,n){const s=++tt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function st(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function rt(e){st().push({schedule:et.Update,system:e})}function ot(e){st().push({schedule:et.Startup,system:e})}function it(e,t){st().push({schedule:e,system:t})}class at{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 n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ze&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new Je(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ze(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class lt{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 ct=Oe(new lt,"Input");class ht{constructor(e){this.target_=e??null}build(e){const n=new lt;e.insertResource(ct,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(et.Last,nt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const dt=new ht;function ut(e,t,n){const s=[];for(const[e,r]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const n=ft(t[e]),o=ft(r);"null"!==n&&"undefined"!==n&&(n!==o&&null!=r&&s.push({field:e,expected:n,actual:o,value:r}))}return s}function ft(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function pt(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let gt=null;function yt(e){gt=e}function mt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),gt&&gt(e,t)}function _t(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="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}:_t(e)}}return t}class wt{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 mt(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){mt(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.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(n){mt(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){mt(t,`removeParent(entity=${e})`)}}insert(e,t,n){return pe(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return pe(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return pe(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(pe(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return mt(n,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");pe(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=ut(t._name,t._default,s);if(e.length>0)throw new Error(pt(t._name,e))}const r={...t._default,...s};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,_t(r))}catch(n){mt(n,`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(n){return mt(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return mt(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){mt(n,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const r=ut(t._name,t._default,e);if(r.length>0)throw new Error(pt(t._name,r));s=e}const r=t.create(s);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.push(n)}catch{}if(this.cppRegistry_)for(const[n,s]of ge)if(pe(s)&&!t.includes(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.push(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const s of n)for(const[n,r]of e)if(r._id===s){t.push(n);break}}return t}getEntitiesWithComponents(e,t=[],n=[]){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();let s=e.map(e=>e._name).sort().join(",");t.length>0&&(s+="|+"+t.map(e=>e._name).sort().join(",")),n.length>0&&(s+="|-"+n.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(s);if(r&&r.version===this.worldVersion_)return r.result;let o=null,i=1/0;for(const t of e)if(!pe(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<i&&(i=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=o?o.keys():this.entities_;for(const t of l){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&a.push(t)}return this.queryCache_.set(s,{version:this.worldVersion_,result:a}),a}}const xt=Oe({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 vt;function bt(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"}(vt||(vt={}));let St=null,Pt=null,Mt=1;const Tt=new Map;function Et(e){St=e,Pt=e.getResourceManager(),Dt()}function Ct(){0!==It&&St&&(St._free(It),It=0),Tt.clear(),Mt=1,Ft=!1,kt.clear(),$t=null,Pt=null,St=null}function Rt(){if(!Pt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Pt}const At={createShader:(e,t)=>Rt().createShader(e,t),releaseShader(e){e>0&&Rt().releaseShader(e)},create(e){const t=Mt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??vt.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Tt.set(t,n),t},get:e=>Tt.get(e),setUniform(e,t,n){const s=Tt.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=Tt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Tt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Tt.get(e);return t?.blendMode??vt.Normal},setDepthTest(e,t){const n=Tt.get(e);n&&(n.depthTest=t)},getShader(e){const t=Tt.get(e);return t?.shader??0},release(e){Tt.delete(e)},isValid:e=>Tt.has(e),releaseAll(){Tt.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??vt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Tt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Mt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Tt.set(n,s),n},toAssetData(e,t){const n=Tt.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=Tt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ft=!1,It=0;const Bt=4096,kt=new Map;let $t=null;function Wt(e){const t=(0===It&&St&&(It=St._malloc(Bt)),It);if(0===t||!St)return{ptr:0,count:0};let n=0,s=0;const r=St.HEAPU8,o=St.HEAPU32,i=St.HEAPF32;for(const[a,l]of e){if(n+128>Bt)break;let e=kt.get(a);e||($t||($t=new TextEncoder),e=$t.encode(a),kt.set(a,e));const c=e.length,h=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=h;let d=0,u=[0,0,0,0];if("number"==typeof l)d=0,u[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)u[e]=l[e]}else"w"in l?(d=3,u=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,u=[l.x,l.y,l.z,0]):"y"in l&&(d=1,u=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=u[e],n+=4;s++}return{ptr:t,count:s}}function Dt(){if(!St||Ft)return;St.materialDataProvider=(e,t,n,s,r)=>{const o=Tt.get(e);if(!o)return St.HEAPU32[t>>2]=0,St.HEAPU32[n>>2]=0,St.HEAPU32[s>>2]=0,void(St.HEAPU32[r>>2]=0);St.HEAPU32[t>>2]=o.shader,St.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Wt(o.uniforms);St.HEAPU32[s>>2]=i,St.HEAPU32[r>>2]=a},Ft=!0}const Ut={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class zt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Lt{constructor(e,t=""){this.cache_=new zt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(At.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())At.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:At.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const Ot=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}]]);function Ht(e,t){Ot.set(e,t)}function jt(e){const t=Ot.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function Xt(e){return Ot.get(e)?.fields??[]}function Yt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Ie,{value:s.name}),!1!==s.visible)for(const n of s.components)Vt(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)}return n}async function Nt(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,h=new Map,d=new Map,u=[];for(const e of r)u.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)u.push((async()=>{try{const s=await t.loadMaterial(e,n);h.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of i)u.push((async()=>{try{const s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)u.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(u);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=h.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Ie,{value:n.name}),!1!==n.visible)for(const s of n.components)Vt(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)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Vt(e,t,n,s){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=me(n.type);if(r)e.insert(t,r,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function qt(e,t){const n=e.getEntitiesWithComponents([Me]);for(const s of n){const n=e.get(s,Me);n&&(n.aspectRatio=t,e.insert(s,Me,n))}}function Gt(e,t){const n=e.getEntitiesWithComponents([Ie]);for(const s of n){const n=e.get(s,Ie);if(n&&n.value===t)return s}return null}class Jt{constructor(e){this.textureCache_=new zt,this.shaderCache_=new zt,this.jsonCache_=new zt,this.textCache_=new zt,this.binaryCache_=new zt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new zt,this.prefabCache_=new zt,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_=d(q.textCanvasSize,q.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,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);if(!r)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),At.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),h="binary"===x(e)?.contentType,d=h?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,h);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Nt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return At.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return At.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){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 n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Kt=Oe(null,"Assets");class Qt{build(e){const t=e.wasmModule;t?e.insertResource(Kt,new Jt(t)):console.warn("AssetPlugin: No WASM module available")}}const Zt=new Qt;class en{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function tn(e,t){const n=e.getResource(Kt);n&&n.registerEmbeddedAssets(t)}async function nn(e,t,n){const{entities:s,rootId:r}=await rn(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await Nt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}const sn=10;async function rn(e,t,n,s,r,o=0){if(o>sn)throw new Error(`Prefab nesting depth exceeded ${sn}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await rn(e,s.nestedPrefab.overrides,n,a,r,o+1);i.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?i.get(s.parent)??null:null),l.push(...t.entities);continue}const c=i.get(s.prefabEntityId),h=s.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:h?null:null!==s.parent?i.get(s.parent)??null:null,children:s.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};on(d,t),l.push(d)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function on(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class an{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return nn(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ln=Oe(null,"Prefabs");class cn{constructor(){this.name="PrefabsPlugin",this.dependencies=[Kt]}build(e){const t=e.getResource(Kt);e.insertResource(ln,new an(e.world,t))}}const hn=new cn;let dn=null,un=0,fn=0,pn=0;const gn=new Float32Array(256);function yn(e){dn=e,un=dn._malloc(64),fn=dn._malloc(64),pn=dn._malloc(1024)}function mn(){dn&&(un&&(dn._free(un),un=0),fn&&(dn._free(fn),fn=0),pn&&(dn._free(pn),pn=0)),dn=null}function _n(){if(!dn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return dn}const wn={r:1,g:1,b:1,a:1},xn={begin(e){const t=_n();try{t.HEAPF32.set(e,un/4),t.draw_begin(un)}catch(e){mt(e,"Draw.begin")}},end(){try{_n().draw_end()}catch(e){mt(e,"Draw.end")}},line(e,t,n,s=1){try{_n().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){mt(e,"Draw.line")}},rect(e,t,n,s=!0){try{_n().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){mt(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{_n().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){mt(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,r=32){try{_n().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){mt(e,"Draw.circle")}},circleOutline(e,t,n,s=1,r=32){try{_n().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){mt(e,"Draw.circleOutline")}},texture(e,t,n,s=wn){try{_n().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){mt(e,"Draw.texture")}},textureRotated(e,t,n,s,r=wn){try{_n().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)}catch(e){mt(e,"Draw.textureRotated")}},setLayer(e){_n().draw_setLayer(e)},setDepth(e){_n().draw_setDepth(e)},getDrawCallCount:()=>dn?dn.draw_getDrawCallCount():0,getPrimitiveCount:()=>dn?dn.draw_getPrimitiveCount():0,setBlendMode(e){_n().draw_setBlendMode(e)},setDepthTest(e){_n().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=_n();s.HEAPF32.set(n,fn/4),s.draw_mesh(e,t,fn)}catch(n){mt(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=_n(),r=At.get(t);if(!r)return;if(xn.setBlendMode(r.blendMode),xn.setDepthTest(r.depthTest),0===r.uniforms.size)return void xn.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,fn/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=Sn(t);if(!(s<0)){if(bt(n))gn[o++]=10,gn[o++]=s,gn[o++]=n.slot??e++,gn[o++]=n.textureId;else if("number"==typeof n)gn[o++]=1,gn[o++]=s,gn[o++]=n;else if(Array.isArray(n)){gn[o++]=n.length,gn[o++]=s;for(let e=0;e<n.length;e++)gn[o++]=n[e]}else"w"in n?(gn[o++]=4,gn[o++]=s,gn[o++]=n.x,gn[o++]=n.y,gn[o++]=n.z,gn[o++]=n.w):"z"in n?(gn[o++]=3,gn[o++]=s,gn[o++]=n.x,gn[o++]=n.y,gn[o++]=n.z):(gn[o++]=2,gn[o++]=s,gn[o++]=n.x,gn[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(gn.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void s.draw_mesh(e,r.shader,fn);s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),pn/4),s.draw_meshWithUniforms(e,r.shader,fn,pn,o)}catch(n){mt(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},vn={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},bn=new Set;function Sn(e){const t=vn[e];return void 0!==t?t:(bn.has(e)||(bn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(vn).join(", ")}`)),-1)}const Pn=new Map;function Mn(e,t,n){Pn.set(e,{fn:t,scene:n??""})}function Tn(e){Pn.delete(e)}function En(){Pn.clear()}var Cn;!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"}(Cn||(Cn={}));let Rn=null,An=0,Fn=0,In=0;function Bn(e){Rn=e,An=Rn._malloc(262144),Fn=Rn._malloc(65536),In=Rn._malloc(256)}function kn(){Rn&&(An&&Rn._free(An),Fn&&Rn._free(Fn),In&&Rn._free(In),An=0,Fn=0,In=0),Rn=null}function $n(){if(!Rn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Rn}const Wn={create(e){const t=$n(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,An/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,In,r).set(o),t.geometry_init(n,An,s,In,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Fn,s).set(e.indices),t.geometry_setIndices16(n,Fn,s)}else{new Uint32Array(t.HEAPU8.buffer,Fn,s).set(e.indices),t.geometry_setIndices32(n,Fn,s)}}return n},updateVertices(e,t,n=0){const s=$n(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,An/4),s.geometry_updateVertices(e,An,r,n)},release(e){e>0&&$n().geometry_release(e)},isValid:e=>!(!Rn||e<=0)&&Rn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Wn.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:Cn.Float2},{name:"a_texCoord",type:Cn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Wn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Cn.Float2},{name:"a_texCoord",type:Cn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Wn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Cn.Float2},{name:"a_texCoord",type:Cn.Float2}],indices:new Uint16Array(i)})}};let Dn=null;function Un(e){Dn=e}function zn(){Dn&&On.isInitialized()&&On.shutdown(),Dn=null}function Ln(){if(!Dn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Dn}const On={init(e,t){try{return Ln().postprocess_init(e,t)}catch(n){return mt(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ln().postprocess_shutdown()}catch(e){mt(e,"PostProcess.shutdown")}},resize(e,t){try{Ln().postprocess_resize(e,t)}catch(n){mt(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ln().postprocess_addPass(e,t)}catch(t){return mt(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ln().postprocess_removePass(e)}catch(t){mt(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ln().postprocess_setPassEnabled(e,t)}catch(t){mt(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ln().postprocess_isPassEnabled(e)}catch(t){return mt(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Ln().postprocess_setUniformFloat(e,t,n)}catch(n){mt(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Ln().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){mt(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ln().postprocess_begin()}catch(e){mt(e,"PostProcess.begin")}},end(){try{Ln().postprocess_end()}catch(e){mt(e,"PostProcess.end")}},getPassCount(){try{return Ln().postprocess_getPassCount()}catch(e){return mt(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Dn)return!1;try{return Dn.postprocess_isInitialized()}catch(e){return mt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ln().postprocess_setBypass(e)}catch(e){mt(e,"PostProcess.setBypass")}},isBypassed(){if(!Dn)return!0;try{return Dn.postprocess_isBypassed()}catch(e){return mt(e,"PostProcess.isBypassed"),!0}},createBlur:()=>At.createShader(Hn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>At.createShader(Hn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>At.createShader(Hn,"#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:()=>At.createShader(Hn,"#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")},Hn="#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 jn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(jn||(jn={}));let Xn=null,Yn=0;function Nn(e){Xn=e,Yn=Xn._malloc(64)}function Vn(){Xn&&Yn&&(Xn._free(Yn),Yn=0),Xn=null}const qn={init(e,t){Xn?.renderer_init(e,t)},resize(e,t){Xn?.renderer_resize(e,t)},begin(e,t){if(Xn&&Yn)try{Xn.HEAPF32.set(e,Yn/4),Xn.renderer_begin(Yn,t??0)}catch(e){mt(e,"Renderer.begin")}},flush(){try{Xn?.renderer_flush()}catch(e){mt(e,"Renderer.flush")}},end(){try{Xn?.renderer_end()}catch(e){mt(e,"Renderer.end")}},submitSprites(e){if(Xn)try{Xn.renderer_submitSprites(e._cpp)}catch(e){mt(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Xn)try{Xn.renderer_submitBitmapText(e._cpp)}catch(e){mt(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Xn)try{Xn.renderer_submitSpine?.(e._cpp)}catch(e){mt(e,"Renderer.submitSpine")}},setStage(e){Xn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Xn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Xn?.renderer_releaseTarget(e)},getTargetTexture:e=>Xn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Xn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Xn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Xn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Xn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Xn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Xn?Xn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Xn?{drawCalls:Xn.renderer_getDrawCalls(),triangles:Xn.renderer_getTriangles(),sprites:Xn.renderer_getSprites(),text:Xn.renderer_getText(),spine:Xn.renderer_getSpine?.()??0,meshes:Xn.renderer_getMeshes(),culled:Xn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Gn=null;function Jn(e){Gn=e}function Kn(){Gn=null}const Qn={enable(){Gn?.gl_enableErrorCheck(!0)},disable(){Gn?.gl_enableErrorCheck(!1)},check:e=>Gn?.gl_checkErrors(e)??0,diagnose(){Gn?.renderer_diagnose()}};class Zn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(qn.resize(s,r),On.isInitialized()&&On.getPassCount()>0&&On.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),qn.setViewport(0,0,s,r),qn.clearBuffers(3),qn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),qn.submitSprites(t),qn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):qn.submitSpine(t),qn.flush(),this.executeDrawCallbacks(n,o),qn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;qn.setViewport(s.x,s.y,s.w,s.h),qn.setScissor(s.x,s.y,s.w,s.h,!0),qn.clearBuffers(r),qn.setScissor(0,0,0,0,!1),qn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),qn.submitSprites(t),qn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):qn.submitSpine(t),qn.flush(),this.executeDrawCallbacks(n,o),qn.end()}executeDrawCallbacks(e,t){const n=Pn;if(n.size>0){xn.begin(e);const s=[];for(const[e,r]of n.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}xn.end();for(const e of s)Tn(e)}}}const es="__scene_transition_overlay__";class ts{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class ns{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,Be,{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),Mn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=On.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){On.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,Be)){const n=this.app_.world.get(e,Be);n.persistent=t,this.app_.world.insert(e,Be,n)}}}class ss{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(n=>{const s=t.duration??q.sceneTransitionDuration,r=t.color??{...q.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:r,targetScene:e,options:t,resolve:n},Mn(es,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;xn.setLayer(9999),xn.setDepth(9999),xn.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{n&&n!==e&&await this.unload(n,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,Tn(es)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Tn(es),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new ts(t);this.scenes_.set(e,n);const s=new ns(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Kt)?this.app_.getResource(Kt):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(Kt)&&(t.assetServer=this.app_.getResource(Kt));const s=await Nt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,Be,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=os(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();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 n=new ts(t);this.scenes_.set(e,n);const s=new ns(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Kt)?this.app_.getResource(Kt):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(Kt)&&(t.assetServer=this.app_.getResource(Kt));const s=await Nt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,Be,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=os(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const r=t?.keepPersistent??!0;for(const e of n.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,Be)){if(this.app_.world.get(e,Be).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Tn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{On.removePass(e)}catch{}n.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}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,Pe)){const n=this.app_.world.get(e,Pe);t.savedAlphas.set(e,n.color.a),n.color={...n.color,a:0},this.app_.world.insert(e,Pe,n)}}}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,Pe)){const n=this.app_.world.get(e,Pe),s=t.savedAlphas.get(e)??1;n.color={...n.color,a:s},this.app_.world.insert(e,Pe,n)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{On.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const rs=Oe(null,"SceneManager");function os(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(rs).getSceneStatus(t)&&n._fn(...s)}}}const is=nt([je(rs),He(Ne)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),as={name:"SceneManager",build(e){const t=new ss(e);e.insertResource(rs,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(rs),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(et.Startup,n),e.addSystemToSchedule(et.Last,is)}};class ls{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=u(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(et.Last);else{this.runSchedule(et.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(et.FixedPreUpdate),this.runSchedule(et.FixedUpdate),this.runSchedule(et.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(et.PreUpdate),this.runSchedule(et.Update),this.runSchedule(et.PostUpdate),this.runSchedule(et.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new wt,this.resources_=new Ye;for(const e of Object.values(et))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ls}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,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(et.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(et.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 yt(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(rs).register(e),this}setInitialScene(e){return this.getResource(rs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new at(this.world_,this.resources_),this.resources_.insert(Ne,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(et.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,En();const e=[Kn,Vn,zn,kn,Ct,mn];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 n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const r=t.get(s);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,r=new Set,o=i=>{if(s.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}r.delete(i),s.add(i),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Ne);t.delta=e,t.elapsed+=e,t.frameCount++}}function cs(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const hs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ds(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case ve.FixedWidth:return o;case ve.FixedHeight:return i;case ve.Expand:return Math.max(o,i);case ve.Shrink:return Math.min(o,i);case ve.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function us(e,t,n,s,r,o){if(0===n||0===s)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,Be);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*n/(i.h*s);let h,d=0,u=0;if(r.projectionType===we.Orthographic){if(u=r.orthoSize,l){u=ds(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}d=u*a,h=ps(-d,d,-u,u,-r.farPlane,r.farPlane)}else h=ys(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=_s(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(xs(h,f)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:u,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const fs=new Float32Array(16);function ps(e,t,n,s,r,o){const i=fs;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const gs=new Float32Array(16);function ys(e,t,n,s){const r=gs;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const ms=new Float32Array(16);function _s(e,t,n){const s=ms;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const ws=new Float32Array(16);function xs(e,t){const n=ws;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var vs,bs,Ss;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(vs||(vs={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(bs||(bs={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Ss||(Ss={}));const Ps=le("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:vs.Left,verticalAlign:bs.Top,wordWrap:!0,overflow:Ss.Visible,lineHeight:1.2}),Ms=le("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 Ts{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(q.textCanvasSize,q.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),u=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*h,p=r?Math.ceil(i):u+2*h;if(r&&e.overflow===Ss.Ellipsis&&u>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${y}, ${m}, ${_})`,r&&e.overflow===Ss.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case bs.Top:x=h;break;case bs.Middle:x=(p-w)/2;break;case bs.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of l){let s;switch(e.align){case vs.Left:s=h;break;case vs.Center:s=f/2;break;case vs.Right:s=f-h;break;default:s=h}n.fillText(t,s,v),v+=c}r&&e.overflow===Ss.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);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[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case vs.Left:return"left";case vs.Center:return"center";case vs.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function Es(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 Cs(e,t,n){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!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class Rs{build(e){ye("Text",Ps);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ts(t),s=e.world,r=new Map;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Ps));for(const e of r.keys())s.valid(e)&&s.has(e,Ps)||r.delete(e);const e=s.getEntitiesWithComponents([Ps]);for(const t of e){const e=s.get(t,Ps),o=s.has(t,Ms)?s.get(t,Ms):null,i=r.get(t);if(i&&!Cs(i,e,o))continue;s.has(t,Pe)||s.insert(t,Pe,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=n.renderForEntity(t,e,o),l=s.get(t,Pe);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,Pe,l),r.set(t,Es(e,o))}}))}}const As=new Rs,Fs=le("UIMask",{enabled:!0,mode:"scissor"});function Is(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function Bs(e,t,n,s,r,o,i,a,l,c,h){const d=e-n*r,u=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function g(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*h]}const[y,m]=g(d,f),[_,w]=g(u,p),x=Math.min(y,_),v=Math.max(y,_),b=Math.min(m,w),S=Math.max(m,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function ks(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],h=e[7],d=e[8],u=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,v=s*h-i*a,b=r*c-o*l,S=r*h-i*l,P=o*h-i*c,M=d*y-u*g,T=d*m-f*g,E=d*_-p*g,C=u*m-f*y,R=u*_-p*y,A=f*_-p*m;let F=w*A-x*R+v*C+b*E-S*T+P*M;return 0===F||(F=1/F,n[0]=(l*A-c*R+h*C)*F,n[1]=(o*R-r*A-i*C)*F,n[2]=(y*P-m*S+_*b)*F,n[3]=(f*S-u*P-p*b)*F,n[4]=(c*E-a*A-h*T)*F,n[5]=(s*A-o*E+i*T)*F,n[6]=(m*v-g*P-_*x)*F,n[7]=(d*P-f*v+p*x)*F,n[8]=(a*R-l*E+h*M)*F,n[9]=(r*E-s*R-i*M)*F,n[10]=(g*S-y*v+_*w)*F,n[11]=(u*v-d*S-p*w)*F,n[12]=(l*T-a*C-c*M)*F,n[13]=(s*C-r*T+o*M)*F,n[14]=(y*x-g*b-m*w)*F,n[15]=(d*b-u*x+f*w)*F),n}function $s(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],h=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:h/d}}function Ws(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function Ds(e,t,n,s,r,o,i,a,l,c){const h=2*Math.atan2(l,c),d=Math.sin(-h),u=Math.cos(-h),f=e-n,p=t-s,g=f*u-p*d+n,y=f*d+p*u+s;return g>=n-r*i&&g<=n+r*(1-i)&&y>=s-o*a&&y<=s+o*(1-a)}function Us(e,t,n,s,r,o,i){if(!e.has(t,Ms)||!e.has(t,Se))return null;const a=e.get(t,Ms),l=e.get(t,Se),c=a.size.x*l.scale.x,h=a.size.y*l.scale.y;return Bs(l.position.x,l.position.y,c,h,a.pivot.x,a.pivot.y,n,s,r,o,i)}function zs(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Fs]);if(0===l.length)return;const c=[],h=[],d=new Set,u=new Set;for(const e of l){const n=t.get(e,Fs);n.enabled&&(d.add(e),"stencil"===n.mode?(h.push(e),u.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,r,o,i,a,l,c){const h=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Ce);){const e=t.get(s,Ce);if(r.has(e.entity)){if("scissor"===t.get(e.entity,Fs).mode){n=!1;break}}s=e.entity}n&&h.push(e)}function d(s,h){const u=e.getChildEntities(n,s);for(const n of u){let s=h;if(r.has(n)){if("scissor"===t.get(n,Fs).mode){const e=Us(t,n,o,i,a,l,c);e&&(s=Is(h,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of h){const n=Us(t,e,o,i,a,l,c);n&&d(e,n)}}(e,t,n,c,d,s,r,o,i,a),h.length>0&&function(e,t,n,s,r){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Ce);){const e=t.get(s,Ce);if(r.has(e.entity)){n=!1;break}s=e.entity}n&&o.push(e)}let i=1;function a(t,s){e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}function l(t,s){const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}for(const e of o){a(e,i++)}}(e,t,n,h,u)}catch(t){e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Ls{build(e){if(ye("UIMask",Fs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(zs(e.wasmModule,e.world))}}const Os=new Ls,Hs=le("Interactable",{enabled:!0,blockRaycast:!0}),js=le("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Xs;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Xs||(Xs={}));const Ys=le("Button",{state:Xs.Normal,transition:null,enabled:!0});class Ns{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Vs=Oe(new Ns,"UIEvents"),qs=ce("ScreenSpace");function Gs(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,h=o.bottom+e.y*a,d=o.bottom+t.y*a;let u,f,p,g;if(e.x===t.x){const e=l+n.x,t=.5*r.x;u=e-t,p=e+t}else u=l+n.x,p=c+s.x;if(e.y===t.y){const e=h+n.y,t=.5*r.y;f=e-t,g=e+t}else f=h+n.y,g=d+s.y;return{centerX:.5*(u+p),centerY:.5*(f+g),width:p-u,height:g-f,rect:{left:u,bottom:f,right:p,top:g}}}function Js(e){return{anchorMinX:e.anchorMin.x,anchorMinY:e.anchorMin.y,anchorMaxX:e.anchorMax.x,anchorMaxY:e.anchorMax.y,offsetMinX:e.offsetMin.x,offsetMinY:e.offsetMin.y,offsetMaxX:e.offsetMax.x,offsetMaxY:e.offsetMax.y,sizeX:e.size.x,sizeY:e.size.y}}function Ks(e,t){return e.anchorMinX!==t.anchorMin.x||e.anchorMinY!==t.anchorMin.y||e.anchorMaxX!==t.anchorMax.x||e.anchorMaxY!==t.anchorMax.y||e.offsetMinX!==t.offsetMin.x||e.offsetMinY!==t.offsetMin.y||e.offsetMaxX!==t.offsetMax.x||e.offsetMaxY!==t.offsetMax.y||e.sizeX!==t.size.x||e.sizeY!==t.size.y}function Qs(e,t){let n=t;for(;;){if(e.has(n,qs))return n;if(!e.has(n,Ce))return null;const t=e.get(n,Ce);if(!e.valid(t.entity))return null;n=t.entity}}function Zs(e,t,n,s,r,o){if(!e.has(t,Ms))return;const i=e.get(t,Ms),a=Gs(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,be);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,be,l),!e.has(t,Re))return;const c=e.get(t,Re);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Zs(e,t,a.rect,a.centerX,a.centerY,!1)}class er{build(e){ye("UIRect",Ms);const t=e.world,n=new Map;let s=NaN,r=NaN,o=NaN,i=NaN;e.addSystemToSchedule(et.PreUpdate,nt([He(xt)],e=>{if(!e.valid)return;const a={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},l=.5*(a.left+a.right),c=.5*(a.bottom+a.top),h=s!==e.worldLeft||r!==e.worldBottom||o!==e.worldRight||i!==e.worldTop;s=e.worldLeft,r=e.worldBottom,o=e.worldRight,i=e.worldTop;const d=new Set;if(h){const e=t.getEntitiesWithComponents([qs,Ms,be]);for(const t of e)d.add(t)}const u=t.getEntitiesWithComponents([Ms]);for(const e of u){const s=t.get(e,Ms),r=n.get(e);if(!r||Ks(r,s)){const n=Qs(t,e);null!==n&&d.add(n)}}for(const e of n.keys())if(!t.valid(e)||!t.has(e,Ms)){n.delete(e);const s=Qs(t,e);null!==s&&d.add(s)}for(const e of d)Zs(t,e,a,l,c,!0);for(const e of u){const s=t.get(e,Ms);n.set(e,Js(s))}},{name:"UILayoutSystem"}))}}const tr=new er,nr=new Float32Array(16),sr=new Float32Array(16);let rr=!0,or=1;function ir(e,t,n,s){t.emit(n,s,n);let r=n;for(;e.has(r,Ce);){const o=e.get(r,Ce).entity;if(!e.valid(o))break;if(!e.has(o,Hs)){r=o;continue}const i=e.get(o,Hs);if(i.enabled&&t.emit(o,s,n),i.blockRaycast)break;r=o}}class ar{build(e){ye("Interactable",Hs),ye("Button",Ys);const t=e.world,n=new Ns;e.insertResource(Vs,n);let s=null,r=null;or="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([js]);for(const e of i){const n=t.get(e,js);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*or,l=o.screenH-e.mouseY*or;!function(e){let t=!1;for(let n=0;n<16;n++)if(sr[n]!==e[n]){t=!0;break}t&&(sr.set(e),rr=!0)}(o.viewProjection),rr&&(ks(o.viewProjection,nr),rr=!1);const c=$s(a,l,nr,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([Hs,Ms,Se]);let d=null,u=-1/0;for(const e of h){t.has(e,js)||t.insert(e,js);if(!t.get(e,Hs).enabled)continue;const n=t.get(e,Se),s=t.get(e,Ms),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Ds(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y,n.rotation.z,n.rotation.w)){let n=0;t.has(e,Pe)&&(n=t.get(e,Pe).layer),n>=u&&(u=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,js)){t.get(s,js).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,js).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,js);e.pressed=!0,e.justPressed=!0,r=d,ir(t,n,d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,js)){const e=t.get(r,js);e.pressed=!1,e.justReleased=!0,ir(t,n,r,"release"),r===s&&ir(t,n,r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(et.Update,nt([],()=>{const e=t.getEntitiesWithComponents([Ys]);for(const n of e){if(t.has(n,Hs)||t.insert(n,Hs,{enabled:!0}),!t.has(n,js))continue;const e=t.get(n,js),s=t.get(n,Ys),r=t.get(n,Hs),o=s.state;if(r.enabled?e.pressed?s.state=Xs.Pressed:e.hovered?s.state=Xs.Hovered:s.state=Xs.Normal:s.state=Xs.Disabled,o!==s.state&&s.transition&&t.has(n,Pe)){const e=t.get(n,Pe),r=s.transition;switch(s.state){case Xs.Normal:e.color={...r.normalColor};break;case Xs.Hovered:e.color={...r.hoveredColor};break;case Xs.Pressed:e.color={...r.pressedColor};break;case Xs.Disabled:e.color={...r.disabledColor}}t.insert(n,Pe,e)}}},{name:"ButtonSystem"}))}}const lr=new ar,cr=le("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 hr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){ye("TextInput",cr);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(q.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,h=0;const u=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(!u)return;const f=u,p=()=>{a||null===i||w()},g=()=>{a=!0},y=()=>{a=!1,w()},m=t=>{if(null===i)return;if("Escape"===t.key)return void v();const s=n.get(i,cr);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Vs).emit(i,"submit"),void v()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,b())},_=()=>{if(null!==i&&n.valid(i)&&n.has(i,cr)){const e=n.get(i,cr);e.focused=!1,e.dirty=!0}i=null};function w(){if(null===i||!n.valid(i))return;const t=n.get(i,cr);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(Vs).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,b()}function x(e){if(i===e)return;v();const t=n.get(e,cr);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),b())}function v(){if(null!==i&&n.valid(i)&&n.has(i,cr)){const e=n.get(i,cr);e.focused=!1,e.dirty=!0}i=null,f.blur()}function b(){l=!0,c=0}function S(e,i,a,c){(r.width<a||r.height<c)&&(r.width=ur(Math.max(r.width,a)),r.height=ur(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const h=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,u=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.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*i.fontSize),g=i.padding;if(i.multiline){const e=dr(o,u,a-2*g);let t=g;for(const n of e)o.fillText(n,g,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(u,g,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=dr(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,n=g+(e.length-1)*p,s=p}else t=g+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const y=o.getImageData(0,0,a,c),m=new Uint8Array(y.data.buffer),_=t.getResourceManager(),w=t._malloc(m.length);t.HEAPU8.set(m,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const v=_.createTexture(a,c,w,m.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,Pe);b.texture=v,b.size.x=a,b.size.y=c,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},n.insert(e,Pe,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",g),f.addEventListener("compositionend",y),f.addEventListener("keydown",m),f.addEventListener("blur",_),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",g),f.removeEventListener("compositionend",y),f.removeEventListener("keydown",m),f.removeEventListener("blur",_),f.remove()},e.addSystemToSchedule(et.PreUpdate,nt([He(Vs)],e=>{const t=n.getEntitiesWithComponents([cr,Hs]);for(const e of t){if(!n.has(e,js))continue;if(n.get(e,js).justPressed)return void x(e)}if(null!==i){const e=n.getEntitiesWithComponents([Hs]);for(const t of e){if(n.has(t,cr))continue;if(!n.has(t,js))continue;if(n.get(t,js).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(et.PreUpdate,nt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,cr)))){n.get(i,cr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,cr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([cr,Ms]);for(const e of a){const t=n.get(e,cr);if(!t.dirty)continue;const s=n.get(e,Ms),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,Pe)||n.insert(e,Pe,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function dr(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function ur(e){let t=1;for(;t<e;)t*=2;return t}const fr=new hr,pr={Simple:0,Sliced:1,Tiled:2,Filled:3},gr={Horizontal:0,Vertical:1},yr={Left:0,Right:1,Bottom:2,Top:3},mr=le("Image",{texture:K,color:{r:1,g:1,b:1,a:1},imageType:pr.Simple,fillMethod:gr.Horizontal,fillOrigin:yr.Left,fillAmount:1,preserveAspect:!1,layer:0,material:0,enabled:!0});const _r=new class{build(e){ye("Image",mr);const t=e.world;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{const e=t.getEntitiesWithComponents([mr]);for(const n of e){const e=t.get(n,mr);t.has(n,Pe)||t.insert(n,Pe,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const s=t.get(n,Pe);if(s.texture=e.texture,s.color.r=e.color.r,s.color.g=e.color.g,s.color.b=e.color.b,s.color.a=e.color.a,s.layer=e.layer,s.material=e.material,t.has(n,Ms)){const e=t.get(n,Ms);s.size.x=e.size.x,s.size.y=e.size.y}if(s.uvOffset.x=0,s.uvOffset.y=0,s.uvScale.x=1,s.uvScale.y=1,e.imageType===pr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));e.fillMethod===gr.Horizontal?e.fillOrigin===yr.Left?(s.uvScale.x=t,s.size.x*=t):(s.uvOffset.x=1-t,s.uvScale.x=t,s.size.x*=t):e.fillOrigin===yr.Bottom?(s.uvScale.y=t,s.size.y*=t):(s.uvOffset.y=1-t,s.uvScale.y=t,s.size.y*=t)}t.insert(n,Pe,s)}},{name:"ImageSystem"}))}},wr=le("Toggle",{isOn:!0,graphicEntity:0,transition:null,enabled:!0});const xr=new class{build(e){ye("Toggle",wr);const t=e.world;e.addSystemToSchedule(et.Update,nt([He(Vs)],e=>{const n=t.getEntitiesWithComponents([wr]);for(const s of n){if(t.has(s,Hs)||t.insert(s,Hs,{enabled:!0}),!t.has(s,js))continue;const n=t.get(s,js),r=t.get(s,wr),o=t.get(s,Hs);if(n.justPressed&&o.enabled&&(r.isOn=!r.isOn,e.emit(s,"change")),r.graphicEntity&&t.valid(r.graphicEntity)){const e=r.graphicEntity;if(t.has(e,Pe)){const n=t.get(e,Pe);n.color.a=r.isOn?1:0,t.insert(e,Pe,n)}}if(r.transition&&t.has(s,Pe)){const e=t.get(s,Pe),i=r.transition;o.enabled?n.pressed?e.color={...i.pressedColor}:n.hovered?e.color={...i.hoveredColor}:e.color={...i.normalColor}:e.color={...i.disabledColor},t.insert(s,Pe,e)}}},{name:"ToggleSystem"}))}};var vr;!function(e){e[e.LeftToRight=0]="LeftToRight",e[e.RightToLeft=1]="RightToLeft",e[e.BottomToTop=2]="BottomToTop",e[e.TopToBottom=3]="TopToBottom"}(vr||(vr={}));const br=le("ProgressBar",{value:0,fillEntity:0,direction:vr.LeftToRight});const Sr=new class{build(e){ye("ProgressBar",br);const t=e.world;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{const e=t.getEntitiesWithComponents([br,Ms]);for(const n of e){const e=t.get(n,br);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=e.fillEntity;if(!t.has(s,Ms))continue;const r=t.get(s,Ms),o=Math.max(0,Math.min(1,e.value));switch(e.direction){case vr.LeftToRight:r.anchorMin={x:0,y:0},r.anchorMax={x:o,y:1};break;case vr.RightToLeft:r.anchorMin={x:1-o,y:0},r.anchorMax={x:1,y:1};break;case vr.BottomToTop:r.anchorMin={x:0,y:0},r.anchorMax={x:1,y:o};break;case vr.TopToBottom:r.anchorMin={x:0,y:1-o},r.anchorMax={x:1,y:1}}r.offsetMin={x:0,y:0},r.offsetMax={x:0,y:0},t.insert(s,Ms,r)}},{name:"ProgressBarSystem"}))}},Pr=le("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Mr=le("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}}),Tr=new Float32Array(16),Er=new Float32Array(16);let Cr=!0;function Rr(e,t,n){const s=e.mouseX*n,r=t.screenH-e.mouseY*n;return function(e){let t=!1;for(let n=0;n<16;n++)if(Er[n]!==e[n]){t=!0;break}t&&(Er.set(e),Cr=!0)}(t.viewProjection),Cr&&(ks(t.viewProjection,Tr),Cr=!1),$s(s,r,Tr,t.vpX,t.vpY,t.vpW,t.vpH)}const Ar=new class{build(e){ye("Draggable",Pr),ye("DragState",Mr);const t=e.world,n=e.getResource(Vs);let s=null,r={x:0,y:0},o=null;const i="undefined"!=typeof window&&window.devicePixelRatio||1;e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,a)=>{if(!a.valid)return;const l=Rr(e,a,i);if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Pr,js]);let n=null;for(const s of e){if(!t.get(s,Pr).enabled)continue;t.get(s,js).hovered&&(n=s)}if(null!==n){s=n,r={x:l.x,y:l.y},t.has(n,Mr)||t.insert(n,Mr);const e=t.get(n,Mr),o=t.get(n,Se);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:l.x,y:l.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Mr)){t.get(s,Mr).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=l.x-r.x,i=l.y-r.y,c=Math.sqrt(e*e+i*i),h=t.get(s,Pr);if(c*(a.vpW/(a.worldRight-a.worldLeft))>=h.dragThreshold){o=s,s=null;t.get(o,Mr).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Mr))return void(o=null);const s=t.get(o,Mr),r=t.get(o,Pr),i=l.x-s.pointerStartWorld.x,a=l.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+i,h=s.startWorldPos.y+a;const d=function(e,t,n,s){let r=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,s,c,h);c=d.x,h=d.y;const u=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-u,y:h-f},s.currentWorldPos={x:c,y:h},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:h-s.startWorldPos.y},t.has(o,be)){const e=function(e,t,n,s){if(!e.has(t,Ce))return{x:n,y:s};const r=e.get(t,Ce).entity;if(!e.valid(r)||!e.has(r,Se))return{x:n,y:s};const o=e.get(r,Se),i=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=2*Math.atan2(o.rotation.z,o.rotation.w),c=Math.sin(-l),h=Math.cos(-l);return{x:(n*h-s*c)/i,y:(n*c+s*h)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,be);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,be,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Fr=le("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const Ir=new class{build(e){ye("ScrollView",Fr);const t=e.world,n=new Map,s=new Float32Array(16),r="undefined"!=typeof window&&window.devicePixelRatio||1;let o=0;e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,i)=>{const a=performance.now()/1e3,l=o>0?Math.min(a-o,.05):0;if(o=a,!i.valid)return;const c=e.mouseX*r,h=i.screenH-e.mouseY*r;ks(i.viewProjection,s);const d=$s(c,h,s,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([Fr,Ms]);for(const s of u){t.has(s,Hs)||t.insert(s,Hs,{enabled:!0,blockRaycast:!0}),t.has(s,Fs)||t.insert(s,Fs,{enabled:!0,mode:"scissor"});const r=t.get(s,Fr),o=t.get(s,Ms);let i=n.get(s);i||(i={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},n.set(s,i));const a=t.has(s,js)?t.get(s,js):null;if(a?.justPressed&&(i.isDragging=!0,i.lastWorldX=d.x,i.lastWorldY=d.y,i.velocityX=0,i.velocityY=0),i.isDragging&&e.isMouseButtonDown(0)){const e=d.x-i.lastWorldX,t=d.y-i.lastWorldY;r.horizontalEnabled&&(r.scrollX-=e,i.velocityX=l>0?-e/l:0),r.verticalEnabled&&(r.scrollY-=t,i.velocityY=l>0?-t/l:0),i.lastWorldX=d.x,i.lastWorldY=d.y}if(i.isDragging&&e.isMouseButtonReleased(0)&&(i.isDragging=!1),a?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,i.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,i.velocityX=0)}if(!i.isDragging&&r.inertia&&l>0){const e=Math.pow(r.decelerationRate,l);r.horizontalEnabled&&Math.abs(i.velocityX)>.1?(r.scrollX+=i.velocityX*l,i.velocityX*=e):i.velocityX=0,r.verticalEnabled&&Math.abs(i.velocityY)>.1?(r.scrollY+=i.velocityY*l,i.velocityY*=e):i.velocityY=0}const c=o.size.x,h=o.size.y,u=Math.max(0,r.contentWidth-c),f=Math.max(0,r.contentHeight-h);if(r.scrollX=Math.max(0,Math.min(r.scrollX,u)),r.scrollY=Math.max(0,Math.min(r.scrollY,f)),0!==r.contentEntity&&t.valid(r.contentEntity)){const e=r.contentEntity;if(t.has(e,be)){const n=t.get(e,be);n.position.x=-r.scrollX,n.position.y=r.scrollY,t.insert(e,be,n)}}}},{name:"ScrollViewSystem"}))}};var Br;!function(e){e[e.LeftToRight=0]="LeftToRight",e[e.RightToLeft=1]="RightToLeft",e[e.BottomToTop=2]="BottomToTop",e[e.TopToBottom=3]="TopToBottom"}(Br||(Br={}));const kr=le("Slider",{value:0,minValue:0,maxValue:1,direction:Br.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1,enabled:!0});const $r=new class{build(e){ye("Slider",kr);const t=e.world,n=new Float32Array(16),s="undefined"!=typeof window&&window.devicePixelRatio||1;let r=null;e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,o)=>{if(!o.valid)return;const i=e.mouseX*s,a=o.screenH-e.mouseY*s;ks(o.viewProjection,n);const l=$s(i,a,n,o.vpX,o.vpY,o.vpW,o.vpH),c=t.getEntitiesWithComponents([kr,Ms,Se]);for(const n of c){t.has(n,Hs)||t.insert(n,Hs,{enabled:!0,blockRaycast:!0});const s=t.get(n,kr),o=t.get(n,Ms),i=t.get(n,Se),a=t.has(n,js)?t.get(n,js):null;if(a?.justPressed&&(r=n),r===n&&e.isMouseButtonDown(0)){const e=o.size.x*i.scale.x,t=o.size.y*i.scale.y,n=i.position.x-o.pivot.x*e,r=i.position.y-o.pivot.y*t;let a;switch(s.direction){case Br.LeftToRight:a=e>0?(l.x-n)/e:0;break;case Br.RightToLeft:a=e>0?1-(l.x-n)/e:0;break;case Br.BottomToTop:a=t>0?(l.y-r)/t:0;break;case Br.TopToBottom:a=t>0?1-(l.y-r)/t:0}a=Math.max(0,Math.min(1,a));let c=s.minValue+a*(s.maxValue-s.minValue);s.wholeNumbers&&(c=Math.round(c)),s.value=Math.max(s.minValue,Math.min(s.maxValue,c))}r===n&&e.isMouseButtonReleased(0)&&(r=null);const c=s.maxValue-s.minValue,h=c>0?(s.value-s.minValue)/c:0;if(0!==s.fillEntity&&t.valid(s.fillEntity)){const e=s.fillEntity;if(t.has(e,Ms)){const n=t.get(e,Ms);switch(s.direction){case Br.LeftToRight:n.anchorMin={x:0,y:0},n.anchorMax={x:h,y:1};break;case Br.RightToLeft:n.anchorMin={x:1-h,y:0},n.anchorMax={x:1,y:1};break;case Br.BottomToTop:n.anchorMin={x:0,y:0},n.anchorMax={x:1,y:h};break;case Br.TopToBottom:n.anchorMin={x:0,y:1-h},n.anchorMax={x:1,y:1}}t.insert(e,Ms,n)}}if(0!==s.handleEntity&&t.valid(s.handleEntity)){const e=s.handleEntity;if(t.has(e,Ms)){const n=t.get(e,Ms);switch(s.direction){case Br.LeftToRight:n.anchorMin={x:h,y:0},n.anchorMax={x:h,y:1};break;case Br.RightToLeft:n.anchorMin={x:1-h,y:0},n.anchorMax={x:1-h,y:1};break;case Br.BottomToTop:n.anchorMin={x:0,y:h},n.anchorMax={x:1,y:h};break;case Br.TopToBottom:n.anchorMin={x:0,y:1-h},n.anchorMax={x:1,y:1-h}}t.insert(e,Ms,n)}}}},{name:"SliderSystem"}))}},Wr=le("Focusable",{tabIndex:0,isFocused:!1});class Dr{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Ur=Oe(new Dr,"FocusManager");const zr=new class{build(e){ye("Focusable",Wr);const t=e.world,n=new Dr;e.insertResource(Ur,n),e.addSystemToSchedule(et.Update,nt([He(ct),He(Vs)],(e,s)=>{const r=t.getEntitiesWithComponents([Wr]);for(const e of r){if(!t.has(e,js))continue;t.get(e,js).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of r){const s=t.get(n,Wr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const i=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?s.length-1:0:a?(i-1+s.length)%s.length:(i+1)%s.length,o(s[l])}function o(e){const r=n.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,Wr)){t.get(r,Wr).isFocused=!1,s.emit(r,"hover_exit",r)}n.focus(e);t.get(e,Wr).isFocused=!0,s.emit(e,"hover_enter",e)}},{name:"FocusSystem"}))}},Lr=le("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});const Or=new class{build(e){ye("SafeArea",Lr);const t=e.world;let n={top:0,bottom:0,left:0,right:0},s=0;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{s++%60==0&&(n=function(){if("undefined"==typeof document)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}());const e=t.getEntitiesWithComponents([Lr,Ms]);for(const s of e){const e=t.get(s,Lr),r=t.get(s,Ms);let o=!1;const i=e.applyTop?n.top:0,a=e.applyBottom?n.bottom:0,l=e.applyLeft?n.left:0,c=e.applyRight?n.right:0;r.offsetMin.x===l&&r.offsetMin.y===a||(r.offsetMin={x:l,y:a},o=!0),r.offsetMax.x===-c&&r.offsetMax.y===-i||(r.offsetMax={x:-c,y:-i},o=!0),o&&t.insert(s,Ms,r)}},{name:"SafeAreaSystem"}))}},Hr=le("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2}),jr=new Map;function Xr(e,t){const n=jr.get(e);n&&(n.renderer=t)}const Yr=new class{build(e){ye("ListView",Hr);const t=e.world;e.addSystemToSchedule(et.PreUpdate,nt([He(ct)],e=>{const n=t.getEntitiesWithComponents([Hr,Ms]);for(const s of n){t.has(s,Hs)||t.insert(s,Hs,{enabled:!0,blockRaycast:!0}),t.has(s,Fs)||t.insert(s,Fs,{enabled:!0,mode:"scissor"});let n=jr.get(s);n||(n={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},jr.set(s,n));const r=t.get(s,Hr),o=t.get(s,Ms),i=o.size.y,a=t.has(s,js)?t.get(s,js):null;if(a?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}const l=Math.max(0,r.itemCount*r.itemHeight-i);r.scrollY=Math.max(0,Math.min(r.scrollY,l));const c=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+i)/r.itemHeight)+r.overscan);for(const[e,s]of n.itemEntities)(e<c||e>=h)&&(t.valid(s)&&t.despawn(s),n.itemEntities.delete(e));for(let e=c;e<h;e++){let i=n.itemEntities.get(e);if(i&&t.valid(i)||(i=t.spawn(),t.insert(i,Ie,{value:`ListItem_${e}`}),t.insert(i,Ms,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o.size.x,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(i,s),n.itemEntities.set(e,i),n.renderer&&n.renderer(e,i)),t.has(i,be)){const n=t.get(i,be);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(i,be,n)}}n.visibleStart=c,n.visibleEnd=h}},{name:"ListViewSystem"}))}},Nr=le("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Vr=new class{build(e){ye("Dropdown",Nr);const t=e.world;e.addSystemToSchedule(et.Update,nt([He(ct),He(Vs)],(e,n)=>{const s=t.getEntitiesWithComponents([Nr]);for(const o of s){t.has(o,Hs)||t.insert(o,Hs,{enabled:!0,blockRaycast:!0});const s=t.get(o,Nr),i=t.has(o,js)?t.get(o,js):null;if(i?.justPressed&&(s.isOpen=!s.isOpen,r(s.listEntity,s.isOpen),n.emit(o,"change",o)),s.isOpen&&e.isMouseButtonPressed(0)&&!i?.hovered){0!==s.listEntity&&t.valid(s.listEntity)&&t.has(s.listEntity,js)&&t.get(s.listEntity,js).hovered||(s.isOpen=!1,r(s.listEntity,!1))}}function r(e,n){if(0===e)return;const s=e;if(!t.valid(s)||!t.has(s,be))return;const r=t.get(s,be),o=n?1:0;r.scale={x:o,y:o,z:o},t.insert(s,be,r)}},{name:"DropdownSystem"}))}};async function qr(e,t,n){const s=e.getResource(rs);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Gr(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 Jr=Oe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Kr=Oe(null,"PhysicsAPI");function Qr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Zr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class eo{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Jr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Gr(this.wasmUrl_,this.factory_).then(s=>{s._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([Te]);for(const n of t){const t=e.world.get(n,Te);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(et.PostUpdate,nt([He(Ne)],a=>{const l=i.getEntitiesWithComponents([$e,be,Se]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,$e),l=i.get(r,Se);if(t.has(r)){const e=n.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||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Qr(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),to(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ze.Kinematic){const e=Qr(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const h=e.world.get(i,be);if(!h)continue;let d=a,u=l,f=c;if(e.world.has(i,Ce)){const t=e.world.get(i,Ce);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Se)){const n=e.world.get(t.entity,Se),s=Qr(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),h=Math.sin(-s);d=(r*i-o*h)/(0!==n.scale.x?n.scale.x:1),u=(r*h+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}h.position.x=d,h.position.y=u;const p=Zr(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(i,be,h)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.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]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<h;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Jr,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Kr,no._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function to(e,t,n){const s=e.world;if(s.has(n,We)){const e=s.get(n,We);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,De)){const e=s.get(n,De);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,Ue)){const e=s.get(n,Ue);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class no{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(no.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 so(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function ro(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function oo(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,h=e.rotation.w,d=a+a,u=l+l,f=c+c,p=a*d,g=a*u,y=a*f,m=l*u,_=l*f,w=c*f,x=h*d,v=h*u,b=h*f;return new Float32Array([(1-(m+w))*r,(g+b)*r,(y-v)*r,0,(g-b)*o,(1-(p+w))*o,(_+x)*o,0,(y+v)*i,(_-x)*i,(1-(p+m))*i,0,e.position.x,e.position.y,e.position.z,1])}async function io(e,t,n,s,r,o,i,a,l){const c=await async function(e,t,n){const s={};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!==s[r])continue;try{s[r]=so(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let h={},d=null;if(r&&(d=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=await r.readText(a),h="binary"===x(l)?.contentType;let d,u;if(h){const e=await r.readBinary(i);u=e.length,d=t._malloc(u),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),n=(new TextEncoder).encode(e);u=n.length,d=t._malloc(u+1),t.HEAPU8.set(n,d),t.HEAPU8[d+u]=0}const f=n.loadSkeleton(d,u,s,s.length,h);if(t._free(d),f<0)continue;o[i]=f;const p=ro(s),g=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=so(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,d,n,s)),o){new eo("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=await async function(e,t,n){const s={};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===s[r])try{let t,o;const i=x(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),h=so(e,c,!1),d=e.getResourceManager();s[r]=d.loadBitmapFont(t,h,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};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===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=At.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=At.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const r={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Xt(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=r[e.type][n[e.field]]||0)}}(n,c,u,f);const p=Yt(e.world,n);if(l&&e.hasResource(rs))for(const t of p.values())e.world.insert(t,Be,{scene:l,persistent:!1});if(r&&d){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=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}(d,n,h,p);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,Fe)?c.get(o,Fe):null,h=!1!==a?.playing,d=a?.timeScale??1;h&&s.update(i,l*d);let u=0;if(c.has(o,Se)){const e=oo(c.get(o,Se),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);u=t._malloc(64),t.HEAPF32.set(e,u>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),h=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,h,d,f);const p=n.HEAPU32[d>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*r),m=new Uint16Array(n.HEAPU8.buffer,h,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(m),t.renderer_submitTriangles(_,r,w,o,p,g,u),t._free(_),t._free(w),n._free(c),n._free(h),n._free(d),n._free(f)}u&&t._free(u)}})}(e,t,r,d,s)}if(a){const t=e.getResource(Kt);t&&t.setAddressableManifest(a)}}function ao(e,t,n){return{name:e,data:t,async setup(){await io(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class lo{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===x(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.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 n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){const t=x(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const co="__preview__";class ho{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(rs);t.register({name:co,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(co),this.loadPromise_=t.load(co).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new lo(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await io(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,co)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Me]);for(const s of n){if(e.get(s,Me).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([Te]);for(const r of s){const s=e.get(r,Te);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=this.app_.getResource(rs).getScene(co),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,be,i);const a={isActive:!0,projectionType:we.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:xe.ColorAndDepth};e.insert(o,Me,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(rs);await e.switchTo(co),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const uo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=qn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:qn.getTargetTexture(n),width:e.width,height:e.height}},release(e){qn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(qn.releaseRenderTarget(e._handle),uo.create({width:t,height:n,depth:!0})),begin(e,t){qn.begin(t,e._handle)},end(){qn.end()},getDepthTexture:e=>qn.getTargetDepthTexture(e._handle)};let fo=!1;function po(e){fo=e}function go(){return fo}function yo(){return!fo}var mo;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(mo||(mo={}));class _o{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${mo[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case mo.Debug:console.debug(t,n);break;case mo.Info:console.log(t,n);break;case mo.Warn:console.warn(t,n);break;case mo.Error:console.error(t,n)}}}class wo{constructor(){this.handlers_=[],this.minLevel_=mo.Info,this.addHandler(new _o)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(mo.Debug,e,t,n)}info(e,t,n){this.log(mo.Info,e,t,n)}warn(e,t,n){this.log(mo.Warn,e,t,n)}error(e,t,n){this.log(mo.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const xo=new wo;function vo(){return xo}function bo(e){xo.setMinLevel(e)}function So(e,t,n){xo.debug(e,t,n)}function Po(e,t,n){xo.info(e,t,n)}function Mo(e,t,n){xo.warn(e,t,n)}function To(e,t,n){xo.error(e,t,n)}const Eo=[As,Os,tr,_r,Sr,lr,Ar,Ir,$r,xr,fr,zr,Or,Yr,Vr];function Co(e,t){return function(e,t){const n=ls.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),yn(e),Et(e),Bn(e),Un(e),Nn(e),Jn(e);const r=new Zn;n.setPipeline(r);let o=u();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=us(e,s,t,r));const i=n.getResource(xt);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(xt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=i();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;qn.setClearColor(e.x,e.y,e.z,e.w)}const h=(u()-o)/1e3;let d;if(qn.resize(t,l),On.isInitialized()&&On.getPassCount()>0&&!On.isBypassed()&&On.resize(t,l),n.hasResource(rs)){const e=n.getResource(rs).getActiveScenes();e.length>0&&(d=new Set(e))}r.setActiveScenes(d??null);const f=us(e,s,t,l,n.world,d);if(a(t,l,f),0===f.length)r.render({registry:{_cpp:s},viewProjection:hs,width:t,height:l,elapsed:h});else{for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),i=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:c},clearFlags:e.clearFlags,elapsed:h})}qn.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(et.First,l),n.addSystemToSchedule(et.Last,c),n.addPlugin(Zt),n.addPlugin(hn),n.addPlugin(dt),n.addPlugin(as),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Eo,...t})}H||(H=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(n,s);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n[s++]=r:r<2048?(n[s++]=192|r>>6,n[s++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,n[s++]=240|r>>18,n[s++]=128|r>>12&63,n[s++]=128|r>>6&63,n[s++]=128|63&r):(n[s++]=224|r>>12,n[s++]=128|r>>6&63,n[s++]=128|63&r)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=j;export{ls as App,Qt as AssetPlugin,en as AssetRefCounter,Jt as AssetServer,Kt as Assets,zt as AsyncCache,Ae as BitmapText,vt as BlendMode,ze as BodyType,We as BoxCollider,Ys as Button,Xs as ButtonState,Me as Camera,Te as Canvas,Ue as CapsuleCollider,Re as Children,De as CircleCollider,xe as ClearFlags,Ke as Commands,Ze as CommandsInstance,Y as DEFAULT_DESIGN_HEIGHT,X as DEFAULT_DESIGN_WIDTH,N as DEFAULT_PIXELS_PER_UNIT,V as DEFAULT_TEXT_CANVAS_SIZE,Cn as DataType,Mr as DragState,Pr as Draggable,xn as Draw,Nr as Dropdown,Qe as EntityCommands,gr as FillMethod,yr as FillOrigin,Ur as FocusManager,Dr as FocusManagerState,Wr as Focusable,Qn as GLDebug,Wn as Geometry,J as INVALID_ENTITY,Q as INVALID_FONT,K as INVALID_TEXTURE,mr as Image,pr as ImageType,ct as Input,ht as InputPlugin,lt as InputState,Hs as Interactable,Hr as ListView,be as LocalTransform,mo as LogLevel,wo as Logger,At as Material,Lt as MaterialLoader,Ve as Mut,Ie as Name,Ce as Parent,no as Physics,Jr as PhysicsEvents,eo as PhysicsPlugin,On as PostProcess,an as PrefabServer,ln as Prefabs,cn as PrefabsPlugin,ho as PreviewPlugin,br as ProgressBar,vr as ProgressBarDirection,we as ProjectionType,Ge as Query,Je as QueryInstance,Zn as RenderPipeline,jn as RenderStage,uo as RenderTexture,qn as Renderer,He as Res,je as ResMut,$e as RigidBody,q as RuntimeConfig,Lr as SafeArea,ve as ScaleMode,rs as SceneManager,ss as SceneManagerState,Be as SceneOwner,et as Schedule,qs as ScreenSpace,Fr as ScrollView,Ut as ShaderSources,kr as Slider,Br as SliderDirection,Fe as SpineAnimation,Pe as Sprite,at as SystemRunner,Ps as Text,vs as TextAlign,cr as TextInput,hr as TextInputPlugin,Ss as TextOverflow,Rs as TextPlugin,Ts as TextRenderer,bs as TextVerticalAlign,Ne as Time,wr as Toggle,xt as UICameraInfo,Ns as UIEventQueue,Vs as UIEvents,js as UIInteraction,ar as UIInteractionPlugin,er as UILayoutPlugin,Fs as UIMask,Ls as UIMaskPlugin,Ms as UIRect,Ee as Velocity,lo as WebAssetProvider,wt as World,Se as WorldTransform,ot as addStartupSystem,rt as addSystem,it as addSystemToSchedule,G as applyRuntimeConfig,Zt as assetPlugin,En as clearDrawCallbacks,de as clearUserComponents,ne as color,Gs as computeUIRectLayout,zs as createMaskProcessor,ao as createRuntimeSceneConfig,Co as createWebApp,So as debug,le as defineComponent,Oe as defineResource,nt as defineSystem,ce as defineTag,To as error,Gt as findEntityByName,cs as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,M as getAllAssetExtensions,R as getAssetMimeType,x as getAssetTypeEntry,me as getComponent,jt as getComponentAssetFields,ke as getComponentDefaults,E as getCustomExtensions,v as getEditorType,vo as getLogger,t as getPlatform,s as getPlatformType,he as getUserComponent,C as getWeChatPackOptions,Po as info,yn as initDrawAPI,Jn as initGLDebugAPI,Bn as initGeometryAPI,Et as initMaterialAPI,Un as initPostProcessAPI,Nn as initRendererAPI,dt as inputPlugin,nn as instantiatePrefab,Is as intersectRects,ks as invertMatrix4,pe as isBuiltinComponent,A as isCustomExtension,go as isEditor,P as isKnownAssetExtension,n as isPlatformInitialized,yo as isRuntime,bt as isTextureRef,r as isWeChat,o as isWeb,Vt as loadComponent,Gr as loadPhysicsModule,io as loadRuntimeScene,Yt as loadSceneData,Nt as loadSceneWithAssets,T as looksLikeAssetPath,i as platformFetch,c as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ds as pointInOBB,Ws as pointInWorldRect,hn as prefabsPlugin,se as quat,ye as registerComponent,Ht as registerComponentAssetFields,Mn as registerDrawCallback,tn as registerEmbeddedAssets,Dt as registerMaterialCallback,as as sceneManagerPlugin,$s as screenToWorld,po as setEditorMode,Xr as setListViewRenderer,bo as setLogLevel,yt as setWasmErrorHandler,mn as shutdownDrawAPI,Kn as shutdownGLDebugAPI,kn as shutdownGeometryAPI,Ct as shutdownMaterialAPI,zn as shutdownPostProcessAPI,Vn as shutdownRendererAPI,fr as textInputPlugin,As as textPlugin,qr as transitionTo,lr as uiInteractionPlugin,tr as uiLayoutPlugin,Os as uiMaskPlugin,Eo as uiPlugins,ue as unregisterComponent,Tn as unregisterDrawCallback,qt as updateCameraAspectRatio,Z as vec2,ee as vec3,te as vec4,Mo as warn,Bs as worldRectToScreen,os as wrapSceneSystem,W as wxFileExists,D as wxFileExistsSync,L as wxGetImagePixels,z as wxLoadImage,O as wxLoadImagePixels,k as wxReadFile,$ as wxReadTextFile,U as wxWriteFile};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function h(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function u(){return t().now()}function f(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const g=[{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}],y={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",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"},m=new Map,_=new Set;for(const e of g)for(const t of e.extensions)m.set(t,e),_.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function x(e){return m.get(w(e))}function v(e){return x(e)?.editorType??"unknown"}function b(e){return x(e)?.addressableType??null}function S(e){for(const t of g)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return _.has(e.toLowerCase())}function M(){return _}function E(e){return"string"==typeof e&&(!!e.includes("/")&&P(w(e)))}function T(){const e=[];for(const t of g)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function C(){return T().map(e=>({type:"suffix",value:e}))}function A(e){return y[e.toLowerCase()]}function R(e){const t=x(e);return t?.wechatPackInclude??!1}let I=null;function F(){return I||(I=wx.getFileSystemManager()),I}function k(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(R(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function B(e){return new Promise((t,n)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(k(e,t.errMsg)))}})})}function z(e,t="utf-8"){return new Promise((n,s)=>{F().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(k(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function U(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function W(e,t){return new Promise((n,s)=>{F().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function D(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function L(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}async function O(e){return L(await D(e))}let H=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return B(e)}async readTextFile(e){return z(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:n}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX*n,s.clientY*n)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX*n,s.clientY*n)}),wx.onTouchEnd(t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)})}},X=1920,Y=1080,N=100,V=512,G={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function q(e){e.Text&&(e.Text._default.fontFamily=G.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=G.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=G.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=G.canvasMatchWidthOrHeight)}const J=0,K=4294967295,Q=4294967295,Z=(e=0,t=0)=>({x:e,y:t}),ee=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),te=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),ne=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),se=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function re(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(re);const t={};for(const n in e)t[n]=re(e[n]);return t}let ie=0;function oe(e,t){const n=++ie;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...re(t),...e}:re(t)}}function ae(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function le(e,t){const n=ae(),s=n.get(e);if(s)return s;const r=oe(e,t);return n.set(e,r),fe(e,t,!1),r}function ce(e){const t=ae(),n=t.get(e);if(n)return n;const s=oe(e,{});return t.set(e,s),fe(e,{},!0),s}function he(e){return ae().get(e)}function de(){ae().clear()}function ue(e){ae().delete(e)}function fe(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function pe(e){return!0===e._builtin}const ge=new Map;function ye(e,t){ge.set(e,t)}function me(e){return ge.get(e)??he(e)}function _e(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return ge.set(e,n),n}const we={Perspective:0,Orthographic:1},xe={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ve={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},be=_e("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Se=_e("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Pe=_e("Sprite",{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Me=_e("Camera",{projectionType:we.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:xe.ColorAndDepth}),Ee=_e("Canvas",{designResolution:{x:X,y:Y},pixelsPerUnit:100,scaleMode:ve.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Te=_e("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ce=_e("Parent",{entity:0}),Ae=_e("Children",{entities:[]}),Re=_e("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:Q,enabled:!0}),Ie=_e("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),Fe={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ke=le("SceneOwner",{scene:"",persistent:!1});function Be(e){const t=me(e);return t?re(t._default):null}ye("Name",Fe);const ze=_e("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),$e=_e("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ue=_e("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),We=_e("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),De={Static:0,Kinematic:1,Dynamic:2};let Le=0;function Oe(e,t){const n=++Le;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function He(e){return{_type:"res",_resource:e}}function je(e){return{_type:"res_mut",_resource:e}}class Xe{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 Ye{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 Xe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ne=Oe({delta:0,elapsed:0,frameCount:0},"Time");function Ve(e){return{_type:"mut",_component:e}}function Ge(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function qe(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{Ge(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class Je{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_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=n.length,i=e.length>0,o=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let h=null;this.world_.beginIteration();try{for(const d of s){if(null!==h&&i)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}if(o){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(i){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];h=d}yield a}}finally{if(this.world_.endIteration(),null!==h&&i)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){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 Ke(){return{_type:"commands"}}class Qe{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=pe(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Ze{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Qe(this,null);return this.spawned_.push(e),e}entity(e){return new Qe(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var et;!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"}(et||(et={}));let tt=0;function nt(e,t,n){const s=++tt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function st(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function rt(e){st().push({schedule:et.Update,system:e})}function it(e){st().push({schedule:et.Startup,system:e})}function ot(e,t){st().push({schedule:e,system:t})}class at{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 n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ze&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new Je(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ze(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class lt{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 ct=Oe(new lt,"Input");class ht{constructor(e){this.target_=e??null}build(e){const n=new lt;e.insertResource(ct,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(et.Last,nt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const dt=new ht;function ut(e,t,n){const s=[];for(const[e,r]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const n=ft(t[e]),i=ft(r);"null"!==n&&"undefined"!==n&&(n!==i&&null!=r&&s.push({field:e,expected:n,actual:i,value:r}))}return s}function ft(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function pt(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let gt=null;function yt(e){gt=e}function mt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),gt&&gt(e,t)}function _t(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="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}:_t(e)}}return t}class wt{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 mt(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){mt(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t)this.tsStorage_.get(n)?.delete(e);this.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(n){mt(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){mt(t,`removeParent(entity=${e})`)}}insert(e,t,n){return pe(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return pe(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return pe(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(pe(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return mt(n,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");pe(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=ut(t._name,t._default,s);if(e.length>0)throw new Error(pt(t._name,e))}const r={...t._default,...s};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,_t(r))}catch(n){mt(n,`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(n){return mt(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return mt(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){mt(n,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const r=ut(t._name,t._default,e);if(r.length>0)throw new Error(pt(t._name,r));s=e}const r=t.create(s);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 n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.push(n)}catch{}if(this.cppRegistry_)for(const[n,s]of ge)if(pe(s)&&!t.includes(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.push(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const s of n)for(const[n,r]of e)if(r._id===s){t.push(n);break}}return t}getEntitiesWithComponents(e,t=[],n=[]){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();let s=e.map(e=>e._name).sort().join(",");t.length>0&&(s+="|+"+t.map(e=>e._name).sort().join(",")),n.length>0&&(s+="|-"+n.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(s);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!pe(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<o&&(o=n,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=i?i.keys():this.entities_;for(const t of l){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&a.push(t)}return this.queryCache_.set(s,{version:this.worldVersion_,result:a}),a}}const xt=Oe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var vt;function bt(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"}(vt||(vt={}));let St=null,Pt=null,Mt=1;const Et=new Map;function Tt(e){St=e,Pt=e.getResourceManager(),Ut()}function Ct(){0!==Ft&&St&&(St._free(Ft),Ft=0),Et.clear(),Mt=1,It=!1,Bt.clear(),zt=null,Pt=null,St=null}function At(){if(!Pt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Pt}const Rt={createShader:(e,t)=>At().createShader(e,t),releaseShader(e){e>0&&At().releaseShader(e)},create(e){const t=Mt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??vt.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Et.set(t,n),t},get:e=>Et.get(e),setUniform(e,t,n){const s=Et.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=Et.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Et.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Et.get(e);return t?.blendMode??vt.Normal},setDepthTest(e,t){const n=Et.get(e);n&&(n.depthTest=t)},getShader(e){const t=Et.get(e);return t?.shader??0},release(e){Et.delete(e)},isValid:e=>Et.has(e),releaseAll(){Et.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??vt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Et.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Mt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Et.set(n,s),n},toAssetData(e,t){const n=Et.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=Et.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let It=!1,Ft=0;const kt=4096,Bt=new Map;let zt=null;function $t(e){const t=(0===Ft&&St&&(Ft=St._malloc(kt)),Ft);if(0===t||!St)return{ptr:0,count:0};let n=0,s=0;const r=St.HEAPU8,i=St.HEAPU32,o=St.HEAPF32;for(const[a,l]of e){if(n+128>kt)break;let e=Bt.get(a);e||(zt||(zt=new TextEncoder),e=zt.encode(a),Bt.set(a,e));const c=e.length,h=4*Math.ceil(c/4);i[t+n>>2]=c,n+=4,r.set(e,t+n),n+=h;let d=0,u=[0,0,0,0];if("number"==typeof l)d=0,u[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)u[e]=l[e]}else"w"in l?(d=3,u=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,u=[l.x,l.y,l.z,0]):"y"in l&&(d=1,u=[l.x,l.y,0,0]);i[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=u[e],n+=4;s++}return{ptr:t,count:s}}function Ut(){if(!St||It)return;St.materialDataProvider=(e,t,n,s,r)=>{const i=Et.get(e);if(!i)return St.HEAPU32[t>>2]=0,St.HEAPU32[n>>2]=0,St.HEAPU32[s>>2]=0,void(St.HEAPU32[r>>2]=0);St.HEAPU32[t>>2]=i.shader,St.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=$t(i.uniforms);St.HEAPU32[s>>2]=o,St.HEAPU32[r>>2]=a},It=!0}const Wt={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 Dt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{i.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);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 Dt,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&&(Rt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Rt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),i=await this.shaderLoader_.load(r);return{handle:Rt.createFromAsset(s,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 n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const Ot=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}]]);function Ht(e,t){Ot.set(e,t)}function jt(e){const t=Ot.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function Xt(e){return Ot.get(e)?.fields??[]}function Yt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Fe,{value:s.name}),!1!==s.visible)for(const n of s.components)Vt(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)}return n}async function Nt(e,t,n){const s=new Map,r=n?.assetServer,i=n?.assetBaseUrl,o=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[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 c=new Map,h=new Map,d=new Map,u=[];for(const e of r)u.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,i=await t.loadTexture(r);c.set(e,i.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of i)u.push((async()=>{try{const s=await t.loadMaterial(e,n);h.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of o)u.push((async()=>{try{const s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)u.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(u);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=h.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,r,i,o);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Fe,{value:n.name}),!1!==n.visible)for(const s of n.components)Vt(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)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Vt(e,t,n,s){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=me(n.type);if(r)e.insert(t,r,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function Gt(e,t){const n=e.getEntitiesWithComponents([Me]);for(const s of n){const n=e.get(s,Me);n&&(n.aspectRatio=t,e.insert(s,Me,n))}}function qt(e,t){const n=e.getEntitiesWithComponents([Fe]);for(const s of n){const n=e.get(s,Fe);if(n&&n.value===t)return s}return null}class Jt{constructor(e){this.textureCache_=new Dt,this.shaderCache_=new Dt,this.jsonCache_=new Dt,this.textCache_=new Dt,this.binaryCache_=new Dt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Dt,this.prefabCache_=new Dt,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_=d(G.textCanvasSize,G.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,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);if(!r)continue;const i=(this.textureRefCounts_.get(s)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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(),Rt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),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),l=[];for(const e of a){const t=o?`${o}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),h="binary"===x(e)?.contentType,d=h?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,i,h);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${s}`:s,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Nt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,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,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),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 l=o.createTexture(t,n,a,i.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Rt.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(s);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return Rt.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){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 n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Kt=Oe(null,"Assets");class Qt{build(e){const t=e.wasmModule;t?e.insertResource(Kt,new Jt(t)):console.warn("AssetPlugin: No WASM module available")}}const Zt=new Qt;class en{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function tn(e,t){const n=e.getResource(Kt);n&&n.registerEmbeddedAssets(t)}async function nn(e,t,n){const{entities:s,rootId:r}=await rn(t,n?.overrides??[],n,void 0,new Set),i={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await Nt(e,i,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=o.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:o}}const sn=10;async function rn(e,t,n,s,r,i=0){if(i>sn)throw new Error(`Prefab nesting depth exceeded ${sn}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await rn(e,s.nestedPrefab.overrides,n,a,r,i+1);o.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?o.get(s.parent)??null:null),l.push(...t.entities);continue}const c=o.get(s.prefabEntityId),h=s.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:h?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};on(d,t),l.push(d)}const c=o.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function on(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class an{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return nn(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ln=Oe(null,"Prefabs");class cn{constructor(){this.name="PrefabsPlugin",this.dependencies=[Kt]}build(e){const t=e.getResource(Kt);e.insertResource(ln,new an(e.world,t))}}const hn=new cn;let dn=null,un=0,fn=0,pn=0;const gn=new Float32Array(256);function yn(e){dn=e,un=dn._malloc(64),fn=dn._malloc(64),pn=dn._malloc(1024)}function mn(){dn&&(un&&(dn._free(un),un=0),fn&&(dn._free(fn),fn=0),pn&&(dn._free(pn),pn=0)),dn=null}function _n(){if(!dn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return dn}const wn={r:1,g:1,b:1,a:1},xn={begin(e){const t=_n();try{t.HEAPF32.set(e,un/4),t.draw_begin(un)}catch(e){mt(e,"Draw.begin")}},end(){try{_n().draw_end()}catch(e){mt(e,"Draw.end")}},line(e,t,n,s=1){try{_n().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){mt(e,"Draw.line")}},rect(e,t,n,s=!0){try{_n().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){mt(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{_n().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){mt(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,r=32){try{_n().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){mt(e,"Draw.circle")}},circleOutline(e,t,n,s=1,r=32){try{_n().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){mt(e,"Draw.circleOutline")}},texture(e,t,n,s=wn){try{_n().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){mt(e,"Draw.texture")}},textureRotated(e,t,n,s,r=wn){try{_n().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)}catch(e){mt(e,"Draw.textureRotated")}},setLayer(e){_n().draw_setLayer(e)},setDepth(e){_n().draw_setDepth(e)},getDrawCallCount:()=>dn?dn.draw_getDrawCallCount():0,getPrimitiveCount:()=>dn?dn.draw_getPrimitiveCount():0,setBlendMode(e){_n().draw_setBlendMode(e)},setDepthTest(e){_n().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=_n();s.HEAPF32.set(n,fn/4),s.draw_mesh(e,t,fn)}catch(n){mt(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=_n(),r=Rt.get(t);if(!r)return;if(xn.setBlendMode(r.blendMode),xn.setDepthTest(r.depthTest),0===r.uniforms.size)return void xn.drawMesh(e,r.shader,n);let i;if(s.HEAPF32.set(n,fn/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,n]of r.uniforms){const s=Sn(t);if(!(s<0)){if(bt(n))gn[i++]=10,gn[i++]=s,gn[i++]=n.slot??e++,gn[i++]=n.textureId;else if("number"==typeof n)gn[i++]=1,gn[i++]=s,gn[i++]=n;else if(Array.isArray(n)){gn[i++]=n.length,gn[i++]=s;for(let e=0;e<n.length;e++)gn[i++]=n[e]}else"w"in n?(gn[i++]=4,gn[i++]=s,gn[i++]=n.x,gn[i++]=n.y,gn[i++]=n.z,gn[i++]=n.w):"z"in n?(gn[i++]=3,gn[i++]=s,gn[i++]=n.x,gn[i++]=n.y,gn[i++]=n.z):(gn[i++]=2,gn[i++]=s,gn[i++]=n.x,gn[i++]=n.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(gn.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}if(0===i)return void s.draw_mesh(e,r.shader,fn);s.HEAPF32.set(r.cachedBuffer_.subarray(0,i),pn/4),s.draw_meshWithUniforms(e,r.shader,fn,pn,i)}catch(n){mt(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},vn={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},bn=new Set;function Sn(e){const t=vn[e];return void 0!==t?t:(bn.has(e)||(bn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(vn).join(", ")}`)),-1)}const Pn=new Map;function Mn(e,t,n){Pn.set(e,{fn:t,scene:n??""})}function En(e){Pn.delete(e)}function Tn(){Pn.clear()}var Cn;!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"}(Cn||(Cn={}));let An=null,Rn=0,In=0,Fn=0;function kn(e){An=e,Rn=An._malloc(262144),In=An._malloc(65536),Fn=An._malloc(256)}function Bn(){An&&(Rn&&An._free(Rn),In&&An._free(In),Fn&&An._free(Fn),Rn=0,In=0,Fn=0),An=null}function zn(){if(!An)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return An}const $n={create(e){const t=zn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Rn/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,Fn,r).set(i),t.geometry_init(n,Rn,s,Fn,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,In,s).set(e.indices),t.geometry_setIndices16(n,In,s)}else{new Uint32Array(t.HEAPU8.buffer,In,s).set(e.indices),t.geometry_setIndices32(n,In,s)}}return n},updateVertices(e,t,n=0){const s=zn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Rn/4),s.geometry_updateVertices(e,Rn,r,n)},release(e){e>0&&zn().geometry_release(e)},isValid:e=>!(!An||e<=0)&&An.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return $n.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:Cn.Float2},{name:"a_texCoord",type:Cn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(i,o,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return $n.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Cn.Float2},{name:"a_texCoord",type:Cn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(r-n);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 $n.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:Cn.Float2},{name:"a_texCoord",type:Cn.Float2}],indices:new Uint16Array(o)})}};let Un=null;function Wn(e){Un=e}function Dn(){Un&&On.isInitialized()&&On.shutdown(),Un=null}function Ln(){if(!Un)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Un}const On={init(e,t){try{return Ln().postprocess_init(e,t)}catch(n){return mt(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ln().postprocess_shutdown()}catch(e){mt(e,"PostProcess.shutdown")}},resize(e,t){try{Ln().postprocess_resize(e,t)}catch(n){mt(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ln().postprocess_addPass(e,t)}catch(t){return mt(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ln().postprocess_removePass(e)}catch(t){mt(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ln().postprocess_setPassEnabled(e,t)}catch(t){mt(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ln().postprocess_isPassEnabled(e)}catch(t){return mt(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Ln().postprocess_setUniformFloat(e,t,n)}catch(n){mt(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Ln().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){mt(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ln().postprocess_begin()}catch(e){mt(e,"PostProcess.begin")}},end(){try{Ln().postprocess_end()}catch(e){mt(e,"PostProcess.end")}},getPassCount(){try{return Ln().postprocess_getPassCount()}catch(e){return mt(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Un)return!1;try{return Un.postprocess_isInitialized()}catch(e){return mt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ln().postprocess_setBypass(e)}catch(e){mt(e,"PostProcess.setBypass")}},isBypassed(){if(!Un)return!0;try{return Un.postprocess_isBypassed()}catch(e){return mt(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Rt.createShader(Hn,"#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:()=>Rt.createShader(Hn,"#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:()=>Rt.createShader(Hn,"#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:()=>Rt.createShader(Hn,"#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")},Hn="#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 jn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(jn||(jn={}));let Xn=null,Yn=0;function Nn(e){Xn=e,Yn=Xn._malloc(64)}function Vn(){Xn&&Yn&&(Xn._free(Yn),Yn=0),Xn=null}const Gn={init(e,t){Xn?.renderer_init(e,t)},resize(e,t){Xn?.renderer_resize(e,t)},begin(e,t){if(Xn&&Yn)try{Xn.HEAPF32.set(e,Yn/4),Xn.renderer_begin(Yn,t??0)}catch(e){mt(e,"Renderer.begin")}},flush(){try{Xn?.renderer_flush()}catch(e){mt(e,"Renderer.flush")}},end(){try{Xn?.renderer_end()}catch(e){mt(e,"Renderer.end")}},submitSprites(e){if(Xn)try{Xn.renderer_submitSprites(e._cpp)}catch(e){mt(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Xn)try{Xn.renderer_submitBitmapText(e._cpp)}catch(e){mt(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Xn)try{Xn.renderer_submitSpine?.(e._cpp)}catch(e){mt(e,"Renderer.submitSpine")}},setStage(e){Xn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Xn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Xn?.renderer_releaseTarget(e)},getTargetTexture:e=>Xn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Xn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Xn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Xn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Xn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Xn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Xn?Xn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Xn?{drawCalls:Xn.renderer_getDrawCalls(),triangles:Xn.renderer_getTriangles(),sprites:Xn.renderer_getSprites(),text:Xn.renderer_getText(),spine:Xn.renderer_getSpine?.()??0,meshes:Xn.renderer_getMeshes(),culled:Xn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let qn=null;function Jn(e){qn=e}function Kn(){qn=null}const Qn={enable(){qn?.gl_enableErrorCheck(!0)},disable(){qn?.gl_enableErrorCheck(!1)},check:e=>qn?.gl_checkErrors(e)??0,diagnose(){qn?.renderer_diagnose()}};class Zn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:i}=e;s===this.lastWidth_&&r===this.lastHeight_||(Gn.resize(s,r),On.isInitialized()&&On.getPassCount()>0&&On.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Gn.setViewport(0,0,s,r),Gn.clearBuffers(3),Gn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Gn.submitSprites(t),Gn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Gn.submitSpine(t),Gn.flush(),this.executeDrawCallbacks(n,i),Gn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:i}=e;Gn.setViewport(s.x,s.y,s.w,s.h),Gn.setScissor(s.x,s.y,s.w,s.h,!0),Gn.clearBuffers(r),Gn.setScissor(0,0,0,0,!1),Gn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Gn.submitSprites(t),Gn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Gn.submitSpine(t),Gn.flush(),this.executeDrawCallbacks(n,i),Gn.end()}executeDrawCallbacks(e,t){const n=Pn;if(n.size>0){xn.begin(e);const s=[];for(const[e,r]of n.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}xn.end();for(const e of s)En(e)}}}const es="__scene_transition_overlay__";class ts{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class ns{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,ke,{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),Mn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=On.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){On.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,ke)){const n=this.app_.world.get(e,ke);n.persistent=t,this.app_.world.insert(e,ke,n)}}}class ss{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(n=>{const s=t.duration??G.sceneTransitionDuration,r=t.color??{...G.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:r,targetScene:e,options:t,resolve:n},Mn(es,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;xn.setLayer(9999),xn.setDepth(9999),xn.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{n&&n!==e&&await this.unload(n,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,En(es)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,En(es),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new ts(t);this.scenes_.set(e,n);const s=new ns(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Kt)?this.app_.getResource(Kt):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(Kt)&&(t.assetServer=this.app_.getResource(Kt));const s=await Nt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,ke,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=is(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();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 n=new ts(t);this.scenes_.set(e,n);const s=new ns(n,this.app_);this.contexts_.set(e,s);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Kt)?this.app_.getResource(Kt):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(Kt)&&(t.assetServer=this.app_.getResource(Kt));const s=await Nt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,ke,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=is(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const r=t?.keepPersistent??!0;for(const e of n.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,ke)){if(this.app_.world.get(e,ke).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())En(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{On.removePass(e)}catch{}n.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,Pe)){const n=this.app_.world.get(e,Pe);t.savedAlphas.set(e,n.color.a),n.color={...n.color,a:0},this.app_.world.insert(e,Pe,n)}}}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,Pe)){const n=this.app_.world.get(e,Pe),s=t.savedAlphas.get(e)??1;n.color={...n.color,a:s},this.app_.world.insert(e,Pe,n)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{On.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const rs=Oe(null,"SceneManager");function is(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(rs).getSceneStatus(t)&&n._fn(...s)}}}const os=nt([je(rs),He(Ne)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),as={name:"SceneManager",build(e){const t=new ss(e);e.insertResource(rs,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(rs),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(et.Startup,n),e.addSystemToSchedule(et.Last,os)}};class ls{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=u(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(et.Last);else{this.runSchedule(et.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(et.FixedPreUpdate),this.runSchedule(et.FixedUpdate),this.runSchedule(et.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(et.PreUpdate),this.runSchedule(et.Update),this.runSchedule(et.PostUpdate),this.runSchedule(et.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new wt,this.resources_=new Ye;for(const e of Object.values(et))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ls}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,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(et.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(et.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 yt(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(rs).register(e),this}setInitialScene(e){return this.getResource(rs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new at(this.world_,this.resources_),this.resources_.insert(Ne,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(et.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,Tn();const e=[Kn,Vn,Dn,Bn,Ct,mn];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 n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const r=t.get(s);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,r=new Set,i=o=>{if(s.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 n=t.get(e);void 0!==n&&i(n)}r.delete(o),s.add(o),n.push(a)};for(let t=0;t<e.length;t++)i(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Ne);t.delta=e,t.elapsed+=e,t.frameCount++}}function cs(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const hs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ds(e,t,n,s,r){const i=e*t/n,o=e;switch(s){case ve.FixedWidth:return i;case ve.FixedHeight:return o;case ve.Expand:return Math.max(i,o);case ve.Shrink:return Math.min(i,o);case ve.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function us(e,t,n,s,r,i){if(0===n||0===s)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,ke);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*n/(o.h*s);let h,d=0,u=0;if(r.projectionType===we.Orthographic){if(u=r.orthoSize,l){u=ds(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}d=u*a,h=ps(-d,d,-u,u,-r.farPlane,r.farPlane)}else h=ys(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=_s(i.position.x,i.position.y,i.position.z);c.push({entity:e,viewProjection:new Float32Array(xs(h,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:u,cameraX:i.position.x,cameraY:i.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const fs=new Float32Array(16);function ps(e,t,n,s,r,i){const o=fs;o.fill(0);const a=t-e,l=s-n,c=i-r;return o[0]=2/a,o[5]=2/l,o[10]=-2/c,o[12]=-(t+e)/a,o[13]=-(s+n)/l,o[14]=-(i+r)/c,o[15]=1,o}const gs=new Float32Array(16);function ys(e,t,n,s){const r=gs;r.fill(0);const i=1/Math.tan(e/2),o=n-s;return r[0]=i/t,r[5]=i,r[10]=(s+n)/o,r[11]=-1,r[14]=2*s*n/o,r}const ms=new Float32Array(16);function _s(e,t,n){const s=ms;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const ws=new Float32Array(16);function xs(e,t){const n=ws;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}const vs={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3},bs=le("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},_dirty:!0});function Ss(e,t){e.has(t,Pe)||e.insert(t,Pe,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function Ps(e,t,n,s){if(!e.has(t,bs))return;const r=e.get(t,bs);switch(n){case 0:r.anchorMin={x:0,y:0},r.anchorMax={x:s,y:1};break;case 1:r.anchorMin={x:1-s,y:0},r.anchorMax={x:1,y:1};break;case 2:r.anchorMin={x:0,y:0},r.anchorMax={x:1,y:s};break;case 3:r.anchorMin={x:0,y:1-s},r.anchorMax={x:1,y:1}}r.offsetMin={x:0,y:0},r.offsetMax={x:0,y:0},e.insert(t,bs,r)}function Ms(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Es(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Ts(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(let i=0;i<t.length;i++){const o=t[i],a=s+o;if(e.measureText(a).width>n&&s){if(Es(o.charCodeAt(0))&&s.length>0&&Es(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Es(s.charCodeAt(t))){e=t;break}e>=0?(r.push(s.substring(0,e+1)),s=s.substring(e+1)+o):(r.push(s),s=o)}else r.push(s),s=o}else s=a}s&&r.push(s)}return r.length>0?r:[""]}function Cs(e){let t=1;for(;t<e;)t*=2;return t}const As={Left:0,Center:1,Right:2},Rs={Top:0,Middle:1,Bottom:2},Is={Visible:0,Clip:1,Ellipsis:2},Fs=le("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:As.Left,verticalAlign:Rs.Top,wordWrap:!0,overflow:Is.Visible,lineHeight:1.2});class ks{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(G.textCanvasSize,G.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.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 l=Ts(n,e.content,a?i:0);const c=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),u=Math.ceil(l.length*c),f=r?Math.ceil(i):d+2*h,p=r?Math.ceil(o):u+2*h;if(r&&e.overflow===Is.Ellipsis&&u>o){const e=Math.floor(o/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,i)}}if(s.width<f||s.height<p){const e=Math.max(s.width,Cs(f)),t=Math.max(s.height,Cs(p));s.width=e,s.height=t}const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${y}, ${m}, ${_})`,r&&e.overflow===Is.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case Rs.Top:x=h;break;case Rs.Middle:x=(p-w)/2;break;case Rs.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of l){let s;switch(e.align){case As.Left:s=h;break;case As.Center:s=f/2;break;case As.Right:s=f-h;break;default:s=h}n.fillText(t,s,v),v+=c}r&&e.overflow===Is.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const E=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);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[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case As.Left:return"left";case As.Center:return"center";case As.Right:return"right"}}}function Bs(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 zs(e,t,n){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!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class $s{build(e){ye("Text",Fs);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ks(t),s=e.world,r=new Map;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Fs));for(const e of r.keys())s.valid(e)&&s.has(e,Fs)||r.delete(e);const e=s.getEntitiesWithComponents([Fs]);for(const t of e){const e=s.get(t,Fs),i=s.has(t,bs)?s.get(t,bs):null,o=r.get(t);if(o&&!zs(o,e,i))continue;Ss(s,t);const a=n.renderForEntity(t,e,i),l=s.get(t,Pe);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,Pe,l),r.set(t,Bs(e,i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Us=new $s,Ws=le("UIMask",{enabled:!0,mode:"scissor"});function Ds(e,t){const n=Math.max(e.x,t.x),s=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:n,y:s,w:Math.max(0,r-n),h:Math.max(0,i-s)}}function Ls(e,t,n,s,r,i,o,a,l,c,h){const d=e-n*r,u=e+n*(1-r),f=t-s*i,p=t+s*(1-i);function g(e,t){const n=o[0]*e+o[4]*t+o[12],s=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*h]}const[y,m]=g(d,f),[_,w]=g(u,p),x=Math.min(y,_),v=Math.max(y,_),b=Math.min(m,w),S=Math.max(m,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function Os(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],i=e[2],o=e[3],a=e[4],l=e[5],c=e[6],h=e[7],d=e[8],u=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],w=s*l-r*a,x=s*c-i*a,v=s*h-o*a,b=r*c-i*l,S=r*h-o*l,P=i*h-o*c,M=d*y-u*g,E=d*m-f*g,T=d*_-p*g,C=u*m-f*y,A=u*_-p*y,R=f*_-p*m;let I=w*R-x*A+v*C+b*T-S*E+P*M;return 0===I||(I=1/I,n[0]=(l*R-c*A+h*C)*I,n[1]=(i*A-r*R-o*C)*I,n[2]=(y*P-m*S+_*b)*I,n[3]=(f*S-u*P-p*b)*I,n[4]=(c*T-a*R-h*E)*I,n[5]=(s*R-i*T+o*E)*I,n[6]=(m*v-g*P-_*x)*I,n[7]=(d*P-f*v+p*x)*I,n[8]=(a*A-l*T+h*M)*I,n[9]=(r*T-s*A-o*M)*I,n[10]=(g*S-y*v+_*w)*I,n[11]=(u*v-d*S-p*w)*I,n[12]=(l*E-a*C-c*M)*I,n[13]=(s*C-r*E+i*M)*I,n[14]=(y*x-g*b-m*w)*I,n[15]=(d*b-u*x+f*w)*I),n}function Hs(e,t,n,s,r,i,o){const a=(e-s)/i*2-1,l=(t-r)/o*2-1,c=n[0]*a+n[4]*l+n[12],h=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:h/d}}function js(e,t,n,s,r,i,o,a){return e>=n-r*o&&e<=n+r*(1-o)&&t>=s-i*a&&t<=s+i*(1-a)}function Xs(e,t,n,s,r,i,o,a,l,c){const h=2*Math.atan2(l,c),d=Math.sin(-h),u=Math.cos(-h),f=e-n,p=t-s,g=f*u-p*d+n,y=f*d+p*u+s;return g>=n-r*o&&g<=n+r*(1-o)&&y>=s-i*a&&y<=s+i*(1-a)}function Ys(e,t,n,s,r,i,o){if(!e.has(t,bs)||!e.has(t,Se))return null;const a=e.get(t,bs),l=e.get(t,Se),c=a.size.x*l.scale.x,h=a.size.y*l.scale.y;return Ls(l.position.x,l.position.y,c,h,a.pivot.x,a.pivot.y,n,s,r,i,o)}function Ns(e,t){return(n,s,r,i,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ws]);if(0===l.length)return;const c=[],h=[],d=new Set,u=new Set;for(const e of l){const n=t.get(e,Ws);n.enabled&&(d.add(e),"stencil"===n.mode?(h.push(e),u.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,r,i,o,a,l,c){const h=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Ce);){const e=t.get(s,Ce);if(r.has(e.entity)){if("scissor"===t.get(e.entity,Ws).mode){n=!1;break}}s=e.entity}n&&h.push(e)}function d(s,h){const u=e.getChildEntities(n,s);for(const n of u){let s=h;if(r.has(n)){if("scissor"===t.get(n,Ws).mode){const e=Ys(t,n,i,o,a,l,c);e&&(s=Ds(h,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of h){const n=Ys(t,e,i,o,a,l,c);n&&d(e,n)}}(e,t,n,c,d,s,r,i,o,a),h.length>0&&function(e,t,n,s,r){e.renderer_clearStencil();const i=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Ce);){const e=t.get(s,Ce);if(r.has(e.entity)){n=!1;break}s=e.entity}n&&i.push(e)}let o=1;function a(t,s){e.renderer_setEntityStencilMask(t,s);const i=e.getChildEntities(n,t);for(const t of i)if(r.has(t)){a(t,o++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}function l(t,s){const i=e.getChildEntities(n,t);for(const t of i)if(r.has(t)){a(t,o++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}for(const e of i){a(e,o++)}}(e,t,n,h,u)}catch(t){e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Vs{build(e){if(ye("UIMask",Ws),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Ns(e.wasmModule,e.world))}}const Gs=new Vs,qs=le("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Js=le("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Ks={Normal:0,Hovered:1,Pressed:2,Disabled:3},Qs=le("Button",{state:Ks.Normal,transition:null});class Zs{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const er=Oe(new Zs,"UIEvents"),tr=ce("ScreenSpace");function nr(e,t,n,s,r,i){const o=i.right-i.left,a=i.top-i.bottom,l=i.left+e.x*o,c=i.left+t.x*o,h=i.bottom+e.y*a,d=i.bottom+t.y*a;let u,f,p,g;if(e.x===t.x){const e=l+n.x,t=.5*r.x;u=e-t,p=e+t}else u=l+n.x,p=c+s.x;if(e.y===t.y){const e=h+n.y,t=.5*r.y;f=e-t,g=e+t}else f=h+n.y,g=d+s.y;return{centerX:.5*(u+p),centerY:.5*(f+g),width:p-u,height:g-f,rect:{left:u,bottom:f,right:p,top:g}}}function sr(e,t){e.anchorMinX=t.anchorMin.x,e.anchorMinY=t.anchorMin.y,e.anchorMaxX=t.anchorMax.x,e.anchorMaxY=t.anchorMax.y,e.offsetMinX=t.offsetMin.x,e.offsetMinY=t.offsetMin.y,e.offsetMaxX=t.offsetMax.x,e.offsetMaxY=t.offsetMax.y,e.sizeX=t.size.x,e.sizeY=t.size.y}function rr(e){return{anchorMinX:e.anchorMin.x,anchorMinY:e.anchorMin.y,anchorMaxX:e.anchorMax.x,anchorMaxY:e.anchorMax.y,offsetMinX:e.offsetMin.x,offsetMinY:e.offsetMin.y,offsetMaxX:e.offsetMax.x,offsetMaxY:e.offsetMax.y,sizeX:e.size.x,sizeY:e.size.y}}function ir(e,t){return e.anchorMinX!==t.anchorMin.x||e.anchorMinY!==t.anchorMin.y||e.anchorMaxX!==t.anchorMax.x||e.anchorMaxY!==t.anchorMax.y||e.offsetMinX!==t.offsetMin.x||e.offsetMinY!==t.offsetMin.y||e.offsetMaxX!==t.offsetMax.x||e.offsetMaxY!==t.offsetMax.y||e.sizeX!==t.size.x||e.sizeY!==t.size.y}function or(e,t,n,s,r,i){if(!e.has(t,bs))return;const o=e.get(t,bs),a=nr(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,n);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const l=e.get(t,be);if(i?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,be,l),!e.has(t,Ae))return;const c=e.get(t,Ae);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&or(e,t,a.rect,a.centerX,a.centerY,!1)}class ar{build(e){ye("UIRect",bs);const t=e.world,n=new Map,s=new Map;let r=NaN,i=NaN,o=NaN,a=NaN;function l(e){let n=s.get(e);return void 0!==n||(n=function(e,t){let n=t;for(;;){if(e.has(n,tr))return n;if(!e.has(n,Ce))return null;const t=e.get(n,Ce);if(!e.valid(t.entity))return null;n=t.entity}}(t,e),s.set(e,n)),n}e.addSystemToSchedule(et.PreUpdate,nt([He(xt)],e=>{if(!e.valid)return;const c={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},h=.5*(c.left+c.right),d=.5*(c.bottom+c.top),u=r!==e.worldLeft||i!==e.worldBottom||o!==e.worldRight||a!==e.worldTop;r=e.worldLeft,i=e.worldBottom,o=e.worldRight,a=e.worldTop;const f=new Set;if(u){s.clear();const e=t.getEntitiesWithComponents([tr,bs,be]);for(const t of e)f.add(t)}for(const e of n.keys())t.valid(e)&&t.has(e,bs)||(n.delete(e),s.delete(e));const p=t.getEntitiesWithComponents([bs]);for(const e of p){const r=t.get(e,bs),i=n.get(e);if(r._dirty||!i||ir(i,r)){r._dirty=!1,s.delete(e);const t=l(e);null!==t&&f.add(t)}}for(const e of f)or(t,e,c,h,d,!0);for(const e of p){const s=t.get(e,bs),r=n.get(e);r?sr(r,s):n.set(e,rr(s))}},{name:"UILayoutSystem"}))}}const lr=new ar,cr=new Float32Array(16),hr=new Float32Array(16);let dr=!0,ur=1;function fr(e,t,n,s){let r=t;for(;e.has(r,Ce);){const t=e.get(r,Ce).entity;if(!e.valid(t))break;if(e.has(t,Ws)){if(e.get(t,Ws).enabled&&e.has(t,bs)&&e.has(t,Se)){const r=e.get(t,Se),i=e.get(t,bs),o=i.size.x*r.scale.x,a=i.size.y*r.scale.y;if(!js(n,s,r.position.x,r.position.y,o,a,i.pivot.x,i.pivot.y))return!0}}r=t}return!1}function pr(e,t,n,s){t.emit(n,s,n);let r=n;for(;e.has(r,Ce);){const i=e.get(r,Ce).entity;if(!e.valid(i))break;if(!e.has(i,qs)){r=i;continue}const o=e.get(i,qs);if(o.enabled&&t.emit(i,s,n),o.blockRaycast)break;r=i}}class gr{build(e){ye("Interactable",qs),ye("Button",Qs);const t=e.world,n=new Zs;e.insertResource(er,n);let s=null,r=null;ur="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,i)=>{n.drain();const o=t.getEntitiesWithComponents([Js]);for(const e of o){const n=t.get(e,Js);n.justPressed=!1,n.justReleased=!1}if(!i.valid)return;const a=e.mouseX*ur,l=i.screenH-e.mouseY*ur;!function(e){let t=!1;for(let n=0;n<16;n++)if(hr[n]!==e[n]){t=!0;break}t&&(hr.set(e),dr=!0)}(i.viewProjection),dr&&(Os(i.viewProjection,cr),dr=!1);const c=Hs(a,l,cr,i.vpX,i.vpY,i.vpW,i.vpH);i.worldMouseX=c.x,i.worldMouseY=c.y;const h=t.getEntitiesWithComponents([qs,bs,Se]);let d=null,u=-1/0;for(const e of h){t.has(e,Js)||t.insert(e,Js);const n=t.get(e,qs);if(!n.enabled)continue;if(!n.raycastTarget)continue;const s=t.get(e,Se),r=t.get(e,bs),i=r.size.x*s.scale.x,o=r.size.y*s.scale.y;if(Xs(c.x,c.y,s.position.x,s.position.y,i,o,r.pivot.x,r.pivot.y,s.rotation.z,s.rotation.w)){if(fr(t,e,c.x,c.y))continue;let n=0;t.has(e,Pe)&&(n=t.get(e,Pe).layer),n>=u&&(u=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,Js)){t.get(s,Js).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,Js).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Js);e.pressed=!0,e.justPressed=!0,r=d,pr(t,n,d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Js)){const e=t.get(r,Js);e.pressed=!1,e.justReleased=!0,pr(t,n,r,"release"),r===s&&pr(t,n,r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(et.Update,nt([],()=>{const e=t.getEntitiesWithComponents([Qs]);for(const n of e){if(t.has(n,qs)||t.insert(n,qs,{enabled:!0}),!t.has(n,Js))continue;const e=t.get(n,Js),s=t.get(n,Qs),r=t.get(n,qs),i=s.state;if(r.enabled?e.pressed?s.state=Ks.Pressed:e.hovered?s.state=Ks.Hovered:s.state=Ks.Normal:s.state=Ks.Disabled,i!==s.state&&s.transition&&t.has(n,Pe)){const i=t.get(n,Pe);i.color=Ms(s.transition,r.enabled,e.pressed,e.hovered),t.insert(n,Pe,i)}}},{name:"ButtonSystem"}))}}const yr=new gr,mr=le("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 _r{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){ye("TextInput",mr);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(G.textCanvasSize,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,l=!0,c=0,h=0;const u=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(!u)return;const f=u,p=()=>{a||null===o||w()},g=()=>{a=!0},y=()=>{a=!1,w()},m=t=>{if(null===o)return;if("Escape"===t.key)return void v();const s=n.get(o,mr);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(er).emit(o,"submit"),void v()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,b())},_=()=>{if(null!==o&&n.valid(o)&&n.has(o,mr)){const e=n.get(o,mr);e.focused=!1,e.dirty=!0}o=null};function w(){if(null===o||!n.valid(o))return;const t=n.get(o,mr);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(er).emit(o,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,b()}function x(e){if(o===e)return;v();const t=n.get(e,mr);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),b())}function v(){if(null!==o&&n.valid(o)&&n.has(o,mr)){const e=n.get(o,mr);e.focused=!1,e.dirty=!0}o=null,f.blur()}function b(){l=!0,c=0}function S(e,o,a,c){(r.width<a||r.height<c)&&(r.width=Cs(Math.max(r.width,a)),r.height=Cs(Math.max(r.height,c))),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,c),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,c),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const d=0===o.value.length,u=d?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=d?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),g=o.padding;if(o.multiline){const e=Ts(i,u,a-2*g);let t=g;for(const n of e)i.fillText(n,g,t),t+=p}else{const e=(c-o.fontSize)/2;i.fillText(u,g,e)}if(o.focused&&l){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,n,s;if(o.multiline){const e=Ts(i,o.value.substring(0,o.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+i.measureText(r).width,n=g+(e.length-1)*p,s=p}else t=g+i.measureText(e).width,n=(c-o.fontSize)/2,s=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,n,2,s)}i.restore();const y=i.getImageData(0,0,a,c),m=new Uint8Array(y.data.buffer),_=t.getResourceManager(),w=t._malloc(m.length);t.HEAPU8.set(m,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const v=_.createTexture(a,c,w,m.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,Pe);b.texture=v,b.size.x=a,b.size.y=c,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},n.insert(e,Pe,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",g),f.addEventListener("compositionend",y),f.addEventListener("keydown",m),f.addEventListener("blur",_),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",g),f.removeEventListener("compositionend",y),f.removeEventListener("keydown",m),f.removeEventListener("blur",_),f.remove()},e.addSystemToSchedule(et.PreUpdate,nt([He(er)],e=>{const t=n.getEntitiesWithComponents([mr,qs]);for(const e of t){if(!n.has(e,Js))continue;if(n.get(e,Js).justPressed)return void x(e)}if(null!==o){const e=n.getEntitiesWithComponents([qs]);for(const t of e){if(n.has(t,mr))continue;if(!n.has(t,Js))continue;if(n.get(t,Js).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(et.PreUpdate,nt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==o&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==o&&n.valid(o)&&n.has(o,mr)))){n.get(o,mr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,mr)||(i.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([mr,bs]);for(const e of a){const t=n.get(e,mr);if(!t.dirty)continue;const s=n.get(e,bs),r=Math.ceil(s.size.x),i=Math.ceil(s.size.y);r<=0||i<=0||(Ss(n,e),S(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const wr=new _r,xr={Simple:0,Sliced:1,Tiled:2,Filled:3},vr={Horizontal:0,Vertical:1},br={Left:0,Right:1,Bottom:2,Top:3},Sr=le("Image",{texture:K,color:{r:1,g:1,b:1,a:1},imageType:xr.Simple,fillMethod:vr.Horizontal,fillOrigin:br.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0});const Pr=new class{build(e){ye("Image",Sr);const t=e.world;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{const e=t.getEntitiesWithComponents([Sr]);for(const n of e){const e=t.get(n,Sr);Ss(t,n);const s=t.get(n,Pe);if(s.texture=e.texture,s.color.r=e.color.r,s.color.g=e.color.g,s.color.b=e.color.b,s.color.a=e.color.a,s.layer=e.layer,s.material=e.material,t.has(n,bs)){const e=t.get(n,bs);s.size.x=e.size.x,s.size.y=e.size.y}if(s.uvOffset.x=0,s.uvOffset.y=0,s.uvScale.x=1,s.uvScale.y=1,e.imageType===xr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));e.fillMethod===vr.Horizontal?e.fillOrigin===br.Left?(s.uvScale.x=t,s.size.x*=t):(s.uvOffset.x=1-t,s.uvScale.x=t,s.size.x*=t):e.fillOrigin===br.Bottom?(s.uvScale.y=t,s.size.y*=t):(s.uvOffset.y=1-t,s.uvScale.y=t,s.size.y*=t)}else e.imageType===xr.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(s.uvScale.x=s.size.x/e.tileSize.x,s.uvScale.y=s.size.y/e.tileSize.y);t.insert(n,Pe,s)}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Mr=le("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Er=le("ToggleGroup",{allowSwitchOff:!1});const Tr=new class{build(e){ye("Toggle",Mr),ye("ToggleGroup",Er);const t=e.world;e.addSystemToSchedule(et.Update,nt([He(er)],e=>{const n=t.getEntitiesWithComponents([Mr]);for(const s of n){if(t.has(s,qs)||t.insert(s,qs,{enabled:!0}),!t.has(s,Js))continue;const r=t.get(s,Js),i=t.get(s,Mr),o=t.get(s,qs);if(r.justPressed&&o.enabled){const r=i.group,o=0!==r&&t.valid(r)&&t.has(r,Er);if(i.isOn&&o){if(!t.get(r,Er).allowSwitchOff)continue}if(i.isOn=!i.isOn,i.isOn&&o)for(const i of n){if(i===s)continue;const n=t.get(i,Mr);n.group===r&&n.isOn&&(n.isOn=!1,e.emit(i,"change"))}e.emit(s,"change")}if(i.graphicEntity&&t.valid(i.graphicEntity)&&t.has(i.graphicEntity,Pe)){const e=t.get(i.graphicEntity,Pe);e.color.a=i.isOn?1:0,t.insert(i.graphicEntity,Pe,e)}if(i.transition&&t.has(s,Pe)){const e=t.get(s,Pe);e.color=Ms(i.transition,o.enabled,r.pressed,r.hovered),t.insert(s,Pe,e)}}},{name:"ToggleSystem"}))}},Cr=vs,Ar=le("ProgressBar",{value:0,fillEntity:0,direction:vs.LeftToRight});const Rr=new class{build(e){ye("ProgressBar",Ar);const t=e.world;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{const e=t.getEntitiesWithComponents([Ar,bs]);for(const n of e){const e=t.get(n,Ar);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=Math.max(0,Math.min(1,e.value));Ps(t,e.fillEntity,e.direction,s)}},{name:"ProgressBarSystem"}))}},Ir=le("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Fr=le("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}}),kr=new Float32Array(16),Br=new Float32Array(16);let zr=!0;function $r(e,t,n){const s=e.mouseX*n,r=t.screenH-e.mouseY*n;return function(e){let t=!1;for(let n=0;n<16;n++)if(Br[n]!==e[n]){t=!0;break}t&&(Br.set(e),zr=!0)}(t.viewProjection),zr&&(Os(t.viewProjection,kr),zr=!1),Hs(s,r,kr,t.vpX,t.vpY,t.vpW,t.vpH)}const Ur=new class{build(e){ye("Draggable",Ir),ye("DragState",Fr);const t=e.world,n=e.getResource(er);let s=null,r={x:0,y:0},i=null;const o="undefined"!=typeof window&&window.devicePixelRatio||1;e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,a)=>{if(!a.valid)return;const l=$r(e,a,o);if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Ir,Js]);let n=null;for(const s of e){if(!t.get(s,Ir).enabled)continue;t.get(s,Js).hovered&&(n=s)}if(null!==n){s=n,r={x:l.x,y:l.y},t.has(n,Fr)||t.insert(n,Fr);const e=t.get(n,Fr),i=t.get(n,Se);e.startWorldPos={x:i.position.x,y:i.position.y},e.currentWorldPos={x:i.position.x,y:i.position.y},e.pointerStartWorld={x:l.x,y:l.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Fr)){t.get(s,Fr).isDragging=!1}s=null}if(null!==s&&null===i){if(!t.valid(s))return void(s=null);const e=l.x-r.x,o=l.y-r.y,c=Math.sqrt(e*e+o*o),h=t.get(s,Ir);if(c*(a.vpW/(a.worldRight-a.worldLeft))>=h.dragThreshold){i=s,s=null;t.get(i,Fr).isDragging=!0,n.emit(i,"drag_start")}}if(null!==i){if(!t.valid(i)||!t.has(i,Fr))return void(i=null);const s=t.get(i,Fr),r=t.get(i,Ir),o=l.x-s.pointerStartWorld.x,a=l.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+o,h=s.startWorldPos.y+a;const d=function(e,t,n,s){let r=e.lockX?t.startWorldPos.x:n,i=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),i=Math.max(i,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),i=Math.min(i,e.constraintMax.y)),{x:r,y:i}}(r,s,c,h);c=d.x,h=d.y;const u=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-u,y:h-f},s.currentWorldPos={x:c,y:h},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:h-s.startWorldPos.y},t.has(i,be)){const e=function(e,t,n,s){if(!e.has(t,Ce))return{x:n,y:s};const r=e.get(t,Ce).entity;if(!e.valid(r)||!e.has(r,Se))return{x:n,y:s};const i=e.get(r,Se),o=0!==i.scale.x?i.scale.x:1,a=0!==i.scale.y?i.scale.y:1,l=2*Math.atan2(i.rotation.z,i.rotation.w),c=Math.sin(-l),h=Math.cos(-l);return{x:(n*h-s*c)/o,y:(n*c+s*h)/a}}(t,i,s.deltaWorld.x,s.deltaWorld.y),n=t.get(i,be);n.position.x+=e.x,n.position.y+=e.y,t.insert(i,be,n)}n.emit(i,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(i,"drag_end"),i=null)}},{name:"DragSystem"}))}},Wr=le("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const Dr=new class{build(e){ye("ScrollView",Wr);const t=e.world,n=new Map;let s=0;e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,r)=>{const i=performance.now()/1e3,o=s>0?Math.min(i-s,.05):0;if(s=i,!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY},l=t.getEntitiesWithComponents([Wr,bs]);for(const s of l){t.has(s,qs)||t.insert(s,qs,{enabled:!0,blockRaycast:!0}),t.has(s,Ws)||t.insert(s,Ws,{enabled:!0,mode:"scissor"});const r=t.get(s,Wr),i=t.get(s,bs);let l=n.get(s);l||(l={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},n.set(s,l));const c=t.has(s,Js)?t.get(s,Js):null;if(c?.justPressed&&(l.isDragging=!0,l.lastWorldX=a.x,l.lastWorldY=a.y,l.velocityX=0,l.velocityY=0),l.isDragging&&e.isMouseButtonDown(0)){const e=a.x-l.lastWorldX,t=a.y-l.lastWorldY;r.horizontalEnabled&&(r.scrollX-=e,l.velocityX=o>0?-e/o:0),r.verticalEnabled&&(r.scrollY-=t,l.velocityY=o>0?-t/o:0),l.lastWorldX=a.x,l.lastWorldY=a.y}if(l.isDragging&&e.isMouseButtonReleased(0)&&(l.isDragging=!1),c?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,l.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,l.velocityX=0)}if(!l.isDragging&&r.inertia&&o>0){const e=Math.pow(r.decelerationRate,o);r.horizontalEnabled&&Math.abs(l.velocityX)>.1?(r.scrollX+=l.velocityX*o,l.velocityX*=e):l.velocityX=0,r.verticalEnabled&&Math.abs(l.velocityY)>.1?(r.scrollY+=l.velocityY*o,l.velocityY*=e):l.velocityY=0}const h=i.size.x,d=i.size.y,u=Math.max(0,r.contentWidth-h),f=Math.max(0,r.contentHeight-d);if(r.scrollX=Math.max(0,Math.min(r.scrollX,u)),r.scrollY=Math.max(0,Math.min(r.scrollY,f)),0!==r.contentEntity&&t.valid(r.contentEntity)&&t.has(r.contentEntity,be)){const e=t.get(r.contentEntity,be);e.position.x=-r.scrollX,e.position.y=r.scrollY,t.insert(r.contentEntity,be,e)}}},{name:"ScrollViewSystem"}))}},Lr=vs,Or=le("Slider",{value:0,minValue:0,maxValue:1,direction:vs.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});const Hr=new class{build(e){ye("Slider",Or);const t=e.world;let n=null;e.addSystemToSchedule(et.PreUpdate,nt([He(ct),He(xt)],(e,s)=>{if(!s.valid)return;const r=s.worldMouseX,i=s.worldMouseY,o=t.getEntitiesWithComponents([Or,bs,Se]);for(const s of o){t.has(s,qs)||t.insert(s,qs,{enabled:!0,blockRaycast:!0});const o=t.get(s,Or),a=t.get(s,bs),l=t.get(s,Se),c=t.has(s,Js)?t.get(s,Js):null;if(c?.justPressed&&(n=s),n===s&&e.isMouseButtonDown(0)){const e=a.size.x*l.scale.x,t=a.size.y*l.scale.y,n=l.position.x-a.pivot.x*e,s=l.position.y-a.pivot.y*t;let c;switch(o.direction){case vs.LeftToRight:c=e>0?(r-n)/e:0;break;case vs.RightToLeft:c=e>0?1-(r-n)/e:0;break;case vs.BottomToTop:c=t>0?(i-s)/t:0;break;case vs.TopToBottom:c=t>0?1-(i-s)/t:0}c=Math.max(0,Math.min(1,c));let h=o.minValue+c*(o.maxValue-o.minValue);o.wholeNumbers&&(h=Math.round(h)),o.value=Math.max(o.minValue,Math.min(o.maxValue,h))}n===s&&e.isMouseButtonReleased(0)&&(n=null);const h=o.maxValue-o.minValue,d=h>0?(o.value-o.minValue)/h:0;if(0!==o.fillEntity&&t.valid(o.fillEntity)&&Ps(t,o.fillEntity,o.direction,d),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,bs)){const e=t.get(o.handleEntity,bs);switch(o.direction){case vs.LeftToRight:e.anchorMin={x:d,y:0},e.anchorMax={x:d,y:1};break;case vs.RightToLeft:e.anchorMin={x:1-d,y:0},e.anchorMax={x:1-d,y:1};break;case vs.BottomToTop:e.anchorMin={x:0,y:d},e.anchorMax={x:1,y:d};break;case vs.TopToBottom:e.anchorMin={x:0,y:1-d},e.anchorMax={x:1,y:1-d}}t.insert(o.handleEntity,bs,e)}}},{name:"SliderSystem"}))}},jr=le("Focusable",{tabIndex:0,isFocused:!1});class Xr{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Yr=Oe(new Xr,"FocusManager");const Nr=new class{build(e){ye("Focusable",jr);const t=e.world,n=new Xr;e.insertResource(Yr,n),e.addSystemToSchedule(et.Update,nt([He(ct),He(er)],(e,s)=>{const r=t.getEntitiesWithComponents([jr]);for(const e of r){if(!t.has(e,Js))continue;t.get(e,Js).justPressed&&i(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of r){const s=t.get(n,jr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const o=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===o?a?s.length-1:0:a?(o-1+s.length)%s.length:(o+1)%s.length,i(s[l])}function i(e){const r=n.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,jr)){t.get(r,jr).isFocused=!1,s.emit(r,"blur",r)}n.focus(e);t.get(e,jr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},Vr=le("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});const Gr=new class{build(e){ye("SafeArea",Vr);const t=e.world;let n={top:0,bottom:0,left:0,right:0},s=0;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{s++%60==0&&(n=function(){if("undefined"==typeof document)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}());const e=t.getEntitiesWithComponents([Vr,bs]);for(const s of e){const e=t.get(s,Vr),r=t.get(s,bs);let i=!1;const o=e.applyTop?n.top:0,a=e.applyBottom?n.bottom:0,l=e.applyLeft?n.left:0,c=e.applyRight?n.right:0;r.offsetMin.x===l&&r.offsetMin.y===a||(r.offsetMin={x:l,y:a},i=!0),r.offsetMax.x===-c&&r.offsetMax.y===-o||(r.offsetMax={x:-c,y:-o},i=!0),i&&t.insert(s,bs,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},qr=le("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2}),Jr=new Map;function Kr(e,t){const n=Jr.get(e);n&&(n.renderer=t)}const Qr=new class{build(e){ye("ListView",qr);const t=e.world;e.addSystemToSchedule(et.PreUpdate,nt([He(ct)],e=>{const n=t.getEntitiesWithComponents([qr,bs]);for(const s of n){t.has(s,qs)||t.insert(s,qs,{enabled:!0,blockRaycast:!0}),t.has(s,Ws)||t.insert(s,Ws,{enabled:!0,mode:"scissor"});let n=Jr.get(s);n||(n={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},Jr.set(s,n));const r=t.get(s,qr),i=t.get(s,bs),o=i.size.y,a=t.has(s,Js)?t.get(s,Js):null;if(a?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}const l=Math.max(0,r.itemCount*r.itemHeight-o);r.scrollY=Math.max(0,Math.min(r.scrollY,l));const c=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+o)/r.itemHeight)+r.overscan);for(const[e,s]of n.itemEntities)(e<c||e>=h)&&(t.valid(s)&&t.despawn(s),n.itemEntities.delete(e));for(let e=c;e<h;e++){let o=n.itemEntities.get(e);if(o&&t.valid(o)||(o=t.spawn(),t.insert(o,Fe,{value:`ListItem_${e}`}),t.insert(o,bs,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i.size.x,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(o,s),n.itemEntities.set(e,o),n.renderer&&n.renderer(e,o)),t.has(o,be)){const n=t.get(o,be);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(o,be,n)}}n.visibleStart=c,n.visibleEnd=h}},{name:"ListViewSystem"}))}},Zr=le("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0}),ei=new Map;const ti=new class{build(e){ye("Dropdown",Zr);const t=e.world;function n(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const r=n.listEntity;if(0===r||!t.valid(r))return;a(r,!0),o(s);const i=t.has(r,bs)?t.get(r,bs):null,c=i?i.size.x:160;for(let e=0;e<n.options.length;e++){const i=t.spawn();t.insert(i,Fe,{value:`Option_${e}`}),t.insert(i,bs,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:30},pivot:{x:.5,y:1}}),t.insert(i,be,{position:{x:0,y:-30*e,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,Fs,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:1,g:1,b:1,a:1},align:0,verticalAlign:1,wordWrap:!1,overflow:1,lineHeight:1.2}),t.insert(i,qs,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(i,r),s.optionEntities.push(i)}i&&(i.size.y=30*n.options.length,t.insert(r,bs,i)),l(s)}function s(e,t,n){t.isOpen=!1,o(n),a(t.listEntity,!1)}function r(e,t,n,r,i){t.selectedIndex=r,s(0,t,n),i.emit(e,"change")}function i(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,Fs))return;const s=t.get(n,Fs),r=e.selectedIndex>=0&&e.selectedIndex<e.options.length?e.options[e.selectedIndex]:"";s.content!==r&&(s.content=r,t.insert(n,Fs,s))}function o(e){for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[]}function a(e,n){if(0===e||!t.valid(e))return;if(!t.has(e,be))return;const s=t.get(e,be),r=n?1:0;s.scale={x:r,y:r,z:r},t.insert(e,be,s)}function l(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,Pe))continue;const r=t.get(s,Pe);n===e.highlightIndex?r.color={r:.3,g:.5,b:.8,a:1}:r.color={r:1,g:1,b:1,a:1},t.insert(s,Pe,r)}}function c(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,Js))continue;if(t.get(n,Js).hovered)return!0}return!1}e.addSystemToSchedule(et.Update,nt([He(ct),He(er)],(e,o)=>{const a=t.getEntitiesWithComponents([Zr]);for(const h of a){t.has(h,qs)||t.insert(h,qs,{enabled:!0,blockRaycast:!0});const a=t.get(h,Zr),d=t.has(h,Js)?t.get(h,Js):null;let u=ei.get(h);if(u||(u={optionEntities:[],highlightIndex:-1},ei.set(h,u)),d?.justPressed&&(a.isOpen?s(h,a,u):n(h,a,u)),a.isOpen){for(let e=0;e<u.optionEntities.length;e++){const n=u.optionEntities[e];if(!t.valid(n)||!t.has(n,Js))continue;if(t.get(n,Js).justPressed){r(h,a,u,e,o);break}}e.isKeyPressed("ArrowDown")?(u.highlightIndex=Math.min(u.highlightIndex+1,a.options.length-1),l(u)):e.isKeyPressed("ArrowUp")?(u.highlightIndex=Math.max(u.highlightIndex-1,0),l(u)):e.isKeyPressed("Enter")&&u.highlightIndex>=0?r(h,a,u,u.highlightIndex,o):e.isKeyPressed("Escape")&&s(h,a,u),e.isMouseButtonPressed(0)&&(d?.hovered||c(u)||s(h,a,u))}i(a)}},{name:"DropdownSystem"}))}},ni=0,si=0,ri=2,ii=le("LayoutGroup",{direction:ni,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:si,reverseOrder:!1});const oi=new class{build(e){ye("LayoutGroup",ii);const t=e.world;e.addSystemToSchedule(et.PreUpdate,nt([],()=>{const e=t.getEntitiesWithComponents([ii,bs,Ae]);for(const n of e){const e=t.get(n,ii),s=t.get(n,bs),r=t.get(n,Ae);if(!r.entities||0===r.entities.length)continue;const i=[];for(const e of r.entities)t.valid(e)&&t.has(e,bs)&&t.has(e,be)&&i.push({entity:e,rect:t.get(e,bs)});if(0===i.length)continue;e.reverseOrder&&i.reverse();const o=s.size.x,a=s.size.y,l=e.padding;l.left,l.right,l.top,l.bottom;const c=e.direction===ni;let h=0;for(const n of i){const s=n.rect.size.x,r=n.rect.size.y;let i,d;c?(i=.5*-o+l.left+h+.5*s,d=e.childAlignment===si?.5*a-l.top-.5*r:e.childAlignment===ri?.5*-a+l.bottom+.5*r:.5*(l.bottom-l.top),h+=s+e.spacing):(i=e.childAlignment===si?.5*-o+l.left+.5*s:e.childAlignment===ri?.5*o-l.right-.5*s:.5*(l.left-l.right),d=.5*a-l.top-h-.5*r,h+=r+e.spacing),n.rect.anchorMin.x=.5,n.rect.anchorMin.y=.5,n.rect.anchorMax.x=.5,n.rect.anchorMax.y=.5,n.rect.offsetMin.x=i,n.rect.offsetMin.y=d;const u=t.get(n.entity,be);u.position.x=i,u.position.y=d,t.insert(n.entity,be,u)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};async function ai(e,t,n){const s=e.getResource(rs);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function li(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 ci=Oe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),hi=Oe(null,"PhysicsAPI");function di(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ui(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class fi{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(ci,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=li(this.wasmUrl_,this.factory_).then(s=>{s._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([Ee]);for(const n of t){const t=e.world.get(n,Ee);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(et.PostUpdate,nt([He(Ne)],a=>{const l=o.getEntitiesWithComponents([ze,be,Se]),c=new Set;for(const r of l){c.add(r);const a=o.get(r,ze),l=o.get(r,Se);if(t.has(r)){const e=n.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||(s._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=di(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*i,l.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),pi(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===De.Kinematic){const e=di(l.rotation);s._physics_setBodyTransform(r,l.position.x*i,l.position.y*i,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<s;r++){const s=i+4*r,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const h=e.world.get(o,be);if(!h)continue;let d=a,u=l,f=c;if(e.world.has(o,Ce)){const t=e.world.get(o,Ce);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Se)){const n=e.world.get(t.entity,Se),s=di(n.rotation),r=a-n.position.x,i=l-n.position.y,o=Math.cos(-s),h=Math.sin(-s);d=(r*o-i*h)/(0!==n.scale.x?n.scale.x:1),u=(r*h+i*o)/(0!==n.scale.y?n.scale.y:1),f=c-s}}h.position.x=d,h.position.y=u;const p=ui(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,be,h)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],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;s.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]*n,contactY:t.HEAPF32[r+5]*n})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;i.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<h;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(ci,{collisionEnters:s,collisionExits:i,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(hi,gi._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function pi(e,t,n){const s=e.world;if(s.has(n,$e)){const e=s.get(n,$e);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,Ue)){const e=s.get(n,Ue);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,We)){const e=s.get(n,We);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class gi{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(gi.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 yi(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),i}function mi(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function _i(e,t,n,s){const r=e.scale.x*t*(n?-1:1),i=e.scale.y*t*(s?-1:1),o=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,h=e.rotation.w,d=a+a,u=l+l,f=c+c,p=a*d,g=a*u,y=a*f,m=l*u,_=l*f,w=c*f,x=h*d,v=h*u,b=h*f;return new Float32Array([(1-(m+w))*r,(g+b)*r,(y-v)*r,0,(g-b)*i,(1-(p+w))*i,(_+x)*i,0,(y+v)*o,(_-x)*o,(1-(p+m))*o,0,e.position.x,e.position.y,e.position.z,1])}async function wi(e,t,n,s,r,i,o,a,l){const c=await async function(e,t,n){const s={};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!==s[r])continue;try{s[r]=yi(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let h={},d=null;if(r&&(d=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,n,s,r){const i={};for(const o of s.entities)for(const s of o.components){if("SpineAnimation"!==s.type||!s.data)continue;const o=s.data.skeletonPath,a=s.data.atlasPath;if(!o||!a)continue;const l=r.resolvePath(o),c=r.resolvePath(a);try{const s=await r.readText(a),h="binary"===x(l)?.contentType;let d,u;if(h){const e=await r.readBinary(o);u=e.length,d=t._malloc(u),t.HEAPU8.set(e,d)}else{const e=await r.readText(o),n=(new TextEncoder).encode(e);u=n.length,d=t._malloc(u+1),t.HEAPU8.set(n,d),t.HEAPU8[d+u]=0}const f=n.loadSkeleton(d,u,s,s.length,h);if(t._free(d),f<0)continue;i[o]=f;const p=mi(s),g=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),o=yi(e,i,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,d,n,s)),i){new fi("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const u=await async function(e,t,n){const s={};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===s[r])try{let t,i;const o=x(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await n.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${o}`:o;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),h=yi(e,c,!1),d=e.getResourceManager();s[r]=d.loadBitmapFont(t,h,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};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===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=Rt.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=Rt.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const r={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Xt(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=r[e.type][n[e.field]]||0)}}(n,c,u,f);const p=Yt(e.world,n);if(l&&e.hasResource(rs))for(const t of p.values())e.world.insert(t,ke,{scene:l,persistent:!1});if(r&&d){const s=function(e,t,n,s){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=n[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const l=s.get(i.id);void 0!==l&&(r[l]=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}(d,n,h,p);!function(e,t,n,s,r){let i=0;e.setSpineRenderer((o,a)=>{let l=a-i;i=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const i=Number(e),o=r[e],a=c.has(i,Ie)?c.get(i,Ie):null,h=!1!==a?.playing,d=a?.timeScale??1;h&&s.update(o,l*d);let u=0;if(c.has(i,Se)){const e=_i(c.get(i,Se),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);u=t._malloc(64),t.HEAPF32.set(e,u>>2)}const f=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(o,e),i=s.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,l=2*i,c=n._malloc(a),h=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,c,h,d,f);const p=n.HEAPU32[d>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*r),m=new Uint16Array(n.HEAPU8.buffer,h,i),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(m),t.renderer_submitTriangles(_,r,w,i,p,g,u),t._free(_),t._free(w),n._free(c),n._free(h),n._free(d),n._free(f)}u&&t._free(u)}})}(e,t,r,d,s)}if(a){const t=e.getResource(Kt);t&&t.setAddressableManifest(a)}}function xi(e,t,n){return{name:e,data:t,async setup(){await wi(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class vi{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===x(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.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 n)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 s){const t=x(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||i.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}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),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),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 bi="__preview__";class Si{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(rs);t.register({name:bi,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(bi),this.loadPromise_=t.load(bi).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new vi(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await wi(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,bi)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Me]);for(const s of n){if(e.get(s,Me).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([Ee]);for(const r of s){const s=e.get(r,Ee);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=this.app_.getResource(rs).getScene(bi),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,be,o);const a={isActive:!0,projectionType:we.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:xe.ColorAndDepth};e.insert(i,Me,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(rs);await e.switchTo(bi),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 Pi={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Gn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Gn.getTargetTexture(n),width:e.width,height:e.height}},release(e){Gn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Gn.releaseRenderTarget(e._handle),Pi.create({width:t,height:n,depth:!0})),begin(e,t){Gn.begin(t,e._handle)},end(){Gn.end()},getDepthTexture:e=>Gn.getTargetDepthTexture(e._handle)};let Mi=!1;function Ei(e){Mi=e}function Ti(){return Mi}function Ci(){return!Mi}var Ai;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Ai||(Ai={}));class Ri{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Ai[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Ai.Debug:console.debug(t,n);break;case Ai.Info:console.log(t,n);break;case Ai.Warn:console.warn(t,n);break;case Ai.Error:console.error(t,n)}}}class Ii{constructor(){this.handlers_=[],this.minLevel_=Ai.Info,this.addHandler(new Ri)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(Ai.Debug,e,t,n)}info(e,t,n){this.log(Ai.Info,e,t,n)}warn(e,t,n){this.log(Ai.Warn,e,t,n)}error(e,t,n){this.log(Ai.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Fi=new Ii;function ki(){return Fi}function Bi(e){Fi.setMinLevel(e)}function zi(e,t,n){Fi.debug(e,t,n)}function $i(e,t,n){Fi.info(e,t,n)}function Ui(e,t,n){Fi.warn(e,t,n)}function Wi(e,t,n){Fi.error(e,t,n)}const Di=[Us,Gs,lr,Pr,Rr,yr,Ur,Dr,Hr,Tr,wr,Nr,Gr,Qr,ti,oi];function Li(e,t){return function(e,t){const n=ls.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),yn(e),Tt(e),kn(e),Wn(e),Nn(e),Jn(e);const r=new Zn;n.setPipeline(r);let i=u();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=us(e,s,t,r));const o=n.getResource(xt);if(i.length>0){const e=i[0],n=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(n.x*t),o.vpY=Math.round((1-n.y-n.h)*r),o.vpW=Math.round(n.w*t),o.vpH=Math.round(n.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}n.insertResource(xt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=o();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Gn.setClearColor(e.x,e.y,e.z,e.w)}const h=(u()-i)/1e3;let d;if(Gn.resize(t,l),On.isInitialized()&&On.getPassCount()>0&&!On.isBypassed()&&On.resize(t,l),n.hasResource(rs)){const e=n.getResource(rs).getActiveScenes();e.length>0&&(d=new Set(e))}r.setActiveScenes(d??null);const f=us(e,s,t,l,n.world,d);if(a(t,l,f),0===f.length)r.render({registry:{_cpp:s},viewProjection:hs,width:t,height:l,elapsed:h});else{for(const e of f){const n=e.viewportRect,i=Math.round(n.x*t),o=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:c},clearFlags:e.clearFlags,elapsed:h})}Gn.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(et.First,l),n.addSystemToSchedule(et.Last,c),n.addPlugin(Zt),n.addPlugin(hn),n.addPlugin(dt),n.addPlugin(as),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Di,...t})}H||(H=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(n,s);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n[s++]=r:r<2048?(n[s++]=192|r>>6,n[s++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,n[s++]=240|r>>18,n[s++]=128|r>>12&63,n[s++]=128|r>>6&63,n[s++]=128|63&r):(n[s++]=224|r>>12,n[s++]=128|r>>6&63,n[s++]=128|63&r)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=j;export{ls as App,Qt as AssetPlugin,en as AssetRefCounter,Jt as AssetServer,Kt as Assets,Dt as AsyncCache,Re as BitmapText,vt as BlendMode,De as BodyType,$e as BoxCollider,Qs as Button,Ks as ButtonState,Me as Camera,Ee as Canvas,We as CapsuleCollider,Ae as Children,Ue as CircleCollider,xe as ClearFlags,Ke as Commands,Ze as CommandsInstance,Y as DEFAULT_DESIGN_HEIGHT,X as DEFAULT_DESIGN_WIDTH,N as DEFAULT_PIXELS_PER_UNIT,V as DEFAULT_TEXT_CANVAS_SIZE,Cn as DataType,Fr as DragState,Ir as Draggable,xn as Draw,Zr as Dropdown,Qe as EntityCommands,vr as FillMethod,br as FillOrigin,Yr as FocusManager,Xr as FocusManagerState,jr as Focusable,Qn as GLDebug,$n as Geometry,J as INVALID_ENTITY,Q as INVALID_FONT,K as INVALID_TEXTURE,Sr as Image,xr as ImageType,ct as Input,ht as InputPlugin,lt as InputState,qs as Interactable,qr as ListView,be as LocalTransform,Ai as LogLevel,Ii as Logger,Rt as Material,Lt as MaterialLoader,Ve as Mut,Fe as Name,Ce as Parent,gi as Physics,ci as PhysicsEvents,fi as PhysicsPlugin,On as PostProcess,an as PrefabServer,ln as Prefabs,cn as PrefabsPlugin,Si as PreviewPlugin,Ar as ProgressBar,Cr as ProgressBarDirection,we as ProjectionType,qe as Query,Je as QueryInstance,Zn as RenderPipeline,jn as RenderStage,Pi as RenderTexture,Gn as Renderer,He as Res,je as ResMut,ze as RigidBody,G as RuntimeConfig,Vr as SafeArea,ve as ScaleMode,rs as SceneManager,ss as SceneManagerState,ke as SceneOwner,et as Schedule,tr as ScreenSpace,Wr as ScrollView,Wt as ShaderSources,Or as Slider,Lr as SliderDirection,Ie as SpineAnimation,Pe as Sprite,at as SystemRunner,Fs as Text,As as TextAlign,mr as TextInput,_r as TextInputPlugin,Is as TextOverflow,$s as TextPlugin,ks as TextRenderer,Rs as TextVerticalAlign,Ne as Time,Mr as Toggle,xt as UICameraInfo,Zs as UIEventQueue,er as UIEvents,Js as UIInteraction,gr as UIInteractionPlugin,ar as UILayoutPlugin,Ws as UIMask,Vs as UIMaskPlugin,bs as UIRect,Te as Velocity,vi as WebAssetProvider,wt as World,Se as WorldTransform,it as addStartupSystem,rt as addSystem,ot as addSystemToSchedule,q as applyRuntimeConfig,Zt as assetPlugin,Tn as clearDrawCallbacks,de as clearUserComponents,ne as color,nr as computeUIRectLayout,Ns as createMaskProcessor,xi as createRuntimeSceneConfig,Li as createWebApp,zi as debug,le as defineComponent,Oe as defineResource,nt as defineSystem,ce as defineTag,Wi as error,qt as findEntityByName,cs as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,M as getAllAssetExtensions,A as getAssetMimeType,x as getAssetTypeEntry,me as getComponent,jt as getComponentAssetFields,Be as getComponentDefaults,T as getCustomExtensions,v as getEditorType,ki as getLogger,t as getPlatform,s as getPlatformType,he as getUserComponent,C as getWeChatPackOptions,$i as info,yn as initDrawAPI,Jn as initGLDebugAPI,kn as initGeometryAPI,Tt as initMaterialAPI,Wn as initPostProcessAPI,Nn as initRendererAPI,dt as inputPlugin,nn as instantiatePrefab,Ds as intersectRects,Os as invertMatrix4,pe as isBuiltinComponent,R as isCustomExtension,Ti as isEditor,P as isKnownAssetExtension,n as isPlatformInitialized,Ci as isRuntime,bt as isTextureRef,r as isWeChat,i as isWeb,Vt as loadComponent,li as loadPhysicsModule,wi as loadRuntimeScene,Yt as loadSceneData,Nt as loadSceneWithAssets,E as looksLikeAssetPath,o as platformFetch,c as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Xs as pointInOBB,js as pointInWorldRect,hn as prefabsPlugin,se as quat,ye as registerComponent,Ht as registerComponentAssetFields,Mn as registerDrawCallback,tn as registerEmbeddedAssets,Ut as registerMaterialCallback,as as sceneManagerPlugin,Hs as screenToWorld,Ei as setEditorMode,Kr as setListViewRenderer,Bi as setLogLevel,yt as setWasmErrorHandler,mn as shutdownDrawAPI,Kn as shutdownGLDebugAPI,Bn as shutdownGeometryAPI,Ct as shutdownMaterialAPI,Dn as shutdownPostProcessAPI,Vn as shutdownRendererAPI,wr as textInputPlugin,Us as textPlugin,ai as transitionTo,yr as uiInteractionPlugin,lr as uiLayoutPlugin,Gs as uiMaskPlugin,Di as uiPlugins,ue as unregisterComponent,En as unregisterDrawCallback,Gt as updateCameraAspectRatio,Z as vec2,ee as vec3,te as vec4,Ui as warn,Ls as worldRectToScreen,is as wrapSceneSystem,$ as wxFileExists,U as wxFileExistsSync,L as wxGetImagePixels,D as wxLoadImage,O as wxLoadImagePixels,B as wxReadFile,z as wxReadTextFile,W as wxWriteFile};
//# sourceMappingURL=index.wechat.js.map
diff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.ts
index 5030484e1..ee8db391e 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -1710,21 +1710,38 @@ declare class InputPlugin implements Plugin {
}
declare const inputPlugin: InputPlugin;
-declare enum TextAlign {
- Left = 0,
- Center = 1,
- Right = 2
-}
-declare enum TextVerticalAlign {
- Top = 0,
- Middle = 1,
- Bottom = 2
-}
-declare enum TextOverflow {
- Visible = 0,
- Clip = 1,
- Ellipsis = 2
+interface ColorTransition {
+ normalColor: Color;
+ hoveredColor: Color;
+ pressedColor: Color;
+ disabledColor: Color;
}
+declare const FillDirection: {
+ readonly LeftToRight: 0;
+ readonly RightToLeft: 1;
+ readonly BottomToTop: 2;
+ readonly TopToBottom: 3;
+};
+type FillDirection = (typeof FillDirection)[keyof typeof FillDirection];
+
+declare const TextAlign: {
+ readonly Left: 0;
+ readonly Center: 1;
+ readonly Right: 2;
+};
+type TextAlign = (typeof TextAlign)[keyof typeof TextAlign];
+declare const TextVerticalAlign: {
+ readonly Top: 0;
+ readonly Middle: 1;
+ readonly Bottom: 2;
+};
+type TextVerticalAlign = (typeof TextVerticalAlign)[keyof typeof TextVerticalAlign];
+declare const TextOverflow: {
+ readonly Visible: 0;
+ readonly Clip: 1;
+ readonly Ellipsis: 2;
+};
+type TextOverflow = (typeof TextOverflow)[keyof typeof TextOverflow];
interface TextData {
content: string;
fontFamily: string;
@@ -1745,6 +1762,7 @@ interface UIRectData {
offsetMax: Vec2;
size: Vec2;
pivot: Vec2;
+ _dirty: boolean;
}
declare const UIRect: ComponentDef<UIRectData>;
@@ -1753,6 +1771,12 @@ declare const UIRect: ComponentDef<UIRectData>;
* @brief Renders text to GPU textures using Canvas 2D API
*/
+interface SizedRect {
+ size: {
+ x: number;
+ y: number;
+ };
+}
interface TextRenderResult {
textureHandle: number;
width: number;
@@ -1767,12 +1791,12 @@ declare class TextRenderer {
/**
* Renders text to a texture and returns the handle
*/
- renderText(text: TextData, uiRect?: UIRectData | null): TextRenderResult;
+ renderText(text: TextData, uiRect?: SizedRect | null): TextRenderResult;
private truncateWithEllipsis;
/**
* Renders text for an entity and caches the result
*/
- renderForEntity(entity: Entity, text: TextData, uiRect?: UIRectData | null): TextRenderResult;
+ renderForEntity(entity: Entity, text: TextData, uiRect?: SizedRect | null): TextRenderResult;
/**
* Gets cached render result for entity
*/
@@ -1786,10 +1810,8 @@ declare class TextRenderer {
* Releases all cached textures
*/
releaseAll(): void;
- private wrapText;
private measureWidth;
private mapAlign;
- private nextPowerOf2;
}
/**
@@ -1834,6 +1856,7 @@ declare function pointInOBB(px: number, py: number, worldX: number, worldY: numb
interface InteractableData {
enabled: boolean;
blockRaycast: boolean;
+ raycastTarget: boolean;
}
declare const Interactable: ComponentDef<InteractableData>;
@@ -1845,26 +1868,21 @@ interface UIInteractionData {
}
declare const UIInteraction: ComponentDef<UIInteractionData>;
-declare enum ButtonState {
- Normal = 0,
- Hovered = 1,
- Pressed = 2,
- Disabled = 3
-}
-interface ButtonTransition {
- normalColor: Color;
- hoveredColor: Color;
- pressedColor: Color;
- disabledColor: Color;
-}
+type ButtonTransition = ColorTransition;
+declare const ButtonState: {
+ readonly Normal: 0;
+ readonly Hovered: 1;
+ readonly Pressed: 2;
+ readonly Disabled: 3;
+};
+type ButtonState = (typeof ButtonState)[keyof typeof ButtonState];
interface ButtonData {
state: ButtonState;
- transition: ButtonTransition | null;
- enabled: boolean;
+ transition: ColorTransition | null;
}
declare const Button: ComponentDef<ButtonData>;
-type UIEventType = 'click' | 'press' | 'release' | 'hover_enter' | 'hover_exit' | 'submit' | 'change' | 'drag_start' | 'drag_move' | 'drag_end' | 'scroll';
+type UIEventType = 'click' | 'press' | 'release' | 'hover_enter' | 'hover_exit' | 'focus' | 'blur' | 'submit' | 'change' | 'drag_start' | 'drag_move' | 'drag_end' | 'scroll';
interface UIEvent {
entity: Entity;
type: UIEventType;
@@ -1892,6 +1910,8 @@ interface UICameraData {
worldBottom: number;
worldRight: number;
worldTop: number;
+ worldMouseX: number;
+ worldMouseY: number;
valid: boolean;
}
declare const UICameraInfo: ResourceDef<UICameraData>;
@@ -1991,36 +2011,36 @@ interface ImageData {
fillOrigin: number;
fillAmount: number;
preserveAspect: boolean;
+ tileSize: {
+ x: number;
+ y: number;
+ };
layer: number;
material: number;
enabled: boolean;
}
declare const Image: ComponentDef<ImageData>;
-interface ToggleTransition {
- normalColor: Color;
- hoveredColor: Color;
- pressedColor: Color;
- disabledColor: Color;
-}
+type ToggleTransition = ColorTransition;
interface ToggleData {
isOn: boolean;
graphicEntity: Entity;
- transition: ToggleTransition | null;
- enabled: boolean;
+ group: Entity;
+ transition: ColorTransition | null;
}
declare const Toggle: ComponentDef<ToggleData>;
-declare enum ProgressBarDirection {
- LeftToRight = 0,
- RightToLeft = 1,
- BottomToTop = 2,
- TopToBottom = 3
-}
+declare const ProgressBarDirection: {
+ readonly LeftToRight: 0;
+ readonly RightToLeft: 1;
+ readonly BottomToTop: 2;
+ readonly TopToBottom: 3;
+};
+type ProgressBarDirection = FillDirection;
interface ProgressBarData {
value: number;
fillEntity: Entity;
- direction: number;
+ direction: FillDirection;
}
declare const ProgressBar: ComponentDef<ProgressBarData>;
@@ -2065,7 +2085,7 @@ interface DragStateData {
declare const DragState: ComponentDef<DragStateData>;
interface ScrollViewData {
- contentEntity: number;
+ contentEntity: Entity;
horizontalEnabled: boolean;
verticalEnabled: boolean;
contentWidth: number;
@@ -2077,21 +2097,21 @@ interface ScrollViewData {
}
declare const ScrollView: ComponentDef<ScrollViewData>;
-declare enum SliderDirection {
- LeftToRight = 0,
- RightToLeft = 1,
- BottomToTop = 2,
- TopToBottom = 3
-}
+declare const SliderDirection: {
+ readonly LeftToRight: 0;
+ readonly RightToLeft: 1;
+ readonly BottomToTop: 2;
+ readonly TopToBottom: 3;
+};
+type SliderDirection = FillDirection;
interface SliderData {
value: number;
minValue: number;
maxValue: number;
- direction: SliderDirection;
- fillEntity: number;
- handleEntity: number;
+ direction: FillDirection;
+ fillEntity: Entity;
+ handleEntity: Entity;
wholeNumbers: boolean;
- enabled: boolean;
}
declare const Slider: ComponentDef<SliderData>;
@@ -2130,8 +2150,8 @@ interface DropdownData {
options: string[];
selectedIndex: number;
isOpen: boolean;
- listEntity: number;
- labelEntity: number;
+ listEntity: Entity;
+ labelEntity: Entity;
}
declare const Dropdown: ComponentDef<DropdownData>;
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index 6adb25e2c..c801e099b 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function h(e,n){return t().instantiateWasm(e,n)}function u(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},i=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},h=()=>{e.onPointerUp(0)},u=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",o),n.addEventListener("mousedown",i),n.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",h),n.addEventListener("wheel",u),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",i),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",h),n.removeEventListener("wheel",u)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,g=1080,m=100,y=512,_={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=_.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=_.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=_.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=_.canvasMatchWidthOrHeight)}const x=0,v=4294967295,b=4294967295,S=(e=0,t=0)=>({x:e,y:t}),P=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),M=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),T=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),E=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function C(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(C);const t={};for(const n in e)t[n]=C(e[n]);return t}let R=0;function A(e,t){const n=++R;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...C(t),...e}:C(t)}}function F(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function I(e,t){const n=F(),s=n.get(e);if(s)return s;const r=A(e,t);return n.set(e,r),U(e,t,!1),r}function k(e){const t=F(),n=t.get(e);if(n)return n;const s=A(e,{});return t.set(e,s),U(e,{},!0),s}function B(e){return F().get(e)}function $(){F().clear()}function D(e){F().delete(e)}function U(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function z(e){return!0===e._builtin}const L=new Map;function W(e,t){L.set(e,t)}function O(e){return L.get(e)??B(e)}function H(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return L.set(e,n),n}const j={Perspective:0,Orthographic:1},X={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Y={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},N=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}}),V=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}}),q=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,enabled:!0}),G=H("Camera",{projectionType:j.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:X.ColorAndDepth}),J=H("Canvas",{designResolution:{x:p,y:g},pixelsPerUnit:100,scaleMode:Y.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),K=H("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Q=H("Parent",{entity:0}),Z=H("Children",{entities:[]}),ee=H("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:b,enabled:!0}),te=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,enabled:!0}),ne={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},se=I("SceneOwner",{scene:"",persistent:!1});function re(e){const t=O(e);return t?C(t._default):null}W("Name",ne);const oe=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,enabled:!0}),ae=H("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),le=H("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ce={Static:0,Kinematic:1,Dynamic:2};let he=0;function ue(e,t){const n=++he;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function de(e){return{_type:"res",_resource:e}}function fe(e){return{_type:"res_mut",_resource:e}}class pe{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 ge{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 pe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const me=ue({delta:0,elapsed:0,frameCount:0},"Time");function ye(e){return{_type:"mut",_component:e}}function _e(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function we(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{_e(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class xe{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>_e(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_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=n.length,o=e.length>0,i=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let h=null;this.world_.beginIteration();try{for(const u of s){if(null!==h&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];h=u}yield a}}finally{if(this.world_.endIteration(),null!==h&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){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 ve(){return{_type:"commands"}}class be{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=z(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Se{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new be(this,null);return this.spawned_.push(e),e}entity(e){return new be(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Pe;!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"}(Pe||(Pe={}));let Me=0;function Te(e,t,n){const s=++Me;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Ee(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ce(e){Ee().push({schedule:Pe.Update,system:e})}function Re(e){Ee().push({schedule:Pe.Startup,system:e})}function Ae(e,t){Ee().push({schedule:e,system:t})}class Fe{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 n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Se&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new xe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Se(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 ke=ue(new Ie,"Input");class Be{constructor(e){this.target_=e??null}build(e){const n=new Ie;e.insertResource(ke,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Pe.Last,Te([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const $e=new Be;function De(e,t,n){const s=[];for(const[e,r]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const n=Ue(t[e]),o=Ue(r);"null"!==n&&"undefined"!==n&&(n!==o&&null!=r&&s.push({field:e,expected:n,actual:o,value:r}))}return s}function Ue(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ze(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let Le=null;function We(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 n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="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 je{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 n of t)this.tsStorage_.get(n)?.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(n){Oe(n,`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,n){return z(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return z(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return z(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(z(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Oe(n,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");z(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=De(t._name,t._default,s);if(e.length>0)throw new Error(ze(t._name,e))}const r={...t._default,...s};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(r))}catch(n){Oe(n,`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(n){return Oe(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return Oe(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Oe(n,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const r=De(t._name,t._default,e);if(r.length>0)throw new Error(ze(t._name,r));s=e}const r=t.create(s);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.push(n)}catch{}if(this.cppRegistry_)for(const[n,s]of L)if(z(s)&&!t.includes(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.push(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const s of n)for(const[n,r]of e)if(r._id===s){t.push(n);break}}return t}getEntitiesWithComponents(e,t=[],n=[]){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();let s=e.map(e=>e._name).sort().join(",");t.length>0&&(s+="|+"+t.map(e=>e._name).sort().join(",")),n.length>0&&(s+="|-"+n.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(s);if(r&&r.version===this.worldVersion_)return r.result;let o=null,i=1/0;for(const t of e)if(!z(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<i&&(i=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=o?o.keys():this.entities_;for(const t of l){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&a.push(t)}return this.queryCache_.set(s,{version:this.worldVersion_,result:a}),a}}const Xe=ue({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 Ye;function Ne(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"}(Ye||(Ye={}));let Ve=null,qe=null,Ge=1;const Je=new Map;function Ke(e){Ve=e,qe=e.getResourceManager(),at()}function Qe(){0!==nt&&Ve&&(Ve._free(nt),nt=0),Je.clear(),Ge=1,tt=!1,rt.clear(),ot=null,qe=null,Ve=null}function Ze(){if(!qe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return qe}const et={createShader:(e,t)=>Ze().createShader(e,t),releaseShader(e){e>0&&Ze().releaseShader(e)},create(e){const t=Ge++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ye.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Je.set(t,n),t},get:e=>Je.get(e),setUniform(e,t,n){const s=Je.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=Je.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Je.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Je.get(e);return t?.blendMode??Ye.Normal},setDepthTest(e,t){const n=Je.get(e);n&&(n.depthTest=t)},getShader(e){const t=Je.get(e);return t?.shader??0},release(e){Je.delete(e)},isValid:e=>Je.has(e),releaseAll(){Je.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Ye.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Je.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ge++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Je.set(n,s),n},toAssetData(e,t){const n=Je.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=Je.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let tt=!1,nt=0;const st=4096,rt=new Map;let ot=null;function it(e){const t=(0===nt&&Ve&&(nt=Ve._malloc(st)),nt);if(0===t||!Ve)return{ptr:0,count:0};let n=0,s=0;const r=Ve.HEAPU8,o=Ve.HEAPU32,i=Ve.HEAPF32;for(const[a,l]of e){if(n+128>st)break;let e=rt.get(a);e||(ot||(ot=new TextEncoder),e=ot.encode(a),rt.set(a,e));const c=e.length,h=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=h;let u=0,d=[0,0,0,0];if("number"==typeof l)u=0,d[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(u=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,d=[l.x,l.y,l.z,0]):"y"in l&&(u=1,d=[l.x,l.y,0,0]);o[t+n>>2]=u,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function at(){if(!Ve||tt)return;Ve.materialDataProvider=(e,t,n,s,r)=>{const o=Je.get(e);if(!o)return Ve.HEAPU32[t>>2]=0,Ve.HEAPU32[n>>2]=0,Ve.HEAPU32[s>>2]=0,void(Ve.HEAPU32[r>>2]=0);Ve.HEAPU32[t>>2]=o.shader,Ve.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=it(o.uniforms);Ve.HEAPU32[s>>2]=i,Ve.HEAPU32[r>>2]=a},tt=!0}const lt={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,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class ht{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&&(et.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())et.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:et.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const ut=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}]]);function dt(e,t){ut.set(e,t)}function ft(e){const t=ut.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function pt(e){return ut.get(e)?.fields??[]}function gt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ne,{value:s.name}),!1!==s.visible)for(const n of s.components)yt(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)}return n}async function mt(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ut.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,h=new Map,u=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)d.push((async()=>{try{const s=await t.loadMaterial(e,n);h.set(e,s.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of i)d.push((async()=>{try{const s=await t.loadBitmapFont(e,n);u.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)d.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ut.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=h.get(t)??0;break;case"font":n[e.field]=u.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,ne,{value:n.name}),!1!==n.visible)for(const s of n.components)yt(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)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function yt(e,t,n,s){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=O(n.type);if(r)e.insert(t,r,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function _t(e,t){const n=e.getEntitiesWithComponents([G]);for(const s of n){const n=e.get(s,G);n&&(n.aspectRatio=t,e.insert(s,G,n))}}function wt(e,t){const n=e.getEntitiesWithComponents([ne]);for(const s of n){const n=e.get(s,ne);if(n&&n.value===t)return s}return null}const xt=[{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}],vt={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"},bt=new Map,St=new Set;for(const e of xt)for(const t of e.extensions)bt.set(t,e),St.add(t);function Pt(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Mt(e){return bt.get(Pt(e))}function Tt(e){return Mt(e)?.editorType??"unknown"}function Et(e){return Mt(e)?.addressableType??null}function Ct(e){for(const t of xt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Rt(e){return St.has(e.toLowerCase())}function At(){return St}function Ft(e){return"string"==typeof e&&(!!e.includes("/")&&Rt(Pt(e)))}function It(){const e=[];for(const t of xt)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function kt(){return It().map(e=>({type:"suffix",value:e}))}function Bt(e){return vt[e.toLowerCase()]}function $t(e){const t=Mt(e);return t?.wechatPackInclude??!1}class Dt{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(_.textCanvasSize,_.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new ht(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);if(!r)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),et.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),h="binary"===Mt(e)?.contentType,u=h?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,h);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=Mt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return mt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return et.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return et.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){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 n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ut=ue(null,"Assets");class zt{build(e){const t=e.wasmModule;t?e.insertResource(Ut,new Dt(t)):console.warn("AssetPlugin: No WASM module available")}}const Lt=new zt;class Wt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Ot(e,t){const n=e.getResource(Ut);n&&n.registerEmbeddedAssets(t)}async function Ht(e,t,n){const{entities:s,rootId:r}=await Xt(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await mt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}const jt=10;async function Xt(e,t,n,s,r,o=0){if(o>jt)throw new Error(`Prefab nesting depth exceeded ${jt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Xt(e,s.nestedPrefab.overrides,n,a,r,o+1);i.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?i.get(s.parent)??null:null),l.push(...t.entities);continue}const c=i.get(s.prefabEntityId),h=s.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:h?null:null!==s.parent?i.get(s.parent)??null:null,children:s.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Yt(u,t),l.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Yt(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Nt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Ht(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Vt=ue(null,"Prefabs");class qt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ut]}build(e){const t=e.getResource(Ut);e.insertResource(Vt,new Nt(e.world,t))}}const Gt=new qt;let Jt=null,Kt=0,Qt=0,Zt=0;const en=new Float32Array(256);function tn(e){Jt=e,Kt=Jt._malloc(64),Qt=Jt._malloc(64),Zt=Jt._malloc(1024)}function nn(){Jt&&(Kt&&(Jt._free(Kt),Kt=0),Qt&&(Jt._free(Qt),Qt=0),Zt&&(Jt._free(Zt),Zt=0)),Jt=null}function sn(){if(!Jt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Jt}const rn={r:1,g:1,b:1,a:1},on={begin(e){const t=sn();try{t.HEAPF32.set(e,Kt/4),t.draw_begin(Kt)}catch(e){Oe(e,"Draw.begin")}},end(){try{sn().draw_end()}catch(e){Oe(e,"Draw.end")}},line(e,t,n,s=1){try{sn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Oe(e,"Draw.line")}},rect(e,t,n,s=!0){try{sn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Oe(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{sn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Oe(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,r=32){try{sn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){Oe(e,"Draw.circle")}},circleOutline(e,t,n,s=1,r=32){try{sn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){Oe(e,"Draw.circleOutline")}},texture(e,t,n,s=rn){try{sn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Oe(e,"Draw.texture")}},textureRotated(e,t,n,s,r=rn){try{sn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)}catch(e){Oe(e,"Draw.textureRotated")}},setLayer(e){sn().draw_setLayer(e)},setDepth(e){sn().draw_setDepth(e)},getDrawCallCount:()=>Jt?Jt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Jt?Jt.draw_getPrimitiveCount():0,setBlendMode(e){sn().draw_setBlendMode(e)},setDepthTest(e){sn().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=sn();s.HEAPF32.set(n,Qt/4),s.draw_mesh(e,t,Qt)}catch(n){Oe(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=sn(),r=et.get(t);if(!r)return;if(on.setBlendMode(r.blendMode),on.setDepthTest(r.depthTest),0===r.uniforms.size)return void on.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,Qt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=cn(t);if(!(s<0)){if(Ne(n))en[o++]=10,en[o++]=s,en[o++]=n.slot??e++,en[o++]=n.textureId;else if("number"==typeof n)en[o++]=1,en[o++]=s,en[o++]=n;else if(Array.isArray(n)){en[o++]=n.length,en[o++]=s;for(let e=0;e<n.length;e++)en[o++]=n[e]}else"w"in n?(en[o++]=4,en[o++]=s,en[o++]=n.x,en[o++]=n.y,en[o++]=n.z,en[o++]=n.w):"z"in n?(en[o++]=3,en[o++]=s,en[o++]=n.x,en[o++]=n.y,en[o++]=n.z):(en[o++]=2,en[o++]=s,en[o++]=n.x,en[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(en.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void s.draw_mesh(e,r.shader,Qt);s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Zt/4),s.draw_meshWithUniforms(e,r.shader,Qt,Zt,o)}catch(n){Oe(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},an={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},ln=new Set;function cn(e){const t=an[e];return void 0!==t?t:(ln.has(e)||(ln.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(an).join(", ")}`)),-1)}const hn=new Map;function un(e,t,n){hn.set(e,{fn:t,scene:n??""})}function dn(e){hn.delete(e)}function fn(){hn.clear()}var pn;!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"}(pn||(pn={}));let gn=null,mn=0,yn=0,_n=0;function wn(e){gn=e,mn=gn._malloc(262144),yn=gn._malloc(65536),_n=gn._malloc(256)}function xn(){gn&&(mn&&gn._free(mn),yn&&gn._free(yn),_n&&gn._free(_n),mn=0,yn=0,_n=0),gn=null}function vn(){if(!gn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return gn}const bn={create(e){const t=vn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,mn/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,_n,r).set(o),t.geometry_init(n,mn,s,_n,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,yn,s).set(e.indices),t.geometry_setIndices16(n,yn,s)}else{new Uint32Array(t.HEAPU8.buffer,yn,s).set(e.indices),t.geometry_setIndices32(n,yn,s)}}return n},updateVertices(e,t,n=0){const s=vn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,mn/4),s.geometry_updateVertices(e,mn,r,n)},release(e){e>0&&vn().geometry_release(e)},isValid:e=>!(!gn||e<=0)&&gn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return bn.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return bn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return bn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array(i)})}};let Sn=null;function Pn(e){Sn=e}function Mn(){Sn&&En.isInitialized()&&En.shutdown(),Sn=null}function Tn(){if(!Sn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Sn}const En={init(e,t){try{return Tn().postprocess_init(e,t)}catch(n){return Oe(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Tn().postprocess_shutdown()}catch(e){Oe(e,"PostProcess.shutdown")}},resize(e,t){try{Tn().postprocess_resize(e,t)}catch(n){Oe(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Tn().postprocess_addPass(e,t)}catch(t){return Oe(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Tn().postprocess_removePass(e)}catch(t){Oe(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Tn().postprocess_setPassEnabled(e,t)}catch(t){Oe(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Tn().postprocess_isPassEnabled(e)}catch(t){return Oe(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Tn().postprocess_setUniformFloat(e,t,n)}catch(n){Oe(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Tn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){Oe(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Tn().postprocess_begin()}catch(e){Oe(e,"PostProcess.begin")}},end(){try{Tn().postprocess_end()}catch(e){Oe(e,"PostProcess.end")}},getPassCount(){try{return Tn().postprocess_getPassCount()}catch(e){return Oe(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Sn)return!1;try{return Sn.postprocess_isInitialized()}catch(e){return Oe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Tn().postprocess_setBypass(e)}catch(e){Oe(e,"PostProcess.setBypass")}},isBypassed(){if(!Sn)return!0;try{return Sn.postprocess_isBypassed()}catch(e){return Oe(e,"PostProcess.isBypassed"),!0}},createBlur:()=>et.createShader(Cn,"#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:()=>et.createShader(Cn,"#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:()=>et.createShader(Cn,"#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:()=>et.createShader(Cn,"#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")},Cn="#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 Rn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Rn||(Rn={}));let An=null,Fn=0;function In(e){An=e,Fn=An._malloc(64)}function kn(){An&&Fn&&(An._free(Fn),Fn=0),An=null}const Bn={init(e,t){An?.renderer_init(e,t)},resize(e,t){An?.renderer_resize(e,t)},begin(e,t){if(An&&Fn)try{An.HEAPF32.set(e,Fn/4),An.renderer_begin(Fn,t??0)}catch(e){Oe(e,"Renderer.begin")}},flush(){try{An?.renderer_flush()}catch(e){Oe(e,"Renderer.flush")}},end(){try{An?.renderer_end()}catch(e){Oe(e,"Renderer.end")}},submitSprites(e){if(An)try{An.renderer_submitSprites(e._cpp)}catch(e){Oe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(An)try{An.renderer_submitBitmapText(e._cpp)}catch(e){Oe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(An)try{An.renderer_submitSpine?.(e._cpp)}catch(e){Oe(e,"Renderer.submitSpine")}},setStage(e){An?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>An?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){An?.renderer_releaseTarget(e)},getTargetTexture:e=>An?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>An?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){An?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){An?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){An?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){An?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>An?An.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>An?{drawCalls:An.renderer_getDrawCalls(),triangles:An.renderer_getTriangles(),sprites:An.renderer_getSprites(),text:An.renderer_getText(),spine:An.renderer_getSpine?.()??0,meshes:An.renderer_getMeshes(),culled:An.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let $n=null;function Dn(e){$n=e}function Un(){$n=null}const zn={enable(){$n?.gl_enableErrorCheck(!0)},disable(){$n?.gl_enableErrorCheck(!1)},check:e=>$n?.gl_checkErrors(e)??0,diagnose(){$n?.renderer_diagnose()}};class Ln{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(Bn.resize(s,r),En.isInitialized()&&En.getPassCount()>0&&En.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Bn.setViewport(0,0,s,r),Bn.clearBuffers(3),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,o),Bn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Bn.setViewport(s.x,s.y,s.w,s.h),Bn.setScissor(s.x,s.y,s.w,s.h,!0),Bn.clearBuffers(r),Bn.setScissor(0,0,0,0,!1),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,o),Bn.end()}executeDrawCallbacks(e,t){const n=hn;if(n.size>0){on.begin(e);const s=[];for(const[e,r]of n.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}on.end();for(const e of s)dn(e)}}}const Wn="__scene_transition_overlay__";class On{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Hn{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),un(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=En.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){En.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 n=this.app_.world.get(e,se);n.persistent=t,this.app_.world.insert(e,se,n)}}}class jn{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(n=>{const s=t.duration??_.sceneTransitionDuration,r=t.color??{..._.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:r,targetScene:e,options:t,resolve:n},un(Wn,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;on.setLayer(9999),on.setDepth(9999),on.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{n&&n!==e&&await this.unload(n,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,dn(Wn)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,dn(Wn),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new On(t);this.scenes_.set(e,n);const s=new Hn(n,this.app_);this.contexts_.set(e,s);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 s=await mt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=Yn(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();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 n=new On(t);this.scenes_.set(e,n);const s=new Hn(n,this.app_);this.contexts_.set(e,s);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 s=await mt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=Yn(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const r=t?.keepPersistent??!0;for(const e of n.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)}n.entities.clear();for(const e of n.drawCallbacks.keys())dn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{En.removePass(e)}catch{}n.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}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,q)){const n=this.app_.world.get(e,q);t.savedAlphas.set(e,n.color.a),n.color={...n.color,a:0},this.app_.world.insert(e,q,n)}}}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,q)){const n=this.app_.world.get(e,q),s=t.savedAlphas.get(e)??1;n.color={...n.color,a:s},this.app_.world.insert(e,q,n)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{En.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Xn=ue(null,"SceneManager");function Yn(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Xn).getSceneStatus(t)&&n._fn(...s)}}}const Nn=Te([fe(Xn),de(me)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Vn={name:"SceneManager",build(e){const t=new jn(e);e.insertResource(Xn,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Xn),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Pe.Startup,n),e.addSystemToSchedule(Pe.Last,Nn)}};class qn{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 n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Pe.Last);else{this.runSchedule(Pe.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Pe.FixedPreUpdate),this.runSchedule(Pe.FixedUpdate),this.runSchedule(Pe.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Pe.PreUpdate),this.runSchedule(Pe.Update),this.runSchedule(Pe.PostUpdate),this.runSchedule(Pe.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new je,this.resources_=new ge;for(const e of Object.values(Pe))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new qn}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,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Pe.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Pe.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 We(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(Xn).register(e),this}setInitialScene(e){return this.getResource(Xn).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Fe(this.world_,this.resources_),this.resources_.insert(me,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Pe.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,fn();const e=[Un,kn,Mn,xn,Qe,nn];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 n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const r=t.get(s);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,r=new Set,o=i=>{if(s.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}r.delete(i),s.add(i),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(me);t.delta=e,t.elapsed+=e,t.frameCount++}}function Gn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Jn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Kn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case Y.FixedWidth:return o;case Y.FixedHeight:return i;case Y.Expand:return Math.max(o,i);case Y.Shrink:return Math.min(o,i);case Y.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Qn(e,t,n,s,r,o){if(0===n||0===s)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,se);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*n/(i.h*s);let h,u=0,d=0;if(r.projectionType===j.Orthographic){if(d=r.orthoSize,l){d=Kn(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}u=d*a,h=es(-u,u,-d,d,-r.farPlane,r.farPlane)}else h=ns(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=rs(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(is(h,f)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:d,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Zn=new Float32Array(16);function es(e,t,n,s,r,o){const i=Zn;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const ts=new Float32Array(16);function ns(e,t,n,s){const r=ts;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const ss=new Float32Array(16);function rs(e,t,n){const s=ss;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const os=new Float32Array(16);function is(e,t){const n=os;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var as,ls,cs;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(as||(as={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(ls||(ls={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(cs||(cs={}));const hs=I("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:as.Left,verticalAlign:ls.Top,wordWrap:!0,overflow:cs.Visible,lineHeight:1.2}),us=I("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 ds{constructor(e){this.cache=new Map,this.module=e,this.canvas=u(_.textCanvasSize,_.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=r?Math.ceil(o):u+2*h,p=r?Math.ceil(i):d+2*h;if(r&&e.overflow===cs.Ellipsis&&d>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const g=Math.round(255*e.color.r),m=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${m}, ${y}, ${_})`,r&&e.overflow===cs.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case ls.Top:x=h;break;case ls.Middle:x=(p-w)/2;break;case ls.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of l){let s;switch(e.align){case as.Left:s=h;break;case as.Center:s=f/2;break;case as.Right:s=f-h;break;default:s=h}n.fillText(t,s,v),v+=c}r&&e.overflow===cs.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);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[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case as.Left:return"left";case as.Center:return"center";case as.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function fs(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 ps(e,t,n){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!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class gs{build(e){W("Text",hs);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ds(t),s=e.world,r=new Map;e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,hs));for(const e of r.keys())s.valid(e)&&s.has(e,hs)||r.delete(e);const e=s.getEntitiesWithComponents([hs]);for(const t of e){const e=s.get(t,hs),o=s.has(t,us)?s.get(t,us):null,i=r.get(t);if(i&&!ps(i,e,o))continue;s.has(t,q)||s.insert(t,q,{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=n.renderForEntity(t,e,o),l=s.get(t,q);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,q,l),r.set(t,fs(e,o))}}))}}const ms=new gs,ys=I("UIMask",{enabled:!0,mode:"scissor"});function _s(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function ws(e,t,n,s,r,o,i,a,l,c,h){const u=e-n*r,d=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function g(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*h]}const[m,y]=g(u,f),[_,w]=g(d,p),x=Math.min(m,_),v=Math.max(m,_),b=Math.min(y,w),S=Math.max(y,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function xs(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],h=e[7],u=e[8],d=e[9],f=e[10],p=e[11],g=e[12],m=e[13],y=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,v=s*h-i*a,b=r*c-o*l,S=r*h-i*l,P=o*h-i*c,M=u*m-d*g,T=u*y-f*g,E=u*_-p*g,C=d*y-f*m,R=d*_-p*m,A=f*_-p*y;let F=w*A-x*R+v*C+b*E-S*T+P*M;return 0===F||(F=1/F,n[0]=(l*A-c*R+h*C)*F,n[1]=(o*R-r*A-i*C)*F,n[2]=(m*P-y*S+_*b)*F,n[3]=(f*S-d*P-p*b)*F,n[4]=(c*E-a*A-h*T)*F,n[5]=(s*A-o*E+i*T)*F,n[6]=(y*v-g*P-_*x)*F,n[7]=(u*P-f*v+p*x)*F,n[8]=(a*R-l*E+h*M)*F,n[9]=(r*E-s*R-i*M)*F,n[10]=(g*S-m*v+_*w)*F,n[11]=(d*v-u*S-p*w)*F,n[12]=(l*T-a*C-c*M)*F,n[13]=(s*C-r*T+o*M)*F,n[14]=(m*x-g*b-y*w)*F,n[15]=(u*b-d*x+f*w)*F),n}function vs(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],h=n[1]*a+n[5]*l+n[13],u=n[3]*a+n[7]*l+n[15];return{x:c/u,y:h/u}}function bs(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function Ss(e,t,n,s,r,o,i,a,l,c){const h=2*Math.atan2(l,c),u=Math.sin(-h),d=Math.cos(-h),f=e-n,p=t-s,g=f*d-p*u+n,m=f*u+p*d+s;return g>=n-r*i&&g<=n+r*(1-i)&&m>=s-o*a&&m<=s+o*(1-a)}function Ps(e,t,n,s,r,o,i){if(!e.has(t,us)||!e.has(t,V))return null;const a=e.get(t,us),l=e.get(t,V),c=a.size.x*l.scale.x,h=a.size.y*l.scale.y;return ws(l.position.x,l.position.y,c,h,a.pivot.x,a.pivot.y,n,s,r,o,i)}function Ms(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([ys]);if(0===l.length)return;const c=[],h=[],u=new Set,d=new Set;for(const e of l){const n=t.get(e,ys);n.enabled&&(u.add(e),"stencil"===n.mode?(h.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,r,o,i,a,l,c){const h=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Q);){const e=t.get(s,Q);if(r.has(e.entity)){if("scissor"===t.get(e.entity,ys).mode){n=!1;break}}s=e.entity}n&&h.push(e)}function u(s,h){const d=e.getChildEntities(n,s);for(const n of d){let s=h;if(r.has(n)){if("scissor"===t.get(n,ys).mode){const e=Ps(t,n,o,i,a,l,c);e&&(s=_s(h,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),u(n,s)}}for(const e of h){const n=Ps(t,e,o,i,a,l,c);n&&u(e,n)}}(e,t,n,c,u,s,r,o,i,a),h.length>0&&function(e,t,n,s,r){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Q);){const e=t.get(s,Q);if(r.has(e.entity)){n=!1;break}s=e.entity}n&&o.push(e)}let i=1;function a(t,s){e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}function l(t,s){const o=e.getChildEntities(n,t);for(const t of o)if(r.has(t)){a(t,i++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}for(const e of o){a(e,i++)}}(e,t,n,h,d)}catch(t){e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Ts{build(e){if(W("UIMask",ys),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Ms(e.wasmModule,e.world))}}const Es=new Ts,Cs=I("Interactable",{enabled:!0,blockRaycast:!0}),Rs=I("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var As;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(As||(As={}));const Fs=I("Button",{state:As.Normal,transition:null,enabled:!0});class Is{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const ks=ue(new Is,"UIEvents"),Bs=k("ScreenSpace");function $s(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,h=o.bottom+e.y*a,u=o.bottom+t.y*a;let d,f,p,g;if(e.x===t.x){const e=l+n.x,t=.5*r.x;d=e-t,p=e+t}else d=l+n.x,p=c+s.x;if(e.y===t.y){const e=h+n.y,t=.5*r.y;f=e-t,g=e+t}else f=h+n.y,g=u+s.y;return{centerX:.5*(d+p),centerY:.5*(f+g),width:p-d,height:g-f,rect:{left:d,bottom:f,right:p,top:g}}}function Ds(e){return{anchorMinX:e.anchorMin.x,anchorMinY:e.anchorMin.y,anchorMaxX:e.anchorMax.x,anchorMaxY:e.anchorMax.y,offsetMinX:e.offsetMin.x,offsetMinY:e.offsetMin.y,offsetMaxX:e.offsetMax.x,offsetMaxY:e.offsetMax.y,sizeX:e.size.x,sizeY:e.size.y}}function Us(e,t){return e.anchorMinX!==t.anchorMin.x||e.anchorMinY!==t.anchorMin.y||e.anchorMaxX!==t.anchorMax.x||e.anchorMaxY!==t.anchorMax.y||e.offsetMinX!==t.offsetMin.x||e.offsetMinY!==t.offsetMin.y||e.offsetMaxX!==t.offsetMax.x||e.offsetMaxY!==t.offsetMax.y||e.sizeX!==t.size.x||e.sizeY!==t.size.y}function zs(e,t){let n=t;for(;;){if(e.has(n,Bs))return n;if(!e.has(n,Q))return null;const t=e.get(n,Q);if(!e.valid(t.entity))return null;n=t.entity}}function Ls(e,t,n,s,r,o){if(!e.has(t,us))return;const i=e.get(t,us),a=$s(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,N);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,N,l),!e.has(t,Z))return;const c=e.get(t,Z);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Ls(e,t,a.rect,a.centerX,a.centerY,!1)}class Ws{build(e){W("UIRect",us);const t=e.world,n=new Map;let s=NaN,r=NaN,o=NaN,i=NaN;e.addSystemToSchedule(Pe.PreUpdate,Te([de(Xe)],e=>{if(!e.valid)return;const a={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},l=.5*(a.left+a.right),c=.5*(a.bottom+a.top),h=s!==e.worldLeft||r!==e.worldBottom||o!==e.worldRight||i!==e.worldTop;s=e.worldLeft,r=e.worldBottom,o=e.worldRight,i=e.worldTop;const u=new Set;if(h){const e=t.getEntitiesWithComponents([Bs,us,N]);for(const t of e)u.add(t)}const d=t.getEntitiesWithComponents([us]);for(const e of d){const s=t.get(e,us),r=n.get(e);if(!r||Us(r,s)){const n=zs(t,e);null!==n&&u.add(n)}}for(const e of n.keys())if(!t.valid(e)||!t.has(e,us)){n.delete(e);const s=zs(t,e);null!==s&&u.add(s)}for(const e of u)Ls(t,e,a,l,c,!0);for(const e of d){const s=t.get(e,us);n.set(e,Ds(s))}},{name:"UILayoutSystem"}))}}const Os=new Ws,Hs=new Float32Array(16),js=new Float32Array(16);let Xs=!0,Ys=1;function Ns(e,t,n,s){t.emit(n,s,n);let r=n;for(;e.has(r,Q);){const o=e.get(r,Q).entity;if(!e.valid(o))break;if(!e.has(o,Cs)){r=o;continue}const i=e.get(o,Cs);if(i.enabled&&t.emit(o,s,n),i.blockRaycast)break;r=o}}class Vs{build(e){W("Interactable",Cs),W("Button",Fs);const t=e.world,n=new Is;e.insertResource(ks,n);let s=null,r=null;Ys="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke),de(Xe)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Rs]);for(const e of i){const n=t.get(e,Rs);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Ys,l=o.screenH-e.mouseY*Ys;!function(e){let t=!1;for(let n=0;n<16;n++)if(js[n]!==e[n]){t=!0;break}t&&(js.set(e),Xs=!0)}(o.viewProjection),Xs&&(xs(o.viewProjection,Hs),Xs=!1);const c=vs(a,l,Hs,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([Cs,us,V]);let u=null,d=-1/0;for(const e of h){t.has(e,Rs)||t.insert(e,Rs);if(!t.get(e,Cs).enabled)continue;const n=t.get(e,V),s=t.get(e,us),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Ss(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y,n.rotation.z,n.rotation.w)){let n=0;t.has(e,q)&&(n=t.get(e,q).layer),n>=d&&(d=n,u=e)}}if(s!==u){if(null!==s&&t.valid(s)&&t.has(s,Rs)){t.get(s,Rs).hovered=!1,n.emit(s,"hover_exit")}if(null!==u){t.get(u,Rs).hovered=!0,n.emit(u,"hover_enter")}s=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,Rs);e.pressed=!0,e.justPressed=!0,r=u,Ns(t,n,u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Rs)){const e=t.get(r,Rs);e.pressed=!1,e.justReleased=!0,Ns(t,n,r,"release"),r===s&&Ns(t,n,r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Pe.Update,Te([],()=>{const e=t.getEntitiesWithComponents([Fs]);for(const n of e){if(t.has(n,Cs)||t.insert(n,Cs,{enabled:!0}),!t.has(n,Rs))continue;const e=t.get(n,Rs),s=t.get(n,Fs),r=t.get(n,Cs),o=s.state;if(r.enabled?e.pressed?s.state=As.Pressed:e.hovered?s.state=As.Hovered:s.state=As.Normal:s.state=As.Disabled,o!==s.state&&s.transition&&t.has(n,q)){const e=t.get(n,q),r=s.transition;switch(s.state){case As.Normal:e.color={...r.normalColor};break;case As.Hovered:e.color={...r.hoveredColor};break;case As.Pressed:e.color={...r.pressedColor};break;case As.Disabled:e.color={...r.disabledColor}}t.insert(n,q,e)}}},{name:"ButtonSystem"}))}}const qs=new Vs,Gs=I("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 Js{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){W("TextInput",Gs);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=u(_.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=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===i||x()},g=()=>{a=!0},m=()=>{a=!1,x()},y=t=>{if(null===i)return;if("Escape"===t.key)return void S();const s=n.get(i,Gs);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(ks).emit(i,"submit"),void S()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,P())},w=()=>{if(null!==i&&n.valid(i)&&n.has(i,Gs)){const e=n.get(i,Gs);e.focused=!1,e.dirty=!0}i=null};function x(){if(null===i||!n.valid(i))return;const t=n.get(i,Gs);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(ks).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,P()}function b(e){if(i===e)return;S();const t=n.get(e,Gs);t.readOnly||(i=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!==i&&n.valid(i)&&n.has(i,Gs)){const e=n.get(i,Gs);e.focused=!1,e.dirty=!0}i=null,f.blur()}function P(){l=!0,c=0}function M(e,i,a,c){(r.width<a||r.height<c)&&(r.width=Qs(Math.max(r.width,a)),r.height=Qs(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const h=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const u=0===i.value.length,d=u?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=u?i.placeholderColor:i.color;o.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*i.fontSize),g=i.padding;if(i.multiline){const e=Ks(o,d,a-2*g);let t=g;for(const n of e)o.fillText(n,g,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(d,g,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=Ks(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,n=g+(e.length-1)*p,s=p}else t=g+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const m=o.getImageData(0,0,a,c),y=new Uint8Array(m.data.buffer),_=t.getResourceManager(),w=t._malloc(y.length);t.HEAPU8.set(y,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const v=_.createTexture(a,c,w,y.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,q);b.texture=v,b.size.x=a,b.size.y=c,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},n.insert(e,q,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",g),f.addEventListener("compositionend",m),f.addEventListener("keydown",y),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",g),f.removeEventListener("compositionend",m),f.removeEventListener("keydown",y),f.removeEventListener("blur",w),f.remove()},e.addSystemToSchedule(Pe.PreUpdate,Te([de(ks)],e=>{const t=n.getEntitiesWithComponents([Gs,Cs]);for(const e of t){if(!n.has(e,Rs))continue;if(n.get(e,Rs).justPressed)return void b(e)}if(null!==i){const e=n.getEntitiesWithComponents([Cs]);for(const t of e){if(n.has(t,Gs))continue;if(!n.has(t,Rs))continue;if(n.get(t,Rs).justPressed)return void S()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,Gs)))){n.get(i,Gs).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Gs)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Gs,us]);for(const e of a){const t=n.get(e,Gs);if(!t.dirty)continue;const s=n.get(e,us),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,q)||n.insert(e,q,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),M(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Ks(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function Qs(e){let t=1;for(;t<e;)t*=2;return t}const Zs=new Js,er={Simple:0,Sliced:1,Tiled:2,Filled:3},tr={Horizontal:0,Vertical:1},nr={Left:0,Right:1,Bottom:2,Top:3},sr=I("Image",{texture:v,color:{r:1,g:1,b:1,a:1},imageType:er.Simple,fillMethod:tr.Horizontal,fillOrigin:nr.Left,fillAmount:1,preserveAspect:!1,layer:0,material:0,enabled:!0});const rr=new class{build(e){W("Image",sr);const t=e.world;e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{const e=t.getEntitiesWithComponents([sr]);for(const n of e){const e=t.get(n,sr);t.has(n,q)||t.insert(n,q,{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 s=t.get(n,q);if(s.texture=e.texture,s.color.r=e.color.r,s.color.g=e.color.g,s.color.b=e.color.b,s.color.a=e.color.a,s.layer=e.layer,s.material=e.material,t.has(n,us)){const e=t.get(n,us);s.size.x=e.size.x,s.size.y=e.size.y}if(s.uvOffset.x=0,s.uvOffset.y=0,s.uvScale.x=1,s.uvScale.y=1,e.imageType===er.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));e.fillMethod===tr.Horizontal?e.fillOrigin===nr.Left?(s.uvScale.x=t,s.size.x*=t):(s.uvOffset.x=1-t,s.uvScale.x=t,s.size.x*=t):e.fillOrigin===nr.Bottom?(s.uvScale.y=t,s.size.y*=t):(s.uvOffset.y=1-t,s.uvScale.y=t,s.size.y*=t)}t.insert(n,q,s)}},{name:"ImageSystem"}))}},or=I("Toggle",{isOn:!0,graphicEntity:0,transition:null,enabled:!0});const ir=new class{build(e){W("Toggle",or);const t=e.world;e.addSystemToSchedule(Pe.Update,Te([de(ks)],e=>{const n=t.getEntitiesWithComponents([or]);for(const s of n){if(t.has(s,Cs)||t.insert(s,Cs,{enabled:!0}),!t.has(s,Rs))continue;const n=t.get(s,Rs),r=t.get(s,or),o=t.get(s,Cs);if(n.justPressed&&o.enabled&&(r.isOn=!r.isOn,e.emit(s,"change")),r.graphicEntity&&t.valid(r.graphicEntity)){const e=r.graphicEntity;if(t.has(e,q)){const n=t.get(e,q);n.color.a=r.isOn?1:0,t.insert(e,q,n)}}if(r.transition&&t.has(s,q)){const e=t.get(s,q),i=r.transition;o.enabled?n.pressed?e.color={...i.pressedColor}:n.hovered?e.color={...i.hoveredColor}:e.color={...i.normalColor}:e.color={...i.disabledColor},t.insert(s,q,e)}}},{name:"ToggleSystem"}))}};var ar;!function(e){e[e.LeftToRight=0]="LeftToRight",e[e.RightToLeft=1]="RightToLeft",e[e.BottomToTop=2]="BottomToTop",e[e.TopToBottom=3]="TopToBottom"}(ar||(ar={}));const lr=I("ProgressBar",{value:0,fillEntity:0,direction:ar.LeftToRight});const cr=new class{build(e){W("ProgressBar",lr);const t=e.world;e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{const e=t.getEntitiesWithComponents([lr,us]);for(const n of e){const e=t.get(n,lr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=e.fillEntity;if(!t.has(s,us))continue;const r=t.get(s,us),o=Math.max(0,Math.min(1,e.value));switch(e.direction){case ar.LeftToRight:r.anchorMin={x:0,y:0},r.anchorMax={x:o,y:1};break;case ar.RightToLeft:r.anchorMin={x:1-o,y:0},r.anchorMax={x:1,y:1};break;case ar.BottomToTop:r.anchorMin={x:0,y:0},r.anchorMax={x:1,y:o};break;case ar.TopToBottom:r.anchorMin={x:0,y:1-o},r.anchorMax={x:1,y:1}}r.offsetMin={x:0,y:0},r.offsetMax={x:0,y:0},t.insert(s,us,r)}},{name:"ProgressBarSystem"}))}},hr=I("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),ur=I("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}}),dr=new Float32Array(16),fr=new Float32Array(16);let pr=!0;function gr(e,t,n){const s=e.mouseX*n,r=t.screenH-e.mouseY*n;return function(e){let t=!1;for(let n=0;n<16;n++)if(fr[n]!==e[n]){t=!0;break}t&&(fr.set(e),pr=!0)}(t.viewProjection),pr&&(xs(t.viewProjection,dr),pr=!1),vs(s,r,dr,t.vpX,t.vpY,t.vpW,t.vpH)}const mr=new class{build(e){W("Draggable",hr),W("DragState",ur);const t=e.world,n=e.getResource(ks);let s=null,r={x:0,y:0},o=null;const i="undefined"!=typeof window&&window.devicePixelRatio||1;e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke),de(Xe)],(e,a)=>{if(!a.valid)return;const l=gr(e,a,i);if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([hr,Rs]);let n=null;for(const s of e){if(!t.get(s,hr).enabled)continue;t.get(s,Rs).hovered&&(n=s)}if(null!==n){s=n,r={x:l.x,y:l.y},t.has(n,ur)||t.insert(n,ur);const e=t.get(n,ur),o=t.get(n,V);e.startWorldPos={x:o.position.x,y:o.position.y},e.currentWorldPos={x:o.position.x,y:o.position.y},e.pointerStartWorld={x:l.x,y:l.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,ur)){t.get(s,ur).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=l.x-r.x,i=l.y-r.y,c=Math.sqrt(e*e+i*i),h=t.get(s,hr);if(c*(a.vpW/(a.worldRight-a.worldLeft))>=h.dragThreshold){o=s,s=null;t.get(o,ur).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,ur))return void(o=null);const s=t.get(o,ur),r=t.get(o,hr),i=l.x-s.pointerStartWorld.x,a=l.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+i,h=s.startWorldPos.y+a;const u=function(e,t,n,s){let r=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,s,c,h);c=u.x,h=u.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:h-f},s.currentWorldPos={x:c,y:h},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:h-s.startWorldPos.y},t.has(o,N)){const e=function(e,t,n,s){if(!e.has(t,Q))return{x:n,y:s};const r=e.get(t,Q).entity;if(!e.valid(r)||!e.has(r,V))return{x:n,y:s};const o=e.get(r,V),i=0!==o.scale.x?o.scale.x:1,a=0!==o.scale.y?o.scale.y:1,l=2*Math.atan2(o.rotation.z,o.rotation.w),c=Math.sin(-l),h=Math.cos(-l);return{x:(n*h-s*c)/i,y:(n*c+s*h)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,N);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,N,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},yr=I("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const _r=new class{build(e){W("ScrollView",yr);const t=e.world,n=new Map,s=new Float32Array(16),r="undefined"!=typeof window&&window.devicePixelRatio||1;let o=0;e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke),de(Xe)],(e,i)=>{const a=performance.now()/1e3,l=o>0?Math.min(a-o,.05):0;if(o=a,!i.valid)return;const c=e.mouseX*r,h=i.screenH-e.mouseY*r;xs(i.viewProjection,s);const u=vs(c,h,s,i.vpX,i.vpY,i.vpW,i.vpH),d=t.getEntitiesWithComponents([yr,us]);for(const s of d){t.has(s,Cs)||t.insert(s,Cs,{enabled:!0,blockRaycast:!0}),t.has(s,ys)||t.insert(s,ys,{enabled:!0,mode:"scissor"});const r=t.get(s,yr),o=t.get(s,us);let i=n.get(s);i||(i={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},n.set(s,i));const a=t.has(s,Rs)?t.get(s,Rs):null;if(a?.justPressed&&(i.isDragging=!0,i.lastWorldX=u.x,i.lastWorldY=u.y,i.velocityX=0,i.velocityY=0),i.isDragging&&e.isMouseButtonDown(0)){const e=u.x-i.lastWorldX,t=u.y-i.lastWorldY;r.horizontalEnabled&&(r.scrollX-=e,i.velocityX=l>0?-e/l:0),r.verticalEnabled&&(r.scrollY-=t,i.velocityY=l>0?-t/l:0),i.lastWorldX=u.x,i.lastWorldY=u.y}if(i.isDragging&&e.isMouseButtonReleased(0)&&(i.isDragging=!1),a?.hovered){const t=e.getScrollDelta();r.verticalEnabled&&0!==t.y&&(r.scrollY+=.1*t.y,i.velocityY=0),r.horizontalEnabled&&0!==t.x&&(r.scrollX+=.1*t.x,i.velocityX=0)}if(!i.isDragging&&r.inertia&&l>0){const e=Math.pow(r.decelerationRate,l);r.horizontalEnabled&&Math.abs(i.velocityX)>.1?(r.scrollX+=i.velocityX*l,i.velocityX*=e):i.velocityX=0,r.verticalEnabled&&Math.abs(i.velocityY)>.1?(r.scrollY+=i.velocityY*l,i.velocityY*=e):i.velocityY=0}const c=o.size.x,h=o.size.y,d=Math.max(0,r.contentWidth-c),f=Math.max(0,r.contentHeight-h);if(r.scrollX=Math.max(0,Math.min(r.scrollX,d)),r.scrollY=Math.max(0,Math.min(r.scrollY,f)),0!==r.contentEntity&&t.valid(r.contentEntity)){const e=r.contentEntity;if(t.has(e,N)){const n=t.get(e,N);n.position.x=-r.scrollX,n.position.y=r.scrollY,t.insert(e,N,n)}}}},{name:"ScrollViewSystem"}))}};var wr;!function(e){e[e.LeftToRight=0]="LeftToRight",e[e.RightToLeft=1]="RightToLeft",e[e.BottomToTop=2]="BottomToTop",e[e.TopToBottom=3]="TopToBottom"}(wr||(wr={}));const xr=I("Slider",{value:0,minValue:0,maxValue:1,direction:wr.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1,enabled:!0});const vr=new class{build(e){W("Slider",xr);const t=e.world,n=new Float32Array(16),s="undefined"!=typeof window&&window.devicePixelRatio||1;let r=null;e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke),de(Xe)],(e,o)=>{if(!o.valid)return;const i=e.mouseX*s,a=o.screenH-e.mouseY*s;xs(o.viewProjection,n);const l=vs(i,a,n,o.vpX,o.vpY,o.vpW,o.vpH),c=t.getEntitiesWithComponents([xr,us,V]);for(const n of c){t.has(n,Cs)||t.insert(n,Cs,{enabled:!0,blockRaycast:!0});const s=t.get(n,xr),o=t.get(n,us),i=t.get(n,V),a=t.has(n,Rs)?t.get(n,Rs):null;if(a?.justPressed&&(r=n),r===n&&e.isMouseButtonDown(0)){const e=o.size.x*i.scale.x,t=o.size.y*i.scale.y,n=i.position.x-o.pivot.x*e,r=i.position.y-o.pivot.y*t;let a;switch(s.direction){case wr.LeftToRight:a=e>0?(l.x-n)/e:0;break;case wr.RightToLeft:a=e>0?1-(l.x-n)/e:0;break;case wr.BottomToTop:a=t>0?(l.y-r)/t:0;break;case wr.TopToBottom:a=t>0?1-(l.y-r)/t:0}a=Math.max(0,Math.min(1,a));let c=s.minValue+a*(s.maxValue-s.minValue);s.wholeNumbers&&(c=Math.round(c)),s.value=Math.max(s.minValue,Math.min(s.maxValue,c))}r===n&&e.isMouseButtonReleased(0)&&(r=null);const c=s.maxValue-s.minValue,h=c>0?(s.value-s.minValue)/c:0;if(0!==s.fillEntity&&t.valid(s.fillEntity)){const e=s.fillEntity;if(t.has(e,us)){const n=t.get(e,us);switch(s.direction){case wr.LeftToRight:n.anchorMin={x:0,y:0},n.anchorMax={x:h,y:1};break;case wr.RightToLeft:n.anchorMin={x:1-h,y:0},n.anchorMax={x:1,y:1};break;case wr.BottomToTop:n.anchorMin={x:0,y:0},n.anchorMax={x:1,y:h};break;case wr.TopToBottom:n.anchorMin={x:0,y:1-h},n.anchorMax={x:1,y:1}}t.insert(e,us,n)}}if(0!==s.handleEntity&&t.valid(s.handleEntity)){const e=s.handleEntity;if(t.has(e,us)){const n=t.get(e,us);switch(s.direction){case wr.LeftToRight:n.anchorMin={x:h,y:0},n.anchorMax={x:h,y:1};break;case wr.RightToLeft:n.anchorMin={x:1-h,y:0},n.anchorMax={x:1-h,y:1};break;case wr.BottomToTop:n.anchorMin={x:0,y:h},n.anchorMax={x:1,y:h};break;case wr.TopToBottom:n.anchorMin={x:0,y:1-h},n.anchorMax={x:1,y:1-h}}t.insert(e,us,n)}}}},{name:"SliderSystem"}))}},br=I("Focusable",{tabIndex:0,isFocused:!1});class Sr{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Pr=ue(new Sr,"FocusManager");const Mr=new class{build(e){W("Focusable",br);const t=e.world,n=new Sr;e.insertResource(Pr,n),e.addSystemToSchedule(Pe.Update,Te([de(ke),de(ks)],(e,s)=>{const r=t.getEntitiesWithComponents([br]);for(const e of r){if(!t.has(e,Rs))continue;t.get(e,Rs).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of r){const s=t.get(n,br);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const i=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?s.length-1:0:a?(i-1+s.length)%s.length:(i+1)%s.length,o(s[l])}function o(e){const r=n.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,br)){t.get(r,br).isFocused=!1,s.emit(r,"hover_exit",r)}n.focus(e);t.get(e,br).isFocused=!0,s.emit(e,"hover_enter",e)}},{name:"FocusSystem"}))}},Tr=I("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});const Er=new class{build(e){W("SafeArea",Tr);const t=e.world;let n={top:0,bottom:0,left:0,right:0},s=0;e.addSystemToSchedule(Pe.PreUpdate,Te([],()=>{s++%60==0&&(n=function(){if("undefined"==typeof document)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}());const e=t.getEntitiesWithComponents([Tr,us]);for(const s of e){const e=t.get(s,Tr),r=t.get(s,us);let o=!1;const i=e.applyTop?n.top:0,a=e.applyBottom?n.bottom:0,l=e.applyLeft?n.left:0,c=e.applyRight?n.right:0;r.offsetMin.x===l&&r.offsetMin.y===a||(r.offsetMin={x:l,y:a},o=!0),r.offsetMax.x===-c&&r.offsetMax.y===-i||(r.offsetMax={x:-c,y:-i},o=!0),o&&t.insert(s,us,r)}},{name:"SafeAreaSystem"}))}},Cr=I("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2}),Rr=new Map;function Ar(e,t){const n=Rr.get(e);n&&(n.renderer=t)}const Fr=new class{build(e){W("ListView",Cr);const t=e.world;e.addSystemToSchedule(Pe.PreUpdate,Te([de(ke)],e=>{const n=t.getEntitiesWithComponents([Cr,us]);for(const s of n){t.has(s,Cs)||t.insert(s,Cs,{enabled:!0,blockRaycast:!0}),t.has(s,ys)||t.insert(s,ys,{enabled:!0,mode:"scissor"});let n=Rr.get(s);n||(n={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},Rr.set(s,n));const r=t.get(s,Cr),o=t.get(s,us),i=o.size.y,a=t.has(s,Rs)?t.get(s,Rs):null;if(a?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}const l=Math.max(0,r.itemCount*r.itemHeight-i);r.scrollY=Math.max(0,Math.min(r.scrollY,l));const c=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+i)/r.itemHeight)+r.overscan);for(const[e,s]of n.itemEntities)(e<c||e>=h)&&(t.valid(s)&&t.despawn(s),n.itemEntities.delete(e));for(let e=c;e<h;e++){let i=n.itemEntities.get(e);if(i&&t.valid(i)||(i=t.spawn(),t.insert(i,ne,{value:`ListItem_${e}`}),t.insert(i,us,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o.size.x,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(i,s),n.itemEntities.set(e,i),n.renderer&&n.renderer(e,i)),t.has(i,N)){const n=t.get(i,N);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(i,N,n)}}n.visibleStart=c,n.visibleEnd=h}},{name:"ListViewSystem"}))}},Ir=I("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const kr=new class{build(e){W("Dropdown",Ir);const t=e.world;e.addSystemToSchedule(Pe.Update,Te([de(ke),de(ks)],(e,n)=>{const s=t.getEntitiesWithComponents([Ir]);for(const o of s){t.has(o,Cs)||t.insert(o,Cs,{enabled:!0,blockRaycast:!0});const s=t.get(o,Ir),i=t.has(o,Rs)?t.get(o,Rs):null;if(i?.justPressed&&(s.isOpen=!s.isOpen,r(s.listEntity,s.isOpen),n.emit(o,"change",o)),s.isOpen&&e.isMouseButtonPressed(0)&&!i?.hovered){0!==s.listEntity&&t.valid(s.listEntity)&&t.has(s.listEntity,Rs)&&t.get(s.listEntity,Rs).hovered||(s.isOpen=!1,r(s.listEntity,!1))}}function r(e,n){if(0===e)return;const s=e;if(!t.valid(s)||!t.has(s,N))return;const r=t.get(s,N),o=n?1:0;r.scale={x:o,y:o,z:o},t.insert(s,N,r)}},{name:"DropdownSystem"}))}};async function Br(e,t,n){const s=e.getResource(Xn);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function $r(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 Dr=ue({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Ur=ue(null,"PhysicsAPI");function zr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Lr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Wr{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Dr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=$r(this.wasmUrl_,this.factory_).then(s=>{s._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([J]);for(const n of t){const t=e.world.get(n,J);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(Pe.PostUpdate,Te([de(me)],a=>{const l=i.getEntitiesWithComponents([oe,N,V]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,oe),l=i.get(r,V);if(t.has(r)){const e=n.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||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=zr(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Or(e,s,r),t.add(r),n.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=zr(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const h=e.world.get(i,N);if(!h)continue;let u=a,d=l,f=c;if(e.world.has(i,Q)){const t=e.world.get(i,Q);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,V)){const n=e.world.get(t.entity,V),s=zr(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),h=Math.sin(-s);u=(r*i-o*h)/(0!==n.scale.x?n.scale.x:1),d=(r*h+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}h.position.x=u,h.position.y=d;const p=Lr(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(i,N,h)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.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]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<h;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Dr,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Ur,Hr._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function Or(e,t,n){const s=e.world;if(s.has(n,ie)){const e=s.get(n,ie);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,ae)){const e=s.get(n,ae);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,le)){const e=s.get(n,le);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Hr{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(Hr.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 jr(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Xr(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Yr(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,h=e.rotation.w,u=a+a,d=l+l,f=c+c,p=a*u,g=a*d,m=a*f,y=l*d,_=l*f,w=c*f,x=h*u,v=h*d,b=h*f;return new Float32Array([(1-(y+w))*r,(g+b)*r,(m-v)*r,0,(g-b)*o,(1-(p+w))*o,(_+x)*o,0,(m+v)*i,(_-x)*i,(1-(p+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Nr(e,t,n,s,r,o,i,a,l){const c=await async function(e,t,n){const s={};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!==s[r])continue;try{s[r]=jr(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);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,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=await r.readText(a),h="binary"===Mt(l)?.contentType;let u,d;if(h){const e=await r.readBinary(i);d=e.length,u=t._malloc(d),t.HEAPU8.set(e,u)}else{const e=await r.readText(i),n=(new TextEncoder).encode(e);d=n.length,u=t._malloc(d+1),t.HEAPU8.set(n,u),t.HEAPU8[u+d]=0}const f=n.loadSkeleton(u,d,s,s.length,h);if(t._free(u),f<0)continue;o[i]=f;const p=Xr(s),g=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=jr(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new Wr("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};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===s[r])try{let t,o;const i=Mt(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),h=jr(e,c,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,h,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};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===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=et.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=et.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const r={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=pt(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=r[e.type][n[e.field]]||0)}}(n,c,d,f);const p=gt(e.world,n);if(l&&e.hasResource(Xn))for(const t of p.values())e.world.insert(t,se,{scene:l,persistent:!1});if(r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=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,n,h,p);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,te)?c.get(o,te):null,h=!1!==a?.playing,u=a?.timeScale??1;h&&s.update(i,l*u);let d=0;if(c.has(o,V)){const e=Yr(c.get(o,V),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),h=n._malloc(l),u=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,h,u,f);const p=n.HEAPU32[u>>2],g=n.HEAPU32[f>>2],m=new Float32Array(n.HEAPF32.buffer,c,8*r),y=new Uint16Array(n.HEAPU8.buffer,h,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(m,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,r,w,o,p,g,d),t._free(_),t._free(w),n._free(c),n._free(h),n._free(u),n._free(f)}d&&t._free(d)}})}(e,t,r,u,s)}if(a){const t=e.getResource(Ut);t&&t.setAddressableManifest(a)}}function Vr(e,t,n){return{name:e,data:t,async setup(){await Nr(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class qr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===Mt(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.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 n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){const t=Mt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Gr="__preview__";class Jr{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(Xn);t.register({name:Gr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Gr),this.loadPromise_=t.load(Gr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new qr(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await Nr(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,Gr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([G]);for(const s of n){if(e.get(s,G).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([J]);for(const r of s){const s=e.get(r,J);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=this.app_.getResource(Xn).getScene(Gr),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,N,i);const a={isActive:!0,projectionType:j.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:X.ColorAndDepth};e.insert(o,G,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(Xn);await e.switchTo(Gr),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 Kr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Bn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Bn.getTargetTexture(n),width:e.width,height:e.height}},release(e){Bn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Bn.releaseRenderTarget(e._handle),Kr.create({width:t,height:n,depth:!0})),begin(e,t){Bn.begin(t,e._handle)},end(){Bn.end()},getDepthTexture:e=>Bn.getTargetDepthTexture(e._handle)};let Qr=!1;function Zr(e){Qr=e}function eo(){return Qr}function to(){return!Qr}var no;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(no||(no={}));class so{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${no[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case no.Debug:console.debug(t,n);break;case no.Info:console.log(t,n);break;case no.Warn:console.warn(t,n);break;case no.Error:console.error(t,n)}}}class ro{constructor(){this.handlers_=[],this.minLevel_=no.Info,this.addHandler(new so)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(no.Debug,e,t,n)}info(e,t,n){this.log(no.Info,e,t,n)}warn(e,t,n){this.log(no.Warn,e,t,n)}error(e,t,n){this.log(no.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const oo=new ro;function io(){return oo}function ao(e){oo.setMinLevel(e)}function lo(e,t,n){oo.debug(e,t,n)}function co(e,t,n){oo.info(e,t,n)}function ho(e,t,n){oo.warn(e,t,n)}function uo(e,t,n){oo.error(e,t,n)}const fo=[ms,Es,Os,rr,cr,qs,mr,_r,vr,ir,Zs,Mr,Er,Fr,kr];function po(e,t){return function(e,t){const n=qn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),tn(e),Ke(e),wn(e),Pn(e),In(e),Dn(e);const r=new Ln;n.setPipeline(r);let o=d();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=Qn(e,s,t,r));const i=n.getResource(Xe);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(Xe,{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 l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=i();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Bn.setClearColor(e.x,e.y,e.z,e.w)}const h=(d()-o)/1e3;let u;if(Bn.resize(t,l),En.isInitialized()&&En.getPassCount()>0&&!En.isBypassed()&&En.resize(t,l),n.hasResource(Xn)){const e=n.getResource(Xn).getActiveScenes();e.length>0&&(u=new Set(e))}r.setActiveScenes(u??null);const f=Qn(e,s,t,l,n.world,u);if(a(t,l,f),0===f.length)r.render({registry:{_cpp:s},viewProjection:Jn,width:t,height:l,elapsed:h});else{for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),i=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:c},clearFlags:e.clearFlags,elapsed:h})}Bn.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Pe.First,l),n.addSystemToSchedule(Pe.Last,c),n.addPlugin(Lt),n.addPlugin(Gt),n.addPlugin($e),n.addPlugin(Vn),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:fo,...t})}e=f;export{qn as App,zt as AssetPlugin,Wt as AssetRefCounter,Dt as AssetServer,Ut as Assets,ct as AsyncCache,ee as BitmapText,Ye as BlendMode,ce as BodyType,ie as BoxCollider,Fs as Button,As as ButtonState,G as Camera,J as Canvas,le as CapsuleCollider,Z as Children,ae as CircleCollider,X as ClearFlags,ve as Commands,Se as CommandsInstance,g as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,m as DEFAULT_PIXELS_PER_UNIT,y as DEFAULT_TEXT_CANVAS_SIZE,pn as DataType,ur as DragState,hr as Draggable,on as Draw,Ir as Dropdown,be as EntityCommands,tr as FillMethod,nr as FillOrigin,Pr as FocusManager,Sr as FocusManagerState,br as Focusable,zn as GLDebug,bn as Geometry,x as INVALID_ENTITY,b as INVALID_FONT,v as INVALID_TEXTURE,sr as Image,er as ImageType,ke as Input,Be as InputPlugin,Ie as InputState,Cs as Interactable,Cr as ListView,N as LocalTransform,no as LogLevel,ro as Logger,et as Material,ht as MaterialLoader,ye as Mut,ne as Name,Q as Parent,Hr as Physics,Dr as PhysicsEvents,Wr as PhysicsPlugin,En as PostProcess,Nt as PrefabServer,Vt as Prefabs,qt as PrefabsPlugin,Jr as PreviewPlugin,lr as ProgressBar,ar as ProgressBarDirection,j as ProjectionType,we as Query,xe as QueryInstance,Ln as RenderPipeline,Rn as RenderStage,Kr as RenderTexture,Bn as Renderer,de as Res,fe as ResMut,oe as RigidBody,_ as RuntimeConfig,Tr as SafeArea,Y as ScaleMode,Xn as SceneManager,jn as SceneManagerState,se as SceneOwner,Pe as Schedule,Bs as ScreenSpace,yr as ScrollView,lt as ShaderSources,xr as Slider,wr as SliderDirection,te as SpineAnimation,q as Sprite,Fe as SystemRunner,hs as Text,as as TextAlign,Gs as TextInput,Js as TextInputPlugin,cs as TextOverflow,gs as TextPlugin,ds as TextRenderer,ls as TextVerticalAlign,me as Time,or as Toggle,Xe as UICameraInfo,Is as UIEventQueue,ks as UIEvents,Rs as UIInteraction,Vs as UIInteractionPlugin,Ws as UILayoutPlugin,ys as UIMask,Ts as UIMaskPlugin,us as UIRect,K as Velocity,qr as WebAssetProvider,je as World,V as WorldTransform,Re as addStartupSystem,Ce as addSystem,Ae as addSystemToSchedule,w as applyRuntimeConfig,Lt as assetPlugin,fn as clearDrawCallbacks,$ as clearUserComponents,T as color,$s as computeUIRectLayout,Ms as createMaskProcessor,Vr as createRuntimeSceneConfig,po as createWebApp,lo as debug,I as defineComponent,ue as defineResource,Te as defineSystem,k as defineTag,uo as error,wt as findEntityByName,Gn as flushPendingSystems,Et as getAddressableType,Ct as getAddressableTypeByEditorType,At as getAllAssetExtensions,Bt as getAssetMimeType,Mt as getAssetTypeEntry,O as getComponent,ft as getComponentAssetFields,re as getComponentDefaults,It as getCustomExtensions,Tt as getEditorType,io as getLogger,t as getPlatform,s as getPlatformType,B as getUserComponent,kt as getWeChatPackOptions,co as info,tn as initDrawAPI,Dn as initGLDebugAPI,wn as initGeometryAPI,Ke as initMaterialAPI,Pn as initPostProcessAPI,In as initRendererAPI,$e as inputPlugin,Ht as instantiatePrefab,_s as intersectRects,xs as invertMatrix4,z as isBuiltinComponent,$t as isCustomExtension,eo as isEditor,Rt as isKnownAssetExtension,n as isPlatformInitialized,to as isRuntime,Ne as isTextureRef,r as isWeChat,o as isWeb,yt as loadComponent,$r as loadPhysicsModule,Nr as loadRuntimeScene,gt as loadSceneData,mt as loadSceneWithAssets,Ft as looksLikeAssetPath,i as platformFetch,c as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ss as pointInOBB,bs as pointInWorldRect,Gt as prefabsPlugin,E as quat,W as registerComponent,dt as registerComponentAssetFields,un as registerDrawCallback,Ot as registerEmbeddedAssets,at as registerMaterialCallback,Vn as sceneManagerPlugin,vs as screenToWorld,Zr as setEditorMode,Ar as setListViewRenderer,ao as setLogLevel,We as setWasmErrorHandler,nn as shutdownDrawAPI,Un as shutdownGLDebugAPI,xn as shutdownGeometryAPI,Qe as shutdownMaterialAPI,Mn as shutdownPostProcessAPI,kn as shutdownRendererAPI,Zs as textInputPlugin,ms as textPlugin,Br as transitionTo,qs as uiInteractionPlugin,Os as uiLayoutPlugin,Es as uiMaskPlugin,fo as uiPlugins,D as unregisterComponent,dn as unregisterDrawCallback,_t as updateCameraAspectRatio,S as vec2,P as vec3,M as vec4,ho as warn,ws as worldRectToScreen,Yn as wrapSceneSystem};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function i(){return"wechat"===e?.name}function r(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function h(e,n){return t().instantiateWasm(e,n)}function u(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),r=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},o=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},h=()=>{e.onPointerUp(0)},u=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",r),n.addEventListener("mousedown",o),n.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",h),n.addEventListener("wheel",u),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",i),n.removeEventListener("mousemove",r),n.removeEventListener("mousedown",o),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",h),n.removeEventListener("wheel",u)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,g=1080,y=100,m=512,_={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=_.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=_.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=_.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=_.canvasMatchWidthOrHeight)}const x=0,v=4294967295,b=4294967295,S=(e=0,t=0)=>({x:e,y:t}),P=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),M=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),E=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),T=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function C(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(C);const t={};for(const n in e)t[n]=C(e[n]);return t}let R=0;function A(e,t){const n=++R;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...C(t),...e}:C(t)}}function I(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const n=I(),s=n.get(e);if(s)return s;const i=A(e,t);return n.set(e,i),U(e,t,!1),i}function k(e){const t=I(),n=t.get(e);if(n)return n;const s=A(e,{});return t.set(e,s),U(e,{},!0),s}function B(e){return I().get(e)}function z(){I().clear()}function $(e){I().delete(e)}function U(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function D(e){return!0===e._builtin}const L=new Map;function W(e,t){L.set(e,t)}function O(e){return L.get(e)??B(e)}function H(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return L.set(e,n),n}const j={Perspective:0,Orthographic:1},X={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Y={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},N=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}}),V=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}}),G=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,enabled:!0}),q=H("Camera",{projectionType:j.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:X.ColorAndDepth}),J=H("Canvas",{designResolution:{x:p,y:g},pixelsPerUnit:100,scaleMode:Y.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),K=H("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Q=H("Parent",{entity:0}),Z=H("Children",{entities:[]}),ee=H("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:b,enabled:!0}),te=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,enabled:!0}),ne={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},se=F("SceneOwner",{scene:"",persistent:!1});function ie(e){const t=O(e);return t?C(t._default):null}W("Name",ne);const re=H("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),oe=H("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ae=H("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),le=H("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ce={Static:0,Kinematic:1,Dynamic:2};let he=0;function ue(e,t){const n=++he;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function de(e){return{_type:"res",_resource:e}}function fe(e){return{_type:"res_mut",_resource:e}}class pe{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 ge{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 pe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const ye=ue({delta:0,elapsed:0,frameCount:0},"Time");function me(e){return{_type:"mut",_component:e}}function _e(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function we(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{_e(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class xe{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>_e(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_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),i=n.length,r=e.length>0,o=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let h=null;this.world_.beginIteration();try{for(const u of s){if(null!==h&&r)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}if(o){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<i;e++)a[e+1]=this.world_.get(u,n[e]);if(r){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];h=u}yield a}}finally{if(this.world_.endIteration(),null!==h&&r)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(h,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){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 ve(){return{_type:"commands"}}class be{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Se{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new be(this,null);return this.spawned_.push(e),e}entity(e){return new be(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Pe;!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"}(Pe||(Pe={}));let Me=0;function Ee(e,t,n){const s=++Me;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Te(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ce(e){Te().push({schedule:Pe.Update,system:e})}function Re(e){Te().push({schedule:Pe.Startup,system:e})}function Ae(e,t){Te().push({schedule:e,system:t})}class Ie{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 n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Se&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new xe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Fe{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 ke=ue(new Fe,"Input");class Be{constructor(e){this.target_=e??null}build(e){const n=new Fe;e.insertResource(ke,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Pe.Last,Ee([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ze=new Be;function $e(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=Ue(t[e]),r=Ue(i);"null"!==n&&"undefined"!==n&&(n!==r&&null!=i&&s.push({field:e,expected:n,actual:r,value:i}))}return s}function Ue(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function De(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let Le=null;function We(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 n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="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 je{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 n of t)this.tsStorage_.get(n)?.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(n){Oe(n,`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,n){return D(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}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 n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Oe(n,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=$e(t._name,t._default,s);if(e.length>0)throw new Error(De(t._name,e))}const i={...t._default,...s};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(i))}catch(n){Oe(n,`insertBuiltin(${t._name}, entity=${e})`)}return i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(n){return Oe(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return Oe(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Oe(n,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const i=$e(t._name,t._default,e);if(i.length>0)throw new Error(De(t._name,i));s=e}const i=t.create(s);this.getStorage(t).set(e,i),this.worldVersion_++;let r=this.entityComponents_.get(e);return r||(r=[],this.entityComponents_.set(e,r)),-1===r.indexOf(t._id)&&r.push(t._id),i}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.push(n)}catch{}if(this.cppRegistry_)for(const[n,s]of L)if(D(s)&&!t.includes(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.push(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const s of n)for(const[n,i]of e)if(i._id===s){t.push(n);break}}return t}getEntitiesWithComponents(e,t=[],n=[]){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();let s=e.map(e=>e._name).sort().join(",");t.length>0&&(s+="|+"+t.map(e=>e._name).sort().join(",")),n.length>0&&(s+="|-"+n.map(e=>e._name).sort().join(","));const i=this.queryCache_.get(s);if(i&&i.version===this.worldVersion_)return i.result;let r=null,o=1/0;for(const t of e)if(!D(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<o&&(o=n,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=r?r.keys():this.entities_;for(const t of l){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&a.push(t)}return this.queryCache_.set(s,{version:this.worldVersion_,result:a}),a}}const Xe=ue({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var Ye;function Ne(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"}(Ye||(Ye={}));let Ve=null,Ge=null,qe=1;const Je=new Map;function Ke(e){Ve=e,Ge=e.getResourceManager(),at()}function Qe(){0!==nt&&Ve&&(Ve._free(nt),nt=0),Je.clear(),qe=1,tt=!1,it.clear(),rt=null,Ge=null,Ve=null}function Ze(){if(!Ge)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ge}const et={createShader:(e,t)=>Ze().createShader(e,t),releaseShader(e){e>0&&Ze().releaseShader(e)},create(e){const t=qe++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ye.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Je.set(t,n),t},get:e=>Je.get(e),setUniform(e,t,n){const s=Je.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=Je.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Je.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Je.get(e);return t?.blendMode??Ye.Normal},setDepthTest(e,t){const n=Je.get(e);n&&(n.depthTest=t)},getShader(e){const t=Je.get(e);return t?.shader??0},release(e){Je.delete(e)},isValid:e=>Je.has(e),releaseAll(){Je.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Ye.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Je.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=qe++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Je.set(n,s),n},toAssetData(e,t){const n=Je.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=Je.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let tt=!1,nt=0;const st=4096,it=new Map;let rt=null;function ot(e){const t=(0===nt&&Ve&&(nt=Ve._malloc(st)),nt);if(0===t||!Ve)return{ptr:0,count:0};let n=0,s=0;const i=Ve.HEAPU8,r=Ve.HEAPU32,o=Ve.HEAPF32;for(const[a,l]of e){if(n+128>st)break;let e=it.get(a);e||(rt||(rt=new TextEncoder),e=rt.encode(a),it.set(a,e));const c=e.length,h=4*Math.ceil(c/4);r[t+n>>2]=c,n+=4,i.set(e,t+n),n+=h;let u=0,d=[0,0,0,0];if("number"==typeof l)u=0,d[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(u=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,d=[l.x,l.y,l.z,0]):"y"in l&&(u=1,d=[l.x,l.y,0,0]);r[t+n>>2]=u,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function at(){if(!Ve||tt)return;Ve.materialDataProvider=(e,t,n,s,i)=>{const r=Je.get(e);if(!r)return Ve.HEAPU32[t>>2]=0,Ve.HEAPU32[n>>2]=0,Ve.HEAPU32[s>>2]=0,void(Ve.HEAPU32[i>>2]=0);Ve.HEAPU32[t>>2]=r.shader,Ve.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=ot(r.uniforms);Ve.HEAPU32[s>>2]=o,Ve.HEAPU32[i>>2]=a},tt=!0}const lt={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,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class ht{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&&(et.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())et.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),r=await this.shaderLoader_.load(i);return{handle:et.createFromAsset(s,r),shaderHandle:r,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const ut=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}]]);function dt(e,t){ut.set(e,t)}function ft(e){const t=ut.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function pt(e){return ut.get(e)?.fields??[]}function gt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ne,{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),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}async function yt(e,t,n){const s=new Map,i=n?.assetServer,r=n?.assetBaseUrl,o=new Map;i&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const i=new Set,r=new Set,o=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ut.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":i.add(t);break;case"material":r.add(t);break;case"font":o.add(t)}}}const c=new Map,h=new Map,u=new Map,d=[];for(const e of i)d.push((async()=>{try{const i=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(i);c.set(e,r.handle),s.set(e,i)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of r)d.push((async()=>{try{const s=await t.loadMaterial(e,n);h.set(e,s.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 s=await t.loadBitmapFont(e,n);u.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)d.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ut.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=h.get(t)??0;break;case"font":n[e.field]=u.get(t)??0}}}}(t,i,r,o);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,ne,{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),i=s.get(n.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}if(i&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&i.setTextureMetadataByPath(t,n.sliceBorder)}return s}function mt(e,t,n,s){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const i=O(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function _t(e,t){const n=e.getEntitiesWithComponents([q]);for(const s of n){const n=e.get(s,q);n&&(n.aspectRatio=t,e.insert(s,q,n))}}function wt(e,t){const n=e.getEntitiesWithComponents([ne]);for(const s of n){const n=e.get(s,ne);if(n&&n.value===t)return s}return null}const xt=[{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}],vt={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"},bt=new Map,St=new Set;for(const e of xt)for(const t of e.extensions)bt.set(t,e),St.add(t);function Pt(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Mt(e){return bt.get(Pt(e))}function Et(e){return Mt(e)?.editorType??"unknown"}function Tt(e){return Mt(e)?.addressableType??null}function Ct(e){for(const t of xt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Rt(e){return St.has(e.toLowerCase())}function At(){return St}function It(e){return"string"==typeof e&&(!!e.includes("/")&&Rt(Pt(e)))}function Ft(){const e=[];for(const t of xt)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function kt(){return Ft().map(e=>({type:"suffix",value:e}))}function Bt(e){return vt[e.toLowerCase()]}function zt(e){const t=Mt(e);return t?.wechatPackInclude??!1}class $t{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(_.textCanvasSize,_.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new ht(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const r=(this.textureRefCounts_.get(s)??1)-1;r<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,r)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),et.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),r=await this.fetchText(i);if(!this.writeToVirtualFS(t,r))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(r),l=[];for(const e of a){const t=o?`${o}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),h="binary"===Mt(e)?.contentType,u=h?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(u,r,h);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=Mt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const i=n?`${n}/${s}`:s;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],i=e.substring(0,e.lastIndexOf("/")),r=i?`${i}/${s}`:s,o=await this.loadTextureRaw(r);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return yt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const i=s??n;return new Promise((n,s)=>{const r=t().createImage();r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(r)},r.onerror=()=>s(new Error(`Failed to load image: ${e}`)),r.src=i})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,i){const r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=r;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const i=this.ctx_.getImageData(0,0,t,n),r=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(r);const o=this.module_.getResourceManager(),a=this.module_._malloc(r.length);this.module_.HEAPU8.set(r,a);const l=o.createTexture(t,n,a,r.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return et.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:r}=this.parseEsShader(s);if(!i||!r)throw new Error(`Invalid shader format: ${e}`);return et.createShader(i,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ut=ue(null,"Assets");class Dt{build(e){const t=e.wasmModule;t?e.insertResource(Ut,new $t(t)):console.warn("AssetPlugin: No WASM module available")}}const Lt=new Dt;class Wt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Ot(e,t){const n=e.getResource(Ut);n&&n.registerEmbeddedAssets(t)}async function Ht(e,t,n){const{entities:s,rootId:i}=await Xt(t,n?.overrides??[],n,void 0,new Set),r={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await yt(e,r,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=o.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:o}}const jt=10;async function Xt(e,t,n,s,i,r=0){if(r>jt)throw new Error(`Prefab nesting depth exceeded ${jt}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Xt(e,s.nestedPrefab.overrides,n,a,i,r+1);o.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?o.get(s.parent)??null:null),l.push(...t.entities);continue}const c=o.get(s.prefabEntityId),h=s.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:h?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Yt(u,t),l.push(u)}const c=o.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Yt(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Nt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Ht(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Vt=ue(null,"Prefabs");class Gt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ut]}build(e){const t=e.getResource(Ut);e.insertResource(Vt,new Nt(e.world,t))}}const qt=new Gt;let Jt=null,Kt=0,Qt=0,Zt=0;const en=new Float32Array(256);function tn(e){Jt=e,Kt=Jt._malloc(64),Qt=Jt._malloc(64),Zt=Jt._malloc(1024)}function nn(){Jt&&(Kt&&(Jt._free(Kt),Kt=0),Qt&&(Jt._free(Qt),Qt=0),Zt&&(Jt._free(Zt),Zt=0)),Jt=null}function sn(){if(!Jt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Jt}const rn={r:1,g:1,b:1,a:1},on={begin(e){const t=sn();try{t.HEAPF32.set(e,Kt/4),t.draw_begin(Kt)}catch(e){Oe(e,"Draw.begin")}},end(){try{sn().draw_end()}catch(e){Oe(e,"Draw.end")}},line(e,t,n,s=1){try{sn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Oe(e,"Draw.line")}},rect(e,t,n,s=!0){try{sn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Oe(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{sn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Oe(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{sn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Oe(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{sn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Oe(e,"Draw.circleOutline")}},texture(e,t,n,s=rn){try{sn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Oe(e,"Draw.texture")}},textureRotated(e,t,n,s,i=rn){try{sn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){Oe(e,"Draw.textureRotated")}},setLayer(e){sn().draw_setLayer(e)},setDepth(e){sn().draw_setDepth(e)},getDrawCallCount:()=>Jt?Jt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Jt?Jt.draw_getPrimitiveCount():0,setBlendMode(e){sn().draw_setBlendMode(e)},setDepthTest(e){sn().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=sn();s.HEAPF32.set(n,Qt/4),s.draw_mesh(e,t,Qt)}catch(n){Oe(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=sn(),i=et.get(t);if(!i)return;if(on.setBlendMode(i.blendMode),on.setDepthTest(i.depthTest),0===i.uniforms.size)return void on.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,Qt/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=cn(t);if(!(s<0)){if(Ne(n))en[r++]=10,en[r++]=s,en[r++]=n.slot??e++,en[r++]=n.textureId;else if("number"==typeof n)en[r++]=1,en[r++]=s,en[r++]=n;else if(Array.isArray(n)){en[r++]=n.length,en[r++]=s;for(let e=0;e<n.length;e++)en[r++]=n[e]}else"w"in n?(en[r++]=4,en[r++]=s,en[r++]=n.x,en[r++]=n.y,en[r++]=n.z,en[r++]=n.w):"z"in n?(en[r++]=3,en[r++]=s,en[r++]=n.x,en[r++]=n.y,en[r++]=n.z):(en[r++]=2,en[r++]=s,en[r++]=n.x,en[r++]=n.y);if(r>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<r)&&(i.cachedBuffer_=new Float32Array(r)),i.cachedBuffer_.set(en.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,Qt);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),Zt/4),s.draw_meshWithUniforms(e,i.shader,Qt,Zt,r)}catch(n){Oe(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},an={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},ln=new Set;function cn(e){const t=an[e];return void 0!==t?t:(ln.has(e)||(ln.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(an).join(", ")}`)),-1)}const hn=new Map;function un(e,t,n){hn.set(e,{fn:t,scene:n??""})}function dn(e){hn.delete(e)}function fn(){hn.clear()}var pn;!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"}(pn||(pn={}));let gn=null,yn=0,mn=0,_n=0;function wn(e){gn=e,yn=gn._malloc(262144),mn=gn._malloc(65536),_n=gn._malloc(256)}function xn(){gn&&(yn&&gn._free(yn),mn&&gn._free(mn),_n&&gn._free(_n),yn=0,mn=0,_n=0),gn=null}function vn(){if(!gn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return gn}const bn={create(e){const t=vn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,yn/4);const i=e.layout.length,r=new Int32Array(i);for(let t=0;t<i;t++)r[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,_n,i).set(r),t.geometry_init(n,yn,s,_n,i,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,mn,s).set(e.indices),t.geometry_setIndices16(n,mn,s)}else{new Uint32Array(t.HEAPU8.buffer,mn,s).set(e.indices),t.geometry_setIndices32(n,mn,s)}}return n},updateVertices(e,t,n=0){const s=vn(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,yn/4),s.geometry_updateVertices(e,yn,i,n)},release(e){e>0&&vn().geometry_release(e)},isValid:e=>!(!gn||e<=0)&&gn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return bn.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const i=s/t*Math.PI*2,r=Math.cos(i)*e,o=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(r,o,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return bn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,i=-1/0;for(const r of e)t=Math.min(t,r.x),n=Math.min(n,r.y),s=Math.max(s,r.x),i=Math.max(i,r.y);const r=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(i-n);r.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return bn.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array(o)})}};let Sn=null;function Pn(e){Sn=e}function Mn(){Sn&&Tn.isInitialized()&&Tn.shutdown(),Sn=null}function En(){if(!Sn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Sn}const Tn={init(e,t){try{return En().postprocess_init(e,t)}catch(n){return Oe(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{En().postprocess_shutdown()}catch(e){Oe(e,"PostProcess.shutdown")}},resize(e,t){try{En().postprocess_resize(e,t)}catch(n){Oe(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return En().postprocess_addPass(e,t)}catch(t){return Oe(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{En().postprocess_removePass(e)}catch(t){Oe(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{En().postprocess_setPassEnabled(e,t)}catch(t){Oe(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return En().postprocess_isPassEnabled(e)}catch(t){return Oe(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{En().postprocess_setUniformFloat(e,t,n)}catch(n){Oe(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{En().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){Oe(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{En().postprocess_begin()}catch(e){Oe(e,"PostProcess.begin")}},end(){try{En().postprocess_end()}catch(e){Oe(e,"PostProcess.end")}},getPassCount(){try{return En().postprocess_getPassCount()}catch(e){return Oe(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Sn)return!1;try{return Sn.postprocess_isInitialized()}catch(e){return Oe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{En().postprocess_setBypass(e)}catch(e){Oe(e,"PostProcess.setBypass")}},isBypassed(){if(!Sn)return!0;try{return Sn.postprocess_isBypassed()}catch(e){return Oe(e,"PostProcess.isBypassed"),!0}},createBlur:()=>et.createShader(Cn,"#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:()=>et.createShader(Cn,"#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:()=>et.createShader(Cn,"#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:()=>et.createShader(Cn,"#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")},Cn="#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 Rn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Rn||(Rn={}));let An=null,In=0;function Fn(e){An=e,In=An._malloc(64)}function kn(){An&&In&&(An._free(In),In=0),An=null}const Bn={init(e,t){An?.renderer_init(e,t)},resize(e,t){An?.renderer_resize(e,t)},begin(e,t){if(An&&In)try{An.HEAPF32.set(e,In/4),An.renderer_begin(In,t??0)}catch(e){Oe(e,"Renderer.begin")}},flush(){try{An?.renderer_flush()}catch(e){Oe(e,"Renderer.flush")}},end(){try{An?.renderer_end()}catch(e){Oe(e,"Renderer.end")}},submitSprites(e){if(An)try{An.renderer_submitSprites(e._cpp)}catch(e){Oe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(An)try{An.renderer_submitBitmapText(e._cpp)}catch(e){Oe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(An)try{An.renderer_submitSpine?.(e._cpp)}catch(e){Oe(e,"Renderer.submitSpine")}},setStage(e){An?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>An?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){An?.renderer_releaseTarget(e)},getTargetTexture:e=>An?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>An?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){An?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){An?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){An?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){An?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>An?An.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>An?{drawCalls:An.renderer_getDrawCalls(),triangles:An.renderer_getTriangles(),sprites:An.renderer_getSprites(),text:An.renderer_getText(),spine:An.renderer_getSpine?.()??0,meshes:An.renderer_getMeshes(),culled:An.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let zn=null;function $n(e){zn=e}function Un(){zn=null}const Dn={enable(){zn?.gl_enableErrorCheck(!0)},disable(){zn?.gl_enableErrorCheck(!1)},check:e=>zn?.gl_checkErrors(e)??0,diagnose(){zn?.renderer_diagnose()}};class Ln{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:r}=e;s===this.lastWidth_&&i===this.lastHeight_||(Bn.resize(s,i),Tn.isInitialized()&&Tn.getPassCount()>0&&Tn.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Bn.setViewport(0,0,s,i),Bn.clearBuffers(3),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,r),Bn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;Bn.setViewport(s.x,s.y,s.w,s.h),Bn.setScissor(s.x,s.y,s.w,s.h,!0),Bn.clearBuffers(i),Bn.setScissor(0,0,0,0,!1),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,r),Bn.end()}executeDrawCallbacks(e,t){const n=hn;if(n.size>0){on.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}on.end();for(const e of s)dn(e)}}}const Wn="__scene_transition_overlay__";class On{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Hn{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),un(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=Tn.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){Tn.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 n=this.app_.world.get(e,se);n.persistent=t,this.app_.world.insert(e,se,n)}}}class jn{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(n=>{const s=t.duration??_.sceneTransitionDuration,i=t.color??{..._.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},un(Wn,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;on.setLayer(9999),on.setDepth(9999),on.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{n&&n!==e&&await this.unload(n,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,dn(Wn)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,dn(Wn),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new On(t);this.scenes_.set(e,n);const s=new Hn(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}if(i){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const s=await yt(this.app_.world,i,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=Yn(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new On(t);this.scenes_.set(e,n);const s=new Hn(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}if(i){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const s=await yt(this.app_.world,i,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=Yn(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,se)){if(this.app_.world.get(e,se).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())dn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{Tn.removePass(e)}catch{}n.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const r=this.loadOrder_.indexOf(e);-1!==r&&this.loadOrder_.splice(r,1),this.activeScene_===e&&(this.activeScene_=null)}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,G)){const n=this.app_.world.get(e,G);t.savedAlphas.set(e,n.color.a),n.color={...n.color,a:0},this.app_.world.insert(e,G,n)}}}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,G)){const n=this.app_.world.get(e,G),s=t.savedAlphas.get(e)??1;n.color={...n.color,a:s},this.app_.world.insert(e,G,n)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{Tn.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Xn=ue(null,"SceneManager");function Yn(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Xn).getSceneStatus(t)&&n._fn(...s)}}}const Nn=Ee([fe(Xn),de(ye)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Vn={name:"SceneManager",build(e){const t=new jn(e);e.insertResource(Xn,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Xn),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Pe.Startup,n),e.addSystemToSchedule(Pe.Last,Nn)}};class Gn{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 n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Pe.Last);else{this.runSchedule(Pe.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Pe.FixedPreUpdate),this.runSchedule(Pe.FixedUpdate),this.runSchedule(Pe.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Pe.PreUpdate),this.runSchedule(Pe.Update),this.runSchedule(Pe.PostUpdate),this.runSchedule(Pe.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new je,this.resources_=new ge;for(const e of Object.values(Pe))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Gn}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,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Pe.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Pe.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 We(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(Xn).register(e),this}setInitialScene(e){return this.getResource(Xn).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ie(this.world_,this.resources_),this.resources_.insert(ye,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Pe.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,fn();const e=[Un,kn,Mn,xn,Qe,nn];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 n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,r=o=>{if(s.has(o))return;if(i.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&r(n)}i.delete(o),s.add(o),n.push(a)};for(let t=0;t<e.length;t++)r(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(ye);t.delta=e,t.elapsed+=e,t.frameCount++}}function qn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Jn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Kn(e,t,n,s,i){const r=e*t/n,o=e;switch(s){case Y.FixedWidth:return r;case Y.FixedHeight:return o;case Y.Expand:return Math.max(r,o);case Y.Shrink:return Math.min(r,o);case Y.Match:{const e=i;return Math.pow(r,1-e)*Math.pow(o,e)}default:return o}}function Qn(e,t,n,s,i,r){if(0===n||0===s)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=r&&i?o.filter(e=>{const t=i.tryGet(e,se);return!t||""===t.scene||r.has(t.scene)}):o;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),r=t.getLocalTransform(e),o={x:i.viewportX,y:i.viewportY,w:i.viewportW,h:i.viewportH},a=o.w*n/(o.h*s);let h,u=0,d=0;if(i.projectionType===j.Orthographic){if(d=i.orthoSize,l){d=Kn(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}u=d*a,h=es(-u,u,-d,d,-i.farPlane,i.farPlane)}else h=ns(i.fov*Math.PI/180,a,i.nearPlane,i.farPlane);const f=is(r.position.x,r.position.y,r.position.z);c.push({entity:e,viewProjection:new Float32Array(os(h,f)),viewportRect:o,clearFlags:i.clearFlags,priority:i.priority,halfW:u,halfH:d,cameraX:r.position.x,cameraY:r.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Zn=new Float32Array(16);function es(e,t,n,s,i,r){const o=Zn;o.fill(0);const a=t-e,l=s-n,c=r-i;return o[0]=2/a,o[5]=2/l,o[10]=-2/c,o[12]=-(t+e)/a,o[13]=-(s+n)/l,o[14]=-(r+i)/c,o[15]=1,o}const ts=new Float32Array(16);function ns(e,t,n,s){const i=ts;i.fill(0);const r=1/Math.tan(e/2),o=n-s;return i[0]=r/t,i[5]=r,i[10]=(s+n)/o,i[11]=-1,i[14]=2*s*n/o,i}const ss=new Float32Array(16);function is(e,t,n){const s=ss;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const rs=new Float32Array(16);function os(e,t){const n=rs;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const as={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3},ls=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},_dirty:!0});function cs(e,t){e.has(t,G)||e.insert(t,G,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function hs(e,t,n,s){if(!e.has(t,ls))return;const i=e.get(t,ls);switch(n){case 0:i.anchorMin={x:0,y:0},i.anchorMax={x:s,y:1};break;case 1:i.anchorMin={x:1-s,y:0},i.anchorMax={x:1,y:1};break;case 2:i.anchorMin={x:0,y:0},i.anchorMax={x:1,y:s};break;case 3:i.anchorMin={x:0,y:1-s},i.anchorMax={x:1,y:1}}i.offsetMin={x:0,y:0},i.offsetMax={x:0,y:0},e.insert(t,ls,i)}function us(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function ds(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function fs(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let r=0;r<t.length;r++){const o=t[r],a=s+o;if(e.measureText(a).width>n&&s){if(ds(o.charCodeAt(0))&&s.length>0&&ds(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!ds(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+o):(i.push(s),s=o)}else i.push(s),s=o}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function ps(e){let t=1;for(;t<e;)t*=2;return t}const gs={Left:0,Center:1,Right:2},ys={Top:0,Middle:1,Bottom:2},ms={Visible:0,Clip:1,Ellipsis:2},_s=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:gs.Left,verticalAlign:ys.Top,wordWrap:!0,overflow:ms.Visible,lineHeight:1.2});class ws{constructor(e){this.cache=new Map,this.module=e,this.canvas=u(_.textCanvasSize,_.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,r=i?t.size.x:0,o=i?t.size.y:0,a=e.wordWrap&&i;let l=fs(n,e.content,a?r:0);const c=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=i?Math.ceil(r):u+2*h,p=i?Math.ceil(o):d+2*h;if(i&&e.overflow===ms.Ellipsis&&d>o){const e=Math.floor(o/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,r)}}if(s.width<f||s.height<p){const e=Math.max(s.width,ps(f)),t=Math.max(s.height,ps(p));s.width=e,s.height=t}const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${y}, ${m}, ${_})`,i&&e.overflow===ms.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(i)switch(e.verticalAlign){case ys.Top:x=h;break;case ys.Middle:x=(p-w)/2;break;case ys.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of l){let s;switch(e.align){case gs.Left:s=h;break;case gs.Center:s=f/2;break;case gs.Right:s=f-h;break;default:s=h}n.fillText(t,s,v),v+=c}i&&e.overflow===ms.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const E=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const i=this.renderText(t,n);return this.cache.set(e,i),i}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case gs.Left:return"left";case gs.Center:return"center";case gs.Right:return"right"}}}function xs(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 vs(e,t,n){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!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class bs{build(e){W("Text",_s);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ws(t),s=e.world,i=new Map;e.addSystemToSchedule(Pe.PreUpdate,Ee([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,_s));for(const e of i.keys())s.valid(e)&&s.has(e,_s)||i.delete(e);const e=s.getEntitiesWithComponents([_s]);for(const t of e){const e=s.get(t,_s),r=s.has(t,ls)?s.get(t,ls):null,o=i.get(t);if(o&&!vs(o,e,r))continue;cs(s,t);const a=n.renderForEntity(t,e,r),l=s.get(t,G);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,G,l),i.set(t,xs(e,r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ss=new bs,Ps=F("UIMask",{enabled:!0,mode:"scissor"});function Ms(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),r=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,i-n),h:Math.max(0,r-s)}}function Es(e,t,n,s,i,r,o,a,l,c,h){const u=e-n*i,d=e+n*(1-i),f=t-s*r,p=t+s*(1-r);function g(e,t){const n=o[0]*e+o[4]*t+o[12],s=o[1]*e+o[5]*t+o[13],i=o[3]*e+o[7]*t+o[15];return[a+(.5*(n/i)+.5)*c,l+(.5*(s/i)+.5)*h]}const[y,m]=g(u,f),[_,w]=g(d,p),x=Math.min(y,_),v=Math.max(y,_),b=Math.min(m,w),S=Math.max(m,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function Ts(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],r=e[2],o=e[3],a=e[4],l=e[5],c=e[6],h=e[7],u=e[8],d=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],w=s*l-i*a,x=s*c-r*a,v=s*h-o*a,b=i*c-r*l,S=i*h-o*l,P=r*h-o*c,M=u*y-d*g,E=u*m-f*g,T=u*_-p*g,C=d*m-f*y,R=d*_-p*y,A=f*_-p*m;let I=w*A-x*R+v*C+b*T-S*E+P*M;return 0===I||(I=1/I,n[0]=(l*A-c*R+h*C)*I,n[1]=(r*R-i*A-o*C)*I,n[2]=(y*P-m*S+_*b)*I,n[3]=(f*S-d*P-p*b)*I,n[4]=(c*T-a*A-h*E)*I,n[5]=(s*A-r*T+o*E)*I,n[6]=(m*v-g*P-_*x)*I,n[7]=(u*P-f*v+p*x)*I,n[8]=(a*R-l*T+h*M)*I,n[9]=(i*T-s*R-o*M)*I,n[10]=(g*S-y*v+_*w)*I,n[11]=(d*v-u*S-p*w)*I,n[12]=(l*E-a*C-c*M)*I,n[13]=(s*C-i*E+r*M)*I,n[14]=(y*x-g*b-m*w)*I,n[15]=(u*b-d*x+f*w)*I),n}function Cs(e,t,n,s,i,r,o){const a=(e-s)/r*2-1,l=(t-i)/o*2-1,c=n[0]*a+n[4]*l+n[12],h=n[1]*a+n[5]*l+n[13],u=n[3]*a+n[7]*l+n[15];return{x:c/u,y:h/u}}function Rs(e,t,n,s,i,r,o,a){return e>=n-i*o&&e<=n+i*(1-o)&&t>=s-r*a&&t<=s+r*(1-a)}function As(e,t,n,s,i,r,o,a,l,c){const h=2*Math.atan2(l,c),u=Math.sin(-h),d=Math.cos(-h),f=e-n,p=t-s,g=f*d-p*u+n,y=f*u+p*d+s;return g>=n-i*o&&g<=n+i*(1-o)&&y>=s-r*a&&y<=s+r*(1-a)}function Is(e,t,n,s,i,r,o){if(!e.has(t,ls)||!e.has(t,V))return null;const a=e.get(t,ls),l=e.get(t,V),c=a.size.x*l.scale.x,h=a.size.y*l.scale.y;return Es(l.position.x,l.position.y,c,h,a.pivot.x,a.pivot.y,n,s,i,r,o)}function Fs(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ps]);if(0===l.length)return;const c=[],h=[],u=new Set,d=new Set;for(const e of l){const n=t.get(e,Ps);n.enabled&&(u.add(e),"stencil"===n.mode?(h.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,r,o,a,l,c){const h=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Q);){const e=t.get(s,Q);if(i.has(e.entity)){if("scissor"===t.get(e.entity,Ps).mode){n=!1;break}}s=e.entity}n&&h.push(e)}function u(s,h){const d=e.getChildEntities(n,s);for(const n of d){let s=h;if(i.has(n)){if("scissor"===t.get(n,Ps).mode){const e=Is(t,n,r,o,a,l,c);e&&(s=Ms(h,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),u(n,s)}}for(const e of h){const n=Is(t,e,r,o,a,l,c);n&&u(e,n)}}(e,t,n,c,u,s,i,r,o,a),h.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const r=[];for(const e of s){let n=!0,s=e;for(;t.has(s,Q);){const e=t.get(s,Q);if(i.has(e.entity)){n=!1;break}s=e.entity}n&&r.push(e)}let o=1;function a(t,s){e.renderer_setEntityStencilMask(t,s);const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){a(t,o++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}function l(t,s){const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){a(t,o++)}else e.renderer_setEntityStencilTest(t,s),l(t,s)}for(const e of r){a(e,o++)}}(e,t,n,h,d)}catch(t){e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class ks{build(e){if(W("UIMask",Ps),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Fs(e.wasmModule,e.world))}}const Bs=new ks,zs=F("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),$s=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Us={Normal:0,Hovered:1,Pressed:2,Disabled:3},Ds=F("Button",{state:Us.Normal,transition:null});class Ls{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Ws=ue(new Ls,"UIEvents"),Os=k("ScreenSpace");function Hs(e,t,n,s,i,r){const o=r.right-r.left,a=r.top-r.bottom,l=r.left+e.x*o,c=r.left+t.x*o,h=r.bottom+e.y*a,u=r.bottom+t.y*a;let d,f,p,g;if(e.x===t.x){const e=l+n.x,t=.5*i.x;d=e-t,p=e+t}else d=l+n.x,p=c+s.x;if(e.y===t.y){const e=h+n.y,t=.5*i.y;f=e-t,g=e+t}else f=h+n.y,g=u+s.y;return{centerX:.5*(d+p),centerY:.5*(f+g),width:p-d,height:g-f,rect:{left:d,bottom:f,right:p,top:g}}}function js(e,t){e.anchorMinX=t.anchorMin.x,e.anchorMinY=t.anchorMin.y,e.anchorMaxX=t.anchorMax.x,e.anchorMaxY=t.anchorMax.y,e.offsetMinX=t.offsetMin.x,e.offsetMinY=t.offsetMin.y,e.offsetMaxX=t.offsetMax.x,e.offsetMaxY=t.offsetMax.y,e.sizeX=t.size.x,e.sizeY=t.size.y}function Xs(e){return{anchorMinX:e.anchorMin.x,anchorMinY:e.anchorMin.y,anchorMaxX:e.anchorMax.x,anchorMaxY:e.anchorMax.y,offsetMinX:e.offsetMin.x,offsetMinY:e.offsetMin.y,offsetMaxX:e.offsetMax.x,offsetMaxY:e.offsetMax.y,sizeX:e.size.x,sizeY:e.size.y}}function Ys(e,t){return e.anchorMinX!==t.anchorMin.x||e.anchorMinY!==t.anchorMin.y||e.anchorMaxX!==t.anchorMax.x||e.anchorMaxY!==t.anchorMax.y||e.offsetMinX!==t.offsetMin.x||e.offsetMinY!==t.offsetMin.y||e.offsetMaxX!==t.offsetMax.x||e.offsetMaxY!==t.offsetMax.y||e.sizeX!==t.size.x||e.sizeY!==t.size.y}function Ns(e,t,n,s,i,r){if(!e.has(t,ls))return;const o=e.get(t,ls),a=Hs(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,n);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const l=e.get(t,N);if(r?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-i),e.insert(t,N,l),!e.has(t,Z))return;const c=e.get(t,Z);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Ns(e,t,a.rect,a.centerX,a.centerY,!1)}class Vs{build(e){W("UIRect",ls);const t=e.world,n=new Map,s=new Map;let i=NaN,r=NaN,o=NaN,a=NaN;function l(e){let n=s.get(e);return void 0!==n||(n=function(e,t){let n=t;for(;;){if(e.has(n,Os))return n;if(!e.has(n,Q))return null;const t=e.get(n,Q);if(!e.valid(t.entity))return null;n=t.entity}}(t,e),s.set(e,n)),n}e.addSystemToSchedule(Pe.PreUpdate,Ee([de(Xe)],e=>{if(!e.valid)return;const c={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},h=.5*(c.left+c.right),u=.5*(c.bottom+c.top),d=i!==e.worldLeft||r!==e.worldBottom||o!==e.worldRight||a!==e.worldTop;i=e.worldLeft,r=e.worldBottom,o=e.worldRight,a=e.worldTop;const f=new Set;if(d){s.clear();const e=t.getEntitiesWithComponents([Os,ls,N]);for(const t of e)f.add(t)}for(const e of n.keys())t.valid(e)&&t.has(e,ls)||(n.delete(e),s.delete(e));const p=t.getEntitiesWithComponents([ls]);for(const e of p){const i=t.get(e,ls),r=n.get(e);if(i._dirty||!r||Ys(r,i)){i._dirty=!1,s.delete(e);const t=l(e);null!==t&&f.add(t)}}for(const e of f)Ns(t,e,c,h,u,!0);for(const e of p){const s=t.get(e,ls),i=n.get(e);i?js(i,s):n.set(e,Xs(s))}},{name:"UILayoutSystem"}))}}const Gs=new Vs,qs=new Float32Array(16),Js=new Float32Array(16);let Ks=!0,Qs=1;function Zs(e,t,n,s){let i=t;for(;e.has(i,Q);){const t=e.get(i,Q).entity;if(!e.valid(t))break;if(e.has(t,Ps)){if(e.get(t,Ps).enabled&&e.has(t,ls)&&e.has(t,V)){const i=e.get(t,V),r=e.get(t,ls),o=r.size.x*i.scale.x,a=r.size.y*i.scale.y;if(!Rs(n,s,i.position.x,i.position.y,o,a,r.pivot.x,r.pivot.y))return!0}}i=t}return!1}function ei(e,t,n,s){t.emit(n,s,n);let i=n;for(;e.has(i,Q);){const r=e.get(i,Q).entity;if(!e.valid(r))break;if(!e.has(r,zs)){i=r;continue}const o=e.get(r,zs);if(o.enabled&&t.emit(r,s,n),o.blockRaycast)break;i=r}}class ti{build(e){W("Interactable",zs),W("Button",Ds);const t=e.world,n=new Ls;e.insertResource(Ws,n);let s=null,i=null;Qs="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Pe.PreUpdate,Ee([de(ke),de(Xe)],(e,r)=>{n.drain();const o=t.getEntitiesWithComponents([$s]);for(const e of o){const n=t.get(e,$s);n.justPressed=!1,n.justReleased=!1}if(!r.valid)return;const a=e.mouseX*Qs,l=r.screenH-e.mouseY*Qs;!function(e){let t=!1;for(let n=0;n<16;n++)if(Js[n]!==e[n]){t=!0;break}t&&(Js.set(e),Ks=!0)}(r.viewProjection),Ks&&(Ts(r.viewProjection,qs),Ks=!1);const c=Cs(a,l,qs,r.vpX,r.vpY,r.vpW,r.vpH);r.worldMouseX=c.x,r.worldMouseY=c.y;const h=t.getEntitiesWithComponents([zs,ls,V]);let u=null,d=-1/0;for(const e of h){t.has(e,$s)||t.insert(e,$s);const n=t.get(e,zs);if(!n.enabled)continue;if(!n.raycastTarget)continue;const s=t.get(e,V),i=t.get(e,ls),r=i.size.x*s.scale.x,o=i.size.y*s.scale.y;if(As(c.x,c.y,s.position.x,s.position.y,r,o,i.pivot.x,i.pivot.y,s.rotation.z,s.rotation.w)){if(Zs(t,e,c.x,c.y))continue;let n=0;t.has(e,G)&&(n=t.get(e,G).layer),n>=d&&(d=n,u=e)}}if(s!==u){if(null!==s&&t.valid(s)&&t.has(s,$s)){t.get(s,$s).hovered=!1,n.emit(s,"hover_exit")}if(null!==u){t.get(u,$s).hovered=!0,n.emit(u,"hover_enter")}s=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,$s);e.pressed=!0,e.justPressed=!0,i=u,ei(t,n,u,"press")}if(e.isMouseButtonReleased(0)&&null!==i){if(t.valid(i)&&t.has(i,$s)){const e=t.get(i,$s);e.pressed=!1,e.justReleased=!0,ei(t,n,i,"release"),i===s&&ei(t,n,i,"click")}i=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Pe.Update,Ee([],()=>{const e=t.getEntitiesWithComponents([Ds]);for(const n of e){if(t.has(n,zs)||t.insert(n,zs,{enabled:!0}),!t.has(n,$s))continue;const e=t.get(n,$s),s=t.get(n,Ds),i=t.get(n,zs),r=s.state;if(i.enabled?e.pressed?s.state=Us.Pressed:e.hovered?s.state=Us.Hovered:s.state=Us.Normal:s.state=Us.Disabled,r!==s.state&&s.transition&&t.has(n,G)){const r=t.get(n,G);r.color=us(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,G,r)}}},{name:"ButtonSystem"}))}}const ni=new ti,si=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 ii{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){W("TextInput",si);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=u(_.textCanvasSize,64),r=i.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,l=!0,c=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()},g=()=>{a=!0},y=()=>{a=!1,x()},m=t=>{if(null===o)return;if("Escape"===t.key)return void b();const s=n.get(o,si);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Ws).emit(o,"submit"),void b()}let i=s.cursorPos;"ArrowLeft"===t.key?i=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?i=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?i=0:"End"===t.key&&(i=s.value.length),i!==s.cursorPos&&(s.cursorPos=i,f.selectionStart=i,f.selectionEnd=i,s.dirty=!0,S())},w=()=>{if(null!==o&&n.valid(o)&&n.has(o,si)){const e=n.get(o,si);e.focused=!1,e.dirty=!0}o=null};function x(){if(null===o||!n.valid(o))return;const t=n.get(o,si);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(Ws).emit(o,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,S()}function v(e){if(o===e)return;b();const t=n.get(e,si);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),S())}function b(){if(null!==o&&n.valid(o)&&n.has(o,si)){const e=n.get(o,si);e.focused=!1,e.dirty=!0}o=null,f.blur()}function S(){l=!0,c=0}function P(e,o,a,c){(i.width<a||i.height<c)&&(i.width=ps(Math.max(i.width,a)),i.height=ps(Math.max(i.height,c))),r.clearRect(0,0,i.width,i.height);const h=o.backgroundColor;r.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,r.fillRect(0,0,a,c),r.save(),r.beginPath(),r.rect(o.padding,0,a-2*o.padding,c),r.clip(),r.font=`${o.fontSize}px ${o.fontFamily}`,r.textBaseline="top",r.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;r.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),g=o.padding;if(o.multiline){const e=fs(r,d,a-2*g);let t=g;for(const n of e)r.fillText(n,g,t),t+=p}else{const e=(c-o.fontSize)/2;r.fillText(d,g,e)}if(o.focused&&l){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,n,s;if(o.multiline){const e=fs(r,o.value.substring(0,o.cursorPos),a-2*g),i=e.length>0?e[e.length-1]:"";t=g+r.measureText(i).width,n=g+(e.length-1)*p,s=p}else t=g+r.measureText(e).width,n=(c-o.fontSize)/2,s=o.fontSize;r.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,r.fillRect(t,n,2,s)}r.restore();const y=r.getImageData(0,0,a,c),m=new Uint8Array(y.data.buffer),_=t.getResourceManager(),w=t._malloc(m.length);t.HEAPU8.set(m,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const v=_.createTexture(a,c,w,m.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,G);b.texture=v,b.size.x=a,b.size.y=c,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},n.insert(e,G,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",g),f.addEventListener("compositionend",y),f.addEventListener("keydown",m),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",g),f.removeEventListener("compositionend",y),f.removeEventListener("keydown",m),f.removeEventListener("blur",w),f.remove()},e.addSystemToSchedule(Pe.PreUpdate,Ee([de(Ws)],e=>{const t=n.getEntitiesWithComponents([si,zs]);for(const e of t){if(!n.has(e,$s))continue;if(n.get(e,$s).justPressed)return void v(e)}if(null!==o){const e=n.getEntitiesWithComponents([zs]);for(const t of e){if(n.has(t,si))continue;if(!n.has(t,$s))continue;if(n.get(t,$s).justPressed)return void b()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Pe.PreUpdate,Ee([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),i=0===h?0:(e-h)/1e3;if(h=e,null!==o&&(c+=i,c>=.5&&(c-=.5,l=!l,null!==o&&n.valid(o)&&n.has(o,si)))){n.get(o,si).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,si)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([si,ls]);for(const e of a){const t=n.get(e,si);if(!t.dirty)continue;const s=n.get(e,ls),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(cs(n,e),P(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const ri=new ii,oi={Simple:0,Sliced:1,Tiled:2,Filled:3},ai={Horizontal:0,Vertical:1},li={Left:0,Right:1,Bottom:2,Top:3},ci=F("Image",{texture:v,color:{r:1,g:1,b:1,a:1},imageType:oi.Simple,fillMethod:ai.Horizontal,fillOrigin:li.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0});const hi=new class{build(e){W("Image",ci);const t=e.world;e.addSystemToSchedule(Pe.PreUpdate,Ee([],()=>{const e=t.getEntitiesWithComponents([ci]);for(const n of e){const e=t.get(n,ci);cs(t,n);const s=t.get(n,G);if(s.texture=e.texture,s.color.r=e.color.r,s.color.g=e.color.g,s.color.b=e.color.b,s.color.a=e.color.a,s.layer=e.layer,s.material=e.material,t.has(n,ls)){const e=t.get(n,ls);s.size.x=e.size.x,s.size.y=e.size.y}if(s.uvOffset.x=0,s.uvOffset.y=0,s.uvScale.x=1,s.uvScale.y=1,e.imageType===oi.Filled){const t=Math.max(0,Math.min(1,e.fillAmount));e.fillMethod===ai.Horizontal?e.fillOrigin===li.Left?(s.uvScale.x=t,s.size.x*=t):(s.uvOffset.x=1-t,s.uvScale.x=t,s.size.x*=t):e.fillOrigin===li.Bottom?(s.uvScale.y=t,s.size.y*=t):(s.uvOffset.y=1-t,s.uvScale.y=t,s.size.y*=t)}else e.imageType===oi.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(s.uvScale.x=s.size.x/e.tileSize.x,s.uvScale.y=s.size.y/e.tileSize.y);t.insert(n,G,s)}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},ui=F("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),di=F("ToggleGroup",{allowSwitchOff:!1});const fi=new class{build(e){W("Toggle",ui),W("ToggleGroup",di);const t=e.world;e.addSystemToSchedule(Pe.Update,Ee([de(Ws)],e=>{const n=t.getEntitiesWithComponents([ui]);for(const s of n){if(t.has(s,zs)||t.insert(s,zs,{enabled:!0}),!t.has(s,$s))continue;const i=t.get(s,$s),r=t.get(s,ui),o=t.get(s,zs);if(i.justPressed&&o.enabled){const i=r.group,o=0!==i&&t.valid(i)&&t.has(i,di);if(r.isOn&&o){if(!t.get(i,di).allowSwitchOff)continue}if(r.isOn=!r.isOn,r.isOn&&o)for(const r of n){if(r===s)continue;const n=t.get(r,ui);n.group===i&&n.isOn&&(n.isOn=!1,e.emit(r,"change"))}e.emit(s,"change")}if(r.graphicEntity&&t.valid(r.graphicEntity)&&t.has(r.graphicEntity,G)){const e=t.get(r.graphicEntity,G);e.color.a=r.isOn?1:0,t.insert(r.graphicEntity,G,e)}if(r.transition&&t.has(s,G)){const e=t.get(s,G);e.color=us(r.transition,o.enabled,i.pressed,i.hovered),t.insert(s,G,e)}}},{name:"ToggleSystem"}))}},pi=as,gi=F("ProgressBar",{value:0,fillEntity:0,direction:as.LeftToRight});const yi=new class{build(e){W("ProgressBar",gi);const t=e.world;e.addSystemToSchedule(Pe.PreUpdate,Ee([],()=>{const e=t.getEntitiesWithComponents([gi,ls]);for(const n of e){const e=t.get(n,gi);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=Math.max(0,Math.min(1,e.value));hs(t,e.fillEntity,e.direction,s)}},{name:"ProgressBarSystem"}))}},mi=F("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),_i=F("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}}),wi=new Float32Array(16),xi=new Float32Array(16);let vi=!0;function bi(e,t,n){const s=e.mouseX*n,i=t.screenH-e.mouseY*n;return function(e){let t=!1;for(let n=0;n<16;n++)if(xi[n]!==e[n]){t=!0;break}t&&(xi.set(e),vi=!0)}(t.viewProjection),vi&&(Ts(t.viewProjection,wi),vi=!1),Cs(s,i,wi,t.vpX,t.vpY,t.vpW,t.vpH)}const Si=new class{build(e){W("Draggable",mi),W("DragState",_i);const t=e.world,n=e.getResource(Ws);let s=null,i={x:0,y:0},r=null;const o="undefined"!=typeof window&&window.devicePixelRatio||1;e.addSystemToSchedule(Pe.PreUpdate,Ee([de(ke),de(Xe)],(e,a)=>{if(!a.valid)return;const l=bi(e,a,o);if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([mi,$s]);let n=null;for(const s of e){if(!t.get(s,mi).enabled)continue;t.get(s,$s).hovered&&(n=s)}if(null!==n){s=n,i={x:l.x,y:l.y},t.has(n,_i)||t.insert(n,_i);const e=t.get(n,_i),r=t.get(n,V);e.startWorldPos={x:r.position.x,y:r.position.y},e.currentWorldPos={x:r.position.x,y:r.position.y},e.pointerStartWorld={x:l.x,y:l.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,_i)){t.get(s,_i).isDragging=!1}s=null}if(null!==s&&null===r){if(!t.valid(s))return void(s=null);const e=l.x-i.x,o=l.y-i.y,c=Math.sqrt(e*e+o*o),h=t.get(s,mi);if(c*(a.vpW/(a.worldRight-a.worldLeft))>=h.dragThreshold){r=s,s=null;t.get(r,_i).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,_i))return void(r=null);const s=t.get(r,_i),i=t.get(r,mi),o=l.x-s.pointerStartWorld.x,a=l.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+o,h=s.startWorldPos.y+a;const u=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,r=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),r=Math.max(r,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),r=Math.min(r,e.constraintMax.y)),{x:i,y:r}}(i,s,c,h);c=u.x,h=u.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:h-f},s.currentWorldPos={x:c,y:h},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:h-s.startWorldPos.y},t.has(r,N)){const e=function(e,t,n,s){if(!e.has(t,Q))return{x:n,y:s};const i=e.get(t,Q).entity;if(!e.valid(i)||!e.has(i,V))return{x:n,y:s};const r=e.get(i,V),o=0!==r.scale.x?r.scale.x:1,a=0!==r.scale.y?r.scale.y:1,l=2*Math.atan2(r.rotation.z,r.rotation.w),c=Math.sin(-l),h=Math.cos(-l);return{x:(n*h-s*c)/o,y:(n*c+s*h)/a}}(t,r,s.deltaWorld.x,s.deltaWorld.y),n=t.get(r,N);n.position.x+=e.x,n.position.y+=e.y,t.insert(r,N,n)}n.emit(r,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(r,"drag_end"),r=null)}},{name:"DragSystem"}))}},Pi=F("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135});const Mi=new class{build(e){W("ScrollView",Pi);const t=e.world,n=new Map;let s=0;e.addSystemToSchedule(Pe.PreUpdate,Ee([de(ke),de(Xe)],(e,i)=>{const r=performance.now()/1e3,o=s>0?Math.min(r-s,.05):0;if(s=r,!i.valid)return;const a={x:i.worldMouseX,y:i.worldMouseY},l=t.getEntitiesWithComponents([Pi,ls]);for(const s of l){t.has(s,zs)||t.insert(s,zs,{enabled:!0,blockRaycast:!0}),t.has(s,Ps)||t.insert(s,Ps,{enabled:!0,mode:"scissor"});const i=t.get(s,Pi),r=t.get(s,ls);let l=n.get(s);l||(l={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0},n.set(s,l));const c=t.has(s,$s)?t.get(s,$s):null;if(c?.justPressed&&(l.isDragging=!0,l.lastWorldX=a.x,l.lastWorldY=a.y,l.velocityX=0,l.velocityY=0),l.isDragging&&e.isMouseButtonDown(0)){const e=a.x-l.lastWorldX,t=a.y-l.lastWorldY;i.horizontalEnabled&&(i.scrollX-=e,l.velocityX=o>0?-e/o:0),i.verticalEnabled&&(i.scrollY-=t,l.velocityY=o>0?-t/o:0),l.lastWorldX=a.x,l.lastWorldY=a.y}if(l.isDragging&&e.isMouseButtonReleased(0)&&(l.isDragging=!1),c?.hovered){const t=e.getScrollDelta();i.verticalEnabled&&0!==t.y&&(i.scrollY+=.1*t.y,l.velocityY=0),i.horizontalEnabled&&0!==t.x&&(i.scrollX+=.1*t.x,l.velocityX=0)}if(!l.isDragging&&i.inertia&&o>0){const e=Math.pow(i.decelerationRate,o);i.horizontalEnabled&&Math.abs(l.velocityX)>.1?(i.scrollX+=l.velocityX*o,l.velocityX*=e):l.velocityX=0,i.verticalEnabled&&Math.abs(l.velocityY)>.1?(i.scrollY+=l.velocityY*o,l.velocityY*=e):l.velocityY=0}const h=r.size.x,u=r.size.y,d=Math.max(0,i.contentWidth-h),f=Math.max(0,i.contentHeight-u);if(i.scrollX=Math.max(0,Math.min(i.scrollX,d)),i.scrollY=Math.max(0,Math.min(i.scrollY,f)),0!==i.contentEntity&&t.valid(i.contentEntity)&&t.has(i.contentEntity,N)){const e=t.get(i.contentEntity,N);e.position.x=-i.scrollX,e.position.y=i.scrollY,t.insert(i.contentEntity,N,e)}}},{name:"ScrollViewSystem"}))}},Ei=as,Ti=F("Slider",{value:0,minValue:0,maxValue:1,direction:as.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});const Ci=new class{build(e){W("Slider",Ti);const t=e.world;let n=null;e.addSystemToSchedule(Pe.PreUpdate,Ee([de(ke),de(Xe)],(e,s)=>{if(!s.valid)return;const i=s.worldMouseX,r=s.worldMouseY,o=t.getEntitiesWithComponents([Ti,ls,V]);for(const s of o){t.has(s,zs)||t.insert(s,zs,{enabled:!0,blockRaycast:!0});const o=t.get(s,Ti),a=t.get(s,ls),l=t.get(s,V),c=t.has(s,$s)?t.get(s,$s):null;if(c?.justPressed&&(n=s),n===s&&e.isMouseButtonDown(0)){const e=a.size.x*l.scale.x,t=a.size.y*l.scale.y,n=l.position.x-a.pivot.x*e,s=l.position.y-a.pivot.y*t;let c;switch(o.direction){case as.LeftToRight:c=e>0?(i-n)/e:0;break;case as.RightToLeft:c=e>0?1-(i-n)/e:0;break;case as.BottomToTop:c=t>0?(r-s)/t:0;break;case as.TopToBottom:c=t>0?1-(r-s)/t:0}c=Math.max(0,Math.min(1,c));let h=o.minValue+c*(o.maxValue-o.minValue);o.wholeNumbers&&(h=Math.round(h)),o.value=Math.max(o.minValue,Math.min(o.maxValue,h))}n===s&&e.isMouseButtonReleased(0)&&(n=null);const h=o.maxValue-o.minValue,u=h>0?(o.value-o.minValue)/h:0;if(0!==o.fillEntity&&t.valid(o.fillEntity)&&hs(t,o.fillEntity,o.direction,u),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,ls)){const e=t.get(o.handleEntity,ls);switch(o.direction){case as.LeftToRight:e.anchorMin={x:u,y:0},e.anchorMax={x:u,y:1};break;case as.RightToLeft:e.anchorMin={x:1-u,y:0},e.anchorMax={x:1-u,y:1};break;case as.BottomToTop:e.anchorMin={x:0,y:u},e.anchorMax={x:1,y:u};break;case as.TopToBottom:e.anchorMin={x:0,y:1-u},e.anchorMax={x:1,y:1-u}}t.insert(o.handleEntity,ls,e)}}},{name:"SliderSystem"}))}},Ri=F("Focusable",{tabIndex:0,isFocused:!1});class Ai{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Ii=ue(new Ai,"FocusManager");const Fi=new class{build(e){W("Focusable",Ri);const t=e.world,n=new Ai;e.insertResource(Ii,n),e.addSystemToSchedule(Pe.Update,Ee([de(ke),de(Ws)],(e,s)=>{const i=t.getEntitiesWithComponents([Ri]);for(const e of i){if(!t.has(e,$s))continue;t.get(e,$s).justPressed&&r(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){const s=t.get(n,Ri);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const o=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===o?a?s.length-1:0:a?(o-1+s.length)%s.length:(o+1)%s.length,r(s[l])}function r(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Ri)){t.get(i,Ri).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Ri).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},ki=F("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});const Bi=new class{build(e){W("SafeArea",ki);const t=e.world;let n={top:0,bottom:0,left:0,right:0},s=0;e.addSystemToSchedule(Pe.PreUpdate,Ee([],()=>{s++%60==0&&(n=function(){if("undefined"==typeof document)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}());const e=t.getEntitiesWithComponents([ki,ls]);for(const s of e){const e=t.get(s,ki),i=t.get(s,ls);let r=!1;const o=e.applyTop?n.top:0,a=e.applyBottom?n.bottom:0,l=e.applyLeft?n.left:0,c=e.applyRight?n.right:0;i.offsetMin.x===l&&i.offsetMin.y===a||(i.offsetMin={x:l,y:a},r=!0),i.offsetMax.x===-c&&i.offsetMax.y===-o||(i.offsetMax={x:-c,y:-o},r=!0),r&&t.insert(s,ls,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},zi=F("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2}),$i=new Map;function Ui(e,t){const n=$i.get(e);n&&(n.renderer=t)}const Di=new class{build(e){W("ListView",zi);const t=e.world;e.addSystemToSchedule(Pe.PreUpdate,Ee([de(ke)],e=>{const n=t.getEntitiesWithComponents([zi,ls]);for(const s of n){t.has(s,zs)||t.insert(s,zs,{enabled:!0,blockRaycast:!0}),t.has(s,Ps)||t.insert(s,Ps,{enabled:!0,mode:"scissor"});let n=$i.get(s);n||(n={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},$i.set(s,n));const i=t.get(s,zi),r=t.get(s,ls),o=r.size.y,a=t.has(s,$s)?t.get(s,$s):null;if(a?.hovered){const t=e.getScrollDelta();0!==t.y&&(i.scrollY+=.1*t.y)}const l=Math.max(0,i.itemCount*i.itemHeight-o);i.scrollY=Math.max(0,Math.min(i.scrollY,l));const c=Math.max(0,Math.floor(i.scrollY/i.itemHeight)-i.overscan),h=Math.min(i.itemCount,Math.ceil((i.scrollY+o)/i.itemHeight)+i.overscan);for(const[e,s]of n.itemEntities)(e<c||e>=h)&&(t.valid(s)&&t.despawn(s),n.itemEntities.delete(e));for(let e=c;e<h;e++){let o=n.itemEntities.get(e);if(o&&t.valid(o)||(o=t.spawn(),t.insert(o,ne,{value:`ListItem_${e}`}),t.insert(o,ls,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r.size.x,y:i.itemHeight},pivot:{x:.5,y:1}}),t.setParent(o,s),n.itemEntities.set(e,o),n.renderer&&n.renderer(e,o)),t.has(o,N)){const n=t.get(o,N);n.position.y=-(e*i.itemHeight-i.scrollY),t.insert(o,N,n)}}n.visibleStart=c,n.visibleEnd=h}},{name:"ListViewSystem"}))}},Li=F("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0}),Wi=new Map;const Oi=new class{build(e){W("Dropdown",Li);const t=e.world;function n(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;a(i,!0),o(s);const r=t.has(i,ls)?t.get(i,ls):null,c=r?r.size.x:160;for(let e=0;e<n.options.length;e++){const r=t.spawn();t.insert(r,ne,{value:`Option_${e}`}),t.insert(r,ls,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:30},pivot:{x:.5,y:1}}),t.insert(r,N,{position:{x:0,y:-30*e,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,_s,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:1,g:1,b:1,a:1},align:0,verticalAlign:1,wordWrap:!1,overflow:1,lineHeight:1.2}),t.insert(r,zs,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r)}r&&(r.size.y=30*n.options.length,t.insert(i,ls,r)),l(s)}function s(e,t,n){t.isOpen=!1,o(n),a(t.listEntity,!1)}function i(e,t,n,i,r){t.selectedIndex=i,s(0,t,n),r.emit(e,"change")}function r(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,_s))return;const s=t.get(n,_s),i=e.selectedIndex>=0&&e.selectedIndex<e.options.length?e.options[e.selectedIndex]:"";s.content!==i&&(s.content=i,t.insert(n,_s,s))}function o(e){for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[]}function a(e,n){if(0===e||!t.valid(e))return;if(!t.has(e,N))return;const s=t.get(e,N),i=n?1:0;s.scale={x:i,y:i,z:i},t.insert(e,N,s)}function l(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,G))continue;const i=t.get(s,G);n===e.highlightIndex?i.color={r:.3,g:.5,b:.8,a:1}:i.color={r:1,g:1,b:1,a:1},t.insert(s,G,i)}}function c(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,$s))continue;if(t.get(n,$s).hovered)return!0}return!1}e.addSystemToSchedule(Pe.Update,Ee([de(ke),de(Ws)],(e,o)=>{const a=t.getEntitiesWithComponents([Li]);for(const h of a){t.has(h,zs)||t.insert(h,zs,{enabled:!0,blockRaycast:!0});const a=t.get(h,Li),u=t.has(h,$s)?t.get(h,$s):null;let d=Wi.get(h);if(d||(d={optionEntities:[],highlightIndex:-1},Wi.set(h,d)),u?.justPressed&&(a.isOpen?s(h,a,d):n(h,a,d)),a.isOpen){for(let e=0;e<d.optionEntities.length;e++){const n=d.optionEntities[e];if(!t.valid(n)||!t.has(n,$s))continue;if(t.get(n,$s).justPressed){i(h,a,d,e,o);break}}e.isKeyPressed("ArrowDown")?(d.highlightIndex=Math.min(d.highlightIndex+1,a.options.length-1),l(d)):e.isKeyPressed("ArrowUp")?(d.highlightIndex=Math.max(d.highlightIndex-1,0),l(d)):e.isKeyPressed("Enter")&&d.highlightIndex>=0?i(h,a,d,d.highlightIndex,o):e.isKeyPressed("Escape")&&s(h,a,d),e.isMouseButtonPressed(0)&&(u?.hovered||c(d)||s(h,a,d))}r(a)}},{name:"DropdownSystem"}))}},Hi=0,ji=0,Xi=2,Yi=F("LayoutGroup",{direction:Hi,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:ji,reverseOrder:!1});const Ni=new class{build(e){W("LayoutGroup",Yi);const t=e.world;e.addSystemToSchedule(Pe.PreUpdate,Ee([],()=>{const e=t.getEntitiesWithComponents([Yi,ls,Z]);for(const n of e){const e=t.get(n,Yi),s=t.get(n,ls),i=t.get(n,Z);if(!i.entities||0===i.entities.length)continue;const r=[];for(const e of i.entities)t.valid(e)&&t.has(e,ls)&&t.has(e,N)&&r.push({entity:e,rect:t.get(e,ls)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=s.size.x,a=s.size.y,l=e.padding;l.left,l.right,l.top,l.bottom;const c=e.direction===Hi;let h=0;for(const n of r){const s=n.rect.size.x,i=n.rect.size.y;let r,u;c?(r=.5*-o+l.left+h+.5*s,u=e.childAlignment===ji?.5*a-l.top-.5*i:e.childAlignment===Xi?.5*-a+l.bottom+.5*i:.5*(l.bottom-l.top),h+=s+e.spacing):(r=e.childAlignment===ji?.5*-o+l.left+.5*s:e.childAlignment===Xi?.5*o-l.right-.5*s:.5*(l.left-l.right),u=.5*a-l.top-h-.5*i,h+=i+e.spacing),n.rect.anchorMin.x=.5,n.rect.anchorMin.y=.5,n.rect.anchorMax.x=.5,n.rect.anchorMax.y=.5,n.rect.offsetMin.x=r,n.rect.offsetMin.y=u;const d=t.get(n.entity,N);d.position.x=r,d.position.y=u,t.insert(n.entity,N,d)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};async function Vi(e,t,n){const s=e.getResource(Xn);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Gi(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 qi=ue({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Ji=ue(null,"PhysicsAPI");function Ki(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Qi(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Zi{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(qi,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Gi(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([J]);for(const n of t){const t=e.world.get(n,J);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),r=1/i,o=e.world;e.addSystemToSchedule(Pe.PostUpdate,Ee([de(ye)],a=>{const l=o.getEntitiesWithComponents([re,N,V]),c=new Set;for(const i of l){c.add(i);const a=o.get(i,re),l=o.get(i,V);if(t.has(i)){const e=n.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=Ki(l.rotation);s._physics_createBody(i,a.bodyType,l.position.x*r,l.position.y*r,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),er(e,s,i),t.add(i),n.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ce.Kinematic){const e=Ki(l.rotation);s._physics_setBodyTransform(i,l.position.x*r,l.position.y*r,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const i=t._physics_getDynamicBodyTransforms(),r=i>>2;for(let i=0;i<s;i++){const s=r+4*i,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const h=e.world.get(o,N);if(!h)continue;let u=a,d=l,f=c;if(e.world.has(o,Q)){const t=e.world.get(o,Q);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,V)){const n=e.world.get(t.entity,V),s=Ki(n.rotation),i=a-n.position.x,r=l-n.position.y,o=Math.cos(-s),h=Math.sin(-s);u=(i*o-r*h)/(0!==n.scale.x?n.scale.x:1),d=(i*h+r*o)/(0!==n.scale.y?n.scale.y:1),f=c-s}}h.position.x=u,h.position.y=d;const p=Qi(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,N,h)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let r=0;r<i;r++){const i=e+6*r;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const r=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;r.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<h;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(qi,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Ji,tr._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function er(e,t,n){const s=e.world;if(s.has(n,oe)){const e=s.get(n,oe);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,ae)){const e=s.get(n,ae);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,le)){const e=s.get(n,le);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class tr{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(tr.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,n=!0){const s=e.getResourceManager(),i=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,i);const r=s.createTexture(t.width,t.height,i,t.pixels.length,1,n);return e._free(i),r}function sr(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function ir(e,t,n,s){const i=e.scale.x*t*(n?-1:1),r=e.scale.y*t*(s?-1:1),o=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,h=e.rotation.w,u=a+a,d=l+l,f=c+c,p=a*u,g=a*d,y=a*f,m=l*d,_=l*f,w=c*f,x=h*u,v=h*d,b=h*f;return new Float32Array([(1-(m+w))*i,(g+b)*i,(y-v)*i,0,(g-b)*r,(1-(p+w))*r,(_+x)*r,0,(y+v)*o,(_-x)*o,(1-(p+m))*o,0,e.position.x,e.position.y,e.position.z,1])}async function rr(e,t,n,s,i,r,o,a,l){const c=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const i=t.data.texture;if(void 0!==s[i])continue;try{s[i]=nr(e,await n.loadPixels(i))}catch{s[i]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let h={},u=null;if(i&&(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"])}}(i),h=await async function(e,t,n,s,i){const r={};for(const o of s.entities)for(const s of o.components){if("SpineAnimation"!==s.type||!s.data)continue;const o=s.data.skeletonPath,a=s.data.atlasPath;if(!o||!a)continue;const l=i.resolvePath(o),c=i.resolvePath(a);try{const s=await i.readText(a),h="binary"===Mt(l)?.contentType;let u,d;if(h){const e=await i.readBinary(o);d=e.length,u=t._malloc(d),t.HEAPU8.set(e,u)}else{const e=await i.readText(o),n=(new TextEncoder).encode(e);d=n.length,u=t._malloc(d+1),t.HEAPU8.set(n,u),t.HEAPU8[u+d]=0}const f=n.loadSkeleton(u,d,s,s.length,h);if(t._free(u),f<0)continue;r[o]=f;const p=sr(s),g=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const r=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),o=nr(e,r,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,r.width,r.height)}catch{}}}catch{}}return r}(t,i,u,n,s)),r){new Zi("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(r)).build(e)}const d=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const i=t.data.font;if(void 0===s[i])try{let t,r;const o=Mt(i);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await n.readText(i)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){s[i]=0;continue}const a=i.substring(0,i.lastIndexOf("/")),l=a?`${a}/${o}`:o;t=await n.readText(l),r=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(i),r=i.substring(0,i.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[i]=0;continue}const l=r?`${r}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),h=nr(e,c,!1),u=e.getResourceManager();s[i]=u.loadBitmapFont(t,h,c.width,c.height)}catch{s[i]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const i=e.data.material;if(void 0===n[i])try{const e=JSON.parse(await t.readText(i));if(!e.vertexSource||!e.fragmentSource){n[i]=0;continue}const r=e.vertexSource+e.fragmentSource;let o=s[r];o||(o=et.createShader(e.vertexSource,e.fragmentSource),s[r]=o),n[i]=et.createFromAsset(e,o)}catch{n[i]=0}}return n}(n,s);!function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=pt(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=i[e.type][n[e.field]]||0)}}(n,c,d,f);const p=gt(e.world,n);if(l&&e.hasResource(Xn))for(const t of p.values())e.world.insert(t,se,{scene:l,persistent:!1});if(i&&u){const s=function(e,t,n,s){const i={};for(const r of t.entities)if(!1!==r.visible)for(const t of r.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=n[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const l=s.get(r.id);void 0!==l&&(i[l]=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 i}(u,n,h,p);!function(e,t,n,s,i){let r=0;e.setSpineRenderer((o,a)=>{let l=a-r;r=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in i){const r=Number(e),o=i[e],a=c.has(r,te)?c.get(r,te):null,h=!1!==a?.playing,u=a?.timeScale??1;h&&s.update(o,l*u);let d=0;if(c.has(r,V)){const e=ir(c.get(r,V),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(o,e),r=s.getMeshBatchIndexCount(o,e);if(!i||!r)continue;const a=8*i*4,l=2*r,c=n._malloc(a),h=n._malloc(l),u=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,c,h,u,f);const p=n.HEAPU32[u>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*i),m=new Uint16Array(n.HEAPU8.buffer,h,r),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,w,r).set(m),t.renderer_submitTriangles(_,i,w,r,p,g,d),t._free(_),t._free(w),n._free(c),n._free(h),n._free(u),n._free(f)}d&&t._free(d)}})}(e,t,i,u,s)}if(a){const t=e.getResource(Ut);t&&t.setAddressableManifest(a)}}function or(e,t,n){return{name:e,data:t,async setup(){await rr(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class ar{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,i=e.data.atlasPath;s&&("binary"===Mt(s)?.contentType?n.add(s):t.add(s)),i&&t.add(i)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const r=[];for(const e of s){const t=Mt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||r.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}r.length>0&&await Promise.all(r)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),r=new OffscreenCanvas(i.width,i.height).getContext("2d");r.drawImage(i,0,0);const o=r.getImageData(0,0,i.width,i.height);return i.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const lr="__preview__";class cr{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(Xn);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(),n=new ar(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await rr(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,lr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([q]);for(const s of n){if(e.get(s,q).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([J]);for(const i of s){const s=e.get(i,J);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(Xn).getScene(lr),r=i?i.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,N,o);const a={isActive:!0,projectionType:j.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:X.ColorAndDepth};e.insert(r,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(Xn);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 hr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Bn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Bn.getTargetTexture(n),width:e.width,height:e.height}},release(e){Bn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Bn.releaseRenderTarget(e._handle),hr.create({width:t,height:n,depth:!0})),begin(e,t){Bn.begin(t,e._handle)},end(){Bn.end()},getDepthTexture:e=>Bn.getTargetDepthTexture(e._handle)};let ur=!1;function dr(e){ur=e}function fr(){return ur}function pr(){return!ur}var gr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(gr||(gr={}));class yr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${gr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case gr.Debug:console.debug(t,n);break;case gr.Info:console.log(t,n);break;case gr.Warn:console.warn(t,n);break;case gr.Error:console.error(t,n)}}}class mr{constructor(){this.handlers_=[],this.minLevel_=gr.Info,this.addHandler(new yr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(gr.Debug,e,t,n)}info(e,t,n){this.log(gr.Info,e,t,n)}warn(e,t,n){this.log(gr.Warn,e,t,n)}error(e,t,n){this.log(gr.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const _r=new mr;function wr(){return _r}function xr(e){_r.setMinLevel(e)}function vr(e,t,n){_r.debug(e,t,n)}function br(e,t,n){_r.info(e,t,n)}function Sr(e,t,n){_r.warn(e,t,n)}function Pr(e,t,n){_r.error(e,t,n)}const Mr=[Ss,Bs,Gs,hi,yi,ni,Si,Mi,Ci,fi,ri,Fi,Bi,Di,Oi,Ni];function Er(e,t){return function(e,t){const n=Gn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),tn(e),Ke(e),wn(e),Pn(e),Fn(e),$n(e);const i=new Ln;n.setPipeline(i);let r=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,i,r){r||(r=Qn(e,s,t,i));const o=n.getResource(Xe);if(r.length>0){const e=r[0],n=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(n.x*t),o.vpY=Math.round((1-n.y-n.h)*i),o.vpW=Math.round(n.w*t),o.vpH=Math.round(n.h*i),o.screenW=t,o.screenH=i,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}n.insertResource(Xe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=o();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Bn.setClearColor(e.x,e.y,e.z,e.w)}const h=(d()-r)/1e3;let u;if(Bn.resize(t,l),Tn.isInitialized()&&Tn.getPassCount()>0&&!Tn.isBypassed()&&Tn.resize(t,l),n.hasResource(Xn)){const e=n.getResource(Xn).getActiveScenes();e.length>0&&(u=new Set(e))}i.setActiveScenes(u??null);const f=Qn(e,s,t,l,n.world,u);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Jn,width:t,height:l,elapsed:h});else{for(const e of f){const n=e.viewportRect,r=Math.round(n.x*t),o=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:r,y:o,w:a,h:c},clearFlags:e.clearFlags,elapsed:h})}Bn.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Pe.First,l),n.addSystemToSchedule(Pe.Last,c),n.addPlugin(Lt),n.addPlugin(qt),n.addPlugin(ze),n.addPlugin(Vn),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Mr,...t})}e=f;export{Gn as App,Dt as AssetPlugin,Wt as AssetRefCounter,$t as AssetServer,Ut as Assets,ct as AsyncCache,ee as BitmapText,Ye as BlendMode,ce as BodyType,oe as BoxCollider,Ds as Button,Us as ButtonState,q as Camera,J as Canvas,le as CapsuleCollider,Z as Children,ae as CircleCollider,X as ClearFlags,ve as Commands,Se as CommandsInstance,g as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,y as DEFAULT_PIXELS_PER_UNIT,m as DEFAULT_TEXT_CANVAS_SIZE,pn as DataType,_i as DragState,mi as Draggable,on as Draw,Li as Dropdown,be as EntityCommands,ai as FillMethod,li as FillOrigin,Ii as FocusManager,Ai as FocusManagerState,Ri as Focusable,Dn as GLDebug,bn as Geometry,x as INVALID_ENTITY,b as INVALID_FONT,v as INVALID_TEXTURE,ci as Image,oi as ImageType,ke as Input,Be as InputPlugin,Fe as InputState,zs as Interactable,zi as ListView,N as LocalTransform,gr as LogLevel,mr as Logger,et as Material,ht as MaterialLoader,me as Mut,ne as Name,Q as Parent,tr as Physics,qi as PhysicsEvents,Zi as PhysicsPlugin,Tn as PostProcess,Nt as PrefabServer,Vt as Prefabs,Gt as PrefabsPlugin,cr as PreviewPlugin,gi as ProgressBar,pi as ProgressBarDirection,j as ProjectionType,we as Query,xe as QueryInstance,Ln as RenderPipeline,Rn as RenderStage,hr as RenderTexture,Bn as Renderer,de as Res,fe as ResMut,re as RigidBody,_ as RuntimeConfig,ki as SafeArea,Y as ScaleMode,Xn as SceneManager,jn as SceneManagerState,se as SceneOwner,Pe as Schedule,Os as ScreenSpace,Pi as ScrollView,lt as ShaderSources,Ti as Slider,Ei as SliderDirection,te as SpineAnimation,G as Sprite,Ie as SystemRunner,_s as Text,gs as TextAlign,si as TextInput,ii as TextInputPlugin,ms as TextOverflow,bs as TextPlugin,ws as TextRenderer,ys as TextVerticalAlign,ye as Time,ui as Toggle,Xe as UICameraInfo,Ls as UIEventQueue,Ws as UIEvents,$s as UIInteraction,ti as UIInteractionPlugin,Vs as UILayoutPlugin,Ps as UIMask,ks as UIMaskPlugin,ls as UIRect,K as Velocity,ar as WebAssetProvider,je as World,V as WorldTransform,Re as addStartupSystem,Ce as addSystem,Ae as addSystemToSchedule,w as applyRuntimeConfig,Lt as assetPlugin,fn as clearDrawCallbacks,z as clearUserComponents,E as color,Hs as computeUIRectLayout,Fs as createMaskProcessor,or as createRuntimeSceneConfig,Er as createWebApp,vr as debug,F as defineComponent,ue as defineResource,Ee as defineSystem,k as defineTag,Pr as error,wt as findEntityByName,qn as flushPendingSystems,Tt as getAddressableType,Ct as getAddressableTypeByEditorType,At as getAllAssetExtensions,Bt as getAssetMimeType,Mt as getAssetTypeEntry,O as getComponent,ft as getComponentAssetFields,ie as getComponentDefaults,Ft as getCustomExtensions,Et as getEditorType,wr as getLogger,t as getPlatform,s as getPlatformType,B as getUserComponent,kt as getWeChatPackOptions,br as info,tn as initDrawAPI,$n as initGLDebugAPI,wn as initGeometryAPI,Ke as initMaterialAPI,Pn as initPostProcessAPI,Fn as initRendererAPI,ze as inputPlugin,Ht as instantiatePrefab,Ms as intersectRects,Ts as invertMatrix4,D as isBuiltinComponent,zt as isCustomExtension,fr as isEditor,Rt as isKnownAssetExtension,n as isPlatformInitialized,pr as isRuntime,Ne as isTextureRef,i as isWeChat,r as isWeb,mt as loadComponent,Gi as loadPhysicsModule,rr as loadRuntimeScene,gt as loadSceneData,yt as loadSceneWithAssets,It as looksLikeAssetPath,o as platformFetch,c as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,As as pointInOBB,Rs as pointInWorldRect,qt as prefabsPlugin,T as quat,W as registerComponent,dt as registerComponentAssetFields,un as registerDrawCallback,Ot as registerEmbeddedAssets,at as registerMaterialCallback,Vn as sceneManagerPlugin,Cs as screenToWorld,dr as setEditorMode,Ui as setListViewRenderer,xr as setLogLevel,We as setWasmErrorHandler,nn as shutdownDrawAPI,Un as shutdownGLDebugAPI,xn as shutdownGeometryAPI,Qe as shutdownMaterialAPI,Mn as shutdownPostProcessAPI,kn as shutdownRendererAPI,ri as textInputPlugin,Ss as textPlugin,Vi as transitionTo,ni as uiInteractionPlugin,Gs as uiLayoutPlugin,Bs as uiMaskPlugin,Mr as uiPlugins,$ as unregisterComponent,dn as unregisterDrawCallback,_t as updateCameraAspectRatio,S as vec2,P as vec3,M as vec4,Sr as warn,Es as worldRectToScreen,Yn as wrapSceneSystem};
//# sourceMappingURL=index.js.map