Skip to content

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

feat: expose 12 hardcoded defaults as configurable project settings

esengine5b4790867e96
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index 97988502b..305dc4b8d 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 u=[{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}],d={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 u)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 _(e){return p.has(e.toLowerCase())}function m(){const e=[];for(const t of u)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function y(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(y(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 C(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let A=!1;const E=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)})}},M=1920,R=1080,I=512,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 U=0;function L(e,t){const s=++U;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...k(t),...e}:k(t)}}function D(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function $(e,t){const s=D(),n=s.get(e);if(n)return n;const r=L(e,t);return s.set(e,r),O(e,t,!1),r}function W(e){const t=D(),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 D().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 N(e,t){j.set(e,t)}function V(e){return j.get(e)??z(e)}function X(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return j.set(e,s),s}const G={Perspective:0,Orthographic:1},q={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Y={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},J=X("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=X("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=X("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}),Z=X("Camera",{projectionType:G.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:q.ColorAndDepth}),ee=X("Canvas",{designResolution:{x:M,y:R},pixelsPerUnit:100,scaleMode:Y.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),te=X("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=X("Parent",{entity:0}),ne=X("Children",{entities:[]}),re=X("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B}),oe=X("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}),ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ae=$("SceneOwner",{scene:"",persistent:!1});N("Name",ie);const le=X("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ce=X("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ue=X("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),de=X("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),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 _e(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 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 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 u=null;this.world_.beginIteration();try{for(const d of n){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(d,t[s])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,s[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,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 Ce(e,t,s){const n=++Te;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Ae(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Ee{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 Me{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 Me,"Input");class Ie{constructor(e){this.target_=e??null}build(e){const s=new Me;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,Ce([],()=>{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 Ue(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")}function Le(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}:Le(e)}}return t}class De{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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,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.");this.cppRegistry_&&this.cppRegistry_.destroy(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){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(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;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(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(Ue(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,Le(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(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(Ue(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()}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 $e=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 We;function ze(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(We=exports.BlendMode||(exports.BlendMode={}))[We.Normal=0]="Normal",We[We.Additive=1]="Additive",We[We.Multiply=2]="Multiply",We[We.Screen=3]="Screen",We[We.PremultipliedAlpha=4]="PremultipliedAlpha";let Oe=null,He=null,je=1;const Ne=new Map;function Ve(e){Oe=e,He=e.getResourceManager(),tt()}function Xe(){0!==Je&&Oe&&(Oe._free(Je),Je=0),Ne.clear(),je=1,Ye=!1,Qe.clear(),Ze=null,He=null,Oe=null}function Ge(){if(!He)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return He}const qe={createShader:(e,t)=>Ge().createShader(e,t),releaseShader(e){e>0&&Ge().releaseShader(e)},create(e){const t=je++,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 Ne.set(t,s),t},get:e=>Ne.get(e),setUniform(e,t,s){const n=Ne.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ne.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ne.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ne.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ne.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ne.get(e);return t?.shader??0},release(e){Ne.delete(e)},isValid:e=>Ne.has(e),releaseAll(){Ne.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=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=je++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ne.set(s,n),s},toAssetData(e,t){const s=Ne.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=Ne.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ye=!1,Je=0;const Ke=4096,Qe=new Map;let Ze=null;function et(e){const t=(0===Je&&Oe&&(Je=Oe._malloc(Ke)),Je);if(0===t||!Oe)return{ptr:0,count:0};let s=0,n=0;const r=Oe.HEAPU8,o=Oe.HEAPU32,i=Oe.HEAPF32;for(const[a,l]of e){if(s+128>Ke)break;let e=Qe.get(a);e||(Ze||(Ze=new TextEncoder),e=Ze.encode(a),Qe.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[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++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function tt(){if(!Oe||Ye)return;Oe.materialDataProvider=(e,t,s,n,r)=>{const o=Ne.get(e);if(!o)return Oe.HEAPU32[t>>2]=0,Oe.HEAPU32[s>>2]=0,Oe.HEAPU32[n>>2]=0,void(Oe.HEAPU32[r>>2]=0);Oe.HEAPU32[t>>2]=o.shader,Oe.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=et(o.uniforms);Oe.HEAPU32[n>>2]=i,Oe.HEAPU32[r>>2]=a},Ye=!0}const st={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 nt{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 rt{constructor(e,t=""){this.cache_=new nt,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&&(qe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())qe.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:qe.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 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"}]}]]);function it(e){return ot.get(e)?.fields??[]}function at(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)ct(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 lt(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=ot.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,u=new Map,d=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);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const n=await t.loadBitmapFont(e,s);d.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.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=ot.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]=u.get(t)??0;break;case"font":s[e.field]=d.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)ct(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 ct(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=V(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 ut{constructor(e){this.textureCache_=new nt,this.shaderCache_=new nt,this.jsonCache_=new nt,this.textCache_=new nt,this.binaryCache_=new nt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new nt,this.prefabCache_=new nt,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,I),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new rt(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(),qe.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),u="binary"===g(e)?.contentType,d=u?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(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);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 lt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const 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 qe.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 qe.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 dt=fe(null,"Assets");class ht{build(e){const t=e.wasmModule;t?e.insertResource(dt,new ut(t)):console.warn("AssetPlugin: No WASM module available")}}const pt=new ht;async function ft(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 lt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const gt=10;async function _t(e,t,s,n,r,o=0){if(o>gt)throw new Error(`Prefab nesting depth exceeded ${gt}. 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),u=n.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?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};mt(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 mt(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 yt{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 ft(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const xt=fe(null,"Prefabs");class wt{constructor(){this.name="PrefabsPlugin",this.dependencies=[dt]}build(e){const t=e.getResource(dt);e.insertResource(xt,new yt(e.world,t))}}const vt=new wt;let bt=null,St=0,Pt=0,Tt=0;const Ct=new Float32Array(256);function At(e){bt=e,St=bt._malloc(64),Pt=bt._malloc(64),Tt=bt._malloc(1024)}function Et(){bt&&(St&&(bt._free(St),St=0),Pt&&(bt._free(Pt),Pt=0),Tt&&(bt._free(Tt),Tt=0)),bt=null}function Mt(){if(!bt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return bt}const Rt={r:1,g:1,b:1,a:1},It={begin(e){const t=Mt();t.HEAPF32.set(e,St/4),t.draw_begin(St)},end(){Mt().draw_end()},line(e,t,s,n=1){Mt().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){Mt().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){Mt().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){Mt().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){Mt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=Rt){Mt().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=Rt){Mt().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){Mt().draw_setLayer(e)},setDepth(e){Mt().draw_setDepth(e)},getDrawCallCount:()=>bt?bt.draw_getDrawCallCount():0,getPrimitiveCount:()=>bt?bt.draw_getPrimitiveCount():0,setBlendMode(e){Mt().draw_setBlendMode(e)},setDepthTest(e){Mt().draw_setDepthTest(e)},drawMesh(e,t,s){const n=Mt();n.HEAPF32.set(s,Pt/4),n.draw_mesh(e,t,Pt)},drawMeshWithMaterial(e,t,s){const n=Mt(),r=qe.get(t);if(!r)return;if(It.setBlendMode(r.blendMode),It.setDepthTest(r.depthTest),0===r.uniforms.size)return void It.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,Pt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Bt(t);if(!(n<0)){if(ze(s))Ct[o++]=10,Ct[o++]=n,Ct[o++]=s.slot??e++,Ct[o++]=s.textureId;else if("number"==typeof s)Ct[o++]=1,Ct[o++]=n,Ct[o++]=s;else if(Array.isArray(s)){Ct[o++]=s.length,Ct[o++]=n;for(let e=0;e<s.length;e++)Ct[o++]=s[e]}else"w"in s?(Ct[o++]=4,Ct[o++]=n,Ct[o++]=s.x,Ct[o++]=s.y,Ct[o++]=s.z,Ct[o++]=s.w):"z"in s?(Ct[o++]=3,Ct[o++]=n,Ct[o++]=s.x,Ct[o++]=s.y,Ct[o++]=s.z):(Ct[o++]=2,Ct[o++]=n,Ct[o++]=s.x,Ct[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(Ct.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Tt/4),n.draw_meshWithUniforms(e,r.shader,Pt,Tt,o)):n.draw_mesh(e,r.shader,Pt)}},Ft={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};function Bt(e){return Ft[e]??-1}const kt=new Map;function Ut(e,t,s){kt.set(e,{fn:t,scene:s??""})}function Lt(e){kt.delete(e)}function Dt(){kt.clear()}var $t;exports.DataType=void 0,($t=exports.DataType||(exports.DataType={}))[$t.Float=1]="Float",$t[$t.Float2=2]="Float2",$t[$t.Float3=3]="Float3",$t[$t.Float4=4]="Float4",$t[$t.Int=5]="Int",$t[$t.Int2=6]="Int2",$t[$t.Int3=7]="Int3",$t[$t.Int4=8]="Int4";let Wt=null,zt=0,Ot=0,Ht=0;function jt(e){Wt=e,zt=Wt._malloc(262144),Ot=Wt._malloc(65536),Ht=Wt._malloc(256)}function Nt(){Wt&&(zt&&Wt._free(zt),Ot&&Wt._free(Ot),Ht&&Wt._free(Ht),zt=0,Ot=0,Ht=0),Wt=null}function Vt(){if(!Wt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Wt}const Xt={create(e){const t=Vt(),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,zt/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,Ht,r).set(o),t.geometry_init(s,zt,n,Ht,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,Ot,n).set(e.indices),t.geometry_setIndices16(s,Ot,n)}else{new Uint32Array(t.HEAPU8.buffer,Ot,n).set(e.indices),t.geometry_setIndices32(s,Ot,n)}}return s},updateVertices(e,t,s=0){const n=Vt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,zt/4),n.geometry_updateVertices(e,zt,r,s)},release(e){e>0&&Vt().geometry_release(e)},isValid:e=>!(!Wt||e<=0)&&Wt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Xt.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 Xt.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 Xt.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 Gt=null;function qt(e){Gt=e}function Yt(){Gt&&Kt.isInitialized()&&Kt.shutdown(),Gt=null}function Jt(){if(!Gt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Gt}const Kt={init:(e,t)=>Jt().postprocess_init(e,t),shutdown(){Jt().postprocess_shutdown()},resize(e,t){Jt().postprocess_resize(e,t)},addPass:(e,t)=>Jt().postprocess_addPass(e,t),removePass(e){Jt().postprocess_removePass(e)},setEnabled(e,t){Jt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Jt().postprocess_isPassEnabled(e),setUniform(e,t,s){Jt().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Jt().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Jt().postprocess_begin()},end(){Jt().postprocess_end()},getPassCount:()=>Jt().postprocess_getPassCount(),isInitialized:()=>!!Gt&&Gt.postprocess_isInitialized(),setBypass(e){Jt().postprocess_setBypass(e)},isBypassed:()=>!Gt||Gt.postprocess_isBypassed(),createBlur:()=>qe.createShader(Qt,"#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:()=>qe.createShader(Qt,"#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:()=>qe.createShader(Qt,"#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:()=>qe.createShader(Qt,"#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")},Qt="#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 Zt;exports.RenderStage=void 0,(Zt=exports.RenderStage||(exports.RenderStage={}))[Zt.Background=0]="Background",Zt[Zt.Opaque=1]="Opaque",Zt[Zt.Transparent=2]="Transparent",Zt[Zt.Overlay=3]="Overlay";let es=null,ts=0;function ss(e){es=e,ts=es._malloc(64)}function ns(){es&&ts&&(es._free(ts),ts=0),es=null}const rs={init(e,t){es?.renderer_init(e,t)},resize(e,t){es?.renderer_resize(e,t)},begin(e,t){es&&ts&&(es.HEAPF32.set(e,ts/4),es.renderer_begin(ts,t??0))},flush(){es?.renderer_flush()},end(){es?.renderer_end()},submitSprites(e){es&&es.renderer_submitSprites(e._cpp)},submitBitmapText(e){es&&es.renderer_submitBitmapText(e._cpp)},submitSpine(e){es&&es.renderer_submitSpine?.(e._cpp)},setStage(e){es?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>es?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){es?.renderer_releaseTarget(e)},getTargetTexture:e=>es?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>es?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){es?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){es?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){es?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){es?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>es?es.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>es?{drawCalls:es.renderer_getDrawCalls(),triangles:es.renderer_getTriangles(),sprites:es.renderer_getSprites(),text:es.renderer_getText(),spine:es.renderer_getSpine?.()??0,meshes:es.renderer_getMeshes(),culled:es.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let os=null;function is(e){os=e}function as(){os=null}const ls={enable(){os?.gl_enableErrorCheck(!0)},disable(){os?.gl_enableErrorCheck(!1)},check:e=>os?.gl_checkErrors(e)??0,diagnose(){os?.renderer_diagnose()}};class cs{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_||(rs.resize(n,r),Kt.isInitialized()&&Kt.getPassCount()>0&&Kt.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),rs.setViewport(0,0,n,r),rs.clearBuffers(3),rs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),rs.submitSprites(t),rs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):rs.submitSpine(t),rs.flush(),this.executeDrawCallbacks(s,o),rs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;rs.setViewport(n.x,n.y,n.w,n.h),rs.setScissor(n.x,n.y,n.w,n.h,!0),rs.clearBuffers(r),rs.setScissor(0,0,0,0,!1),rs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),rs.submitSprites(t),rs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):rs.submitSpine(t),rs.flush(),this.executeDrawCallbacks(s,o),rs.end()}executeDrawCallbacks(e,t){const s=kt;if(s.size>0){It.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)}It.end();for(const e of n)Lt(e)}}}const us="__scene_transition_overlay__",ds={r:0,g:0,b:0,a:1};class hs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class ps{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),Ut(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Kt.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Kt.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 fs{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??.3,r=t.color??ds;t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Ut(us,()=>{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;It.setLayer(9999),It.setDepth(9999),It.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,Lt(us)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Lt(us),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new hs(t);this.scenes_.set(e,s);const n=new ps(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(dt)?this.app_.getResource(dt):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(dt)&&(t.assetServer=this.app_.getResource(dt));const n=await lt(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 hs(t);this.scenes_.set(e,s);const n=new ps(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(dt)?this.app_.getResource(dt):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(dt)&&(t.assetServer=this.app_.getResource(dt));const n=await lt(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())Lt(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Kt.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{Kt.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 gs=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(gs).getSceneStatus(t)&&s._fn(...n)}}}const ms=Ce([_e(gs),ge(xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),ys={name:"SceneManager",build(e){const t=new fs(e);e.insertResource(gs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(gs),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,ms)}};class xs{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,.25);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),n++;n>=8&&(this.fixedAccumulator_=0),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new De,this.resources_=new ye;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new xs}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this}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_}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}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(gs).register(e),this}setInitialScene(e){return this.getResource(gs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ee(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,Dt();const e=[as,ns,Yt,Nt,Xe,Et];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){let t=this.systems_.get(e);if(t&&this.runner_&&!this.frame_paused_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)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 ws=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function vs(e,t,s,n,r){const o=e*t/s,i=e;switch(n){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 bs(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 u,d=0,h=0;if(r.projectionType===G.Orthographic){if(h=r.orthoSize,l){h=vs(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}d=h*a,u=Ps(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Cs(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=Es(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(Rs(u,p)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Ss=new Float32Array(16);function Ps(e,t,s,n,r,o){const i=Ss;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 Ts=new Float32Array(16);function Cs(e,t,s,n){const r=Ts;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 As=new Float32Array(16);function Es(e,t,s){const n=As;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 Ms=new Float32Array(16);function Rs(e,t){const s=Ms;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 Is,Fs,Bs;exports.TextAlign=void 0,(Is=exports.TextAlign||(exports.TextAlign={}))[Is.Left=0]="Left",Is[Is.Center=1]="Center",Is[Is.Right=2]="Right",exports.TextVerticalAlign=void 0,(Fs=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[Fs.Top=0]="Top",Fs[Fs.Middle=1]="Middle",Fs[Fs.Bottom=2]="Bottom",exports.TextOverflow=void 0,(Bs=exports.TextOverflow||(exports.TextOverflow={}))[Bs.Visible=0]="Visible",Bs[Bs.Clip=1]="Clip",Bs[Bs.Ellipsis=2]="Ellipsis";const ks=$("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=$("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 Ls{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(I,I),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),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=r?Math.ceil(o):d+2*u,f=r?Math.ceil(i):h+2*u;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),_=Math.round(255*e.color.g),m=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${_}, ${m}, ${y})`,r&&e.overflow===exports.TextOverflow.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 exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-x)/2;break;case exports.TextVerticalAlign.Bottom:w=f-x-u;break;default:w=u}else w=u;let v=w;for(const t of l){let n;switch(e.align){case exports.TextAlign.Left:n=u;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-u;break;default:n=u}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 C=P.createTexture(p,f,T,S.length,1,!0);return this.module._free(T),{textureHandle:C,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 Ds(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 $s(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 Ws{build(e){N("Text",ks);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Ls(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,ks));for(const e of r.keys())n.valid(e)&&n.has(e,ks)||r.delete(e);const e=n.getEntitiesWithComponents([ks]);for(const t of e){const e=n.get(t,ks),o=n.has(t,Us)?n.get(t,Us):null,i=r.get(t);if(i&&!$s(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,Ds(e,o))}}))}}const zs=new Ws,Os=$("UIMask",{enabled:!0});function Hs(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 js(e,t,s,n,r,o,i,a,l,c,u){const d=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)*u]}const[_,m]=g(d,p),[y,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 Ns(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],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],g=e[12],_=e[13],m=e[14],y=e[15],x=n*l-r*a,w=n*c-o*a,v=n*u-i*a,b=r*c-o*l,S=r*u-i*l,P=o*u-i*c,T=d*_-h*g,C=d*m-p*g,A=d*y-f*g,E=h*m-p*_,M=h*y-f*_,R=p*y-f*m;let I=x*R-w*M+v*E+b*A-S*C+P*T;return 0===I||(I=1/I,s[0]=(l*R-c*M+u*E)*I,s[1]=(o*M-r*R-i*E)*I,s[2]=(_*P-m*S+y*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*A-a*R-u*C)*I,s[5]=(n*R-o*A+i*C)*I,s[6]=(m*v-g*P-y*w)*I,s[7]=(d*P-p*v+f*w)*I,s[8]=(a*M-l*A+u*T)*I,s[9]=(r*A-n*M-i*T)*I,s[10]=(g*S-_*v+y*x)*I,s[11]=(h*v-d*S-f*x)*I,s[12]=(l*C-a*E-c*T)*I,s[13]=(n*E-r*C+o*T)*I,s[14]=(_*w-g*b-m*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function Vs(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],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function Xs(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 Gs(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,u=a.size.y*l.scale.y;return js(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function qs(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Os]);if(0!==l.length)try{!function(e,t,s,n,r,o,i,a,l){const c=new Set;for(const e of n){t.get(e,Os).enabled&&c.add(e)}const u=[];for(const e of n){if(!c.has(e))continue;let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(c.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(c.has(s)){const e=Gs(t,s,r,o,i,a,l);e&&(n=Hs(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Gs(t,e,r,o,i,a,l);s&&d(e,s)}}(e,t,s,l,n,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Ys{build(e){if(N("UIMask",Os),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(qs(e.wasmModule,e.world))}}const Js=new Ys,Ks=$("Interactable",{enabled:!0}),Qs=$("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Zs;exports.ButtonState=void 0,(Zs=exports.ButtonState||(exports.ButtonState={}))[Zs.Normal=0]="Normal",Zs[Zs.Hovered=1]="Hovered",Zs[Zs.Pressed=2]="Pressed",Zs[Zs.Disabled=3]="Disabled";const en=$("Button",{state:exports.ButtonState.Normal,transition:null});class tn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const sn=fe(new tn,"UIEvents"),nn=W("ScreenSpace");function rn(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,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,g;if(l===c&&u===d){const e=l+s.x,t=u+s.y,n=.5*r.x,o=.5*r.y;h=e-n,p=t-o,f=e+n,g=t+o}else h=l+s.x,p=u+s.y,f=c+n.x,g=d+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 on(e,t,s,n,r,o){if(!e.has(t,Us))return;const i=e.get(t,Us),a=rn(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)&&on(e,t,a.rect,a.centerX,a.centerY,!1)}class an{build(e){N("UIRect",Us);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge($e)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),o=t.getEntitiesWithComponents([nn,Us,J]);for(const e of o)on(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const ln=new an,cn=new Float32Array(16),un=new Float32Array(16);let dn=!0,hn=1;class pn{build(e){N("Interactable",Ks),N("Button",en);const t=e.world,s=new tn;e.insertResource(sn,s);let n=null,r=null;hn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(Re),ge($e)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([Qs]);for(const e of i){const s=t.get(e,Qs);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*hn,l=o.screenH-e.mouseY*hn;!function(e){let t=!1;for(let s=0;s<16;s++)if(un[s]!==e[s]){t=!0;break}t&&(un.set(e),dn=!0)}(o.viewProjection),dn&&(Ns(o.viewProjection,cn),dn=!1);const c=Vs(a,l,cn,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Ks,Us,K]);let d=null,h=-1/0;for(const e of u){t.has(e,Qs)||t.insert(e,Qs);if(!t.get(e,Ks).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(Xs(c.x,c.y,s.position.x,s.position.y,r,o,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Q)&&(s=t.get(e,Q).layer),s>=h&&(h=s,d=e)}}if(n!==d){if(null!==n&&t.valid(n)&&t.has(n,Qs)){t.get(n,Qs).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,Qs).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Qs);e.pressed=!0,e.justPressed=!0,r=d,s.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Qs)){const e=t.get(r,Qs);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,Ce([],()=>{const e=t.getEntitiesWithComponents([en]);for(const s of e){if(t.has(s,Ks)||t.insert(s,Ks,{enabled:!0}),!t.has(s,Qs))continue;const e=t.get(s,Qs),n=t.get(s,en),r=t.get(s,Ks),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 fn=new pn,gn=$("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 _n{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){N("TextInput",gn);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,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,u=0,d=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},_=()=>{l=!1,x()},m=t=>{if(null===a)return;if("Escape"===t.key)return void v();const n=s.get(a,gn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(sn).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())},y=()=>{if(null!==a&&s.valid(a)&&s.has(a,gn)){const e=s.get(a,gn);e.focused=!1,e.dirty=!0}a=null};function x(){if(null===a||!s.valid(a))return;const t=s.get(a,gn);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(sn).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,gn);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,gn)){const e=s.get(a,gn);e.focused=!1,e.dirty=!0}a=null,p.blur()}function b(){c=!0,u=0}function S(e,i,a,l){(r.width<a||r.height<l)&&(r.width=yn(Math.max(r.width,a)),r.height=yn(Math.max(r.height,l))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.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 d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?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=mn(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=mn(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 _=o.getImageData(0,0,a,l),m=new Uint8Array(_.data.buffer),y=t.getResourceManager(),x=t._malloc(m.length);t.HEAPU8.set(m,x);const w=n.get(e);void 0!==w&&y.releaseTexture(w);const v=y.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",_),p.addEventListener("keydown",m),p.addEventListener("blur",y),this.cleanupListeners_=()=>{p.removeEventListener("input",f),p.removeEventListener("compositionstart",g),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",m),p.removeEventListener("blur",y),p.remove()},e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(sn)],e=>{const t=s.getEntitiesWithComponents([gn,Ks]);for(const e of t){if(!s.has(e,Qs))continue;if(s.get(e,Qs).justPressed)return void w(e)}if(null!==a){const e=s.getEntitiesWithComponents([Ks]);for(const t of e){if(s.has(t,gn))continue;if(!s.has(t,Qs))continue;if(s.get(t,Qs).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=r,u>=.5&&(u-=.5,c=!c,null!==a&&s.valid(a)&&s.has(a,gn)))){s.get(a,gn).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,gn)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([gn,Us]);for(const e of i){const t=s.get(e,gn);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 mn(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 yn(e){let t=1;for(;t<e;)t*=2;return t}const xn=new _n;async function wn(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 vn=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),bn=fe(null,"PhysicsAPI");function Sn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Pn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Tn{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(vn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=wn(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,Ce([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=Sn(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),Cn(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=Sn(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 u=e.world.get(i,J);if(!u)continue;let d=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=Sn(s.rotation),r=a-s.position.x,o=l-s.position.y,i=Math.cos(-n),u=Math.sin(-n);d=(r*i-o*u)/(0!==s.scale.x?s.scale.x:1),h=(r*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=Pn(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,J,u)}}(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=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(vn,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(bn,An._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Cn(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,ue)){const e=n.get(s,ue);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,de)){const e=n.get(s,de);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 An{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(An.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 En(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 Mn(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 Rn(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,u=e.rotation.w,d=a+a,h=l+l,p=c+c,f=a*d,g=a*h,_=a*p,m=l*h,y=l*p,x=c*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(m+x))*r,(g+b)*r,(_-v)*r,0,(g-b)*o,(1-(f+x))*o,(y+w)*o,0,(_+v)*i,(y-w)*i,(1-(f+m))*i,0,e.position.x,e.position.y,e.position.z,1])}async function In(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]=En(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 u={},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),u=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),u="binary"===g(l)?.contentType;let d,h;if(u){const e=await r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,n,n.length,u);if(t._free(d),p<0)continue;o[i]=p;const f=Mn(n),_=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=_+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=En(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,d,s,n)),o){new Tn("",{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),u=En(e,c,!1),d=e.getResourceManager();n[r]=d.loadBitmapFont(t,u,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=qe.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=qe.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=it(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=at(e.world,s);if(l&&e.hasResource(gs))for(const t of f.values())e.world.insert(t,ae,{scene:l,persistent:!1});if(r&&d){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}(d,s,u,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,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,l*d);let h=0;if(c.has(o,K)){const e=Rn(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),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,u,d,p);const f=s.HEAPU32[d>>2],g=s.HEAPU32[p>>2],_=new Float32Array(s.HEAPF32.buffer,c,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,o),y=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(y,r,x,o,f,g,h),t._free(y),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,d,n)}if(a){const t=e.getResource(dt);t&&t.setAddressableManifest(a)}}class Fn{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 Bn="__preview__";const kn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=rs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:rs.getTargetTexture(s),width:e.width,height:e.height}},release(e){rs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(rs.releaseRenderTarget(e._handle),kn.create({width:t,height:s,depth:!0})),begin(e,t){rs.begin(t,e._handle)},end(){rs.end()},getDepthTexture:e=>rs.getTargetDepthTexture(e._handle)};let Un=!1;var Ln;exports.LogLevel=void 0,(Ln=exports.LogLevel||(exports.LogLevel={}))[Ln.Debug=0]="Debug",Ln[Ln.Info=1]="Info",Ln[Ln.Warn=2]="Warn",Ln[Ln.Error=3]="Error";class Dn{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 $n{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Dn)}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 Wn=new $n;const zn=[zs,Js,ln,fn,xn];A||(A=!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=E,exports.App=xs,exports.AssetPlugin=ht,exports.AssetRefCounter=class{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}},exports.AssetServer=ut,exports.Assets=dt,exports.AsyncCache=nt,exports.BitmapText=re,exports.BodyType=he,exports.BoxCollider=ce,exports.Button=en,exports.Camera=Z,exports.Canvas=ee,exports.CapsuleCollider=de,exports.Children=ne,exports.CircleCollider=ue,exports.ClearFlags=q,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Se,exports.DEFAULT_DESIGN_HEIGHT=R,exports.DEFAULT_DESIGN_WIDTH=M,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=I,exports.Draw=It,exports.EntityCommands=be,exports.GLDebug=ls,exports.Geometry=Xt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Input=Re,exports.InputPlugin=Ie,exports.InputState=Me,exports.Interactable=Ks,exports.LocalTransform=J,exports.Logger=$n,exports.Material=qe,exports.MaterialLoader=rt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=An,exports.PhysicsEvents=vn,exports.PhysicsPlugin=Tn,exports.PostProcess=Kt,exports.PrefabServer=yt,exports.Prefabs=xt,exports.PrefabsPlugin=wt,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(gs);t.register({name:Bn,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Bn),this.loadPromise_=t.load(Bn).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 Fn(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await In(this.app_,this.app_.wasmModule,t,n,r,null,void 0,null,Bn)}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(gs).getScene(Bn),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:G.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:q.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(gs);await e.switchTo(Bn),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.ProjectionType=G,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=cs,exports.RenderTexture=kn,exports.Renderer=rs,exports.Res=ge,exports.ResMut=_e,exports.RigidBody=le,exports.ScaleMode=Y,exports.SceneManager=gs,exports.SceneManagerState=fs,exports.SceneOwner=ae,exports.ScreenSpace=nn,exports.ShaderSources=st,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ee,exports.Text=ks,exports.TextInput=gn,exports.TextInputPlugin=_n,exports.TextPlugin=Ws,exports.TextRenderer=Ls,exports.Time=xe,exports.UICameraInfo=$e,exports.UIEventQueue=tn,exports.UIEvents=sn,exports.UIInteraction=Qs,exports.UIInteractionPlugin=pn,exports.UILayoutPlugin=an,exports.UIMask=Os,exports.UIMaskPlugin=Ys,exports.UIRect=Us,exports.Velocity=te,exports.WebAssetProvider=Fn,exports.World=De,exports.WorldTransform=K,exports.addStartupSystem=function(e){Ae().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Ae().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Ae().push({schedule:e,system:t})},exports.assetPlugin=pt,exports.clearDrawCallbacks=Dt,exports.clearUserComponents=function(){D().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=rn,exports.createMaskProcessor=qs,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await In(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=xs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),At(e),Ve(e),jt(e),qt(e),ss(e),is(e);const r=new cs;s.pipeline_=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=bs(e,n,t,r));const i=s.getResource($e);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($e,{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)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;rs.setClearColor(e.x,e.y,e.z,e.w)}const d=(a()-o)/1e3;let h;if(rs.resize(t,c),Kt.isInitialized()&&Kt.getPassCount()>0&&!Kt.isBypassed()&&Kt.resize(t,c),s.hasResource(gs)){const e=s.getResource(gs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=bs(e,n,t,c,s.world,h);if(l(t,c,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:ws,width:t,height:c,elapsed:d});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:d})}rs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(pt),s.addPlugin(vt),s.addPlugin(Fe),s.addPlugin(ys),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:zn,...t})},exports.debug=function(e,t,s){Wn.debug(e,t,s)},exports.defineComponent=$,exports.defineResource=fe,exports.defineSystem=Ce,exports.defineTag=W,exports.error=function(e,t,s){Wn.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 u)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return p},exports.getAssetMimeType=function(e){return d[e.toLowerCase()]},exports.getAssetTypeEntry=g,exports.getComponent=V,exports.getComponentAssetFields=function(e){const t=ot.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=V(e);return t?k(t._default):null},exports.getCustomExtensions=m,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return Wn},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=z,exports.getWeChatPackOptions=function(){return m().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Wn.info(e,t,s)},exports.initDrawAPI=At,exports.initGLDebugAPI=is,exports.initGeometryAPI=jt,exports.initMaterialAPI=Ve,exports.initPostProcessAPI=qt,exports.initRendererAPI=ss,exports.inputPlugin=Fe,exports.instantiatePrefab=ft,exports.intersectRects=Hs,exports.invertMatrix4=Ns,exports.isBuiltinComponent=H,exports.isCustomExtension=y,exports.isEditor=function(){return Un},exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Un},exports.isTextureRef=ze,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=ct,exports.loadPhysicsModule=wn,exports.loadRuntimeScene=In,exports.loadSceneData=at,exports.loadSceneWithAssets=lt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&_(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.pointInWorldRect=Xs,exports.prefabsPlugin=vt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=N,exports.registerComponentAssetFields=function(e,t){ot.set(e,t)},exports.registerDrawCallback=Ut,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(dt);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=tt,exports.sceneManagerPlugin=ys,exports.screenToWorld=Vs,exports.setEditorMode=function(e){Un=e},exports.setLogLevel=function(e){Wn.setMinLevel(e)},exports.shutdownDrawAPI=Et,exports.shutdownGLDebugAPI=as,exports.shutdownGeometryAPI=Nt,exports.shutdownMaterialAPI=Xe,exports.shutdownPostProcessAPI=Yt,exports.shutdownRendererAPI=ns,exports.textInputPlugin=xn,exports.textPlugin=zs,exports.transitionTo=async function(e,t,s){const n=e.getResource(gs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=fn,exports.uiLayoutPlugin=ln,exports.uiMaskPlugin=Js,exports.uiPlugins=zn,exports.unregisterDrawCallback=Lt,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){Wn.warn(e,t,s)},exports.worldRectToScreen=js,exports.wrapSceneSystem=_s,exports.wxFileExists=P,exports.wxFileExistsSync=function(e){const t=w();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=C,exports.wxLoadImage=T,exports.wxLoadImagePixels=async function(e){return C(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 u=[{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}],d={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 u)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 _(e){return p.has(e.toLowerCase())}function m(){const e=[];for(const t of u)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function y(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(y(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 C(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let A=!1;const E=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)})}},M=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 U=0;function D(e,t){const s=++U;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 $(e,t){const s=L(),n=s.get(e);if(n)return n;const r=D(e,t);return s.set(e,r),O(e,t,!1),r}function W(e){const t=L(),s=t.get(e);if(s)return s;const n=D(e,{});return t.set(e,n),O(e,{},!0),n}function z(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 N(e,t){j.set(e,t)}function V(e){return j.get(e)??z(e)}function X(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return j.set(e,s),s}const G={Perspective:0,Orthographic:1},q={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Y={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},J=X("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=X("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=X("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}),Z=X("Camera",{projectionType:G.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:q.ColorAndDepth}),ee=X("Canvas",{designResolution:{x:M,y:R},pixelsPerUnit:100,scaleMode:Y.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),te=X("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=X("Parent",{entity:0}),ne=X("Children",{entities:[]}),re=X("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B}),oe=X("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}),ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ae=$("SceneOwner",{scene:"",persistent:!1});N("Name",ie);const le=X("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ce=X("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ue=X("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),de=X("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),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 _e(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 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 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 u=null;this.world_.beginIteration();try{for(const d of n){if(null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(d,t[s])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,s[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,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 Ce(e,t,s){const n=++Te;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Ae(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Ee{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 Me{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 Me,"Input");class Ie{constructor(e){this.target_=e??null}build(e){const s=new Me;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,Ce([],()=>{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 Ue(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")}function De(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}:De(e)}}return t}class Le{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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,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.");this.cppRegistry_&&this.cppRegistry_.destroy(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){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(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;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(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(Ue(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,De(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(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(Ue(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()}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 $e=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 We;function ze(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(We=exports.BlendMode||(exports.BlendMode={}))[We.Normal=0]="Normal",We[We.Additive=1]="Additive",We[We.Multiply=2]="Multiply",We[We.Screen=3]="Screen",We[We.PremultipliedAlpha=4]="PremultipliedAlpha";let Oe=null,He=null,je=1;const Ne=new Map;function Ve(e){Oe=e,He=e.getResourceManager(),tt()}function Xe(){0!==Je&&Oe&&(Oe._free(Je),Je=0),Ne.clear(),je=1,Ye=!1,Qe.clear(),Ze=null,He=null,Oe=null}function Ge(){if(!He)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return He}const qe={createShader:(e,t)=>Ge().createShader(e,t),releaseShader(e){e>0&&Ge().releaseShader(e)},create(e){const t=je++,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 Ne.set(t,s),t},get:e=>Ne.get(e),setUniform(e,t,s){const n=Ne.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ne.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ne.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ne.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ne.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ne.get(e);return t?.shader??0},release(e){Ne.delete(e)},isValid:e=>Ne.has(e),releaseAll(){Ne.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=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=je++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ne.set(s,n),s},toAssetData(e,t){const s=Ne.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=Ne.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ye=!1,Je=0;const Ke=4096,Qe=new Map;let Ze=null;function et(e){const t=(0===Je&&Oe&&(Je=Oe._malloc(Ke)),Je);if(0===t||!Oe)return{ptr:0,count:0};let s=0,n=0;const r=Oe.HEAPU8,o=Oe.HEAPU32,i=Oe.HEAPF32;for(const[a,l]of e){if(s+128>Ke)break;let e=Qe.get(a);e||(Ze||(Ze=new TextEncoder),e=Ze.encode(a),Qe.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[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++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function tt(){if(!Oe||Ye)return;Oe.materialDataProvider=(e,t,s,n,r)=>{const o=Ne.get(e);if(!o)return Oe.HEAPU32[t>>2]=0,Oe.HEAPU32[s>>2]=0,Oe.HEAPU32[n>>2]=0,void(Oe.HEAPU32[r>>2]=0);Oe.HEAPU32[t>>2]=o.shader,Oe.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=et(o.uniforms);Oe.HEAPU32[n>>2]=i,Oe.HEAPU32[r>>2]=a},Ye=!0}const st={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 nt{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 rt{constructor(e,t=""){this.cache_=new nt,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&&(qe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())qe.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:qe.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 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"}]}]]);function it(e){return ot.get(e)?.fields??[]}function at(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)ct(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 lt(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=ot.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,u=new Map,d=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);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const n=await t.loadBitmapFont(e,s);d.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.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=ot.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]=u.get(t)??0;break;case"font":s[e.field]=d.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)ct(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 ct(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=V(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 ut{constructor(e){this.textureCache_=new nt,this.shaderCache_=new nt,this.jsonCache_=new nt,this.textCache_=new nt,this.binaryCache_=new nt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new nt,this.prefabCache_=new nt,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 rt(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(),qe.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),u="binary"===g(e)?.contentType,d=u?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(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);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 lt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const 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 qe.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 qe.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 dt=fe(null,"Assets");class ht{build(e){const t=e.wasmModule;t?e.insertResource(dt,new ut(t)):console.warn("AssetPlugin: No WASM module available")}}const pt=new ht;async function ft(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 lt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const gt=10;async function _t(e,t,s,n,r,o=0){if(o>gt)throw new Error(`Prefab nesting depth exceeded ${gt}. 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),u=n.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?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};mt(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 mt(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 yt{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 ft(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const xt=fe(null,"Prefabs");class wt{constructor(){this.name="PrefabsPlugin",this.dependencies=[dt]}build(e){const t=e.getResource(dt);e.insertResource(xt,new yt(e.world,t))}}const vt=new wt;let bt=null,St=0,Pt=0,Tt=0;const Ct=new Float32Array(256);function At(e){bt=e,St=bt._malloc(64),Pt=bt._malloc(64),Tt=bt._malloc(1024)}function Et(){bt&&(St&&(bt._free(St),St=0),Pt&&(bt._free(Pt),Pt=0),Tt&&(bt._free(Tt),Tt=0)),bt=null}function Mt(){if(!bt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return bt}const Rt={r:1,g:1,b:1,a:1},It={begin(e){const t=Mt();t.HEAPF32.set(e,St/4),t.draw_begin(St)},end(){Mt().draw_end()},line(e,t,s,n=1){Mt().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){Mt().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){Mt().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){Mt().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){Mt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=Rt){Mt().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=Rt){Mt().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){Mt().draw_setLayer(e)},setDepth(e){Mt().draw_setDepth(e)},getDrawCallCount:()=>bt?bt.draw_getDrawCallCount():0,getPrimitiveCount:()=>bt?bt.draw_getPrimitiveCount():0,setBlendMode(e){Mt().draw_setBlendMode(e)},setDepthTest(e){Mt().draw_setDepthTest(e)},drawMesh(e,t,s){const n=Mt();n.HEAPF32.set(s,Pt/4),n.draw_mesh(e,t,Pt)},drawMeshWithMaterial(e,t,s){const n=Mt(),r=qe.get(t);if(!r)return;if(It.setBlendMode(r.blendMode),It.setDepthTest(r.depthTest),0===r.uniforms.size)return void It.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,Pt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Bt(t);if(!(n<0)){if(ze(s))Ct[o++]=10,Ct[o++]=n,Ct[o++]=s.slot??e++,Ct[o++]=s.textureId;else if("number"==typeof s)Ct[o++]=1,Ct[o++]=n,Ct[o++]=s;else if(Array.isArray(s)){Ct[o++]=s.length,Ct[o++]=n;for(let e=0;e<s.length;e++)Ct[o++]=s[e]}else"w"in s?(Ct[o++]=4,Ct[o++]=n,Ct[o++]=s.x,Ct[o++]=s.y,Ct[o++]=s.z,Ct[o++]=s.w):"z"in s?(Ct[o++]=3,Ct[o++]=n,Ct[o++]=s.x,Ct[o++]=s.y,Ct[o++]=s.z):(Ct[o++]=2,Ct[o++]=n,Ct[o++]=s.x,Ct[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(Ct.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Tt/4),n.draw_meshWithUniforms(e,r.shader,Pt,Tt,o)):n.draw_mesh(e,r.shader,Pt)}},Ft={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};function Bt(e){return Ft[e]??-1}const kt=new Map;function Ut(e,t,s){kt.set(e,{fn:t,scene:s??""})}function Dt(e){kt.delete(e)}function Lt(){kt.clear()}var $t;exports.DataType=void 0,($t=exports.DataType||(exports.DataType={}))[$t.Float=1]="Float",$t[$t.Float2=2]="Float2",$t[$t.Float3=3]="Float3",$t[$t.Float4=4]="Float4",$t[$t.Int=5]="Int",$t[$t.Int2=6]="Int2",$t[$t.Int3=7]="Int3",$t[$t.Int4=8]="Int4";let Wt=null,zt=0,Ot=0,Ht=0;function jt(e){Wt=e,zt=Wt._malloc(262144),Ot=Wt._malloc(65536),Ht=Wt._malloc(256)}function Nt(){Wt&&(zt&&Wt._free(zt),Ot&&Wt._free(Ot),Ht&&Wt._free(Ht),zt=0,Ot=0,Ht=0),Wt=null}function Vt(){if(!Wt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Wt}const Xt={create(e){const t=Vt(),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,zt/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,Ht,r).set(o),t.geometry_init(s,zt,n,Ht,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,Ot,n).set(e.indices),t.geometry_setIndices16(s,Ot,n)}else{new Uint32Array(t.HEAPU8.buffer,Ot,n).set(e.indices),t.geometry_setIndices32(s,Ot,n)}}return s},updateVertices(e,t,s=0){const n=Vt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,zt/4),n.geometry_updateVertices(e,zt,r,s)},release(e){e>0&&Vt().geometry_release(e)},isValid:e=>!(!Wt||e<=0)&&Wt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Xt.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 Xt.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 Xt.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 Gt=null;function qt(e){Gt=e}function Yt(){Gt&&Kt.isInitialized()&&Kt.shutdown(),Gt=null}function Jt(){if(!Gt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Gt}const Kt={init:(e,t)=>Jt().postprocess_init(e,t),shutdown(){Jt().postprocess_shutdown()},resize(e,t){Jt().postprocess_resize(e,t)},addPass:(e,t)=>Jt().postprocess_addPass(e,t),removePass(e){Jt().postprocess_removePass(e)},setEnabled(e,t){Jt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Jt().postprocess_isPassEnabled(e),setUniform(e,t,s){Jt().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Jt().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Jt().postprocess_begin()},end(){Jt().postprocess_end()},getPassCount:()=>Jt().postprocess_getPassCount(),isInitialized:()=>!!Gt&&Gt.postprocess_isInitialized(),setBypass(e){Jt().postprocess_setBypass(e)},isBypassed:()=>!Gt||Gt.postprocess_isBypassed(),createBlur:()=>qe.createShader(Qt,"#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:()=>qe.createShader(Qt,"#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:()=>qe.createShader(Qt,"#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:()=>qe.createShader(Qt,"#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")},Qt="#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 Zt;exports.RenderStage=void 0,(Zt=exports.RenderStage||(exports.RenderStage={}))[Zt.Background=0]="Background",Zt[Zt.Opaque=1]="Opaque",Zt[Zt.Transparent=2]="Transparent",Zt[Zt.Overlay=3]="Overlay";let es=null,ts=0;function ss(e){es=e,ts=es._malloc(64)}function ns(){es&&ts&&(es._free(ts),ts=0),es=null}const rs={init(e,t){es?.renderer_init(e,t)},resize(e,t){es?.renderer_resize(e,t)},begin(e,t){es&&ts&&(es.HEAPF32.set(e,ts/4),es.renderer_begin(ts,t??0))},flush(){es?.renderer_flush()},end(){es?.renderer_end()},submitSprites(e){es&&es.renderer_submitSprites(e._cpp)},submitBitmapText(e){es&&es.renderer_submitBitmapText(e._cpp)},submitSpine(e){es&&es.renderer_submitSpine?.(e._cpp)},setStage(e){es?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>es?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){es?.renderer_releaseTarget(e)},getTargetTexture:e=>es?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>es?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){es?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){es?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){es?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){es?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>es?es.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>es?{drawCalls:es.renderer_getDrawCalls(),triangles:es.renderer_getTriangles(),sprites:es.renderer_getSprites(),text:es.renderer_getText(),spine:es.renderer_getSpine?.()??0,meshes:es.renderer_getMeshes(),culled:es.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let os=null;function is(e){os=e}function as(){os=null}const ls={enable(){os?.gl_enableErrorCheck(!0)},disable(){os?.gl_enableErrorCheck(!1)},check:e=>os?.gl_checkErrors(e)??0,diagnose(){os?.renderer_diagnose()}};class cs{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_||(rs.resize(n,r),Kt.isInitialized()&&Kt.getPassCount()>0&&Kt.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),rs.setViewport(0,0,n,r),rs.clearBuffers(3),rs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),rs.submitSprites(t),rs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):rs.submitSpine(t),rs.flush(),this.executeDrawCallbacks(s,o),rs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;rs.setViewport(n.x,n.y,n.w,n.h),rs.setScissor(n.x,n.y,n.w,n.h,!0),rs.clearBuffers(r),rs.setScissor(0,0,0,0,!1),rs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),rs.submitSprites(t),rs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):rs.submitSpine(t),rs.flush(),this.executeDrawCallbacks(s,o),rs.end()}executeDrawCallbacks(e,t){const s=kt;if(s.size>0){It.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)}It.end();for(const e of n)Dt(e)}}}const us="__scene_transition_overlay__";class ds{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class hs{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),Ut(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Kt.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Kt.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 ps{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},Ut(us,()=>{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;It.setLayer(9999),It.setDepth(9999),It.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,Dt(us)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Dt(us),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 ds(t);this.scenes_.set(e,s);const n=new hs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(dt)?this.app_.getResource(dt):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(dt)&&(t.assetServer=this.app_.getResource(dt));const n=await lt(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=gs(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 ds(t);this.scenes_.set(e,s);const n=new hs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(dt)?this.app_.getResource(dt):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(dt)&&(t.assetServer=this.app_.getResource(dt));const n=await lt(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=gs(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())Dt(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Kt.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{Kt.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 fs=fe(null,"SceneManager");function gs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(fs).getSceneStatus(t)&&s._fn(...n)}}}const _s=Ce([_e(fs),ge(xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),ms={name:"SceneManager",build(e){const t=new ps(e);e.insertResource(fs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(fs),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,_s)}};class ys{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.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!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.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),n++;n>=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),requestAnimationFrame(this.mainLoop)},this.world_=new Le,this.resources_=new ye;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ys}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}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_}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}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(fs).register(e),this}setInitialScene(e){return this.getResource(fs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ee(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,Lt();const e=[as,ns,Yt,Nt,Xe,Et];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){let t=this.systems_.get(e);if(t&&this.runner_&&!this.frame_paused_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)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 xs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ws(e,t,s,n,r){const o=e*t/s,i=e;switch(n){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 vs(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 u,d=0,h=0;if(r.projectionType===G.Orthographic){if(h=r.orthoSize,l){h=ws(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}d=h*a,u=Ss(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Ts(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=As(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(Ms(u,p)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const bs=new Float32Array(16);function Ss(e,t,s,n,r,o){const i=bs;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 Ps=new Float32Array(16);function Ts(e,t,s,n){const r=Ps;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 Cs=new Float32Array(16);function As(e,t,s){const n=Cs;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 Es=new Float32Array(16);function Ms(e,t){const s=Es;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 Rs,Is,Fs;exports.TextAlign=void 0,(Rs=exports.TextAlign||(exports.TextAlign={}))[Rs.Left=0]="Left",Rs[Rs.Center=1]="Center",Rs[Rs.Right=2]="Right",exports.TextVerticalAlign=void 0,(Is=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[Is.Top=0]="Top",Is[Is.Middle=1]="Middle",Is[Is.Bottom=2]="Bottom",exports.TextOverflow=void 0,(Fs=exports.TextOverflow||(exports.TextOverflow={}))[Fs.Visible=0]="Visible",Fs[Fs.Clip=1]="Clip",Fs[Fs.Ellipsis=2]="Ellipsis";const Bs=$("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}),ks=$("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 Us{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),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=r?Math.ceil(o):d+2*u,f=r?Math.ceil(i):h+2*u;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),_=Math.round(255*e.color.g),m=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${_}, ${m}, ${y})`,r&&e.overflow===exports.TextOverflow.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 exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-x)/2;break;case exports.TextVerticalAlign.Bottom:w=f-x-u;break;default:w=u}else w=u;let v=w;for(const t of l){let n;switch(e.align){case exports.TextAlign.Left:n=u;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-u;break;default:n=u}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 C=P.createTexture(p,f,T,S.length,1,!0);return this.module._free(T),{textureHandle:C,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 Ds(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 Ls(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 $s{build(e){N("Text",Bs);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Us(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Bs));for(const e of r.keys())n.valid(e)&&n.has(e,Bs)||r.delete(e);const e=n.getEntitiesWithComponents([Bs]);for(const t of e){const e=n.get(t,Bs),o=n.has(t,ks)?n.get(t,ks):null,i=r.get(t);if(i&&!Ls(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,Ds(e,o))}}))}}const Ws=new $s,zs=$("UIMask",{enabled:!0});function Os(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 Hs(e,t,s,n,r,o,i,a,l,c,u){const d=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)*u]}const[_,m]=g(d,p),[y,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 js(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],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],g=e[12],_=e[13],m=e[14],y=e[15],x=n*l-r*a,w=n*c-o*a,v=n*u-i*a,b=r*c-o*l,S=r*u-i*l,P=o*u-i*c,T=d*_-h*g,C=d*m-p*g,A=d*y-f*g,E=h*m-p*_,M=h*y-f*_,R=p*y-f*m;let I=x*R-w*M+v*E+b*A-S*C+P*T;return 0===I||(I=1/I,s[0]=(l*R-c*M+u*E)*I,s[1]=(o*M-r*R-i*E)*I,s[2]=(_*P-m*S+y*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*A-a*R-u*C)*I,s[5]=(n*R-o*A+i*C)*I,s[6]=(m*v-g*P-y*w)*I,s[7]=(d*P-p*v+f*w)*I,s[8]=(a*M-l*A+u*T)*I,s[9]=(r*A-n*M-i*T)*I,s[10]=(g*S-_*v+y*x)*I,s[11]=(h*v-d*S-f*x)*I,s[12]=(l*C-a*E-c*T)*I,s[13]=(n*E-r*C+o*T)*I,s[14]=(_*w-g*b-m*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function Ns(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],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function Vs(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 Xs(e,t,s,n,r,o,i){if(!e.has(t,ks)||!e.has(t,K))return null;const a=e.get(t,ks),l=e.get(t,K),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Hs(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function Gs(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([zs]);if(0!==l.length)try{!function(e,t,s,n,r,o,i,a,l){const c=new Set;for(const e of n){t.get(e,zs).enabled&&c.add(e)}const u=[];for(const e of n){if(!c.has(e))continue;let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(c.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(c.has(s)){const e=Xs(t,s,r,o,i,a,l);e&&(n=Os(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Xs(t,e,r,o,i,a,l);s&&d(e,s)}}(e,t,s,l,n,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class qs{build(e){if(N("UIMask",zs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Gs(e.wasmModule,e.world))}}const Ys=new qs,Js=$("Interactable",{enabled:!0}),Ks=$("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Qs;exports.ButtonState=void 0,(Qs=exports.ButtonState||(exports.ButtonState={}))[Qs.Normal=0]="Normal",Qs[Qs.Hovered=1]="Hovered",Qs[Qs.Pressed=2]="Pressed",Qs[Qs.Disabled=3]="Disabled";const Zs=$("Button",{state:exports.ButtonState.Normal,transition:null});class en{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const tn=fe(new en,"UIEvents"),sn=W("ScreenSpace");function nn(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,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,g;if(l===c&&u===d){const e=l+s.x,t=u+s.y,n=.5*r.x,o=.5*r.y;h=e-n,p=t-o,f=e+n,g=t+o}else h=l+s.x,p=u+s.y,f=c+n.x,g=d+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 rn(e,t,s,n,r,o){if(!e.has(t,ks))return;const i=e.get(t,ks),a=nn(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)&&rn(e,t,a.rect,a.centerX,a.centerY,!1)}class on{build(e){N("UIRect",ks);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge($e)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),o=t.getEntitiesWithComponents([sn,ks,J]);for(const e of o)rn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const an=new on,ln=new Float32Array(16),cn=new Float32Array(16);let un=!0,dn=1;class hn{build(e){N("Interactable",Js),N("Button",Zs);const t=e.world,s=new en;e.insertResource(tn,s);let n=null,r=null;dn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(Re),ge($e)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([Ks]);for(const e of i){const s=t.get(e,Ks);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*dn,l=o.screenH-e.mouseY*dn;!function(e){let t=!1;for(let s=0;s<16;s++)if(cn[s]!==e[s]){t=!0;break}t&&(cn.set(e),un=!0)}(o.viewProjection),un&&(js(o.viewProjection,ln),un=!1);const c=Ns(a,l,ln,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Js,ks,K]);let d=null,h=-1/0;for(const e of u){t.has(e,Ks)||t.insert(e,Ks);if(!t.get(e,Js).enabled)continue;const s=t.get(e,K),n=t.get(e,ks),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(Vs(c.x,c.y,s.position.x,s.position.y,r,o,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Q)&&(s=t.get(e,Q).layer),s>=h&&(h=s,d=e)}}if(n!==d){if(null!==n&&t.valid(n)&&t.has(n,Ks)){t.get(n,Ks).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,Ks).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Ks);e.pressed=!0,e.justPressed=!0,r=d,s.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ks)){const e=t.get(r,Ks);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,Ce([],()=>{const e=t.getEntitiesWithComponents([Zs]);for(const s of e){if(t.has(s,Js)||t.insert(s,Js,{enabled:!0}),!t.has(s,Ks))continue;const e=t.get(s,Ks),n=t.get(s,Zs),r=t.get(s,Js),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 pn=new hn,fn=$("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 gn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){N("TextInput",fn);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,u=0,d=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},_=()=>{l=!1,x()},m=t=>{if(null===a)return;if("Escape"===t.key)return void v();const n=s.get(a,fn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(tn).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())},y=()=>{if(null!==a&&s.valid(a)&&s.has(a,fn)){const e=s.get(a,fn);e.focused=!1,e.dirty=!0}a=null};function x(){if(null===a||!s.valid(a))return;const t=s.get(a,fn);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(tn).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,fn);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,fn)){const e=s.get(a,fn);e.focused=!1,e.dirty=!0}a=null,p.blur()}function b(){c=!0,u=0}function S(e,i,a,l){(r.width<a||r.height<l)&&(r.width=mn(Math.max(r.width,a)),r.height=mn(Math.max(r.height,l))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.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 d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?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=_n(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=_n(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 _=o.getImageData(0,0,a,l),m=new Uint8Array(_.data.buffer),y=t.getResourceManager(),x=t._malloc(m.length);t.HEAPU8.set(m,x);const w=n.get(e);void 0!==w&&y.releaseTexture(w);const v=y.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",_),p.addEventListener("keydown",m),p.addEventListener("blur",y),this.cleanupListeners_=()=>{p.removeEventListener("input",f),p.removeEventListener("compositionstart",g),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",m),p.removeEventListener("blur",y),p.remove()},e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(tn)],e=>{const t=s.getEntitiesWithComponents([fn,Js]);for(const e of t){if(!s.has(e,Ks))continue;if(s.get(e,Ks).justPressed)return void w(e)}if(null!==a){const e=s.getEntitiesWithComponents([Js]);for(const t of e){if(s.has(t,fn))continue;if(!s.has(t,Ks))continue;if(s.get(t,Ks).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=r,u>=.5&&(u-=.5,c=!c,null!==a&&s.valid(a)&&s.has(a,fn)))){s.get(a,fn).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,fn)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([fn,ks]);for(const e of i){const t=s.get(e,fn);if(!t.dirty)continue;const n=s.get(e,ks),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 _n(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(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 mn(e){let t=1;for(;t<e;)t*=2;return t}const yn=new gn;async function xn(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 wn=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),vn=fe(null,"PhysicsAPI");function bn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Sn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Pn{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(wn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=xn(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,Ce([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=bn(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),Tn(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=bn(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 u=e.world.get(i,J);if(!u)continue;let d=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=bn(s.rotation),r=a-s.position.x,o=l-s.position.y,i=Math.cos(-n),u=Math.sin(-n);d=(r*i-o*u)/(0!==s.scale.x?s.scale.x:1),h=(r*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=Sn(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,J,u)}}(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=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(wn,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(vn,Cn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Tn(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,ue)){const e=n.get(s,ue);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,de)){const e=n.get(s,de);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 Cn{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(Cn.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 An(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 En(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 Mn(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,u=e.rotation.w,d=a+a,h=l+l,p=c+c,f=a*d,g=a*h,_=a*p,m=l*h,y=l*p,x=c*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(m+x))*r,(g+b)*r,(_-v)*r,0,(g-b)*o,(1-(f+x))*o,(y+w)*o,0,(_+v)*i,(y-w)*i,(1-(f+m))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Rn(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]=An(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 u={},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),u=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),u="binary"===g(l)?.contentType;let d,h;if(u){const e=await r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,n,n.length,u);if(t._free(d),p<0)continue;o[i]=p;const f=En(n),_=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=_+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=An(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,d,s,n)),o){new Pn("",{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),u=An(e,c,!1),d=e.getResourceManager();n[r]=d.loadBitmapFont(t,u,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=qe.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=qe.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=it(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=at(e.world,s);if(l&&e.hasResource(fs))for(const t of f.values())e.world.insert(t,ae,{scene:l,persistent:!1});if(r&&d){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}(d,s,u,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,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,l*d);let h=0;if(c.has(o,K)){const e=Mn(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),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,u,d,p);const f=s.HEAPU32[d>>2],g=s.HEAPU32[p>>2],_=new Float32Array(s.HEAPF32.buffer,c,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,o),y=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(y,r,x,o,f,g,h),t._free(y),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,d,n)}if(a){const t=e.getResource(dt);t&&t.setAddressableManifest(a)}}class In{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 Fn="__preview__";const Bn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=rs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:rs.getTargetTexture(s),width:e.width,height:e.height}},release(e){rs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(rs.releaseRenderTarget(e._handle),Bn.create({width:t,height:s,depth:!0})),begin(e,t){rs.begin(t,e._handle)},end(){rs.end()},getDepthTexture:e=>rs.getTargetDepthTexture(e._handle)};let kn=!1;var Un;exports.LogLevel=void 0,(Un=exports.LogLevel||(exports.LogLevel={}))[Un.Debug=0]="Debug",Un[Un.Info=1]="Info",Un[Un.Warn=2]="Warn",Un[Un.Error=3]="Error";class Dn{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 Ln{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Dn)}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 $n=new Ln;const Wn=[Ws,Ys,an,pn,yn];A||(A=!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=E,exports.App=ys,exports.AssetPlugin=ht,exports.AssetRefCounter=class{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}},exports.AssetServer=ut,exports.Assets=dt,exports.AsyncCache=nt,exports.BitmapText=re,exports.BodyType=he,exports.BoxCollider=ce,exports.Button=Zs,exports.Camera=Z,exports.Canvas=ee,exports.CapsuleCollider=de,exports.Children=ne,exports.CircleCollider=ue,exports.ClearFlags=q,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Se,exports.DEFAULT_DESIGN_HEIGHT=R,exports.DEFAULT_DESIGN_WIDTH=M,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.Draw=It,exports.EntityCommands=be,exports.GLDebug=ls,exports.Geometry=Xt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Input=Re,exports.InputPlugin=Ie,exports.InputState=Me,exports.Interactable=Js,exports.LocalTransform=J,exports.Logger=Ln,exports.Material=qe,exports.MaterialLoader=rt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=Cn,exports.PhysicsEvents=wn,exports.PhysicsPlugin=Pn,exports.PostProcess=Kt,exports.PrefabServer=yt,exports.Prefabs=xt,exports.PrefabsPlugin=wt,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(fs);t.register({name:Fn,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Fn),this.loadPromise_=t.load(Fn).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 In(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await Rn(this.app_,this.app_.wasmModule,t,n,r,null,void 0,null,Fn)}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(fs).getScene(Fn),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:G.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:q.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(fs);await e.switchTo(Fn),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.ProjectionType=G,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=cs,exports.RenderTexture=Bn,exports.Renderer=rs,exports.Res=ge,exports.ResMut=_e,exports.RigidBody=le,exports.RuntimeConfig=I,exports.ScaleMode=Y,exports.SceneManager=fs,exports.SceneManagerState=ps,exports.SceneOwner=ae,exports.ScreenSpace=sn,exports.ShaderSources=st,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ee,exports.Text=Bs,exports.TextInput=fn,exports.TextInputPlugin=gn,exports.TextPlugin=$s,exports.TextRenderer=Us,exports.Time=xe,exports.UICameraInfo=$e,exports.UIEventQueue=en,exports.UIEvents=tn,exports.UIInteraction=Ks,exports.UIInteractionPlugin=hn,exports.UILayoutPlugin=on,exports.UIMask=zs,exports.UIMaskPlugin=qs,exports.UIRect=ks,exports.Velocity=te,exports.WebAssetProvider=In,exports.World=Le,exports.WorldTransform=K,exports.addStartupSystem=function(e){Ae().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Ae().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Ae().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=pt,exports.clearDrawCallbacks=Lt,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=nn,exports.createMaskProcessor=Gs,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await Rn(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=ys.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),At(e),Ve(e),jt(e),qt(e),ss(e),is(e);const r=new cs;s.pipeline_=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=vs(e,n,t,r));const i=s.getResource($e);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($e,{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)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;rs.setClearColor(e.x,e.y,e.z,e.w)}const d=(a()-o)/1e3;let h;if(rs.resize(t,c),Kt.isInitialized()&&Kt.getPassCount()>0&&!Kt.isBypassed()&&Kt.resize(t,c),s.hasResource(fs)){const e=s.getResource(fs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=vs(e,n,t,c,s.world,h);if(l(t,c,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:xs,width:t,height:c,elapsed:d});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:d})}rs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(pt),s.addPlugin(vt),s.addPlugin(Fe),s.addPlugin(ms),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Wn,...t})},exports.debug=function(e,t,s){$n.debug(e,t,s)},exports.defineComponent=$,exports.defineResource=fe,exports.defineSystem=Ce,exports.defineTag=W,exports.error=function(e,t,s){$n.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 u)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return p},exports.getAssetMimeType=function(e){return d[e.toLowerCase()]},exports.getAssetTypeEntry=g,exports.getComponent=V,exports.getComponentAssetFields=function(e){const t=ot.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=V(e);return t?k(t._default):null},exports.getCustomExtensions=m,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return $n},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=z,exports.getWeChatPackOptions=function(){return m().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){$n.info(e,t,s)},exports.initDrawAPI=At,exports.initGLDebugAPI=is,exports.initGeometryAPI=jt,exports.initMaterialAPI=Ve,exports.initPostProcessAPI=qt,exports.initRendererAPI=ss,exports.inputPlugin=Fe,exports.instantiatePrefab=ft,exports.intersectRects=Os,exports.invertMatrix4=js,exports.isBuiltinComponent=H,exports.isCustomExtension=y,exports.isEditor=function(){return kn},exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!kn},exports.isTextureRef=ze,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=ct,exports.loadPhysicsModule=xn,exports.loadRuntimeScene=Rn,exports.loadSceneData=at,exports.loadSceneWithAssets=lt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&_(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.pointInWorldRect=Vs,exports.prefabsPlugin=vt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=N,exports.registerComponentAssetFields=function(e,t){ot.set(e,t)},exports.registerDrawCallback=Ut,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(dt);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=tt,exports.sceneManagerPlugin=ms,exports.screenToWorld=Ns,exports.setEditorMode=function(e){kn=e},exports.setLogLevel=function(e){$n.setMinLevel(e)},exports.shutdownDrawAPI=Et,exports.shutdownGLDebugAPI=as,exports.shutdownGeometryAPI=Nt,exports.shutdownMaterialAPI=Xe,exports.shutdownPostProcessAPI=Yt,exports.shutdownRendererAPI=ns,exports.textInputPlugin=yn,exports.textPlugin=Ws,exports.transitionTo=async function(e,t,s){const n=e.getResource(fs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=pn,exports.uiLayoutPlugin=an,exports.uiMaskPlugin=Ys,exports.uiPlugins=Wn,exports.unregisterDrawCallback=Dt,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){$n.warn(e,t,s)},exports.worldRectToScreen=Hs,exports.wrapSceneSystem=gs,exports.wxFileExists=P,exports.wxFileExistsSync=function(e){const t=w();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=C,exports.wxLoadImage=T,exports.wxLoadImagePixels=async function(e){return C(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}`))}})})};
//# 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 8a10fced2..2a6610731 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 s(){return null!==e}function n(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,s){return t().instantiateWasm(e,s)}function h(e,s){return t().createCanvas(e,s)}function d(){return t().now()}function f(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 p(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 _=[{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}],g={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,y=new Set;for(const e of _)for(const t of e.extensions)m.set(t,e),y.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 _)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return y.has(e.toLowerCase())}function C(){return y}function T(e){return"string"==typeof e&&(!!e.includes("/")&&P(w(e)))}function E(){const e=[];for(const t of _)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function M(){return E().map(e=>({type:"suffix",value:e}))}function A(e){return g[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 s=t.toLowerCase();if(s.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 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)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(k(e,t.errMsg)))}})})}function U(e,t="utf-8"){return new Promise((s,n)=>{F().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(k(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function D(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function z(e,t){return new Promise((s,n)=>{F().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function W(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 L(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)}}async function O(e){return L(await W(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 U(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(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)})}},N=1920,X=1080,V=100,q=512,G=0,Y=4294967295,J=4294967295,K=(e=0,t=0)=>({x:e,y:t}),Q=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),Z=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),ee=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),te=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function se(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(se);const t={};for(const s in e)t[s]=se(e[s]);return t}let ne=0;function re(e,t){const s=++ne;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...se(t),...e}:se(t)}}function ie(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function oe(e,t){const s=ie(),n=s.get(e);if(n)return n;const r=re(e,t);return s.set(e,r),ue(e,t,!1),r}function ae(e){const t=ie(),s=t.get(e);if(s)return s;const n=re(e,{});return t.set(e,n),ue(e,{},!0),n}function ce(e){return ie().get(e)}function le(){ie().clear()}function ue(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function he(e){return!0===e._builtin}const de=new Map;function fe(e,t){de.set(e,t)}function pe(e){return de.get(e)??ce(e)}function _e(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return de.set(e,s),s}const ge={Perspective:0,Orthographic:1},me={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ye={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},we=_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}}),xe=_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}}),ve=_e("Sprite",{texture:Y,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}),be=_e("Camera",{projectionType:ge.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:me.ColorAndDepth}),Se=_e("Canvas",{designResolution:{x:N,y:X},pixelsPerUnit:100,scaleMode:ye.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Pe=_e("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ce=_e("Parent",{entity:0}),Te=_e("Children",{entities:[]}),Ee=_e("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:J}),Me=_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}),Ae={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Re=oe("SceneOwner",{scene:"",persistent:!1});function Ie(e){const t=pe(e);return t?se(t._default):null}fe("Name",Ae);const Fe=_e("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ke=_e("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Be=_e("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Ue=_e("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),$e={Static:0,Kinematic:1,Dynamic:2};let De=0;function ze(e,t){const s=++De;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function We(e){return{_type:"res",_resource:e}}function Le(e){return{_type:"res_mut",_resource:e}}class Oe{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 He{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 Oe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const je=ze({delta:0,elapsed:0,frameCount:0},"Time");function Ne(e){return{_type:"mut",_component:e}}function Xe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ve(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{Xe(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class qe{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>Xe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let u=null;this.world_.beginIteration();try{for(const h of n){if(null!==u&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(h,t[s])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<r;e++)a[e+1]=this.world_.get(h,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];u=h}yield a}}finally{if(this.world_.endIteration(),null!==u&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Ge(){return{_type:"commands"}}class Ye{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=he(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 Je{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ye(this,null);return this.spawned_.push(e),e}entity(e){return new Ye(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 Ke;!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"}(Ke||(Ke={}));let Qe=0;function Ze(e,t,s){const n=++Qe;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function et(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function tt(e){et().push({schedule:Ke.Update,system:e})}function st(e){et().push({schedule:Ke.Startup,system:e})}function nt(e,t){et().push({schedule:e,system:t})}class rt{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 Je&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new qe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Je(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class it{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 ot=ze(new it,"Input");class at{constructor(e){this.target_=e??null}build(e){const s=new it;e.insertResource(ot,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(Ke.Last,Ze([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ct=new at;function lt(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=ut(t[e]),i=ut(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function ut(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ht(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")}function dt(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}:dt(e)}}return t}class ft{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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,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.");this.cppRegistry_&&this.cppRegistry_.destroy(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){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return he(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return he(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return he(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(he(t)){if(!this.cppRegistry_)return null;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(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.");he(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=lt(t._name,t._default,n);if(e.length>0)throw new Error(ht(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,dt(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(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=lt(t._name,t._default,e);if(r.length>0)throw new Error(ht(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!he(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=i?i.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const pt=ze({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 _t;function gt(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"}(_t||(_t={}));let mt=null,yt=null,wt=1;const xt=new Map;function vt(e){mt=e,yt=e.getResourceManager(),It()}function bt(){0!==Tt&&mt&&(mt._free(Tt),Tt=0),xt.clear(),wt=1,Ct=!1,Mt.clear(),At=null,yt=null,mt=null}function St(){if(!yt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return yt}const Pt={createShader:(e,t)=>St().createShader(e,t),releaseShader(e){e>0&&St().releaseShader(e)},create(e){const t=wt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??_t.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 xt.set(t,s),t},get:e=>xt.get(e),setUniform(e,t,s){const n=xt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=xt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=xt.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=xt.get(e);return t?.blendMode??_t.Normal},setDepthTest(e,t){const s=xt.get(e);s&&(s.depthTest=t)},getShader(e){const t=xt.get(e);return t?.shader??0},release(e){xt.delete(e)},isValid:e=>xt.has(e),releaseAll(){xt.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??_t.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=xt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=wt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return xt.set(s,n),s},toAssetData(e,t){const s=xt.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=xt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ct=!1,Tt=0;const Et=4096,Mt=new Map;let At=null;function Rt(e){const t=(0===Tt&&mt&&(Tt=mt._malloc(Et)),Tt);if(0===t||!mt)return{ptr:0,count:0};let s=0,n=0;const r=mt.HEAPU8,i=mt.HEAPU32,o=mt.HEAPF32;for(const[a,c]of e){if(s+128>Et)break;let e=Mt.get(a);e||(At||(At=new TextEncoder),e=At.encode(a),Mt.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function It(){if(!mt||Ct)return;mt.materialDataProvider=(e,t,s,n,r)=>{const i=xt.get(e);if(!i)return mt.HEAPU32[t>>2]=0,mt.HEAPU32[s>>2]=0,mt.HEAPU32[n>>2]=0,void(mt.HEAPU32[r>>2]=0);mt.HEAPU32[t>>2]=i.shader,mt.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=Rt(i.uniforms);mt.HEAPU32[n>>2]=o,mt.HEAPU32[r>>2]=a},Ct=!0}const Ft={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 kt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Bt{constructor(e,t=""){this.cache_=new kt,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&&(Pt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Pt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const s=await c(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:Pt.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const 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"}]}]]);function $t(e,t){Ut.set(e,t)}function Dt(e){const t=Ut.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function zt(e){return Ut.get(e)?.fields??[]}function Wt(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,Ae,{value:n.name}),!1!==n.visible)for(const s of n.components)Ot(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 Lt(e,t,s){const n=new Map,r=s?.assetServer,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ut.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const l=new Map,u=new Map,h=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);l.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);h.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),h.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ut.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=u.get(t)??0;break;case"font":s[e.field]=h.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Ae,{value:s.name}),!1!==s.visible)for(const n of s.components)Ot(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function Ot(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=pe(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function Ht(e,t){const s=e.getEntitiesWithComponents([be]);for(const n of s){const s=e.get(n,be);s&&(s.aspectRatio=t,e.insert(n,be,s))}}function jt(e,t){const s=e.getEntitiesWithComponents([Ae]);for(const n of s){const s=e.get(n,Ae);if(s&&s.value===t)return n}return null}class Nt{constructor(e){this.textureCache_=new kt,this.shaderCache_=new kt,this.jsonCache_=new kt,this.textCache_=new kt,this.binaryCache_=new kt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new kt,this.prefabCache_=new kt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=h(q,q),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Bt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,i)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Pt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),c=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),u="binary"===x(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(h,i,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return Lt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,s,a,i.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Pt.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return Pt.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await c(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return c(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Xt=ze(null,"Assets");class Vt{build(e){const t=e.wasmModule;t?e.insertResource(Xt,new Nt(t)):console.warn("AssetPlugin: No WASM module available")}}const qt=new Vt;class Gt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Yt(e,t){const s=e.getResource(Xt);s&&s.registerEmbeddedAssets(t)}async function Jt(e,t,s){const{entities:n,rootId:r}=await Qt(t,s?.overrides??[],s,void 0,new Set),i={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await Lt(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const Kt=10;async function Qt(e,t,s,n,r,i=0){if(i>Kt)throw new Error(`Prefab nesting depth exceeded ${Kt}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Qt(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),c.push(...t.entities);continue}const l=o.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,h={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Zt(h,t),c.push(h)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function Zt(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 es{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Jt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ts=ze(null,"Prefabs");class ss{constructor(){this.name="PrefabsPlugin",this.dependencies=[Xt]}build(e){const t=e.getResource(Xt);e.insertResource(ts,new es(e.world,t))}}const ns=new ss;let rs=null,is=0,os=0,as=0;const cs=new Float32Array(256);function ls(e){rs=e,is=rs._malloc(64),os=rs._malloc(64),as=rs._malloc(1024)}function us(){rs&&(is&&(rs._free(is),is=0),os&&(rs._free(os),os=0),as&&(rs._free(as),as=0)),rs=null}function hs(){if(!rs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return rs}const ds={r:1,g:1,b:1,a:1},fs={begin(e){const t=hs();t.HEAPF32.set(e,is/4),t.draw_begin(is)},end(){hs().draw_end()},line(e,t,s,n=1){hs().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){hs().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){hs().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){hs().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){hs().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=ds){hs().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=ds){hs().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){hs().draw_setLayer(e)},setDepth(e){hs().draw_setDepth(e)},getDrawCallCount:()=>rs?rs.draw_getDrawCallCount():0,getPrimitiveCount:()=>rs?rs.draw_getPrimitiveCount():0,setBlendMode(e){hs().draw_setBlendMode(e)},setDepthTest(e){hs().draw_setDepthTest(e)},drawMesh(e,t,s){const n=hs();n.HEAPF32.set(s,os/4),n.draw_mesh(e,t,os)},drawMeshWithMaterial(e,t,s){const n=hs(),r=Pt.get(t);if(!r)return;if(fs.setBlendMode(r.blendMode),fs.setDepthTest(r.depthTest),0===r.uniforms.size)return void fs.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,os/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=_s(t);if(!(n<0)){if(gt(s))cs[i++]=10,cs[i++]=n,cs[i++]=s.slot??e++,cs[i++]=s.textureId;else if("number"==typeof s)cs[i++]=1,cs[i++]=n,cs[i++]=s;else if(Array.isArray(s)){cs[i++]=s.length,cs[i++]=n;for(let e=0;e<s.length;e++)cs[i++]=s[e]}else"w"in s?(cs[i++]=4,cs[i++]=n,cs[i++]=s.x,cs[i++]=s.y,cs[i++]=s.z,cs[i++]=s.w):"z"in s?(cs[i++]=3,cs[i++]=n,cs[i++]=s.x,cs[i++]=s.y,cs[i++]=s.z):(cs[i++]=2,cs[i++]=n,cs[i++]=s.x,cs[i++]=s.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<i)&&(r.cachedBuffer_=new Float32Array(i)),r.cachedBuffer_.set(cs.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}0!==i?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),as/4),n.draw_meshWithUniforms(e,r.shader,os,as,i)):n.draw_mesh(e,r.shader,os)}},ps={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};function _s(e){return ps[e]??-1}const gs=new Map;function ms(e,t,s){gs.set(e,{fn:t,scene:s??""})}function ys(e){gs.delete(e)}function ws(){gs.clear()}var xs;!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"}(xs||(xs={}));let vs=null,bs=0,Ss=0,Ps=0;function Cs(e){vs=e,bs=vs._malloc(262144),Ss=vs._malloc(65536),Ps=vs._malloc(256)}function Ts(){vs&&(bs&&vs._free(bs),Ss&&vs._free(Ss),Ps&&vs._free(Ps),bs=0,Ss=0,Ps=0),vs=null}function Es(){if(!vs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return vs}const Ms={create(e){const t=Es(),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,bs/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,Ps,r).set(i),t.geometry_init(s,bs,n,Ps,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,Ss,n).set(e.indices),t.geometry_setIndices16(s,Ss,n)}else{new Uint32Array(t.HEAPU8.buffer,Ss,n).set(e.indices),t.geometry_setIndices32(s,Ss,n)}}return s},updateVertices(e,t,s=0){const n=Es(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,bs/4),n.geometry_updateVertices(e,bs,r,s)},release(e){e>0&&Es().geometry_release(e)},isValid:e=>!(!vs||e<=0)&&vs.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Ms.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:xs.Float2},{name:"a_texCoord",type:xs.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Ms.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:xs.Float2},{name:"a_texCoord",type:xs.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return Ms.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:xs.Float2},{name:"a_texCoord",type:xs.Float2}],indices:new Uint16Array(o)})}};let As=null;function Rs(e){As=e}function Is(){As&&ks.isInitialized()&&ks.shutdown(),As=null}function Fs(){if(!As)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return As}const ks={init:(e,t)=>Fs().postprocess_init(e,t),shutdown(){Fs().postprocess_shutdown()},resize(e,t){Fs().postprocess_resize(e,t)},addPass:(e,t)=>Fs().postprocess_addPass(e,t),removePass(e){Fs().postprocess_removePass(e)},setEnabled(e,t){Fs().postprocess_setPassEnabled(e,t)},isEnabled:e=>Fs().postprocess_isPassEnabled(e),setUniform(e,t,s){Fs().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Fs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Fs().postprocess_begin()},end(){Fs().postprocess_end()},getPassCount:()=>Fs().postprocess_getPassCount(),isInitialized:()=>!!As&&As.postprocess_isInitialized(),setBypass(e){Fs().postprocess_setBypass(e)},isBypassed:()=>!As||As.postprocess_isBypassed(),createBlur:()=>Pt.createShader(Bs,"#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:()=>Pt.createShader(Bs,"#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:()=>Pt.createShader(Bs,"#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:()=>Pt.createShader(Bs,"#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")},Bs="#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 Us;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Us||(Us={}));let $s=null,Ds=0;function zs(e){$s=e,Ds=$s._malloc(64)}function Ws(){$s&&Ds&&($s._free(Ds),Ds=0),$s=null}const Ls={init(e,t){$s?.renderer_init(e,t)},resize(e,t){$s?.renderer_resize(e,t)},begin(e,t){$s&&Ds&&($s.HEAPF32.set(e,Ds/4),$s.renderer_begin(Ds,t??0))},flush(){$s?.renderer_flush()},end(){$s?.renderer_end()},submitSprites(e){$s&&$s.renderer_submitSprites(e._cpp)},submitBitmapText(e){$s&&$s.renderer_submitBitmapText(e._cpp)},submitSpine(e){$s&&$s.renderer_submitSpine?.(e._cpp)},setStage(e){$s?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>$s?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){$s?.renderer_releaseTarget(e)},getTargetTexture:e=>$s?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>$s?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){$s?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){$s?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){$s?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){$s?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>$s?$s.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>$s?{drawCalls:$s.renderer_getDrawCalls(),triangles:$s.renderer_getTriangles(),sprites:$s.renderer_getSprites(),text:$s.renderer_getText(),spine:$s.renderer_getSpine?.()??0,meshes:$s.renderer_getMeshes(),culled:$s.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Os=null;function Hs(e){Os=e}function js(){Os=null}const Ns={enable(){Os?.gl_enableErrorCheck(!0)},disable(){Os?.gl_enableErrorCheck(!1)},check:e=>Os?.gl_checkErrors(e)??0,diagnose(){Os?.renderer_diagnose()}};class Xs{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Ls.resize(n,r),ks.isInitialized()&&ks.getPassCount()>0&&ks.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,i):Ls.submitSpine(t),Ls.flush(),this.executeDrawCallbacks(s,i),Ls.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=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,i):Ls.submitSpine(t),Ls.flush(),this.executeDrawCallbacks(s,i),Ls.end()}executeDrawCallbacks(e,t){const s=gs;if(s.size>0){fs.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)}fs.end();for(const e of n)ys(e)}}}const Vs="__scene_transition_overlay__",qs={r:0,g:0,b:0,a:1};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,Re,{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),ms(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=ks.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){ks.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,Re)){const s=this.app_.world.get(e,Re);s.persistent=t,this.app_.world.insert(e,Re,s)}}}class Js{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.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??.3,r=t.color??qs;t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},ms(Vs,()=>{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;fs.setLayer(9999),fs.setDepth(9999),fs.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,ys(Vs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,ys(Vs),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(Xt)?this.app_.getResource(Xt):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(Xt)&&(t.assetServer=this.app_.getResource(Xt));const n=await Lt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Re,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Qs(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(Xt)?this.app_.getResource(Xt):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(Xt)&&(t.assetServer=this.app_.getResource(Xt));const n=await Lt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Re,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Qs(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,Re)){if(this.app_.world.get(e,Re).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())ys(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{ks.removePass(e)}catch{}s.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=null)}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(t&&"running"===t.status){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,ve)){const s=this.app_.world.get(e,ve);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,ve,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,ve)){const s=this.app_.world.get(e,ve),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,ve,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{ks.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 Ks=ze(null,"SceneManager");function Qs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Ks).getSceneStatus(t)&&s._fn(...n)}}}const Zs=Ze([Le(Ks),We(je)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),en={name:"SceneManager",build(e){const t=new Js(e);e.insertResource(Ks,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ks),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Ke.Startup,s),e.addSystemToSchedule(Ke.Last,Zs)}};class tn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,.25);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Ke.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ke.FixedPreUpdate),this.runSchedule(Ke.FixedUpdate),this.runSchedule(Ke.FixedPostUpdate),n++;n>=8&&(this.fixedAccumulator_=0),this.runSchedule(Ke.PreUpdate),this.runSchedule(Ke.Update),this.runSchedule(Ke.PostUpdate),this.runSchedule(Ke.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ft,this.resources_=new He;for(const e of Object.values(Ke))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new tn}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}addSystem(e){return this.addSystemToSchedule(Ke.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ke.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_}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}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Ks).register(e),this}setInitialScene(e){return this.getResource(Ks).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new rt(this.world_,this.resources_),this.resources_.insert(je,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ke.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,ws();const e=[js,Ws,Is,Ts,bt,us];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){let t=this.systems_.get(e);if(t&&this.runner_&&!this.frame_paused_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)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(je);t.delta=e,t.elapsed+=e,t.frameCount++}}function sn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const nn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function rn(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case ye.FixedWidth:return i;case ye.FixedHeight:return o;case ye.Expand:return Math.max(i,o);case ye.Shrink:return Math.min(i,o);case ye.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function on(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,Re);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let u,h=0,d=0;if(r.projectionType===ge.Orthographic){if(d=r.orthoSize,c){d=rn(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}h=d*a,u=cn(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=un(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=dn(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(pn(u,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const an=new Float32Array(16);function cn(e,t,s,n,r,i){const o=an;o.fill(0);const a=t-e,c=n-s,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+s)/c,o[14]=-(i+r)/l,o[15]=1,o}const ln=new Float32Array(16);function un(e,t,s,n){const r=ln;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const hn=new Float32Array(16);function dn(e,t,s){const n=hn;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 fn=new Float32Array(16);function pn(e,t){const s=fn;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 _n,gn,mn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(_n||(_n={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(gn||(gn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(mn||(mn={}));const yn=oe("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:_n.Left,verticalAlign:gn.Top,wordWrap:!0,overflow:mn.Visible,lineHeight:1.2}),wn=oe("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 xn{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(q,q),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):h+2*u,p=r?Math.ceil(o):d+2*u;if(r&&e.overflow===mn.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),g=Math.round(255*e.color.g),m=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${_}, ${g}, ${m}, ${y})`,r&&e.overflow===mn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case gn.Top:x=u;break;case gn.Middle:x=(p-w)/2;break;case gn.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let n;switch(e.align){case _n.Left:n=u;break;case _n.Center:n=f/2;break;case _n.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=l}r&&e.overflow===mn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case _n.Left:return"left";case _n.Center:return"center";case _n.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function vn(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 bn(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 Sn{build(e){fe("Text",yn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new xn(t),n=e.world,r=new Map;e.addSystemToSchedule(Ke.PreUpdate,Ze([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,yn));for(const e of r.keys())n.valid(e)&&n.has(e,yn)||r.delete(e);const e=n.getEntitiesWithComponents([yn]);for(const t of e){const e=n.get(t,yn),i=n.has(t,wn)?n.get(t,wn):null,o=r.get(t);if(o&&!bn(o,e,i))continue;n.has(t,ve)||n.insert(t,ve,{texture:Y,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,i),c=n.get(t,ve);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,ve,c),r.set(t,vn(e,i))}}))}}const Pn=new Sn,Cn=oe("UIMask",{enabled:!0});function Tn(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function En(e,t,s,n,r,i,o,a,c,l,u){const h=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*u]}const[g,m]=_(h,f),[y,w]=_(d,p),x=Math.min(g,y),v=Math.max(g,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 Mn(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],c=e[5],l=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],_=e[12],g=e[13],m=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*u-o*a,b=r*l-i*c,S=r*u-o*c,P=i*u-o*l,C=h*g-d*_,T=h*m-f*_,E=h*y-p*_,M=d*m-f*g,A=d*y-p*g,R=f*y-p*m;let I=w*R-x*A+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*R-l*A+u*M)*I,s[1]=(i*A-r*R-o*M)*I,s[2]=(g*P-m*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*R-u*T)*I,s[5]=(n*R-i*E+o*T)*I,s[6]=(m*v-_*P-y*x)*I,s[7]=(h*P-f*v+p*x)*I,s[8]=(a*A-c*E+u*C)*I,s[9]=(r*E-n*A-o*C)*I,s[10]=(_*S-g*v+y*w)*I,s[11]=(d*v-h*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(g*x-_*b-m*w)*I,s[15]=(h*b-d*x+f*w)*I),s}function An(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,c=(t-r)/o*2-1,l=s[0]*a+s[4]*c+s[12],u=s[1]*a+s[5]*c+s[13],h=s[3]*a+s[7]*c+s[15];return{x:l/h,y:u/h}}function Rn(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function In(e,t,s,n,r,i,o){if(!e.has(t,wn)||!e.has(t,xe))return null;const a=e.get(t,wn),c=e.get(t,xe),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return En(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,s,n,r,i,o)}function Fn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Cn]);if(0!==c.length)try{!function(e,t,s,n,r,i,o,a,c){const l=new Set;for(const e of n){t.get(e,Cn).enabled&&l.add(e)}const u=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,Ce);){const e=t.get(n,Ce);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function h(n,u){const d=e.getChildEntities(s,n);for(const s of d){let n=u;if(l.has(s)){const e=In(t,s,r,i,o,a,c);e&&(n=Tn(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of u){const s=In(t,e,r,i,o,a,c);s&&h(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class kn{build(e){if(fe("UIMask",Cn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Fn(e.wasmModule,e.world))}}const Bn=new kn,Un=oe("Interactable",{enabled:!0}),$n=oe("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Dn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Dn||(Dn={}));const zn=oe("Button",{state:Dn.Normal,transition:null});class Wn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const Ln=ze(new Wn,"UIEvents"),On=ae("ScreenSpace");function Hn(e,t,s,n,r,i){const o=i.right-i.left,a=i.top-i.bottom,c=i.left+e.x*o,l=i.left+t.x*o,u=i.bottom+e.y*a,h=i.bottom+t.y*a;let d,f,p,_;if(c===l&&u===h){const e=c+s.x,t=u+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=c+s.x,f=u+s.y,p=l+n.x,_=h+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function jn(e,t,s,n,r,i){if(!e.has(t,wn))return;const o=e.get(t,wn),a=Hn(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const c=e.get(t,we);if(i?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,we,c),!e.has(t,Te))return;const l=e.get(t,Te);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&jn(e,t,a.rect,a.centerX,a.centerY,!1)}class Nn{build(e){fe("UIRect",wn);const t=e.world;e.addSystemToSchedule(Ke.PreUpdate,Ze([We(pt)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([On,wn,we]);for(const e of i)jn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Xn=new Nn,Vn=new Float32Array(16),qn=new Float32Array(16);let Gn=!0,Yn=1;class Jn{build(e){fe("Interactable",Un),fe("Button",zn);const t=e.world,s=new Wn;e.insertResource(Ln,s);let n=null,r=null;Yn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Ke.PreUpdate,Ze([We(ot),We(pt)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([$n]);for(const e of o){const s=t.get(e,$n);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*Yn,c=i.screenH-e.mouseY*Yn;!function(e){let t=!1;for(let s=0;s<16;s++)if(qn[s]!==e[s]){t=!0;break}t&&(qn.set(e),Gn=!0)}(i.viewProjection),Gn&&(Mn(i.viewProjection,Vn),Gn=!1);const l=An(a,c,Vn,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([Un,wn,xe]);let h=null,d=-1/0;for(const e of u){t.has(e,$n)||t.insert(e,$n);if(!t.get(e,Un).enabled)continue;const s=t.get(e,xe),n=t.get(e,wn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(Rn(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,ve)&&(s=t.get(e,ve).layer),s>=d&&(d=s,h=e)}}if(n!==h){if(null!==n&&t.valid(n)&&t.has(n,$n)){t.get(n,$n).hovered=!1,s.emit(n,"hover_exit")}if(null!==h){t.get(h,$n).hovered=!0,s.emit(h,"hover_enter")}n=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,$n);e.pressed=!0,e.justPressed=!0,r=h,s.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,$n)){const e=t.get(r,$n);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Ke.Update,Ze([],()=>{const e=t.getEntitiesWithComponents([zn]);for(const s of e){if(t.has(s,Un)||t.insert(s,Un,{enabled:!0}),!t.has(s,$n))continue;const e=t.get(s,$n),n=t.get(s,zn),r=t.get(s,Un),i=n.state;if(r.enabled?e.pressed?n.state=Dn.Pressed:e.hovered?n.state=Dn.Hovered:n.state=Dn.Normal:n.state=Dn.Disabled,i!==n.state&&n.transition&&t.has(s,ve)){const e=t.get(s,ve),r=n.transition;switch(n.state){case Dn.Normal:e.color={...r.normalColor};break;case Dn.Hovered:e.color={...r.hoveredColor};break;case Dn.Pressed:e.color={...r.pressedColor};break;case Dn.Disabled:e.color={...r.disabledColor}}t.insert(s,ve,e)}}},{name:"ButtonSystem"}))}}const Kn=new Jn,Qn=oe("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 Zn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){fe("TextInput",Qn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=h(q,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,u=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||w()},_=()=>{a=!0},g=()=>{a=!1,w()},m=t=>{if(null===o)return;if("Escape"===t.key)return void v();const n=s.get(o,Qn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Ln).emit(o,"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,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,b())},y=()=>{if(null!==o&&s.valid(o)&&s.has(o,Qn)){const e=s.get(o,Qn);e.focused=!1,e.dirty=!0}o=null};function w(){if(null===o||!s.valid(o))return;const t=s.get(o,Qn);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(Ln).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,b()}function x(e){if(o===e)return;v();const t=s.get(e,Qn);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&&s.valid(o)&&s.has(o,Qn)){const e=s.get(o,Qn);e.focused=!1,e.dirty=!0}o=null,f.blur()}function b(){c=!0,l=0}function S(e,o,a,l){(r.width<a||r.height<l)&&(r.width=tr(Math.max(r.width,a)),r.height=tr(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const u=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,i.fillRect(0,0,a,l),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,l),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const h=0===o.value.length,d=h?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=h?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=er(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&c){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=er(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(l-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const g=i.getImageData(0,0,a,l),m=new Uint8Array(g.data.buffer),y=t.getResourceManager(),w=t._malloc(m.length);t.HEAPU8.set(m,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,m.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,ve);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,ve,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",g),f.addEventListener("keydown",m),f.addEventListener("blur",y),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",g),f.removeEventListener("keydown",m),f.removeEventListener("blur",y),f.remove()},e.addSystemToSchedule(Ke.PreUpdate,Ze([We(Ln)],e=>{const t=s.getEntitiesWithComponents([Qn,Un]);for(const e of t){if(!s.has(e,$n))continue;if(s.get(e,$n).justPressed)return void x(e)}if(null!==o){const e=s.getEntitiesWithComponents([Un]);for(const t of e){if(s.has(t,Qn))continue;if(!s.has(t,$n))continue;if(s.get(t,$n).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Ke.PreUpdate,Ze([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,Qn)))){s.get(o,Qn).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Qn)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Qn,wn]);for(const e of a){const t=s.get(e,Qn);if(!t.dirty)continue;const n=s.get(e,wn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,ve)||s.insert(e,ve,{texture:Y,color:{r:1,g:1,b:1,a:1},size:{x:r,y:i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function er(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function tr(e){let t=1;for(;t<e;)t*=2;return t}const sr=new Zn;async function nr(e,t,s){const n=e.getResource(Ks);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function rr(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 ir=ze({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),or=ze(null,"PhysicsAPI");function ar(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function cr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class lr{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(ir,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=rr(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([Se]);for(const s of t){const t=e.world.get(s,Se);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Ke.PostUpdate,Ze([We(je)],a=>{const c=o.getEntitiesWithComponents([Fe,we,xe]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,Fe),c=o.get(r,xe);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=ar(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),ur(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===$e.Kinematic){const e=ar(c.rotation);n._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const u=e.world.get(o,we);if(!u)continue;let h=a,d=c,f=l;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,xe)){const s=e.world.get(t.entity,xe),n=ar(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),u=Math.sin(-n);h=(r*o-i*u)/(0!==s.scale.x?s.scale.x:1),d=(r*u+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}u.position.x=h,u.position.y=d;const p=cr(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,we,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<o;s++){const n=e+2*s;i.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<c;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(ir,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(or,hr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function ur(e,t,s){const n=e.world;if(n.has(s,ke)){const e=n.get(s,ke);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,Be)){const e=n.get(s,Be);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 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 dr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function fr(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 pr(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,g=a*f,m=c*d,y=c*f,w=l*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(m+w))*r,(_+b)*r,(g-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(g+v)*o,(y-x)*o,(1-(p+m))*o,0,e.position.x,e.position.y,e.position.z,1])}async function _r(e,t,s,n,r,i,o,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=dr(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let u={},h=null;if(r&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===x(c)?.contentType;let h,d;if(u){const e=await r.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const f=s.loadSkeleton(h,d,n,n.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=fr(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=dr(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,h,s,n)),i){new lr("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=x(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${o}`:o;t=await s.readText(c),i=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=i?`${i}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),u=dr(e,l,!1),h=e.getResourceManager();n[r]=h.loadBitmapFont(t,u,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=Pt.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=Pt.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=zt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,d,f);const p=Wt(e.world,s);if(c&&e.hasResource(Ks))for(const t of p.values())e.world.insert(t,Re,{scene:c,persistent:!1});if(r&&h){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=n.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(h,s,u,p);!function(e,t,s,n,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,Me)?l.get(i,Me):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(o,c*h);let d=0;if(l.has(i,xe)){const e=pr(l.get(i,xe),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=s._malloc(a),u=s._malloc(c),h=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,u,h,f);const p=s.HEAPU32[h>>2],_=s.HEAPU32[f>>2],g=new Float32Array(s.HEAPF32.buffer,l,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(m),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(u),s._free(h),s._free(f)}d&&t._free(d)}})}(e,t,r,h,n)}if(a){const t=e.getResource(Xt);t&&t.setAddressableManifest(a)}}function gr(e,t,s){return{name:e,data:t,async setup(){await _r(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class mr{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"===x(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=x(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||i.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}i.length>0&&await Promise.all(i)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const yr="__preview__";class wr{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(Ks);t.register({name:yr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(yr),this.loadPromise_=t.load(yr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new mr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await _r(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,yr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([be]);for(const n of s){if(e.get(n,be).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([Se]);for(const r of n){const n=e.get(r,Se);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(Ks).getScene(yr),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,we,o);const a={isActive:!0,projectionType:ge.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:me.ColorAndDepth};e.insert(i,be,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(Ks);await e.switchTo(yr),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 xr={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),xr.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;function br(e){vr=e}function Sr(){return vr}function Pr(){return!vr}var Cr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Cr||(Cr={}));class Tr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Cr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Cr.Debug:console.debug(t,s);break;case Cr.Info:console.log(t,s);break;case Cr.Warn:console.warn(t,s);break;case Cr.Error:console.error(t,s)}}}class Er{constructor(){this.handlers_=[],this.minLevel_=Cr.Info,this.addHandler(new Tr)}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(Cr.Debug,e,t,s)}info(e,t,s){this.log(Cr.Info,e,t,s)}warn(e,t,s){this.log(Cr.Warn,e,t,s)}error(e,t,s){this.log(Cr.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 Mr=new Er;function Ar(){return Mr}function Rr(e){Mr.setMinLevel(e)}function Ir(e,t,s){Mr.debug(e,t,s)}function Fr(e,t,s){Mr.info(e,t,s)}function kr(e,t,s){Mr.warn(e,t,s)}function Br(e,t,s){Mr.error(e,t,s)}const Ur=[Pn,Bn,Xn,Kn,sr];function $r(e,t){return function(e,t){const s=tn.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ls(e),vt(e),Cs(e),Rs(e),zs(e),Hs(e);const r=new Xs;s.pipeline_=r;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=on(e,n,t,r));const o=s.getResource(pt);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}s.insertResource(pt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=o();if(0===t||0===c)return;const l=e.registry_getCanvasEntity(n);if(l>=0){const e=n.getCanvas(l).backgroundColor;Ls.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-i)/1e3;let h;if(Ls.resize(t,c),ks.isInitialized()&&ks.getPassCount()>0&&!ks.isBypassed()&&ks.resize(t,c),s.hasResource(Ks)){const e=s.getResource(Ks).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=on(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:nn,width:t,height:c,elapsed:u});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:l},clearFlags:e.clearFlags,elapsed:u})}Ls.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Ke.First,c),s.addSystemToSchedule(Ke.Last,l),s.addPlugin(qt),s.addPlugin(ns),s.addPlugin(ct),s.addPlugin(en),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Ur,...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 s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(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 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),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=j;export{tn as App,Vt as AssetPlugin,Gt as AssetRefCounter,Nt as AssetServer,Xt as Assets,kt as AsyncCache,Ee as BitmapText,_t as BlendMode,$e as BodyType,ke as BoxCollider,zn as Button,Dn as ButtonState,be as Camera,Se as Canvas,Ue as CapsuleCollider,Te as Children,Be as CircleCollider,me as ClearFlags,Ge as Commands,Je as CommandsInstance,X as DEFAULT_DESIGN_HEIGHT,N as DEFAULT_DESIGN_WIDTH,V as DEFAULT_PIXELS_PER_UNIT,q as DEFAULT_TEXT_CANVAS_SIZE,xs as DataType,fs as Draw,Ye as EntityCommands,Ns as GLDebug,Ms as Geometry,G as INVALID_ENTITY,J as INVALID_FONT,Y as INVALID_TEXTURE,ot as Input,at as InputPlugin,it as InputState,Un as Interactable,we as LocalTransform,Cr as LogLevel,Er as Logger,Pt as Material,Bt as MaterialLoader,Ne as Mut,Ae as Name,Ce as Parent,hr as Physics,ir as PhysicsEvents,lr as PhysicsPlugin,ks as PostProcess,es as PrefabServer,ts as Prefabs,ss as PrefabsPlugin,wr as PreviewPlugin,ge as ProjectionType,Ve as Query,qe as QueryInstance,Xs as RenderPipeline,Us as RenderStage,xr as RenderTexture,Ls as Renderer,We as Res,Le as ResMut,Fe as RigidBody,ye as ScaleMode,Ks as SceneManager,Js as SceneManagerState,Re as SceneOwner,Ke as Schedule,On as ScreenSpace,Ft as ShaderSources,Me as SpineAnimation,ve as Sprite,rt as SystemRunner,yn as Text,_n as TextAlign,Qn as TextInput,Zn as TextInputPlugin,mn as TextOverflow,Sn as TextPlugin,xn as TextRenderer,gn as TextVerticalAlign,je as Time,pt as UICameraInfo,Wn as UIEventQueue,Ln as UIEvents,$n as UIInteraction,Jn as UIInteractionPlugin,Nn as UILayoutPlugin,Cn as UIMask,kn as UIMaskPlugin,wn as UIRect,Pe as Velocity,mr as WebAssetProvider,ft as World,xe as WorldTransform,st as addStartupSystem,tt as addSystem,nt as addSystemToSchedule,qt as assetPlugin,ws as clearDrawCallbacks,le as clearUserComponents,ee as color,Hn as computeUIRectLayout,Fn as createMaskProcessor,gr as createRuntimeSceneConfig,$r as createWebApp,Ir as debug,oe as defineComponent,ze as defineResource,Ze as defineSystem,ae as defineTag,Br as error,jt as findEntityByName,sn as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,C as getAllAssetExtensions,A as getAssetMimeType,x as getAssetTypeEntry,pe as getComponent,Dt as getComponentAssetFields,Ie as getComponentDefaults,E as getCustomExtensions,v as getEditorType,Ar as getLogger,t as getPlatform,n as getPlatformType,ce as getUserComponent,M as getWeChatPackOptions,Fr as info,ls as initDrawAPI,Hs as initGLDebugAPI,Cs as initGeometryAPI,vt as initMaterialAPI,Rs as initPostProcessAPI,zs as initRendererAPI,ct as inputPlugin,Jt as instantiatePrefab,Tn as intersectRects,Mn as invertMatrix4,he as isBuiltinComponent,R as isCustomExtension,Sr as isEditor,P as isKnownAssetExtension,s as isPlatformInitialized,Pr as isRuntime,gt as isTextureRef,r as isWeChat,i as isWeb,Ot as loadComponent,rr as loadPhysicsModule,_r as loadRuntimeScene,Wt as loadSceneData,Lt as loadSceneWithAssets,T as looksLikeAssetPath,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,Rn as pointInWorldRect,ns as prefabsPlugin,te as quat,fe as registerComponent,$t as registerComponentAssetFields,ms as registerDrawCallback,Yt as registerEmbeddedAssets,It as registerMaterialCallback,en as sceneManagerPlugin,An as screenToWorld,br as setEditorMode,Rr as setLogLevel,us as shutdownDrawAPI,js as shutdownGLDebugAPI,Ts as shutdownGeometryAPI,bt as shutdownMaterialAPI,Is as shutdownPostProcessAPI,Ws as shutdownRendererAPI,sr as textInputPlugin,Pn as textPlugin,nr as transitionTo,Kn as uiInteractionPlugin,Xn as uiLayoutPlugin,Bn as uiMaskPlugin,Ur as uiPlugins,ys as unregisterDrawCallback,Ht as updateCameraAspectRatio,K as vec2,Q as vec3,Z as vec4,kr as warn,En as worldRectToScreen,Qs as wrapSceneSystem,$ as wxFileExists,D as wxFileExistsSync,L as wxGetImagePixels,W as wxLoadImage,O as wxLoadImagePixels,B as wxReadFile,U as wxReadTextFile,z 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 s(){return null!==e}function n(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,s){return t().instantiateWasm(e,s)}function h(e,s){return t().createCanvas(e,s)}function d(){return t().now()}function f(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 p(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 _=[{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}],g={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,y=new Set;for(const e of _)for(const t of e.extensions)m.set(t,e),y.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 _)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return y.has(e.toLowerCase())}function C(){return y}function T(e){return"string"==typeof e&&(!!e.includes("/")&&P(w(e)))}function E(){const e=[];for(const t of _)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function M(){return E().map(e=>({type:"suffix",value:e}))}function A(e){return g[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 s=t.toLowerCase();if(s.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 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)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(k(e,t.errMsg)))}})})}function U(e,t="utf-8"){return new Promise((s,n)=>{F().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(k(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function D(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function z(e,t){return new Promise((s,n)=>{F().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function W(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 O(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)}}async function L(e){return O(await W(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 U(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(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)})}},N=1920,X=1080,V=100,q=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 Y(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,s=0)=>({x:e,y:t,z:s}),te=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),se=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),ne=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function re(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(re);const t={};for(const s in e)t[s]=re(e[s]);return t}let ie=0;function oe(e,t){const s=++ie;return{_id:Symbol(`Component_${s}_${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 ce(e,t){const s=ae(),n=s.get(e);if(n)return n;const r=oe(e,t);return s.set(e,r),de(e,t,!1),r}function le(e){const t=ae(),s=t.get(e);if(s)return s;const n=oe(e,{});return t.set(e,n),de(e,{},!0),n}function ue(e){return ae().get(e)}function he(){ae().clear()}function de(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function fe(e){return!0===e._builtin}const pe=new Map;function _e(e,t){pe.set(e,t)}function ge(e){return pe.get(e)??ue(e)}function me(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return pe.set(e,s),s}const ye={Perspective:0,Orthographic:1},we={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},xe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ve=me("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),be=me("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Se=me("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}),Pe=me("Camera",{projectionType:ye.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:we.ColorAndDepth}),Ce=me("Canvas",{designResolution:{x:N,y:X},pixelsPerUnit:100,scaleMode:xe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Te=me("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ee=me("Parent",{entity:0}),Me=me("Children",{entities:[]}),Ae=me("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:Q}),Re=me("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}),Ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Fe=ce("SceneOwner",{scene:"",persistent:!1});function ke(e){const t=ge(e);return t?re(t._default):null}_e("Name",Ie);const Be=me("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Ue=me("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),$e=me("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),De=me("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ze={Static:0,Kinematic:1,Dynamic:2};let We=0;function Oe(e,t){const s=++We;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Le(e){return{_type:"res",_resource:e}}function He(e){return{_type:"res_mut",_resource:e}}class je{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 Ne{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 je(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Xe=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=[],s=[]){const n=[];return e.forEach((e,t)=>{qe(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class Ye{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_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let u=null;this.world_.beginIteration();try{for(const h of n){if(null!==u&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(h,t[s])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<r;e++)a[e+1]=this.world_.get(h,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];u=h}yield a}}finally{if(this.world_.endIteration(),null!==u&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Je(){return{_type:"commands"}}class Ke{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=fe(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 Qe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ke(this,null);return this.spawned_.push(e),e}entity(e){return new Ke(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 Ze;!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"}(Ze||(Ze={}));let et=0;function tt(e,t,s){const n=++et;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function st(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function nt(e){st().push({schedule:Ze.Update,system:e})}function rt(e){st().push({schedule:Ze.Startup,system:e})}function it(e,t){st().push({schedule:e,system:t})}class ot{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 Qe&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new Ye(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Qe(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class at{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 at,"Input");class lt{constructor(e){this.target_=e??null}build(e){const s=new at;e.insertResource(ct,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(Ze.Last,tt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ut=new lt;function ht(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=dt(t[e]),i=dt(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function dt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ft(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")}function pt(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}:pt(e)}}return t}class _t{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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,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.");this.cppRegistry_&&this.cppRegistry_.destroy(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){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return fe(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return fe(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return fe(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(fe(t)){if(!this.cppRegistry_)return null;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(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.");fe(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=ht(t._name,t._default,n);if(e.length>0)throw new Error(ft(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,pt(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(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=ht(t._name,t._default,e);if(r.length>0)throw new Error(ft(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!fe(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=i?i.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const gt=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 mt;function yt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(mt||(mt={}));let wt=null,xt=null,vt=1;const bt=new Map;function St(e){wt=e,xt=e.getResourceManager(),kt()}function Pt(){0!==Mt&&wt&&(wt._free(Mt),Mt=0),bt.clear(),vt=1,Et=!1,Rt.clear(),It=null,xt=null,wt=null}function Ct(){if(!xt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return xt}const Tt={createShader:(e,t)=>Ct().createShader(e,t),releaseShader(e){e>0&&Ct().releaseShader(e)},create(e){const t=vt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??mt.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return bt.set(t,s),t},get:e=>bt.get(e),setUniform(e,t,s){const n=bt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=bt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=bt.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=bt.get(e);return t?.blendMode??mt.Normal},setDepthTest(e,t){const s=bt.get(e);s&&(s.depthTest=t)},getShader(e){const t=bt.get(e);return t?.shader??0},release(e){bt.delete(e)},isValid:e=>bt.has(e),releaseAll(){bt.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??mt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=bt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=vt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return bt.set(s,n),s},toAssetData(e,t){const s=bt.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=bt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Et=!1,Mt=0;const At=4096,Rt=new Map;let It=null;function Ft(e){const t=(0===Mt&&wt&&(Mt=wt._malloc(At)),Mt);if(0===t||!wt)return{ptr:0,count:0};let s=0,n=0;const r=wt.HEAPU8,i=wt.HEAPU32,o=wt.HEAPF32;for(const[a,c]of e){if(s+128>At)break;let e=Rt.get(a);e||(It||(It=new TextEncoder),e=It.encode(a),Rt.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function kt(){if(!wt||Et)return;wt.materialDataProvider=(e,t,s,n,r)=>{const i=bt.get(e);if(!i)return wt.HEAPU32[t>>2]=0,wt.HEAPU32[s>>2]=0,wt.HEAPU32[n>>2]=0,void(wt.HEAPU32[r>>2]=0);wt.HEAPU32[t>>2]=i.shader,wt.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=Ft(i.uniforms);wt.HEAPU32[n>>2]=o,wt.HEAPU32[r>>2]=a},Et=!0}const Bt={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 Ut{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class $t{constructor(e,t=""){this.cache_=new Ut,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&&(Tt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Tt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const s=await c(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:Tt.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const Dt=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function zt(e,t){Dt.set(e,t)}function Wt(e){const t=Dt.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function Ot(e){return Dt.get(e)?.fields??[]}function Lt(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)jt(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 Ht(e,t,s){const n=new Map,r=s?.assetServer,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Dt.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const l=new Map,u=new Map,h=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);l.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);h.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),h.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Dt.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=u.get(t)??0;break;case"font":s[e.field]=h.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Ie,{value:s.name}),!1!==s.visible)for(const n of s.components)jt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function jt(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=ge(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function Nt(e,t){const s=e.getEntitiesWithComponents([Pe]);for(const n of s){const s=e.get(n,Pe);s&&(s.aspectRatio=t,e.insert(n,Pe,s))}}function Xt(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}class Vt{constructor(e){this.textureCache_=new Ut,this.shaderCache_=new Ut,this.jsonCache_=new Ut,this.textCache_=new Ut,this.binaryCache_=new Ut,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ut,this.prefabCache_=new Ut,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=h(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 $t(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,i)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Tt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),c=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),u="binary"===x(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(h,i,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return Ht(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,s,a,i.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Tt.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return Tt.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await c(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return c(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const qt=Oe(null,"Assets");class Gt{build(e){const t=e.wasmModule;t?e.insertResource(qt,new Vt(t)):console.warn("AssetPlugin: No WASM module available")}}const Yt=new Gt;class Jt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Kt(e,t){const s=e.getResource(qt);s&&s.registerEmbeddedAssets(t)}async function Qt(e,t,s){const{entities:n,rootId:r}=await es(t,s?.overrides??[],s,void 0,new Set),i={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await Ht(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const Zt=10;async function es(e,t,s,n,r,i=0){if(i>Zt)throw new Error(`Prefab nesting depth exceeded ${Zt}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await es(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),c.push(...t.entities);continue}const l=o.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,h={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};ts(h,t),c.push(h)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function ts(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 ss{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 Qt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ns=Oe(null,"Prefabs");class rs{constructor(){this.name="PrefabsPlugin",this.dependencies=[qt]}build(e){const t=e.getResource(qt);e.insertResource(ns,new ss(e.world,t))}}const is=new rs;let os=null,as=0,cs=0,ls=0;const us=new Float32Array(256);function hs(e){os=e,as=os._malloc(64),cs=os._malloc(64),ls=os._malloc(1024)}function ds(){os&&(as&&(os._free(as),as=0),cs&&(os._free(cs),cs=0),ls&&(os._free(ls),ls=0)),os=null}function fs(){if(!os)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return os}const ps={r:1,g:1,b:1,a:1},_s={begin(e){const t=fs();t.HEAPF32.set(e,as/4),t.draw_begin(as)},end(){fs().draw_end()},line(e,t,s,n=1){fs().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){fs().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){fs().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){fs().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){fs().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=ps){fs().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=ps){fs().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){fs().draw_setLayer(e)},setDepth(e){fs().draw_setDepth(e)},getDrawCallCount:()=>os?os.draw_getDrawCallCount():0,getPrimitiveCount:()=>os?os.draw_getPrimitiveCount():0,setBlendMode(e){fs().draw_setBlendMode(e)},setDepthTest(e){fs().draw_setDepthTest(e)},drawMesh(e,t,s){const n=fs();n.HEAPF32.set(s,cs/4),n.draw_mesh(e,t,cs)},drawMeshWithMaterial(e,t,s){const n=fs(),r=Tt.get(t);if(!r)return;if(_s.setBlendMode(r.blendMode),_s.setDepthTest(r.depthTest),0===r.uniforms.size)return void _s.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,cs/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=ms(t);if(!(n<0)){if(yt(s))us[i++]=10,us[i++]=n,us[i++]=s.slot??e++,us[i++]=s.textureId;else if("number"==typeof s)us[i++]=1,us[i++]=n,us[i++]=s;else if(Array.isArray(s)){us[i++]=s.length,us[i++]=n;for(let e=0;e<s.length;e++)us[i++]=s[e]}else"w"in s?(us[i++]=4,us[i++]=n,us[i++]=s.x,us[i++]=s.y,us[i++]=s.z,us[i++]=s.w):"z"in s?(us[i++]=3,us[i++]=n,us[i++]=s.x,us[i++]=s.y,us[i++]=s.z):(us[i++]=2,us[i++]=n,us[i++]=s.x,us[i++]=s.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<i)&&(r.cachedBuffer_=new Float32Array(i)),r.cachedBuffer_.set(us.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}0!==i?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),ls/4),n.draw_meshWithUniforms(e,r.shader,cs,ls,i)):n.draw_mesh(e,r.shader,cs)}},gs={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};function ms(e){return gs[e]??-1}const ys=new Map;function ws(e,t,s){ys.set(e,{fn:t,scene:s??""})}function xs(e){ys.delete(e)}function vs(){ys.clear()}var bs;!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"}(bs||(bs={}));let Ss=null,Ps=0,Cs=0,Ts=0;function Es(e){Ss=e,Ps=Ss._malloc(262144),Cs=Ss._malloc(65536),Ts=Ss._malloc(256)}function Ms(){Ss&&(Ps&&Ss._free(Ps),Cs&&Ss._free(Cs),Ts&&Ss._free(Ts),Ps=0,Cs=0,Ts=0),Ss=null}function As(){if(!Ss)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ss}const Rs={create(e){const t=As(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Ps/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Ts,r).set(i),t.geometry_init(s,Ps,n,Ts,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,Cs,n).set(e.indices),t.geometry_setIndices16(s,Cs,n)}else{new Uint32Array(t.HEAPU8.buffer,Cs,n).set(e.indices),t.geometry_setIndices32(s,Cs,n)}}return s},updateVertices(e,t,s=0){const n=As(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Ps/4),n.geometry_updateVertices(e,Ps,r,s)},release(e){e>0&&As().geometry_release(e)},isValid:e=>!(!Ss||e<=0)&&Ss.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Rs.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:bs.Float2},{name:"a_texCoord",type:bs.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Rs.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:bs.Float2},{name:"a_texCoord",type:bs.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return Rs.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:bs.Float2},{name:"a_texCoord",type:bs.Float2}],indices:new Uint16Array(o)})}};let Is=null;function Fs(e){Is=e}function ks(){Is&&Us.isInitialized()&&Us.shutdown(),Is=null}function Bs(){if(!Is)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Is}const Us={init:(e,t)=>Bs().postprocess_init(e,t),shutdown(){Bs().postprocess_shutdown()},resize(e,t){Bs().postprocess_resize(e,t)},addPass:(e,t)=>Bs().postprocess_addPass(e,t),removePass(e){Bs().postprocess_removePass(e)},setEnabled(e,t){Bs().postprocess_setPassEnabled(e,t)},isEnabled:e=>Bs().postprocess_isPassEnabled(e),setUniform(e,t,s){Bs().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Bs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Bs().postprocess_begin()},end(){Bs().postprocess_end()},getPassCount:()=>Bs().postprocess_getPassCount(),isInitialized:()=>!!Is&&Is.postprocess_isInitialized(),setBypass(e){Bs().postprocess_setBypass(e)},isBypassed:()=>!Is||Is.postprocess_isBypassed(),createBlur:()=>Tt.createShader($s,"#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:()=>Tt.createShader($s,"#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:()=>Tt.createShader($s,"#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:()=>Tt.createShader($s,"#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")},$s="#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 Ds;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ds||(Ds={}));let zs=null,Ws=0;function Os(e){zs=e,Ws=zs._malloc(64)}function Ls(){zs&&Ws&&(zs._free(Ws),Ws=0),zs=null}const Hs={init(e,t){zs?.renderer_init(e,t)},resize(e,t){zs?.renderer_resize(e,t)},begin(e,t){zs&&Ws&&(zs.HEAPF32.set(e,Ws/4),zs.renderer_begin(Ws,t??0))},flush(){zs?.renderer_flush()},end(){zs?.renderer_end()},submitSprites(e){zs&&zs.renderer_submitSprites(e._cpp)},submitBitmapText(e){zs&&zs.renderer_submitBitmapText(e._cpp)},submitSpine(e){zs&&zs.renderer_submitSpine?.(e._cpp)},setStage(e){zs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>zs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){zs?.renderer_releaseTarget(e)},getTargetTexture:e=>zs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>zs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){zs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){zs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){zs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){zs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>zs?zs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>zs?{drawCalls:zs.renderer_getDrawCalls(),triangles:zs.renderer_getTriangles(),sprites:zs.renderer_getSprites(),text:zs.renderer_getText(),spine:zs.renderer_getSpine?.()??0,meshes:zs.renderer_getMeshes(),culled:zs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let js=null;function Ns(e){js=e}function Xs(){js=null}const Vs={enable(){js?.gl_enableErrorCheck(!0)},disable(){js?.gl_enableErrorCheck(!1)},check:e=>js?.gl_checkErrors(e)??0,diagnose(){js?.renderer_diagnose()}};class qs{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Hs.resize(n,r),Us.isInitialized()&&Us.getPassCount()>0&&Us.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Hs.setViewport(0,0,n,r),Hs.clearBuffers(3),Hs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Hs.submitSprites(t),Hs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Hs.submitSpine(t),Hs.flush(),this.executeDrawCallbacks(s,i),Hs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Hs.setViewport(n.x,n.y,n.w,n.h),Hs.setScissor(n.x,n.y,n.w,n.h,!0),Hs.clearBuffers(r),Hs.setScissor(0,0,0,0,!1),Hs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Hs.submitSprites(t),Hs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Hs.submitSpine(t),Hs.flush(),this.executeDrawCallbacks(s,i),Hs.end()}executeDrawCallbacks(e,t){const s=ys;if(s.size>0){_s.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)}_s.end();for(const e of n)xs(e)}}}const Gs="__scene_transition_overlay__";class Ys{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Js{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Fe,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),ws(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Us.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Us.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,Fe)){const s=this.app_.world.get(e,Fe);s.persistent=t,this.app_.world.insert(e,Fe,s)}}}class Ks{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.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??G.sceneTransitionDuration,r=t.color??{...G.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},ws(Gs,()=>{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;_s.setLayer(9999),_s.setDepth(9999),_s.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,xs(Gs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,xs(Gs),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 Ys(t);this.scenes_.set(e,s);const n=new Js(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(qt)?this.app_.getResource(qt):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(qt)&&(t.assetServer=this.app_.getResource(qt));const n=await Ht(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Fe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Zs(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 Ys(t);this.scenes_.set(e,s);const n=new Js(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(qt)?this.app_.getResource(qt):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(qt)&&(t.assetServer=this.app_.getResource(qt));const n=await Ht(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Fe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Zs(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,Fe)){if(this.app_.world.get(e,Fe).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())xs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Us.removePass(e)}catch{}s.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=null)}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(t&&"running"===t.status){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Se)){const s=this.app_.world.get(e,Se);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Se,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,Se)){const s=this.app_.world.get(e,Se),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Se,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Us.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 Qs=Oe(null,"SceneManager");function Zs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Qs).getSceneStatus(t)&&s._fn(...n)}}}const en=tt([He(Qs),Le(Xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),tn={name:"SceneManager",build(e){const t=new Ks(e);e.insertResource(Qs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Qs),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Ze.Startup,s),e.addSystemToSchedule(Ze.Last,en)}};class sn{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.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Ze.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ze.FixedPreUpdate),this.runSchedule(Ze.FixedUpdate),this.runSchedule(Ze.FixedPostUpdate),n++;n>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Ze.PreUpdate),this.runSchedule(Ze.Update),this.runSchedule(Ze.PostUpdate),this.runSchedule(Ze.Last),requestAnimationFrame(this.mainLoop)},this.world_=new _t,this.resources_=new Ne;for(const e of Object.values(Ze))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new sn}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}addSystem(e){return this.addSystemToSchedule(Ze.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ze.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_}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}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(Qs).register(e),this}setInitialScene(e){return this.getResource(Qs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new ot(this.world_,this.resources_),this.resources_.insert(Xe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ze.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,vs();const e=[Xs,Ls,ks,Ms,Pt,ds];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){let t=this.systems_.get(e);if(t&&this.runner_&&!this.frame_paused_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)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++}}function nn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const rn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function on(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case xe.FixedWidth:return i;case xe.FixedHeight:return o;case xe.Expand:return Math.max(i,o);case xe.Shrink:return Math.min(i,o);case xe.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function an(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,Fe);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let u,h=0,d=0;if(r.projectionType===ye.Orthographic){if(d=r.orthoSize,c){d=on(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}h=d*a,u=ln(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=hn(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=fn(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(_n(u,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const cn=new Float32Array(16);function ln(e,t,s,n,r,i){const o=cn;o.fill(0);const a=t-e,c=n-s,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+s)/c,o[14]=-(i+r)/l,o[15]=1,o}const un=new Float32Array(16);function hn(e,t,s,n){const r=un;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const dn=new Float32Array(16);function fn(e,t,s){const n=dn;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 pn=new Float32Array(16);function _n(e,t){const s=pn;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 gn,mn,yn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(gn||(gn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(mn||(mn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(yn||(yn={}));const wn=ce("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:gn.Left,verticalAlign:mn.Top,wordWrap:!0,overflow:yn.Visible,lineHeight:1.2}),xn=ce("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 vn{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(G.textCanvasSize,G.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):h+2*u,p=r?Math.ceil(o):d+2*u;if(r&&e.overflow===yn.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),g=Math.round(255*e.color.g),m=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${_}, ${g}, ${m}, ${y})`,r&&e.overflow===yn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case mn.Top:x=u;break;case mn.Middle:x=(p-w)/2;break;case mn.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let n;switch(e.align){case gn.Left:n=u;break;case gn.Center:n=f/2;break;case gn.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=l}r&&e.overflow===yn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case gn.Left:return"left";case gn.Center:return"center";case gn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function bn(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 Sn(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class Pn{build(e){_e("Text",wn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new vn(t),n=e.world,r=new Map;e.addSystemToSchedule(Ze.PreUpdate,tt([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,wn));for(const e of r.keys())n.valid(e)&&n.has(e,wn)||r.delete(e);const e=n.getEntitiesWithComponents([wn]);for(const t of e){const e=n.get(t,wn),i=n.has(t,xn)?n.get(t,xn):null,o=r.get(t);if(o&&!Sn(o,e,i))continue;n.has(t,Se)||n.insert(t,Se,{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=s.renderForEntity(t,e,i),c=n.get(t,Se);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,Se,c),r.set(t,bn(e,i))}}))}}const Cn=new Pn,Tn=ce("UIMask",{enabled:!0});function En(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function Mn(e,t,s,n,r,i,o,a,c,l,u){const h=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*u]}const[g,m]=_(h,f),[y,w]=_(d,p),x=Math.min(g,y),v=Math.max(g,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 An(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],c=e[5],l=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],_=e[12],g=e[13],m=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*u-o*a,b=r*l-i*c,S=r*u-o*c,P=i*u-o*l,C=h*g-d*_,T=h*m-f*_,E=h*y-p*_,M=d*m-f*g,A=d*y-p*g,R=f*y-p*m;let I=w*R-x*A+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*R-l*A+u*M)*I,s[1]=(i*A-r*R-o*M)*I,s[2]=(g*P-m*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*R-u*T)*I,s[5]=(n*R-i*E+o*T)*I,s[6]=(m*v-_*P-y*x)*I,s[7]=(h*P-f*v+p*x)*I,s[8]=(a*A-c*E+u*C)*I,s[9]=(r*E-n*A-o*C)*I,s[10]=(_*S-g*v+y*w)*I,s[11]=(d*v-h*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(g*x-_*b-m*w)*I,s[15]=(h*b-d*x+f*w)*I),s}function Rn(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,c=(t-r)/o*2-1,l=s[0]*a+s[4]*c+s[12],u=s[1]*a+s[5]*c+s[13],h=s[3]*a+s[7]*c+s[15];return{x:l/h,y:u/h}}function In(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function Fn(e,t,s,n,r,i,o){if(!e.has(t,xn)||!e.has(t,be))return null;const a=e.get(t,xn),c=e.get(t,be),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return Mn(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,s,n,r,i,o)}function kn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Tn]);if(0!==c.length)try{!function(e,t,s,n,r,i,o,a,c){const l=new Set;for(const e of n){t.get(e,Tn).enabled&&l.add(e)}const u=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,Ee);){const e=t.get(n,Ee);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function h(n,u){const d=e.getChildEntities(s,n);for(const s of d){let n=u;if(l.has(s)){const e=Fn(t,s,r,i,o,a,c);e&&(n=En(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of u){const s=Fn(t,e,r,i,o,a,c);s&&h(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class Bn{build(e){if(_e("UIMask",Tn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(kn(e.wasmModule,e.world))}}const Un=new Bn,$n=ce("Interactable",{enabled:!0}),Dn=ce("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var zn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(zn||(zn={}));const Wn=ce("Button",{state:zn.Normal,transition:null});class On{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const Ln=Oe(new On,"UIEvents"),Hn=le("ScreenSpace");function jn(e,t,s,n,r,i){const o=i.right-i.left,a=i.top-i.bottom,c=i.left+e.x*o,l=i.left+t.x*o,u=i.bottom+e.y*a,h=i.bottom+t.y*a;let d,f,p,_;if(c===l&&u===h){const e=c+s.x,t=u+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=c+s.x,f=u+s.y,p=l+n.x,_=h+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function Nn(e,t,s,n,r,i){if(!e.has(t,xn))return;const o=e.get(t,xn),a=jn(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const c=e.get(t,ve);if(i?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,ve,c),!e.has(t,Me))return;const l=e.get(t,Me);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&Nn(e,t,a.rect,a.centerX,a.centerY,!1)}class Xn{build(e){_e("UIRect",xn);const t=e.world;e.addSystemToSchedule(Ze.PreUpdate,tt([Le(gt)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([Hn,xn,ve]);for(const e of i)Nn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Vn=new Xn,qn=new Float32Array(16),Gn=new Float32Array(16);let Yn=!0,Jn=1;class Kn{build(e){_e("Interactable",$n),_e("Button",Wn);const t=e.world,s=new On;e.insertResource(Ln,s);let n=null,r=null;Jn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Ze.PreUpdate,tt([Le(ct),Le(gt)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([Dn]);for(const e of o){const s=t.get(e,Dn);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*Jn,c=i.screenH-e.mouseY*Jn;!function(e){let t=!1;for(let s=0;s<16;s++)if(Gn[s]!==e[s]){t=!0;break}t&&(Gn.set(e),Yn=!0)}(i.viewProjection),Yn&&(An(i.viewProjection,qn),Yn=!1);const l=Rn(a,c,qn,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([$n,xn,be]);let h=null,d=-1/0;for(const e of u){t.has(e,Dn)||t.insert(e,Dn);if(!t.get(e,$n).enabled)continue;const s=t.get(e,be),n=t.get(e,xn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(In(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Se)&&(s=t.get(e,Se).layer),s>=d&&(d=s,h=e)}}if(n!==h){if(null!==n&&t.valid(n)&&t.has(n,Dn)){t.get(n,Dn).hovered=!1,s.emit(n,"hover_exit")}if(null!==h){t.get(h,Dn).hovered=!0,s.emit(h,"hover_enter")}n=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,Dn);e.pressed=!0,e.justPressed=!0,r=h,s.emit(h,"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,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Ze.Update,tt([],()=>{const e=t.getEntitiesWithComponents([Wn]);for(const s of e){if(t.has(s,$n)||t.insert(s,$n,{enabled:!0}),!t.has(s,Dn))continue;const e=t.get(s,Dn),n=t.get(s,Wn),r=t.get(s,$n),i=n.state;if(r.enabled?e.pressed?n.state=zn.Pressed:e.hovered?n.state=zn.Hovered:n.state=zn.Normal:n.state=zn.Disabled,i!==n.state&&n.transition&&t.has(s,Se)){const e=t.get(s,Se),r=n.transition;switch(n.state){case zn.Normal:e.color={...r.normalColor};break;case zn.Hovered:e.color={...r.hoveredColor};break;case zn.Pressed:e.color={...r.pressedColor};break;case zn.Disabled:e.color={...r.disabledColor}}t.insert(s,Se,e)}}},{name:"ButtonSystem"}))}}const Qn=new Kn,Zn=ce("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 er{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){_e("TextInput",Zn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=h(G.textCanvasSize,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,u=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||w()},_=()=>{a=!0},g=()=>{a=!1,w()},m=t=>{if(null===o)return;if("Escape"===t.key)return void v();const n=s.get(o,Zn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Ln).emit(o,"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,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,b())},y=()=>{if(null!==o&&s.valid(o)&&s.has(o,Zn)){const e=s.get(o,Zn);e.focused=!1,e.dirty=!0}o=null};function w(){if(null===o||!s.valid(o))return;const t=s.get(o,Zn);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(Ln).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,b()}function x(e){if(o===e)return;v();const t=s.get(e,Zn);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&&s.valid(o)&&s.has(o,Zn)){const e=s.get(o,Zn);e.focused=!1,e.dirty=!0}o=null,f.blur()}function b(){c=!0,l=0}function S(e,o,a,l){(r.width<a||r.height<l)&&(r.width=sr(Math.max(r.width,a)),r.height=sr(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const u=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,i.fillRect(0,0,a,l),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,l),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const h=0===o.value.length,d=h?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=h?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=tr(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&c){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=tr(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(l-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const g=i.getImageData(0,0,a,l),m=new Uint8Array(g.data.buffer),y=t.getResourceManager(),w=t._malloc(m.length);t.HEAPU8.set(m,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,m.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,Se);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,Se,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",g),f.addEventListener("keydown",m),f.addEventListener("blur",y),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",g),f.removeEventListener("keydown",m),f.removeEventListener("blur",y),f.remove()},e.addSystemToSchedule(Ze.PreUpdate,tt([Le(Ln)],e=>{const t=s.getEntitiesWithComponents([Zn,$n]);for(const e of t){if(!s.has(e,Dn))continue;if(s.get(e,Dn).justPressed)return void x(e)}if(null!==o){const e=s.getEntitiesWithComponents([$n]);for(const t of e){if(s.has(t,Zn))continue;if(!s.has(t,Dn))continue;if(s.get(t,Dn).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Ze.PreUpdate,tt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,Zn)))){s.get(o,Zn).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Zn)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Zn,xn]);for(const e of a){const t=s.get(e,Zn);if(!t.dirty)continue;const n=s.get(e,xn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,Se)||s.insert(e,Se,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:r,y:i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function tr(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function sr(e){let t=1;for(;t<e;)t*=2;return t}const nr=new er;async function rr(e,t,s){const n=e.getResource(Qs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}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 or=Oe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ar=Oe(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 lr(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(or,{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([Ce]);for(const s of t){const t=e.world.get(s,Ce);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Ze.PostUpdate,tt([Le(Xe)],a=>{const c=o.getEntitiesWithComponents([Be,ve,be]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,Be),c=o.get(r,be);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=cr(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),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===ze.Kinematic){const e=cr(c.rotation);n._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const u=e.world.get(o,ve);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(o,Ee)){const t=e.world.get(o,Ee);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,be)){const s=e.world.get(t.entity,be),n=cr(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),u=Math.sin(-n);h=(r*o-i*u)/(0!==s.scale.x?s.scale.x:1),d=(r*u+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}u.position.x=h,u.position.y=d;const p=lr(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,ve,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<o;s++){const n=e+2*s;i.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<c;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(or,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(ar,dr._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,Ue)){const e=n.get(s,Ue);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,$e)){const e=n.get(s,$e);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,De)){const e=n.get(s,De);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 dr{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(dr.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 i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function pr(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 _r(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,g=a*f,m=c*d,y=c*f,w=l*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(m+w))*r,(_+b)*r,(g-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(g+v)*o,(y-x)*o,(1-(p+m))*o,0,e.position.x,e.position.y,e.position.z,1])}async function gr(e,t,s,n,r,i,o,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=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,l);let u={},h=null;if(r&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===x(c)?.contentType;let h,d;if(u){const e=await r.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const f=s.loadSkeleton(h,d,n,n.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=pr(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=fr(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,h,s,n)),i){new ur("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=x(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${o}`:o;t=await s.readText(c),i=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=i?`${i}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),u=fr(e,l,!1),h=e.getResourceManager();n[r]=h.loadBitmapFont(t,u,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=Tt.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=Tt.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=Ot(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,d,f);const p=Lt(e.world,s);if(c&&e.hasResource(Qs))for(const t of p.values())e.world.insert(t,Fe,{scene:c,persistent:!1});if(r&&h){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=n.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(h,s,u,p);!function(e,t,s,n,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,Re)?l.get(i,Re):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(o,c*h);let d=0;if(l.has(i,be)){const e=_r(l.get(i,be),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=s._malloc(a),u=s._malloc(c),h=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,u,h,f);const p=s.HEAPU32[h>>2],_=s.HEAPU32[f>>2],g=new Float32Array(s.HEAPF32.buffer,l,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(m),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(u),s._free(h),s._free(f)}d&&t._free(d)}})}(e,t,r,h,n)}if(a){const t=e.getResource(qt);t&&t.setAddressableManifest(a)}}function mr(e,t,s){return{name:e,data:t,async setup(){await gr(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class yr{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"===x(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=x(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||i.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}i.length>0&&await Promise.all(i)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const wr="__preview__";class xr{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(Qs);t.register({name:wr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(wr),this.loadPromise_=t.load(wr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new yr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await gr(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,wr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Pe]);for(const n of s){if(e.get(n,Pe).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([Ce]);for(const r of n){const n=e.get(r,Ce);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(Qs).getScene(wr),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,ve,o);const a={isActive:!0,projectionType:ye.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:we.ColorAndDepth};e.insert(i,Pe,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(Qs);await e.switchTo(wr),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 vr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Hs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Hs.getTargetTexture(s),width:e.width,height:e.height}},release(e){Hs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Hs.releaseRenderTarget(e._handle),vr.create({width:t,height:s,depth:!0})),begin(e,t){Hs.begin(t,e._handle)},end(){Hs.end()},getDepthTexture:e=>Hs.getTargetDepthTexture(e._handle)};let br=!1;function Sr(e){br=e}function Pr(){return br}function Cr(){return!br}var Tr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Tr||(Tr={}));class Er{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Tr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Tr.Debug:console.debug(t,s);break;case Tr.Info:console.log(t,s);break;case Tr.Warn:console.warn(t,s);break;case Tr.Error:console.error(t,s)}}}class Mr{constructor(){this.handlers_=[],this.minLevel_=Tr.Info,this.addHandler(new Er)}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(Tr.Debug,e,t,s)}info(e,t,s){this.log(Tr.Info,e,t,s)}warn(e,t,s){this.log(Tr.Warn,e,t,s)}error(e,t,s){this.log(Tr.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 Ar=new Mr;function Rr(){return Ar}function Ir(e){Ar.setMinLevel(e)}function Fr(e,t,s){Ar.debug(e,t,s)}function kr(e,t,s){Ar.info(e,t,s)}function Br(e,t,s){Ar.warn(e,t,s)}function Ur(e,t,s){Ar.error(e,t,s)}const $r=[Cn,Un,Vn,Qn,nr];function Dr(e,t){return function(e,t){const s=sn.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),hs(e),St(e),Es(e),Fs(e),Os(e),Ns(e);const r=new qs;s.pipeline_=r;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=an(e,n,t,r));const o=s.getResource(gt);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}s.insertResource(gt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=o();if(0===t||0===c)return;const l=e.registry_getCanvasEntity(n);if(l>=0){const e=n.getCanvas(l).backgroundColor;Hs.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-i)/1e3;let h;if(Hs.resize(t,c),Us.isInitialized()&&Us.getPassCount()>0&&!Us.isBypassed()&&Us.resize(t,c),s.hasResource(Qs)){const e=s.getResource(Qs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=an(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:rn,width:t,height:c,elapsed:u});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:l},clearFlags:e.clearFlags,elapsed:u})}Hs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Ze.First,c),s.addSystemToSchedule(Ze.Last,l),s.addPlugin(Yt),s.addPlugin(is),s.addPlugin(ut),s.addPlugin(tn),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:$r,...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 s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(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 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),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=j;export{sn as App,Gt as AssetPlugin,Jt as AssetRefCounter,Vt as AssetServer,qt as Assets,Ut as AsyncCache,Ae as BitmapText,mt as BlendMode,ze as BodyType,Ue as BoxCollider,Wn as Button,zn as ButtonState,Pe as Camera,Ce as Canvas,De as CapsuleCollider,Me as Children,$e as CircleCollider,we as ClearFlags,Je as Commands,Qe as CommandsInstance,X as DEFAULT_DESIGN_HEIGHT,N as DEFAULT_DESIGN_WIDTH,V as DEFAULT_PIXELS_PER_UNIT,q as DEFAULT_TEXT_CANVAS_SIZE,bs as DataType,_s as Draw,Ke as EntityCommands,Vs as GLDebug,Rs as Geometry,J as INVALID_ENTITY,Q as INVALID_FONT,K as INVALID_TEXTURE,ct as Input,lt as InputPlugin,at as InputState,$n as Interactable,ve as LocalTransform,Tr as LogLevel,Mr as Logger,Tt as Material,$t as MaterialLoader,Ve as Mut,Ie as Name,Ee as Parent,dr as Physics,or as PhysicsEvents,ur as PhysicsPlugin,Us as PostProcess,ss as PrefabServer,ns as Prefabs,rs as PrefabsPlugin,xr as PreviewPlugin,ye as ProjectionType,Ge as Query,Ye as QueryInstance,qs as RenderPipeline,Ds as RenderStage,vr as RenderTexture,Hs as Renderer,Le as Res,He as ResMut,Be as RigidBody,G as RuntimeConfig,xe as ScaleMode,Qs as SceneManager,Ks as SceneManagerState,Fe as SceneOwner,Ze as Schedule,Hn as ScreenSpace,Bt as ShaderSources,Re as SpineAnimation,Se as Sprite,ot as SystemRunner,wn as Text,gn as TextAlign,Zn as TextInput,er as TextInputPlugin,yn as TextOverflow,Pn as TextPlugin,vn as TextRenderer,mn as TextVerticalAlign,Xe as Time,gt as UICameraInfo,On as UIEventQueue,Ln as UIEvents,Dn as UIInteraction,Kn as UIInteractionPlugin,Xn as UILayoutPlugin,Tn as UIMask,Bn as UIMaskPlugin,xn as UIRect,Te as Velocity,yr as WebAssetProvider,_t as World,be as WorldTransform,rt as addStartupSystem,nt as addSystem,it as addSystemToSchedule,Y as applyRuntimeConfig,Yt as assetPlugin,vs as clearDrawCallbacks,he as clearUserComponents,se as color,jn as computeUIRectLayout,kn as createMaskProcessor,mr as createRuntimeSceneConfig,Dr as createWebApp,Fr as debug,ce as defineComponent,Oe as defineResource,tt as defineSystem,le as defineTag,Ur as error,Xt as findEntityByName,nn as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,C as getAllAssetExtensions,A as getAssetMimeType,x as getAssetTypeEntry,ge as getComponent,Wt as getComponentAssetFields,ke as getComponentDefaults,E as getCustomExtensions,v as getEditorType,Rr as getLogger,t as getPlatform,n as getPlatformType,ue as getUserComponent,M as getWeChatPackOptions,kr as info,hs as initDrawAPI,Ns as initGLDebugAPI,Es as initGeometryAPI,St as initMaterialAPI,Fs as initPostProcessAPI,Os as initRendererAPI,ut as inputPlugin,Qt as instantiatePrefab,En as intersectRects,An as invertMatrix4,fe as isBuiltinComponent,R as isCustomExtension,Pr as isEditor,P as isKnownAssetExtension,s as isPlatformInitialized,Cr as isRuntime,yt as isTextureRef,r as isWeChat,i as isWeb,jt as loadComponent,ir as loadPhysicsModule,gr as loadRuntimeScene,Lt as loadSceneData,Ht as loadSceneWithAssets,T as looksLikeAssetPath,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,In as pointInWorldRect,is as prefabsPlugin,ne as quat,_e as registerComponent,zt as registerComponentAssetFields,ws as registerDrawCallback,Kt as registerEmbeddedAssets,kt as registerMaterialCallback,tn as sceneManagerPlugin,Rn as screenToWorld,Sr as setEditorMode,Ir as setLogLevel,ds as shutdownDrawAPI,Xs as shutdownGLDebugAPI,Ms as shutdownGeometryAPI,Pt as shutdownMaterialAPI,ks as shutdownPostProcessAPI,Ls as shutdownRendererAPI,nr as textInputPlugin,Cn as textPlugin,rr as transitionTo,Qn as uiInteractionPlugin,Vn as uiLayoutPlugin,Un as uiMaskPlugin,$r as uiPlugins,xs as unregisterDrawCallback,Nt as updateCameraAspectRatio,Z as vec2,ee as vec3,te as vec4,Br as warn,Mn as worldRectToScreen,Zs as wrapSceneSystem,$ as wxFileExists,D as wxFileExistsSync,O as wxGetImagePixels,W as wxLoadImage,L as wxLoadImagePixels,B as wxReadFile,U as wxReadTextFile,z 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 c5de4d852..0f307cff2 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -2,6 +2,32 @@ declare const DEFAULT_DESIGN_WIDTH = 1920;
declare const DEFAULT_DESIGN_HEIGHT = 1080;
declare const DEFAULT_PIXELS_PER_UNIT = 100;
declare const DEFAULT_TEXT_CANVAS_SIZE = 512;
+declare const RuntimeConfig: {
+ sceneTransitionDuration: number;
+ sceneTransitionColor: {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+ };
+ defaultFontFamily: string;
+ canvasScaleMode: number;
+ canvasMatchWidthOrHeight: number;
+ maxDeltaTime: number;
+ maxFixedSteps: number;
+ textCanvasSize: number;
+};
+declare function applyRuntimeConfig(components: {
+ Text?: {
+ _default: Record<string, unknown>;
+ };
+ TextInput?: {
+ _default: Record<string, unknown>;
+ };
+ Canvas?: {
+ _default: Record<string, unknown>;
+ };
+}): void;
/**
* @file types.ts
@@ -1562,6 +1588,8 @@ declare class App {
private lastTime_;
private fixedTimestep_;
private fixedAccumulator_;
+ private maxDeltaTime_;
+ private maxFixedSteps_;
private module_;
private pipeline_;
private spineInitPromise_?;
@@ -1592,6 +1620,8 @@ declare class App {
set physicsModule(m: unknown);
get world(): World;
setFixedTimestep(timestep: number): this;
+ setMaxDeltaTime(v: number): this;
+ setMaxFixedSteps(v: number): this;
onError(handler: (error: unknown, systemName: string) => void): this;
onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;
insertResource<T>(resource: ResourceDef<T>, value: T): this;
@@ -2743,5 +2773,5 @@ declare const uiPlugins: Plugin[];
declare function createWebApp(module: ESEngineModule, options?: WebAppOptions): App;
-export { App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_PIXELS_PER_UNIT, DEFAULT_TEXT_CANVAS_SIZE, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, Interactable, LocalTransform$1 as LocalTransform, LogLevel, Logger, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProjectionType, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, ScaleMode, SceneManager, SceneManagerState, SceneOwner, Schedule, ScreenSpace, ShaderSources, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform$1 as WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeUIRectLayout, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defineComponent, defineResource, defineSystem, defineTag, error, findEntityByName, flushPendingSystems, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFields, getComponentDefaults, getCustomExtensions, getEditorType, getLogger, getPlatform, getPlatformType, getUserComponent, getWeChatPackOptions, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, looksLikeAssetPath, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInWorldRect, prefabsPlugin, quat, registerComponent, registerComponentAssetFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, sceneManagerPlugin, screenToWorld, setEditorMode, setLogLevel, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textInputPlugin, textPlugin, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, worldRectToScreen, wrapSceneSystem };
+export { App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_PIXELS_PER_UNIT, DEFAULT_TEXT_CANVAS_SIZE, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, Interactable, LocalTransform$1 as LocalTransform, LogLevel, Logger, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProjectionType, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, RuntimeConfig, ScaleMode, SceneManager, SceneManagerState, SceneOwner, Schedule, ScreenSpace, ShaderSources, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform$1 as WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, applyRuntimeConfig, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeUIRectLayout, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defineComponent, defineResource, defineSystem, defineTag, error, findEntityByName, flushPendingSystems, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFields, getComponentDefaults, getCustomExtensions, getEditorType, getLogger, getPlatform, getPlatformType, getUserComponent, getWeChatPackOptions, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, looksLikeAssetPath, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInWorldRect, prefabsPlugin, quat, registerComponent, registerComponentAssetFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, sceneManagerPlugin, screenToWorld, setEditorMode, setLogLevel, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textInputPlugin, textPlugin, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, worldRectToScreen, wrapSceneSystem };
export type { AddressableAssetType, AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AddressableResultMap, AnyComponentDef, AssetBundle, AssetContentType, AssetRefInfo, AssetTypeEntry, AssetsData, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, EditorAssetType, Entity, FileLoadOptions, FontHandle, GeometryHandle, GeometryOptions, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, LoadedMaterial, LocalTransformData, LogEntry, LogHandler, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, PrefabData, PrefabEntityData, PrefabOverride, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, RuntimeSceneOptions, SceneComponentData, SceneConfig, SceneContext, SceneData, SceneEntityData, SceneLoadOptions, SceneOwnerData, SceneStatus, ScreenRect, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder$1 as SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemOptions, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, TransitionConfig, TransitionOptions, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index 81238c78d..bf43a43e5 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return null!==e}function n(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,s){return t().instantiateWasm(e,s)}function h(e,s){return t().createCanvas(e,s)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const s=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),n={};return s.headers.forEach((e,t)=>{n[t]=e}),{ok:s.ok,status:s.status,statusText:s.statusText,headers:n,json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let s;s="string"==typeof e?await this.readFile(e):e;const n=await WebAssembly.instantiate(s,t);return{instance:n.instance,module:n.module}}createImage(){return new Image}createCanvas(e,t){let s;return s="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),s.width=e,s.height=t,s}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t??document.querySelector("canvas")??document.body,n=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),i=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},o=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},u=()=>{e.onPointerUp(0)},h=t=>{const s=t;e.onWheel(s.deltaX,s.deltaY)};document.addEventListener("keydown",n),document.addEventListener("keyup",r),s.addEventListener("mousemove",i),s.addEventListener("mousedown",o),s.addEventListener("mouseup",a),s.addEventListener("touchstart",c),s.addEventListener("touchmove",l),s.addEventListener("touchend",u),s.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",r),s.removeEventListener("mousemove",i),s.removeEventListener("mousedown",o),s.removeEventListener("mouseup",a),s.removeEventListener("touchstart",c),s.removeEventListener("touchmove",l),s.removeEventListener("touchend",u),s.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,_=1080,g=100,m=512,y=0,w=4294967295,x=4294967295,v=(e=0,t=0)=>({x:e,y:t}),b=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),S=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),P=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),C=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function T(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(T);const t={};for(const s in e)t[s]=T(e[s]);return t}let E=0;function M(e,t){const s=++E;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...T(t),...e}:T(t)}}function A(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function R(e,t){const s=A(),n=s.get(e);if(n)return n;const r=M(e,t);return s.set(e,r),B(e,t,!1),r}function I(e){const t=A(),s=t.get(e);if(s)return s;const n=M(e,{});return t.set(e,n),B(e,{},!0),n}function F(e){return A().get(e)}function k(){A().clear()}function B(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function U(e){return!0===e._builtin}const $=new Map;function L(e,t){$.set(e,t)}function D(e){return $.get(e)??F(e)}function z(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return $.set(e,s),s}const O={Perspective:0,Orthographic:1},H={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},W={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},j=z("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),N=z("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),V=z("Sprite",{texture:w,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}),X=z("Camera",{projectionType:O.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:H.ColorAndDepth}),Y=z("Canvas",{designResolution:{x:p,y:_},pixelsPerUnit:100,scaleMode:W.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),q=z("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),G=z("Parent",{entity:0}),J=z("Children",{entities:[]}),K=z("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:x}),Q=z("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}),Z={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ee=R("SceneOwner",{scene:"",persistent:!1});function te(e){const t=D(e);return t?T(t._default):null}L("Name",Z);const se=z("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ne=z("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),re=z("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ie=z("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),oe={Static:0,Kinematic:1,Dynamic:2};let ae=0;function ce(e,t){const s=++ae;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function le(e){return{_type:"res",_resource:e}}function ue(e){return{_type:"res_mut",_resource:e}}class he{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 de{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 he(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const fe=ce({delta:0,elapsed:0,frameCount:0},"Time");function pe(e){return{_type:"mut",_component:e}}function _e(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function ge(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{_e(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class me{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_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let u=null;this.world_.beginIteration();try{for(const h of n){if(null!==u&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(h,t[s])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<r;e++)a[e+1]=this.world_.get(h,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];u=h}yield a}}finally{if(this.world_.endIteration(),null!==u&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function ye(){return{_type:"commands"}}class we{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=U(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 xe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new we(this,null);return this.spawned_.push(e),e}entity(e){return new we(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 ve;!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"}(ve||(ve={}));let be=0;function Se(e,t,s){const n=++be;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Pe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ce(e){Pe().push({schedule:ve.Update,system:e})}function Te(e){Pe().push({schedule:ve.Startup,system:e})}function Ee(e,t){Pe().push({schedule:e,system:t})}class Me{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 xe&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new me(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new xe(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=ce(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(ve.Last,Se([],()=>{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 ke(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=Be(t[e]),i=Be(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function Be(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ue(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")}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 Le{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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,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.");this.cppRegistry_&&this.cppRegistry_.destroy(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){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return U(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return U(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return U(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(U(t)){if(!this.cppRegistry_)return null;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(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.");U(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=ke(t._name,t._default,n);if(e.length>0)throw new Error(Ue(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,$e(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(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=ke(t._name,t._default,e);if(r.length>0)throw new Error(Ue(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!U(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=i?i.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const De=ce({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 ze;function Oe(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"}(ze||(ze={}));let He=null,We=null,je=1;const Ne=new Map;function Ve(e){He=e,We=e.getResourceManager(),tt()}function Xe(){0!==Je&&He&&(He._free(Je),Je=0),Ne.clear(),je=1,Ge=!1,Qe.clear(),Ze=null,We=null,He=null}function Ye(){if(!We)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return We}const qe={createShader:(e,t)=>Ye().createShader(e,t),releaseShader(e){e>0&&Ye().releaseShader(e)},create(e){const t=je++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??ze.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 Ne.set(t,s),t},get:e=>Ne.get(e),setUniform(e,t,s){const n=Ne.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ne.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ne.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ne.get(e);return t?.blendMode??ze.Normal},setDepthTest(e,t){const s=Ne.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ne.get(e);return t?.shader??0},release(e){Ne.delete(e)},isValid:e=>Ne.has(e),releaseAll(){Ne.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??ze.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=je++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ne.set(s,n),s},toAssetData(e,t){const s=Ne.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=Ne.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ge=!1,Je=0;const Ke=4096,Qe=new Map;let Ze=null;function et(e){const t=(0===Je&&He&&(Je=He._malloc(Ke)),Je);if(0===t||!He)return{ptr:0,count:0};let s=0,n=0;const r=He.HEAPU8,i=He.HEAPU32,o=He.HEAPF32;for(const[a,c]of e){if(s+128>Ke)break;let e=Qe.get(a);e||(Ze||(Ze=new TextEncoder),e=Ze.encode(a),Qe.set(a,e));const l=e.length,u=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof c)h=0,d[0]=c;else if(Array.isArray(c)){h=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}else"w"in c?(h=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(h=2,d=[c.x,c.y,c.z,0]):"y"in c&&(h=1,d=[c.x,c.y,0,0]);i[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function tt(){if(!He||Ge)return;He.materialDataProvider=(e,t,s,n,r)=>{const i=Ne.get(e);if(!i)return He.HEAPU32[t>>2]=0,He.HEAPU32[s>>2]=0,He.HEAPU32[n>>2]=0,void(He.HEAPU32[r>>2]=0);He.HEAPU32[t>>2]=i.shader,He.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=et(i.uniforms);He.HEAPU32[n>>2]=o,He.HEAPU32[r>>2]=a},Ge=!0}const st={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 nt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class rt{constructor(e,t=""){this.cache_=new nt,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&&(qe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())qe.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const s=await c(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:qe.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const it=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function ot(e,t){it.set(e,t)}function at(e){const t=it.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function ct(e){return it.get(e)?.fields??[]}function lt(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,Z,{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,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=it.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const l=new Map,u=new Map,h=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);l.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);h.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),h.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=it.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=u.get(t)??0;break;case"font":s[e.field]=h.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Z,{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=o.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=D(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function dt(e,t){const s=e.getEntitiesWithComponents([X]);for(const n of s){const s=e.get(n,X);s&&(s.aspectRatio=t,e.insert(n,X,s))}}function ft(e,t){const s=e.getEntitiesWithComponents([Z]);for(const n of s){const s=e.get(n,Z);if(s&&s.value===t)return n}return null}const pt=[{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}],_t={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"},gt=new Map,mt=new Set;for(const e of pt)for(const t of e.extensions)gt.set(t,e),mt.add(t);function yt(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function wt(e){return gt.get(yt(e))}function xt(e){return wt(e)?.editorType??"unknown"}function vt(e){return wt(e)?.addressableType??null}function bt(e){for(const t of pt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function St(e){return mt.has(e.toLowerCase())}function Pt(){return mt}function Ct(e){return"string"==typeof e&&(!!e.includes("/")&&St(yt(e)))}function Tt(){const e=[];for(const t of pt)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function Et(){return Tt().map(e=>({type:"suffix",value:e}))}function Mt(e){return _t[e.toLowerCase()]}function At(e){const t=wt(e);return t?.wechatPackInclude??!1}class Rt{constructor(e){this.textureCache_=new nt,this.shaderCache_=new nt,this.jsonCache_=new nt,this.textCache_=new nt,this.binaryCache_=new nt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new nt,this.prefabCache_=new nt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=h(m,m),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new rt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,i)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),qe.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),c=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),u="binary"===wt(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(h,i,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=wt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return 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 i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,s,a,i.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return qe.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return qe.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await c(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return c(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const It=ce(null,"Assets");class Ft{build(e){const t=e.wasmModule;t?e.insertResource(It,new Rt(t)):console.warn("AssetPlugin: No WASM module available")}}const kt=new Ft;class Bt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Ut(e,t){const s=e.getResource(It);s&&s.registerEmbeddedAssets(t)}async function $t(e,t,s){const{entities:n,rootId:r}=await Dt(t,s?.overrides??[],s,void 0,new Set),i={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await ut(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const Lt=10;async function Dt(e,t,s,n,r,i=0){if(i>Lt)throw new Error(`Prefab nesting depth exceeded ${Lt}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Dt(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),c.push(...t.entities);continue}const l=o.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,h={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};zt(h,t),c.push(h)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function zt(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 Ot{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 $t(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Ht=ce(null,"Prefabs");class Wt{constructor(){this.name="PrefabsPlugin",this.dependencies=[It]}build(e){const t=e.getResource(It);e.insertResource(Ht,new Ot(e.world,t))}}const jt=new Wt;let Nt=null,Vt=0,Xt=0,Yt=0;const qt=new Float32Array(256);function Gt(e){Nt=e,Vt=Nt._malloc(64),Xt=Nt._malloc(64),Yt=Nt._malloc(1024)}function Jt(){Nt&&(Vt&&(Nt._free(Vt),Vt=0),Xt&&(Nt._free(Xt),Xt=0),Yt&&(Nt._free(Yt),Yt=0)),Nt=null}function Kt(){if(!Nt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Nt}const Qt={r:1,g:1,b:1,a:1},Zt={begin(e){const t=Kt();t.HEAPF32.set(e,Vt/4),t.draw_begin(Vt)},end(){Kt().draw_end()},line(e,t,s,n=1){Kt().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){Kt().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){Kt().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){Kt().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){Kt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=Qt){Kt().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=Qt){Kt().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){Kt().draw_setLayer(e)},setDepth(e){Kt().draw_setDepth(e)},getDrawCallCount:()=>Nt?Nt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Nt?Nt.draw_getPrimitiveCount():0,setBlendMode(e){Kt().draw_setBlendMode(e)},setDepthTest(e){Kt().draw_setDepthTest(e)},drawMesh(e,t,s){const n=Kt();n.HEAPF32.set(s,Xt/4),n.draw_mesh(e,t,Xt)},drawMeshWithMaterial(e,t,s){const n=Kt(),r=qe.get(t);if(!r)return;if(Zt.setBlendMode(r.blendMode),Zt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Zt.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,Xt/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=ts(t);if(!(n<0)){if(Oe(s))qt[i++]=10,qt[i++]=n,qt[i++]=s.slot??e++,qt[i++]=s.textureId;else if("number"==typeof s)qt[i++]=1,qt[i++]=n,qt[i++]=s;else if(Array.isArray(s)){qt[i++]=s.length,qt[i++]=n;for(let e=0;e<s.length;e++)qt[i++]=s[e]}else"w"in s?(qt[i++]=4,qt[i++]=n,qt[i++]=s.x,qt[i++]=s.y,qt[i++]=s.z,qt[i++]=s.w):"z"in s?(qt[i++]=3,qt[i++]=n,qt[i++]=s.x,qt[i++]=s.y,qt[i++]=s.z):(qt[i++]=2,qt[i++]=n,qt[i++]=s.x,qt[i++]=s.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<i)&&(r.cachedBuffer_=new Float32Array(i)),r.cachedBuffer_.set(qt.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}0!==i?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),Yt/4),n.draw_meshWithUniforms(e,r.shader,Xt,Yt,i)):n.draw_mesh(e,r.shader,Xt)}},es={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};function ts(e){return es[e]??-1}const ss=new Map;function ns(e,t,s){ss.set(e,{fn:t,scene:s??""})}function rs(e){ss.delete(e)}function is(){ss.clear()}var os;!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"}(os||(os={}));let as=null,cs=0,ls=0,us=0;function hs(e){as=e,cs=as._malloc(262144),ls=as._malloc(65536),us=as._malloc(256)}function ds(){as&&(cs&&as._free(cs),ls&&as._free(ls),us&&as._free(us),cs=0,ls=0,us=0),as=null}function fs(){if(!as)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return as}const ps={create(e){const t=fs(),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,cs/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,us,r).set(i),t.geometry_init(s,cs,n,us,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,ls,n).set(e.indices),t.geometry_setIndices16(s,ls,n)}else{new Uint32Array(t.HEAPU8.buffer,ls,n).set(e.indices),t.geometry_setIndices32(s,ls,n)}}return s},updateVertices(e,t,s=0){const n=fs(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,cs/4),n.geometry_updateVertices(e,cs,r,s)},release(e){e>0&&fs().geometry_release(e)},isValid:e=>!(!as||e<=0)&&as.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return ps.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:os.Float2},{name:"a_texCoord",type:os.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return ps.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:os.Float2},{name:"a_texCoord",type:os.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return ps.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:os.Float2},{name:"a_texCoord",type:os.Float2}],indices:new Uint16Array(o)})}};let _s=null;function gs(e){_s=e}function ms(){_s&&ws.isInitialized()&&ws.shutdown(),_s=null}function ys(){if(!_s)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return _s}const ws={init:(e,t)=>ys().postprocess_init(e,t),shutdown(){ys().postprocess_shutdown()},resize(e,t){ys().postprocess_resize(e,t)},addPass:(e,t)=>ys().postprocess_addPass(e,t),removePass(e){ys().postprocess_removePass(e)},setEnabled(e,t){ys().postprocess_setPassEnabled(e,t)},isEnabled:e=>ys().postprocess_isPassEnabled(e),setUniform(e,t,s){ys().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){ys().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){ys().postprocess_begin()},end(){ys().postprocess_end()},getPassCount:()=>ys().postprocess_getPassCount(),isInitialized:()=>!!_s&&_s.postprocess_isInitialized(),setBypass(e){ys().postprocess_setBypass(e)},isBypassed:()=>!_s||_s.postprocess_isBypassed(),createBlur:()=>qe.createShader(xs,"#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:()=>qe.createShader(xs,"#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:()=>qe.createShader(xs,"#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:()=>qe.createShader(xs,"#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")},xs="#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 vs;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(vs||(vs={}));let bs=null,Ss=0;function Ps(e){bs=e,Ss=bs._malloc(64)}function Cs(){bs&&Ss&&(bs._free(Ss),Ss=0),bs=null}const Ts={init(e,t){bs?.renderer_init(e,t)},resize(e,t){bs?.renderer_resize(e,t)},begin(e,t){bs&&Ss&&(bs.HEAPF32.set(e,Ss/4),bs.renderer_begin(Ss,t??0))},flush(){bs?.renderer_flush()},end(){bs?.renderer_end()},submitSprites(e){bs&&bs.renderer_submitSprites(e._cpp)},submitBitmapText(e){bs&&bs.renderer_submitBitmapText(e._cpp)},submitSpine(e){bs&&bs.renderer_submitSpine?.(e._cpp)},setStage(e){bs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>bs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){bs?.renderer_releaseTarget(e)},getTargetTexture:e=>bs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>bs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){bs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){bs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){bs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){bs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>bs?bs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>bs?{drawCalls:bs.renderer_getDrawCalls(),triangles:bs.renderer_getTriangles(),sprites:bs.renderer_getSprites(),text:bs.renderer_getText(),spine:bs.renderer_getSpine?.()??0,meshes:bs.renderer_getMeshes(),culled:bs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Es=null;function Ms(e){Es=e}function As(){Es=null}const Rs={enable(){Es?.gl_enableErrorCheck(!0)},disable(){Es?.gl_enableErrorCheck(!1)},check:e=>Es?.gl_checkErrors(e)??0,diagnose(){Es?.renderer_diagnose()}};class Is{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Ts.resize(n,r),ws.isInitialized()&&ws.getPassCount()>0&&ws.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Ts.setViewport(0,0,n,r),Ts.clearBuffers(3),Ts.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Ts.submitSprites(t),Ts.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Ts.submitSpine(t),Ts.flush(),this.executeDrawCallbacks(s,i),Ts.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Ts.setViewport(n.x,n.y,n.w,n.h),Ts.setScissor(n.x,n.y,n.w,n.h,!0),Ts.clearBuffers(r),Ts.setScissor(0,0,0,0,!1),Ts.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ts.submitSprites(t),Ts.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Ts.submitSpine(t),Ts.flush(),this.executeDrawCallbacks(s,i),Ts.end()}executeDrawCallbacks(e,t){const s=ss;if(s.size>0){Zt.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)}Zt.end();for(const e of n)rs(e)}}}const Fs="__scene_transition_overlay__",ks={r:0,g:0,b:0,a:1};class Bs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Us{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,ee,{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),ns(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=ws.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){ws.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,ee)){const s=this.app_.world.get(e,ee);s.persistent=t,this.app_.world.insert(e,ee,s)}}}class $s{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??.3,r=t.color??ks;t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},ns(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;Zt.setLayer(9999),Zt.setDepth(9999),Zt.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,rs(Fs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,rs(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 Bs(t);this.scenes_.set(e,s);const n=new Us(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(It)?this.app_.getResource(It):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(It)&&(t.assetServer=this.app_.getResource(It));const n=await ut(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ee,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Ds(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 Bs(t);this.scenes_.set(e,s);const n=new Us(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(It)?this.app_.getResource(It):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(It)&&(t.assetServer=this.app_.getResource(It));const n=await ut(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ee,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Ds(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,ee)){if(this.app_.world.get(e,ee).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())rs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{ws.removePass(e)}catch{}s.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=null)}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(t&&"running"===t.status){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,V)){const s=this.app_.world.get(e,V);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,V,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,V)){const s=this.app_.world.get(e,V),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,V,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{ws.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 Ls=ce(null,"SceneManager");function Ds(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Ls).getSceneStatus(t)&&s._fn(...n)}}}const zs=Se([ue(Ls),le(fe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Os={name:"SceneManager",build(e){const t=new $s(e);e.insertResource(Ls,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ls),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(ve.Startup,s),e.addSystemToSchedule(ve.Last,zs)}};class Hs{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,.25);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(ve.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ve.FixedPreUpdate),this.runSchedule(ve.FixedUpdate),this.runSchedule(ve.FixedPostUpdate),n++;n>=8&&(this.fixedAccumulator_=0),this.runSchedule(ve.PreUpdate),this.runSchedule(ve.Update),this.runSchedule(ve.PostUpdate),this.runSchedule(ve.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Le,this.resources_=new de;for(const e of Object.values(ve))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Hs}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}addSystem(e){return this.addSystemToSchedule(ve.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ve.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_}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}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Ls).register(e),this}setInitialScene(e){return this.getResource(Ls).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Me(this.world_,this.resources_),this.resources_.insert(fe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(ve.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,is();const e=[As,Cs,ms,ds,Xe,Jt];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){let t=this.systems_.get(e);if(t&&this.runner_&&!this.frame_paused_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)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(fe);t.delta=e,t.elapsed+=e,t.frameCount++}}function Ws(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const js=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ns(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case W.FixedWidth:return i;case W.FixedHeight:return o;case W.Expand:return Math.max(i,o);case W.Shrink:return Math.min(i,o);case W.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function Vs(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,ee);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let u,h=0,d=0;if(r.projectionType===O.Orthographic){if(d=r.orthoSize,c){d=Ns(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}h=d*a,u=Ys(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Gs(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=Ks(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(Zs(u,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const Xs=new Float32Array(16);function Ys(e,t,s,n,r,i){const o=Xs;o.fill(0);const a=t-e,c=n-s,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+s)/c,o[14]=-(i+r)/l,o[15]=1,o}const qs=new Float32Array(16);function Gs(e,t,s,n){const r=qs;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const Js=new Float32Array(16);function Ks(e,t,s){const n=Js;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 Qs=new Float32Array(16);function Zs(e,t){const s=Qs;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 en,tn,sn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(en||(en={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(tn||(tn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(sn||(sn={}));const nn=R("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:en.Left,verticalAlign:tn.Top,wordWrap:!0,overflow:sn.Visible,lineHeight:1.2}),rn=R("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 on{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(m,m),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):h+2*u,p=r?Math.ceil(o):d+2*u;if(r&&e.overflow===sn.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),g=Math.round(255*e.color.g),m=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${_}, ${g}, ${m}, ${y})`,r&&e.overflow===sn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case tn.Top:x=u;break;case tn.Middle:x=(p-w)/2;break;case tn.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let n;switch(e.align){case en.Left:n=u;break;case en.Center:n=f/2;break;case en.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=l}r&&e.overflow===sn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case en.Left:return"left";case en.Center:return"center";case en.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function an(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 cn(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 ln{build(e){L("Text",nn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new on(t),n=e.world,r=new Map;e.addSystemToSchedule(ve.PreUpdate,Se([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,nn));for(const e of r.keys())n.valid(e)&&n.has(e,nn)||r.delete(e);const e=n.getEntitiesWithComponents([nn]);for(const t of e){const e=n.get(t,nn),i=n.has(t,rn)?n.get(t,rn):null,o=r.get(t);if(o&&!cn(o,e,i))continue;n.has(t,V)||n.insert(t,V,{texture:w,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,i),c=n.get(t,V);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,V,c),r.set(t,an(e,i))}}))}}const un=new ln,hn=R("UIMask",{enabled:!0});function dn(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function fn(e,t,s,n,r,i,o,a,c,l,u){const h=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*u]}const[g,m]=_(h,f),[y,w]=_(d,p),x=Math.min(g,y),v=Math.max(g,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 pn(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],c=e[5],l=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],_=e[12],g=e[13],m=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*u-o*a,b=r*l-i*c,S=r*u-o*c,P=i*u-o*l,C=h*g-d*_,T=h*m-f*_,E=h*y-p*_,M=d*m-f*g,A=d*y-p*g,R=f*y-p*m;let I=w*R-x*A+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*R-l*A+u*M)*I,s[1]=(i*A-r*R-o*M)*I,s[2]=(g*P-m*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*R-u*T)*I,s[5]=(n*R-i*E+o*T)*I,s[6]=(m*v-_*P-y*x)*I,s[7]=(h*P-f*v+p*x)*I,s[8]=(a*A-c*E+u*C)*I,s[9]=(r*E-n*A-o*C)*I,s[10]=(_*S-g*v+y*w)*I,s[11]=(d*v-h*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(g*x-_*b-m*w)*I,s[15]=(h*b-d*x+f*w)*I),s}function _n(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,c=(t-r)/o*2-1,l=s[0]*a+s[4]*c+s[12],u=s[1]*a+s[5]*c+s[13],h=s[3]*a+s[7]*c+s[15];return{x:l/h,y:u/h}}function gn(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function mn(e,t,s,n,r,i,o){if(!e.has(t,rn)||!e.has(t,N))return null;const a=e.get(t,rn),c=e.get(t,N),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return fn(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,s,n,r,i,o)}function yn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([hn]);if(0!==c.length)try{!function(e,t,s,n,r,i,o,a,c){const l=new Set;for(const e of n){t.get(e,hn).enabled&&l.add(e)}const u=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,G);){const e=t.get(n,G);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function h(n,u){const d=e.getChildEntities(s,n);for(const s of d){let n=u;if(l.has(s)){const e=mn(t,s,r,i,o,a,c);e&&(n=dn(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of u){const s=mn(t,e,r,i,o,a,c);s&&h(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class wn{build(e){if(L("UIMask",hn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(yn(e.wasmModule,e.world))}}const xn=new wn,vn=R("Interactable",{enabled:!0}),bn=R("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Sn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Sn||(Sn={}));const Pn=R("Button",{state:Sn.Normal,transition:null});class Cn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const Tn=ce(new Cn,"UIEvents"),En=I("ScreenSpace");function Mn(e,t,s,n,r,i){const o=i.right-i.left,a=i.top-i.bottom,c=i.left+e.x*o,l=i.left+t.x*o,u=i.bottom+e.y*a,h=i.bottom+t.y*a;let d,f,p,_;if(c===l&&u===h){const e=c+s.x,t=u+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=c+s.x,f=u+s.y,p=l+n.x,_=h+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function An(e,t,s,n,r,i){if(!e.has(t,rn))return;const o=e.get(t,rn),a=Mn(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const c=e.get(t,j);if(i?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,j,c),!e.has(t,J))return;const l=e.get(t,J);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&An(e,t,a.rect,a.centerX,a.centerY,!1)}class Rn{build(e){L("UIRect",rn);const t=e.world;e.addSystemToSchedule(ve.PreUpdate,Se([le(De)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([En,rn,j]);for(const e of i)An(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const In=new Rn,Fn=new Float32Array(16),kn=new Float32Array(16);let Bn=!0,Un=1;class $n{build(e){L("Interactable",vn),L("Button",Pn);const t=e.world,s=new Cn;e.insertResource(Tn,s);let n=null,r=null;Un="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(ve.PreUpdate,Se([le(Re),le(De)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([bn]);for(const e of o){const s=t.get(e,bn);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*Un,c=i.screenH-e.mouseY*Un;!function(e){let t=!1;for(let s=0;s<16;s++)if(kn[s]!==e[s]){t=!0;break}t&&(kn.set(e),Bn=!0)}(i.viewProjection),Bn&&(pn(i.viewProjection,Fn),Bn=!1);const l=_n(a,c,Fn,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([vn,rn,N]);let h=null,d=-1/0;for(const e of u){t.has(e,bn)||t.insert(e,bn);if(!t.get(e,vn).enabled)continue;const s=t.get(e,N),n=t.get(e,rn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(gn(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,V)&&(s=t.get(e,V).layer),s>=d&&(d=s,h=e)}}if(n!==h){if(null!==n&&t.valid(n)&&t.has(n,bn)){t.get(n,bn).hovered=!1,s.emit(n,"hover_exit")}if(null!==h){t.get(h,bn).hovered=!0,s.emit(h,"hover_enter")}n=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,bn);e.pressed=!0,e.justPressed=!0,r=h,s.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,bn)){const e=t.get(r,bn);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(ve.Update,Se([],()=>{const e=t.getEntitiesWithComponents([Pn]);for(const s of e){if(t.has(s,vn)||t.insert(s,vn,{enabled:!0}),!t.has(s,bn))continue;const e=t.get(s,bn),n=t.get(s,Pn),r=t.get(s,vn),i=n.state;if(r.enabled?e.pressed?n.state=Sn.Pressed:e.hovered?n.state=Sn.Hovered:n.state=Sn.Normal:n.state=Sn.Disabled,i!==n.state&&n.transition&&t.has(s,V)){const e=t.get(s,V),r=n.transition;switch(n.state){case Sn.Normal:e.color={...r.normalColor};break;case Sn.Hovered:e.color={...r.hoveredColor};break;case Sn.Pressed:e.color={...r.pressedColor};break;case Sn.Disabled:e.color={...r.disabledColor}}t.insert(s,V,e)}}},{name:"ButtonSystem"}))}}const Ln=new $n,Dn=R("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 zn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){L("TextInput",Dn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=h(m,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,u=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||v()},_=()=>{a=!0},g=()=>{a=!1,v()},y=t=>{if(null===o)return;if("Escape"===t.key)return void S();const n=s.get(o,Dn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Tn).emit(o,"submit"),void S()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,P())},x=()=>{if(null!==o&&s.valid(o)&&s.has(o,Dn)){const e=s.get(o,Dn);e.focused=!1,e.dirty=!0}o=null};function v(){if(null===o||!s.valid(o))return;const t=s.get(o,Dn);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(Tn).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,P()}function b(e){if(o===e)return;S();const t=s.get(e,Dn);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),P())}function S(){if(null!==o&&s.valid(o)&&s.has(o,Dn)){const e=s.get(o,Dn);e.focused=!1,e.dirty=!0}o=null,f.blur()}function P(){c=!0,l=0}function C(e,o,a,l){(r.width<a||r.height<l)&&(r.width=Hn(Math.max(r.width,a)),r.height=Hn(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const u=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,i.fillRect(0,0,a,l),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,l),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const h=0===o.value.length,d=h?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=h?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=On(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&c){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=On(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(l-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const g=i.getImageData(0,0,a,l),m=new Uint8Array(g.data.buffer),y=t.getResourceManager(),w=t._malloc(m.length);t.HEAPU8.set(m,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,m.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,V);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,V,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",g),f.addEventListener("keydown",y),f.addEventListener("blur",x),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",g),f.removeEventListener("keydown",y),f.removeEventListener("blur",x),f.remove()},e.addSystemToSchedule(ve.PreUpdate,Se([le(Tn)],e=>{const t=s.getEntitiesWithComponents([Dn,vn]);for(const e of t){if(!s.has(e,bn))continue;if(s.get(e,bn).justPressed)return void b(e)}if(null!==o){const e=s.getEntitiesWithComponents([vn]);for(const t of e){if(s.has(t,Dn))continue;if(!s.has(t,bn))continue;if(s.get(t,bn).justPressed)return void S()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(ve.PreUpdate,Se([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,Dn)))){s.get(o,Dn).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Dn)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Dn,rn]);for(const e of a){const t=s.get(e,Dn);if(!t.dirty)continue;const n=s.get(e,rn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,V)||s.insert(e,V,{texture:w,color:{r:1,g:1,b:1,a:1},size:{x:r,y:i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),C(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function On(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function Hn(e){let t=1;for(;t<e;)t*=2;return t}const Wn=new zn;async function jn(e,t,s){const n=e.getResource(Ls);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Nn(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 Vn=ce({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Xn=ce(null,"PhysicsAPI");function Yn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function qn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Gn{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(Vn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Nn(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([Y]);for(const s of t){const t=e.world.get(s,Y);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(ve.PostUpdate,Se([le(fe)],a=>{const c=o.getEntitiesWithComponents([se,j,N]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,se),c=o.get(r,N);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=Yn(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Jn(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===oe.Kinematic){const e=Yn(c.rotation);n._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const u=e.world.get(o,j);if(!u)continue;let h=a,d=c,f=l;if(e.world.has(o,G)){const t=e.world.get(o,G);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,N)){const s=e.world.get(t.entity,N),n=Yn(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),u=Math.sin(-n);h=(r*o-i*u)/(0!==s.scale.x?s.scale.x:1),d=(r*u+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}u.position.x=h,u.position.y=d;const p=qn(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,j,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<o;s++){const n=e+2*s;i.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<c;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Vn,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Xn,Kn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Jn(e,t,s){const n=e.world;if(n.has(s,ne)){const e=n.get(s,ne);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,re)){const e=n.get(s,re);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,ie)){const e=n.get(s,ie);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 Kn{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(Kn.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 Qn(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function Zn(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 er(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,h=a+a,d=c+c,f=l+l,p=a*h,_=a*d,g=a*f,m=c*d,y=c*f,w=l*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(m+w))*r,(_+b)*r,(g-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(g+v)*o,(y-x)*o,(1-(p+m))*o,0,e.position.x,e.position.y,e.position.z,1])}async function tr(e,t,s,n,r,i,o,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=Qn(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let u={},h=null;if(r&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===wt(c)?.contentType;let h,d;if(u){const e=await r.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const f=s.loadSkeleton(h,d,n,n.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=Zn(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=Qn(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,h,s,n)),i){new Gn("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=wt(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${o}`:o;t=await s.readText(c),i=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=i?`${i}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),u=Qn(e,l,!1),h=e.getResourceManager();n[r]=h.loadBitmapFont(t,u,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=qe.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=qe.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=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,l,d,f);const p=lt(e.world,s);if(c&&e.hasResource(Ls))for(const t of p.values())e.world.insert(t,ee,{scene:c,persistent:!1});if(r&&h){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=n.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(h,s,u,p);!function(e,t,s,n,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,Q)?l.get(i,Q):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(o,c*h);let d=0;if(l.has(i,N)){const e=er(l.get(i,N),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=s._malloc(a),u=s._malloc(c),h=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,u,h,f);const p=s.HEAPU32[h>>2],_=s.HEAPU32[f>>2],g=new Float32Array(s.HEAPF32.buffer,l,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(m),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(u),s._free(h),s._free(f)}d&&t._free(d)}})}(e,t,r,h,n)}if(a){const t=e.getResource(It);t&&t.setAddressableManifest(a)}}function sr(e,t,s){return{name:e,data:t,async setup(){await tr(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class nr{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"===wt(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=wt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||i.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}i.length>0&&await Promise.all(i)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const rr="__preview__";class ir{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(Ls);t.register({name:rr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(rr),this.loadPromise_=t.load(rr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new nr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await tr(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,rr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([X]);for(const n of s){if(e.get(n,X).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([Y]);for(const r of n){const n=e.get(r,Y);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(Ls).getScene(rr),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,j,o);const a={isActive:!0,projectionType:O.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:H.ColorAndDepth};e.insert(i,X,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(Ls);await e.switchTo(rr),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 or={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ts.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ts.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ts.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ts.releaseRenderTarget(e._handle),or.create({width:t,height:s,depth:!0})),begin(e,t){Ts.begin(t,e._handle)},end(){Ts.end()},getDepthTexture:e=>Ts.getTargetDepthTexture(e._handle)};let ar=!1;function cr(e){ar=e}function lr(){return ar}function ur(){return!ar}var hr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(hr||(hr={}));class dr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${hr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case hr.Debug:console.debug(t,s);break;case hr.Info:console.log(t,s);break;case hr.Warn:console.warn(t,s);break;case hr.Error:console.error(t,s)}}}class fr{constructor(){this.handlers_=[],this.minLevel_=hr.Info,this.addHandler(new dr)}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(hr.Debug,e,t,s)}info(e,t,s){this.log(hr.Info,e,t,s)}warn(e,t,s){this.log(hr.Warn,e,t,s)}error(e,t,s){this.log(hr.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 pr=new fr;function _r(){return pr}function gr(e){pr.setMinLevel(e)}function mr(e,t,s){pr.debug(e,t,s)}function yr(e,t,s){pr.info(e,t,s)}function wr(e,t,s){pr.warn(e,t,s)}function xr(e,t,s){pr.error(e,t,s)}const vr=[un,xn,In,Ln,Wn];function br(e,t){return function(e,t){const s=Hs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Gt(e),Ve(e),hs(e),gs(e),Ps(e),Ms(e);const r=new Is;s.pipeline_=r;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=Vs(e,n,t,r));const o=s.getResource(De);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}s.insertResource(De,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=o();if(0===t||0===c)return;const l=e.registry_getCanvasEntity(n);if(l>=0){const e=n.getCanvas(l).backgroundColor;Ts.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-i)/1e3;let h;if(Ts.resize(t,c),ws.isInitialized()&&ws.getPassCount()>0&&!ws.isBypassed()&&ws.resize(t,c),s.hasResource(Ls)){const e=s.getResource(Ls).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=Vs(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:js,width:t,height:c,elapsed:u});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:l},clearFlags:e.clearFlags,elapsed:u})}Ts.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(ve.First,c),s.addSystemToSchedule(ve.Last,l),s.addPlugin(kt),s.addPlugin(jt),s.addPlugin(Fe),s.addPlugin(Os),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:vr,...t})}e=f;export{Hs as App,Ft as AssetPlugin,Bt as AssetRefCounter,Rt as AssetServer,It as Assets,nt as AsyncCache,K as BitmapText,ze as BlendMode,oe as BodyType,ne as BoxCollider,Pn as Button,Sn as ButtonState,X as Camera,Y as Canvas,ie as CapsuleCollider,J as Children,re as CircleCollider,H as ClearFlags,ye as Commands,xe as CommandsInstance,_ as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,g as DEFAULT_PIXELS_PER_UNIT,m as DEFAULT_TEXT_CANVAS_SIZE,os as DataType,Zt as Draw,we as EntityCommands,Rs as GLDebug,ps as Geometry,y as INVALID_ENTITY,x as INVALID_FONT,w as INVALID_TEXTURE,Re as Input,Ie as InputPlugin,Ae as InputState,vn as Interactable,j as LocalTransform,hr as LogLevel,fr as Logger,qe as Material,rt as MaterialLoader,pe as Mut,Z as Name,G as Parent,Kn as Physics,Vn as PhysicsEvents,Gn as PhysicsPlugin,ws as PostProcess,Ot as PrefabServer,Ht as Prefabs,Wt as PrefabsPlugin,ir as PreviewPlugin,O as ProjectionType,ge as Query,me as QueryInstance,Is as RenderPipeline,vs as RenderStage,or as RenderTexture,Ts as Renderer,le as Res,ue as ResMut,se as RigidBody,W as ScaleMode,Ls as SceneManager,$s as SceneManagerState,ee as SceneOwner,ve as Schedule,En as ScreenSpace,st as ShaderSources,Q as SpineAnimation,V as Sprite,Me as SystemRunner,nn as Text,en as TextAlign,Dn as TextInput,zn as TextInputPlugin,sn as TextOverflow,ln as TextPlugin,on as TextRenderer,tn as TextVerticalAlign,fe as Time,De as UICameraInfo,Cn as UIEventQueue,Tn as UIEvents,bn as UIInteraction,$n as UIInteractionPlugin,Rn as UILayoutPlugin,hn as UIMask,wn as UIMaskPlugin,rn as UIRect,q as Velocity,nr as WebAssetProvider,Le as World,N as WorldTransform,Te as addStartupSystem,Ce as addSystem,Ee as addSystemToSchedule,kt as assetPlugin,is as clearDrawCallbacks,k as clearUserComponents,P as color,Mn as computeUIRectLayout,yn as createMaskProcessor,sr as createRuntimeSceneConfig,br as createWebApp,mr as debug,R as defineComponent,ce as defineResource,Se as defineSystem,I as defineTag,xr as error,ft as findEntityByName,Ws as flushPendingSystems,vt as getAddressableType,bt as getAddressableTypeByEditorType,Pt as getAllAssetExtensions,Mt as getAssetMimeType,wt as getAssetTypeEntry,D as getComponent,at as getComponentAssetFields,te as getComponentDefaults,Tt as getCustomExtensions,xt as getEditorType,_r as getLogger,t as getPlatform,n as getPlatformType,F as getUserComponent,Et as getWeChatPackOptions,yr as info,Gt as initDrawAPI,Ms as initGLDebugAPI,hs as initGeometryAPI,Ve as initMaterialAPI,gs as initPostProcessAPI,Ps as initRendererAPI,Fe as inputPlugin,$t as instantiatePrefab,dn as intersectRects,pn as invertMatrix4,U as isBuiltinComponent,At as isCustomExtension,lr as isEditor,St as isKnownAssetExtension,s as isPlatformInitialized,ur as isRuntime,Oe as isTextureRef,r as isWeChat,i as isWeb,ht as loadComponent,Nn as loadPhysicsModule,tr as loadRuntimeScene,lt as loadSceneData,ut as loadSceneWithAssets,Ct as looksLikeAssetPath,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,gn as pointInWorldRect,jt as prefabsPlugin,C as quat,L as registerComponent,ot as registerComponentAssetFields,ns as registerDrawCallback,Ut as registerEmbeddedAssets,tt as registerMaterialCallback,Os as sceneManagerPlugin,_n as screenToWorld,cr as setEditorMode,gr as setLogLevel,Jt as shutdownDrawAPI,As as shutdownGLDebugAPI,ds as shutdownGeometryAPI,Xe as shutdownMaterialAPI,ms as shutdownPostProcessAPI,Cs as shutdownRendererAPI,Wn as textInputPlugin,un as textPlugin,jn as transitionTo,Ln as uiInteractionPlugin,In as uiLayoutPlugin,xn as uiMaskPlugin,vr as uiPlugins,rs as unregisterDrawCallback,dt as updateCameraAspectRatio,v as vec2,b as vec3,S as vec4,wr as warn,fn as worldRectToScreen,Ds as wrapSceneSystem};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return null!==e}function n(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,s){return t().instantiateWasm(e,s)}function h(e,s){return t().createCanvas(e,s)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const s=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),n={};return s.headers.forEach((e,t)=>{n[t]=e}),{ok:s.ok,status:s.status,statusText:s.statusText,headers:n,json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let s;s="string"==typeof e?await this.readFile(e):e;const n=await WebAssembly.instantiate(s,t);return{instance:n.instance,module:n.module}}createImage(){return new Image}createCanvas(e,t){let s;return s="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),s.width=e,s.height=t,s}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t??document.querySelector("canvas")??document.body,n=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),i=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},o=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},u=()=>{e.onPointerUp(0)},h=t=>{const s=t;e.onWheel(s.deltaX,s.deltaY)};document.addEventListener("keydown",n),document.addEventListener("keyup",r),s.addEventListener("mousemove",i),s.addEventListener("mousedown",o),s.addEventListener("mouseup",a),s.addEventListener("touchstart",l),s.addEventListener("touchmove",c),s.addEventListener("touchend",u),s.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",r),s.removeEventListener("mousemove",i),s.removeEventListener("mousedown",o),s.removeEventListener("mouseup",a),s.removeEventListener("touchstart",l),s.removeEventListener("touchmove",c),s.removeEventListener("touchend",u),s.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,_=1080,m=100,g=512,y={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function w(e){e.Text&&(e.Text._default.fontFamily=y.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=y.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=y.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=y.canvasMatchWidthOrHeight)}const x=0,v=4294967295,b=4294967295,S=(e=0,t=0)=>({x:e,y:t}),P=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),C=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),T=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),E=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function M(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(M);const t={};for(const s in e)t[s]=M(e[s]);return t}let A=0;function R(e,t){const s=++A;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...M(t),...e}:M(t)}}function I(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const s=I(),n=s.get(e);if(n)return n;const r=R(e,t);return s.set(e,r),$(e,t,!1),r}function k(e){const t=I(),s=t.get(e);if(s)return s;const n=R(e,{});return t.set(e,n),$(e,{},!0),n}function B(e){return I().get(e)}function U(){I().clear()}function $(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function D(e){return!0===e._builtin}const z=new Map;function L(e,t){z.set(e,t)}function O(e){return z.get(e)??B(e)}function H(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return z.set(e,s),s}const W={Perspective:0,Orthographic:1},j={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},N={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},V=H("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),X=H("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Y=H("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),q=H("Camera",{projectionType:W.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:j.ColorAndDepth}),G=H("Canvas",{designResolution:{x:p,y:_},pixelsPerUnit:100,scaleMode:N.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),J=H("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),K=H("Parent",{entity:0}),Q=H("Children",{entities:[]}),Z=H("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:b}),ee=H("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),te={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},se=F("SceneOwner",{scene:"",persistent:!1});function ne(e){const t=O(e);return t?M(t._default):null}L("Name",te);const re=H("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ie=H("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),oe=H("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ae=H("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),le={Static:0,Kinematic:1,Dynamic:2};let ce=0;function ue(e,t){const s=++ce;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function he(e){return{_type:"res",_resource:e}}function de(e){return{_type:"res_mut",_resource:e}}class fe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class pe{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new fe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const _e=ue({delta:0,elapsed:0,frameCount:0},"Time");function me(e){return{_type:"mut",_component:e}}function ge(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function ye(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{ge(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class we{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ge(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,l=this.mutData_,c=l.length;let u=null;this.world_.beginIteration();try{for(const h of n){if(null!==u&&i)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(h,t[s])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<r;e++)a[e+1]=this.world_.get(h,s[e]);if(i){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=h}yield a}}finally{if(this.world_.endIteration(),null!==u&&i)for(let e=0;e<c;e++){const t=l[e];this.world_.insert(u,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function xe(){return{_type:"commands"}}class ve{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class be{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ve(this,null);return this.spawned_.push(e),e}entity(e){return new ve(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Se;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(Se||(Se={}));let Pe=0;function Ce(e,t,s){const n=++Pe;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Te(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ee(e){Te().push({schedule:Se.Update,system:e})}function Me(e){Te().push({schedule:Se.Startup,system:e})}function Ae(e,t){Te().push({schedule:e,system:t})}class Re{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof be&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new we(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new be(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Fe=ue(new Ie,"Input");class ke{constructor(e){this.target_=e??null}build(e){const s=new Ie;e.insertResource(Fe,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Se.Last,Ce([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Be=new ke;function Ue(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=$e(t[e]),i=$e(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function $e(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")}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 Le{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;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,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.");this.cppRegistry_&&this.cppRegistry_.destroy(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){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return D(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(D(t)){if(!this.cppRegistry_)return null;const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Ue(t._name,t._default,n);if(e.length>0)throw new Error(De(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,ze(r)),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");return this.getBuiltinMethods(t._cppName).get(e)}hasBuiltin(e,t){return!!this.cppRegistry_&&this.getBuiltinMethods(t._cppName).has(e)}removeBuiltin(e,t){this.cppRegistry_&&this.getBuiltinMethods(t._cppName).remove(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=Ue(t._name,t._default,e);if(r.length>0)throw new Error(De(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!D(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const l=i?i.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=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 He;function We(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"}(He||(He={}));let je=null,Ne=null,Ve=1;const Xe=new Map;function Ye(e){je=e,Ne=e.getResourceManager(),nt()}function qe(){0!==Qe&&je&&(je._free(Qe),Qe=0),Xe.clear(),Ve=1,Ke=!1,et.clear(),tt=null,Ne=null,je=null}function Ge(){if(!Ne)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ne}const Je={createShader:(e,t)=>Ge().createShader(e,t),releaseShader(e){e>0&&Ge().releaseShader(e)},create(e){const t=Ve++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??He.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 Xe.set(t,s),t},get:e=>Xe.get(e),setUniform(e,t,s){const n=Xe.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Xe.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Xe.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Xe.get(e);return t?.blendMode??He.Normal},setDepthTest(e,t){const s=Xe.get(e);s&&(s.depthTest=t)},getShader(e){const t=Xe.get(e);return t?.shader??0},release(e){Xe.delete(e)},isValid:e=>Xe.has(e),releaseAll(){Xe.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??He.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Xe.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 Xe.set(s,n),s},toAssetData(e,t){const s=Xe.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=Xe.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ke=!1,Qe=0;const Ze=4096,et=new Map;let tt=null;function st(e){const t=(0===Qe&&je&&(Qe=je._malloc(Ze)),Qe);if(0===t||!je)return{ptr:0,count:0};let s=0,n=0;const r=je.HEAPU8,i=je.HEAPU32,o=je.HEAPF32;for(const[a,l]of e){if(s+128>Ze)break;let e=et.get(a);e||(tt||(tt=new TextEncoder),e=tt.encode(a),et.set(a,e));const c=e.length,u=4*Math.ceil(c/4);i[t+s>>2]=c,s+=4,r.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);i[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function nt(){if(!je||Ke)return;je.materialDataProvider=(e,t,s,n,r)=>{const i=Xe.get(e);if(!i)return je.HEAPU32[t>>2]=0,je.HEAPU32[s>>2]=0,je.HEAPU32[n>>2]=0,void(je.HEAPU32[r>>2]=0);je.HEAPU32[t>>2]=i.shader,je.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=st(i.uniforms);je.HEAPU32[n>>2]=o,je.HEAPU32[r>>2]=a},Ke=!0}const rt={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 i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class ot{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&&(Je.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Je.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 s=await l(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:Je.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const at=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function lt(e,t){at.set(e,t)}function ct(e){const t=at.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function ut(e){return at.get(e)?.fields??[]}function ht(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,te,{value:n.name}),!1!==n.visible)for(const s of n.components)ft(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 dt(e,t,s){const n=new Map,r=s?.assetServer,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=at.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":i.add(t);break;case"font":o.add(t)}}}const c=new Map,u=new Map,h=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);c.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);h.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),h.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=at.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]=u.get(t)??0;break;case"font":s[e.field]=h.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,te,{value:s.name}),!1!==s.visible)for(const n of s.components)ft(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function ft(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=O(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function pt(e,t){const s=e.getEntitiesWithComponents([q]);for(const n of s){const s=e.get(n,q);s&&(s.aspectRatio=t,e.insert(n,q,s))}}function _t(e,t){const s=e.getEntitiesWithComponents([te]);for(const n of s){const s=e.get(n,te);if(s&&s.value===t)return n}return null}const mt=[{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}],gt={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"},yt=new Map,wt=new Set;for(const e of mt)for(const t of e.extensions)yt.set(t,e),wt.add(t);function xt(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function vt(e){return yt.get(xt(e))}function bt(e){return vt(e)?.editorType??"unknown"}function St(e){return vt(e)?.addressableType??null}function Pt(e){for(const t of mt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Ct(e){return wt.has(e.toLowerCase())}function Tt(){return wt}function Et(e){return"string"==typeof e&&(!!e.includes("/")&&Ct(xt(e)))}function Mt(){const e=[];for(const t of mt)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function At(){return Mt().map(e=>({type:"suffix",value:e}))}function Rt(e){return gt[e.toLowerCase()]}function It(e){const t=vt(e);return t?.wechatPackInclude??!1}class Ft{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_=h(y.textCanvasSize,y.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new ot(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,i)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Je.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),l=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),u="binary"===vt(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(h,i,u);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=vt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return dt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const l=o.createTexture(t,s,a,i.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 Je.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return Je.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await l(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const kt=ue(null,"Assets");class Bt{build(e){const t=e.wasmModule;t?e.insertResource(kt,new Ft(t)):console.warn("AssetPlugin: No WASM module available")}}const Ut=new Bt;class $t{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Dt(e,t){const s=e.getResource(kt);s&&s.registerEmbeddedAssets(t)}async function zt(e,t,s){const{entities:n,rootId:r}=await Ot(t,s?.overrides??[],s,void 0,new Set),i={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await dt(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const Lt=10;async function Ot(e,t,s,n,r,i=0){if(i>Lt)throw new Error(`Prefab nesting depth exceeded ${Lt}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const 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 Ot(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?o.get(n.parent)??null:null),l.push(...t.entities);continue}const c=o.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Ht(h,t),l.push(h)}const c=o.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Ht(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 Wt{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 zt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const jt=ue(null,"Prefabs");class Nt{constructor(){this.name="PrefabsPlugin",this.dependencies=[kt]}build(e){const t=e.getResource(kt);e.insertResource(jt,new Wt(e.world,t))}}const Vt=new Nt;let Xt=null,Yt=0,qt=0,Gt=0;const Jt=new Float32Array(256);function Kt(e){Xt=e,Yt=Xt._malloc(64),qt=Xt._malloc(64),Gt=Xt._malloc(1024)}function Qt(){Xt&&(Yt&&(Xt._free(Yt),Yt=0),qt&&(Xt._free(qt),qt=0),Gt&&(Xt._free(Gt),Gt=0)),Xt=null}function Zt(){if(!Xt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Xt}const es={r:1,g:1,b:1,a:1},ts={begin(e){const t=Zt();t.HEAPF32.set(e,Yt/4),t.draw_begin(Yt)},end(){Zt().draw_end()},line(e,t,s,n=1){Zt().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rect(e,t,s,n=!0){Zt().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},rectOutline(e,t,s,n=1){Zt().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)},circle(e,t,s,n=!0,r=32){Zt().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},circleOutline(e,t,s,n=1,r=32){Zt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=es){Zt().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)},textureRotated(e,t,s,n,r=es){Zt().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){Zt().draw_setLayer(e)},setDepth(e){Zt().draw_setDepth(e)},getDrawCallCount:()=>Xt?Xt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Xt?Xt.draw_getPrimitiveCount():0,setBlendMode(e){Zt().draw_setBlendMode(e)},setDepthTest(e){Zt().draw_setDepthTest(e)},drawMesh(e,t,s){const n=Zt();n.HEAPF32.set(s,qt/4),n.draw_mesh(e,t,qt)},drawMeshWithMaterial(e,t,s){const n=Zt(),r=Je.get(t);if(!r)return;if(ts.setBlendMode(r.blendMode),ts.setDepthTest(r.depthTest),0===r.uniforms.size)return void ts.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,qt/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=ns(t);if(!(n<0)){if(We(s))Jt[i++]=10,Jt[i++]=n,Jt[i++]=s.slot??e++,Jt[i++]=s.textureId;else if("number"==typeof s)Jt[i++]=1,Jt[i++]=n,Jt[i++]=s;else if(Array.isArray(s)){Jt[i++]=s.length,Jt[i++]=n;for(let e=0;e<s.length;e++)Jt[i++]=s[e]}else"w"in s?(Jt[i++]=4,Jt[i++]=n,Jt[i++]=s.x,Jt[i++]=s.y,Jt[i++]=s.z,Jt[i++]=s.w):"z"in s?(Jt[i++]=3,Jt[i++]=n,Jt[i++]=s.x,Jt[i++]=s.y,Jt[i++]=s.z):(Jt[i++]=2,Jt[i++]=n,Jt[i++]=s.x,Jt[i++]=s.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<i)&&(r.cachedBuffer_=new Float32Array(i)),r.cachedBuffer_.set(Jt.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}0!==i?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),Gt/4),n.draw_meshWithUniforms(e,r.shader,qt,Gt,i)):n.draw_mesh(e,r.shader,qt)}},ss={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};function ns(e){return ss[e]??-1}const rs=new Map;function is(e,t,s){rs.set(e,{fn:t,scene:s??""})}function os(e){rs.delete(e)}function as(){rs.clear()}var ls;!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"}(ls||(ls={}));let cs=null,us=0,hs=0,ds=0;function fs(e){cs=e,us=cs._malloc(262144),hs=cs._malloc(65536),ds=cs._malloc(256)}function ps(){cs&&(us&&cs._free(us),hs&&cs._free(hs),ds&&cs._free(ds),us=0,hs=0,ds=0),cs=null}function _s(){if(!cs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return cs}const ms={create(e){const t=_s(),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,us/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,ds,r).set(i),t.geometry_init(s,us,n,ds,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,hs,n).set(e.indices),t.geometry_setIndices16(s,hs,n)}else{new Uint32Array(t.HEAPU8.buffer,hs,n).set(e.indices),t.geometry_setIndices32(s,hs,n)}}return s},updateVertices(e,t,s=0){const n=_s(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,us/4),n.geometry_updateVertices(e,us,r,s)},release(e){e>0&&_s().geometry_release(e)},isValid:e=>!(!cs||e<=0)&&cs.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return ms.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:ls.Float2},{name:"a_texCoord",type:ls.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(i,o,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return ms.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:ls.Float2},{name:"a_texCoord",type:ls.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return ms.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:ls.Float2},{name:"a_texCoord",type:ls.Float2}],indices:new Uint16Array(o)})}};let gs=null;function ys(e){gs=e}function ws(){gs&&vs.isInitialized()&&vs.shutdown(),gs=null}function xs(){if(!gs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return gs}const vs={init:(e,t)=>xs().postprocess_init(e,t),shutdown(){xs().postprocess_shutdown()},resize(e,t){xs().postprocess_resize(e,t)},addPass:(e,t)=>xs().postprocess_addPass(e,t),removePass(e){xs().postprocess_removePass(e)},setEnabled(e,t){xs().postprocess_setPassEnabled(e,t)},isEnabled:e=>xs().postprocess_isPassEnabled(e),setUniform(e,t,s){xs().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){xs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){xs().postprocess_begin()},end(){xs().postprocess_end()},getPassCount:()=>xs().postprocess_getPassCount(),isInitialized:()=>!!gs&&gs.postprocess_isInitialized(),setBypass(e){xs().postprocess_setBypass(e)},isBypassed:()=>!gs||gs.postprocess_isBypassed(),createBlur:()=>Je.createShader(bs,"#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:()=>Je.createShader(bs,"#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:()=>Je.createShader(bs,"#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:()=>Je.createShader(bs,"#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")},bs="#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 Ss;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ss||(Ss={}));let Ps=null,Cs=0;function Ts(e){Ps=e,Cs=Ps._malloc(64)}function Es(){Ps&&Cs&&(Ps._free(Cs),Cs=0),Ps=null}const Ms={init(e,t){Ps?.renderer_init(e,t)},resize(e,t){Ps?.renderer_resize(e,t)},begin(e,t){Ps&&Cs&&(Ps.HEAPF32.set(e,Cs/4),Ps.renderer_begin(Cs,t??0))},flush(){Ps?.renderer_flush()},end(){Ps?.renderer_end()},submitSprites(e){Ps&&Ps.renderer_submitSprites(e._cpp)},submitBitmapText(e){Ps&&Ps.renderer_submitBitmapText(e._cpp)},submitSpine(e){Ps&&Ps.renderer_submitSpine?.(e._cpp)},setStage(e){Ps?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Ps?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Ps?.renderer_releaseTarget(e)},getTargetTexture:e=>Ps?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ps?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Ps?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Ps?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Ps?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Ps?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Ps?Ps.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Ps?{drawCalls:Ps.renderer_getDrawCalls(),triangles:Ps.renderer_getTriangles(),sprites:Ps.renderer_getSprites(),text:Ps.renderer_getText(),spine:Ps.renderer_getSpine?.()??0,meshes:Ps.renderer_getMeshes(),culled:Ps.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let As=null;function Rs(e){As=e}function Is(){As=null}const Fs={enable(){As?.gl_enableErrorCheck(!0)},disable(){As?.gl_enableErrorCheck(!1)},check:e=>As?.gl_checkErrors(e)??0,diagnose(){As?.renderer_diagnose()}};class ks{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Ms.resize(n,r),vs.isInitialized()&&vs.getPassCount()>0&&vs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Ms.setViewport(0,0,n,r),Ms.clearBuffers(3),Ms.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Ms.submitSprites(t),Ms.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Ms.submitSpine(t),Ms.flush(),this.executeDrawCallbacks(s,i),Ms.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Ms.setViewport(n.x,n.y,n.w,n.h),Ms.setScissor(n.x,n.y,n.w,n.h,!0),Ms.clearBuffers(r),Ms.setScissor(0,0,0,0,!1),Ms.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ms.submitSprites(t),Ms.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Ms.submitSpine(t),Ms.flush(),this.executeDrawCallbacks(s,i),Ms.end()}executeDrawCallbacks(e,t){const s=rs;if(s.size>0){ts.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)}ts.end();for(const e of n)os(e)}}}const Bs="__scene_transition_overlay__";class Us{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class $s{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),is(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=vs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){vs.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,se)){const s=this.app_.world.get(e,se);s.persistent=t,this.app_.world.insert(e,se,s)}}}class Ds{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??y.sceneTransitionDuration,r=t.color??{...y.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},is(Bs,()=>{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;ts.setLayer(9999),ts.setDepth(9999),ts.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,os(Bs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,os(Bs),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 Us(t);this.scenes_.set(e,s);const n=new $s(s,this.app_);this.contexts_.set(e,n);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 n=await dt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Ls(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 Us(t);this.scenes_.set(e,s);const n=new $s(s,this.app_);this.contexts_.set(e,n);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 n=await dt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=Ls(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,se)){if(this.app_.world.get(e,se).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())os(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{vs.removePass(e)}catch{}s.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=null)}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(t&&"running"===t.status){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Y,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Y,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{vs.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 zs=ue(null,"SceneManager");function Ls(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(zs).getSceneStatus(t)&&s._fn(...n)}}}const Os=Ce([de(zs),he(_e)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Hs={name:"SceneManager",build(e){const t=new Ds(e);e.insertResource(zs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(zs),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Se.Startup,s),e.addSystemToSchedule(Se.Last,Os)}};class Ws{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.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Se.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Se.FixedPreUpdate),this.runSchedule(Se.FixedUpdate),this.runSchedule(Se.FixedPostUpdate),n++;n>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Se.PreUpdate),this.runSchedule(Se.Update),this.runSchedule(Se.PostUpdate),this.runSchedule(Se.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Le,this.resources_=new pe;for(const e of Object.values(Se))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ws}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}addSystem(e){return this.addSystemToSchedule(Se.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Se.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}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}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(zs).register(e),this}setInitialScene(e){return this.getResource(zs).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Re(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Se.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,as();const e=[Is,Es,ws,ps,qe,Qt];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){let t=this.systems_.get(e);if(t&&this.runner_&&!this.frame_paused_){t.some(e=>e.runBefore||e.runAfter)&&(t=this.sortSystems(t));for(const e of t)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}function js(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const Ns=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Vs(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case N.FixedWidth:return i;case N.FixedHeight:return o;case N.Expand:return Math.max(i,o);case N.Shrink:return Math.min(i,o);case N.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function Xs(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,se);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const 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),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let u,h=0,d=0;if(r.projectionType===W.Orthographic){if(d=r.orthoSize,l){d=Vs(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}h=d*a,u=qs(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Js(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=Qs(i.position.x,i.position.y,i.position.z);c.push({entity:e,viewProjection:new Float32Array(en(u,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return c.sort((e,t)=>e.priority-t.priority),c}const Ys=new Float32Array(16);function qs(e,t,s,n,r,i){const o=Ys;o.fill(0);const a=t-e,l=n-s,c=i-r;return o[0]=2/a,o[5]=2/l,o[10]=-2/c,o[12]=-(t+e)/a,o[13]=-(n+s)/l,o[14]=-(i+r)/c,o[15]=1,o}const Gs=new Float32Array(16);function Js(e,t,s,n){const r=Gs;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const Ks=new Float32Array(16);function Qs(e,t,s){const n=Ks;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 Zs=new Float32Array(16);function en(e,t){const s=Zs;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 tn,sn,nn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(tn||(tn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(sn||(sn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(nn||(nn={}));const rn=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:tn.Left,verticalAlign:sn.Top,wordWrap:!0,overflow:nn.Visible,lineHeight:1.2}),on=F("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class an{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(y.textCanvasSize,y.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?i:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=r?Math.ceil(i):h+2*u,p=r?Math.ceil(o):d+2*u;if(r&&e.overflow===nn.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,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${_}, ${m}, ${g}, ${y})`,r&&e.overflow===nn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case sn.Top:x=u;break;case sn.Middle:x=(p-w)/2;break;case sn.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of l){let n;switch(e.align){case tn.Left:n=u;break;case tn.Center:n=f/2;break;case tn.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=c}r&&e.overflow===nn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case tn.Left:return"left";case tn.Center:return"center";case tn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function ln(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 cn(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 un{build(e){L("Text",rn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new an(t),n=e.world,r=new Map;e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,rn));for(const e of r.keys())n.valid(e)&&n.has(e,rn)||r.delete(e);const e=n.getEntitiesWithComponents([rn]);for(const t of e){const e=n.get(t,rn),i=n.has(t,on)?n.get(t,on):null,o=r.get(t);if(o&&!cn(o,e,i))continue;n.has(t,Y)||n.insert(t,Y,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,i),l=n.get(t,Y);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,Y,l),r.set(t,ln(e,i))}}))}}const hn=new un,dn=F("UIMask",{enabled:!0});function fn(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function pn(e,t,s,n,r,i,o,a,l,c,u){const h=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*c,l+(.5*(n/r)+.5)*u]}const[m,g]=_(h,f),[y,w]=_(d,p),x=Math.min(m,y),v=Math.max(m,y),b=Math.min(g,w),S=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function _n(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],_=e[12],m=e[13],g=e[14],y=e[15],w=n*l-r*a,x=n*c-i*a,v=n*u-o*a,b=r*c-i*l,S=r*u-o*l,P=i*u-o*c,C=h*m-d*_,T=h*g-f*_,E=h*y-p*_,M=d*g-f*m,A=d*y-p*m,R=f*y-p*g;let I=w*R-x*A+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(l*R-c*A+u*M)*I,s[1]=(i*A-r*R-o*M)*I,s[2]=(m*P-g*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(c*E-a*R-u*T)*I,s[5]=(n*R-i*E+o*T)*I,s[6]=(g*v-_*P-y*x)*I,s[7]=(h*P-f*v+p*x)*I,s[8]=(a*A-l*E+u*C)*I,s[9]=(r*E-n*A-o*C)*I,s[10]=(_*S-m*v+y*w)*I,s[11]=(d*v-h*S-p*w)*I,s[12]=(l*T-a*M-c*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(m*x-_*b-g*w)*I,s[15]=(h*b-d*x+f*w)*I),s}function mn(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,l=(t-r)/o*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],h=s[3]*a+s[7]*l+s[15];return{x:c/h,y:u/h}}function gn(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function yn(e,t,s,n,r,i,o){if(!e.has(t,on)||!e.has(t,X))return null;const a=e.get(t,on),l=e.get(t,X),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return pn(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,i,o)}function wn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([dn]);if(0!==l.length)try{!function(e,t,s,n,r,i,o,a,l){const c=new Set;for(const e of n){t.get(e,dn).enabled&&c.add(e)}const u=[];for(const e of n){if(!c.has(e))continue;let s=!0,n=e;for(;t.has(n,K);){const e=t.get(n,K);if(c.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function h(n,u){const d=e.getChildEntities(s,n);for(const s of d){let n=u;if(c.has(s)){const e=yn(t,s,r,i,o,a,l);e&&(n=fn(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of u){const s=yn(t,e,r,i,o,a,l);s&&h(e,s)}}(e,t,s,l,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class xn{build(e){if(L("UIMask",dn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(wn(e.wasmModule,e.world))}}const vn=new xn,bn=F("Interactable",{enabled:!0}),Sn=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Pn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Pn||(Pn={}));const Cn=F("Button",{state:Pn.Normal,transition:null});class Tn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const En=ue(new Tn,"UIEvents"),Mn=k("ScreenSpace");function An(e,t,s,n,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,u=i.bottom+e.y*a,h=i.bottom+t.y*a;let d,f,p,_;if(l===c&&u===h){const e=l+s.x,t=u+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=l+s.x,f=u+s.y,p=c+n.x,_=h+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function Rn(e,t,s,n,r,i){if(!e.has(t,on))return;const o=e.get(t,on),a=An(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const l=e.get(t,V);if(i?(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,V,l),!e.has(t,Q))return;const c=e.get(t,Q);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Rn(e,t,a.rect,a.centerX,a.centerY,!1)}class In{build(e){L("UIRect",on);const t=e.world;e.addSystemToSchedule(Se.PreUpdate,Ce([he(Oe)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([Mn,on,V]);for(const e of i)Rn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Fn=new In,kn=new Float32Array(16),Bn=new Float32Array(16);let Un=!0,$n=1;class Dn{build(e){L("Interactable",bn),L("Button",Cn);const t=e.world,s=new Tn;e.insertResource(En,s);let n=null,r=null;$n="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Se.PreUpdate,Ce([he(Fe),he(Oe)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([Sn]);for(const e of o){const s=t.get(e,Sn);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*$n,l=i.screenH-e.mouseY*$n;!function(e){let t=!1;for(let s=0;s<16;s++)if(Bn[s]!==e[s]){t=!0;break}t&&(Bn.set(e),Un=!0)}(i.viewProjection),Un&&(_n(i.viewProjection,kn),Un=!1);const c=mn(a,l,kn,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([bn,on,X]);let h=null,d=-1/0;for(const e of u){t.has(e,Sn)||t.insert(e,Sn);if(!t.get(e,bn).enabled)continue;const s=t.get(e,X),n=t.get(e,on),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(gn(c.x,c.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Y)&&(s=t.get(e,Y).layer),s>=d&&(d=s,h=e)}}if(n!==h){if(null!==n&&t.valid(n)&&t.has(n,Sn)){t.get(n,Sn).hovered=!1,s.emit(n,"hover_exit")}if(null!==h){t.get(h,Sn).hovered=!0,s.emit(h,"hover_enter")}n=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,Sn);e.pressed=!0,e.justPressed=!0,r=h,s.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Sn)){const e=t.get(r,Sn);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Se.Update,Ce([],()=>{const e=t.getEntitiesWithComponents([Cn]);for(const s of e){if(t.has(s,bn)||t.insert(s,bn,{enabled:!0}),!t.has(s,Sn))continue;const e=t.get(s,Sn),n=t.get(s,Cn),r=t.get(s,bn),i=n.state;if(r.enabled?e.pressed?n.state=Pn.Pressed:e.hovered?n.state=Pn.Hovered:n.state=Pn.Normal:n.state=Pn.Disabled,i!==n.state&&n.transition&&t.has(s,Y)){const e=t.get(s,Y),r=n.transition;switch(n.state){case Pn.Normal:e.color={...r.normalColor};break;case Pn.Hovered:e.color={...r.hoveredColor};break;case Pn.Pressed:e.color={...r.pressedColor};break;case Pn.Disabled:e.color={...r.disabledColor}}t.insert(s,Y,e)}}},{name:"ButtonSystem"}))}}const zn=new Dn,Ln=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 On{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){L("TextInput",Ln);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=h(y.textCanvasSize,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,l=!0,c=0,u=0;const d=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!d)return;const f=d,p=()=>{a||null===o||x()},_=()=>{a=!0},m=()=>{a=!1,x()},g=t=>{if(null===o)return;if("Escape"===t.key)return void S();const n=s.get(o,Ln);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(En).emit(o,"submit"),void S()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,P())},w=()=>{if(null!==o&&s.valid(o)&&s.has(o,Ln)){const e=s.get(o,Ln);e.focused=!1,e.dirty=!0}o=null};function x(){if(null===o||!s.valid(o))return;const t=s.get(o,Ln);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(En).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,P()}function b(e){if(o===e)return;S();const t=s.get(e,Ln);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),P())}function S(){if(null!==o&&s.valid(o)&&s.has(o,Ln)){const e=s.get(o,Ln);e.focused=!1,e.dirty=!0}o=null,f.blur()}function P(){l=!0,c=0}function C(e,o,a,c){(r.width<a||r.height<c)&&(r.width=Wn(Math.max(r.width,a)),r.height=Wn(Math.max(r.height,c))),i.clearRect(0,0,r.width,r.height);const u=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.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 h=0===o.value.length,d=h?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=h?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=Hn(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(c-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&l){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=Hn(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(c-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const m=i.getImageData(0,0,a,c),g=new Uint8Array(m.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,c,w,g.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,Y);b.texture=v,b.size.x=a,b.size.y=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},s.insert(e,Y,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",m),f.addEventListener("keydown",g),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",m),f.removeEventListener("keydown",g),f.removeEventListener("blur",w),f.remove()},e.addSystemToSchedule(Se.PreUpdate,Ce([he(En)],e=>{const t=s.getEntitiesWithComponents([Ln,bn]);for(const e of t){if(!s.has(e,Sn))continue;if(s.get(e,Sn).justPressed)return void b(e)}if(null!==o){const e=s.getEntitiesWithComponents([bn]);for(const t of e){if(s.has(t,Ln))continue;if(!s.has(t,Sn))continue;if(s.get(t,Sn).justPressed)return void S()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==o&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==o&&s.valid(o)&&s.has(o,Ln)))){s.get(o,Ln).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Ln)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Ln,on]);for(const e of a){const t=s.get(e,Ln);if(!t.dirty)continue;const n=s.get(e,on),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,Y)||s.insert(e,Y,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:r,y:i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),C(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Hn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function Wn(e){let t=1;for(;t<e;)t*=2;return t}const jn=new On;async function Nn(e,t,s){const n=e.getResource(zs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Vn(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 Xn=ue({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Yn=ue(null,"PhysicsAPI");function qn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Gn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Jn{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(Xn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Vn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([G]);for(const s of t){const t=e.world.get(s,G);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Se.PostUpdate,Ce([he(_e)],a=>{const l=o.getEntitiesWithComponents([re,V,X]),c=new Set;for(const r of l){c.add(r);const a=o.get(r,re),l=o.get(r,X);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=qn(l.rotation);n._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),Kn(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===le.Kinematic){const e=qn(l.rotation);n._physics_setBodyTransform(r,l.position.x*i,l.position.y*i,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(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const u=e.world.get(o,V);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(o,K)){const t=e.world.get(o,K);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,X)){const s=e.world.get(t.entity,X),n=qn(s.rotation),r=a-s.position.x,i=l-s.position.y,o=Math.cos(-n),u=Math.sin(-n);h=(r*o-i*u)/(0!==s.scale.x?s.scale.x:1),d=(r*u+i*o)/(0!==s.scale.y?s.scale.y:1),f=c-n}}u.position.x=h,u.position.y=d;const p=Gn(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,V,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<o;s++){const n=e+2*s;i.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],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=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Xn,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Yn,Qn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Kn(e,t,s){const n=e.world;if(n.has(s,ie)){const e=n.get(s,ie);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,oe)){const e=n.get(s,oe);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ae)){const e=n.get(s,ae);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Qn{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(Qn.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 Zn(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function er(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 tr(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,f=c+c,p=a*h,_=a*d,m=a*f,g=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*r,(_+b)*r,(m-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function sr(e,t,s,n,r,i,o,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]=Zn(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 u={},h=null;if(r&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const l=r.resolvePath(o),c=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===vt(l)?.contentType;let h,d;if(u){const e=await r.readBinary(o);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const f=s.loadSkeleton(h,d,n,n.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=er(n),_=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=Zn(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,h,s,n)),i){new Jn("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=vt(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${o}`:o;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=Zn(e,c,!1),h=e.getResourceManager();n[r]=h.loadBitmapFont(t,u,c.width,c.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=Je.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=Je.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=ut(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,d,f);const p=ht(e.world,s);if(l&&e.hasResource(zs))for(const t of p.values())e.world.insert(t,se,{scene:l,persistent:!1});if(r&&h){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const l=n.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}(h,s,u,p);!function(e,t,s,n,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,ee)?c.get(i,ee):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(o,l*h);let d=0;if(c.has(i,X)){const e=tr(c.get(i,X),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,l=2*i,c=s._malloc(a),u=s._malloc(l),h=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,c,u,h,f);const p=s.HEAPU32[h>>2],_=s.HEAPU32[f>>2],m=new Float32Array(s.HEAPF32.buffer,c,8*r),g=new Uint16Array(s.HEAPU8.buffer,u,i),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(c),s._free(u),s._free(h),s._free(f)}d&&t._free(d)}})}(e,t,r,h,n)}if(a){const t=e.getResource(kt);t&&t.setAddressableManifest(a)}}function nr(e,t,s){return{name:e,data:t,async setup(){await sr(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class rr{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"===vt(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=vt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||i.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}i.length>0&&await Promise.all(i)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const ir="__preview__";class or{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(zs);t.register({name:ir,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(ir),this.loadPromise_=t.load(ir).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new rr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await sr(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,ir)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([q]);for(const n of s){if(e.get(n,q).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([G]);for(const r of n){const n=e.get(r,G);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(zs).getScene(ir),i=r?r.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(i,V,o);const a={isActive:!0,projectionType:W.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:j.ColorAndDepth};e.insert(i,q,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(zs);await e.switchTo(ir),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 ar={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ms.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ms.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ms.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ms.releaseRenderTarget(e._handle),ar.create({width:t,height:s,depth:!0})),begin(e,t){Ms.begin(t,e._handle)},end(){Ms.end()},getDepthTexture:e=>Ms.getTargetDepthTexture(e._handle)};let lr=!1;function cr(e){lr=e}function ur(){return lr}function hr(){return!lr}var dr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(dr||(dr={}));class fr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${dr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case dr.Debug:console.debug(t,s);break;case dr.Info:console.log(t,s);break;case dr.Warn:console.warn(t,s);break;case dr.Error:console.error(t,s)}}}class pr{constructor(){this.handlers_=[],this.minLevel_=dr.Info,this.addHandler(new fr)}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(dr.Debug,e,t,s)}info(e,t,s){this.log(dr.Info,e,t,s)}warn(e,t,s){this.log(dr.Warn,e,t,s)}error(e,t,s){this.log(dr.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 _r=new pr;function mr(){return _r}function gr(e){_r.setMinLevel(e)}function yr(e,t,s){_r.debug(e,t,s)}function wr(e,t,s){_r.info(e,t,s)}function xr(e,t,s){_r.warn(e,t,s)}function vr(e,t,s){_r.error(e,t,s)}const br=[hn,vn,Fn,zn,jn];function Sr(e,t){return function(e,t){const s=Ws.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Kt(e),Ye(e),fs(e),ys(e),Ts(e),Rs(e);const r=new ks;s.pipeline_=r;let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=Xs(e,n,t,r));const o=s.getResource(Oe);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}s.insertResource(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 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(n);if(c>=0){const e=n.getCanvas(c).backgroundColor;Ms.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-i)/1e3;let h;if(Ms.resize(t,l),vs.isInitialized()&&vs.getPassCount()>0&&!vs.isBypassed()&&vs.resize(t,l),s.hasResource(zs)){const e=s.getResource(zs).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=Xs(e,n,t,l,s.world,h);if(a(t,l,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:Ns,width:t,height:l,elapsed:u});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:c},clearFlags:e.clearFlags,elapsed:u})}Ms.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(Se.First,l),s.addSystemToSchedule(Se.Last,c),s.addPlugin(Ut),s.addPlugin(Vt),s.addPlugin(Be),s.addPlugin(Hs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:br,...t})}e=f;export{Ws as App,Bt as AssetPlugin,$t as AssetRefCounter,Ft as AssetServer,kt as Assets,it as AsyncCache,Z as BitmapText,He as BlendMode,le as BodyType,ie as BoxCollider,Cn as Button,Pn as ButtonState,q as Camera,G as Canvas,ae as CapsuleCollider,Q as Children,oe as CircleCollider,j as ClearFlags,xe as Commands,be as CommandsInstance,_ as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,m as DEFAULT_PIXELS_PER_UNIT,g as DEFAULT_TEXT_CANVAS_SIZE,ls as DataType,ts as Draw,ve as EntityCommands,Fs as GLDebug,ms as Geometry,x as INVALID_ENTITY,b as INVALID_FONT,v as INVALID_TEXTURE,Fe as Input,ke as InputPlugin,Ie as InputState,bn as Interactable,V as LocalTransform,dr as LogLevel,pr as Logger,Je as Material,ot as MaterialLoader,me as Mut,te as Name,K as Parent,Qn as Physics,Xn as PhysicsEvents,Jn as PhysicsPlugin,vs as PostProcess,Wt as PrefabServer,jt as Prefabs,Nt as PrefabsPlugin,or as PreviewPlugin,W as ProjectionType,ye as Query,we as QueryInstance,ks as RenderPipeline,Ss as RenderStage,ar as RenderTexture,Ms as Renderer,he as Res,de as ResMut,re as RigidBody,y as RuntimeConfig,N as ScaleMode,zs as SceneManager,Ds as SceneManagerState,se as SceneOwner,Se as Schedule,Mn as ScreenSpace,rt as ShaderSources,ee as SpineAnimation,Y as Sprite,Re as SystemRunner,rn as Text,tn as TextAlign,Ln as TextInput,On as TextInputPlugin,nn as TextOverflow,un as TextPlugin,an as TextRenderer,sn as TextVerticalAlign,_e as Time,Oe as UICameraInfo,Tn as UIEventQueue,En as UIEvents,Sn as UIInteraction,Dn as UIInteractionPlugin,In as UILayoutPlugin,dn as UIMask,xn as UIMaskPlugin,on as UIRect,J as Velocity,rr as WebAssetProvider,Le as World,X as WorldTransform,Me as addStartupSystem,Ee as addSystem,Ae as addSystemToSchedule,w as applyRuntimeConfig,Ut as assetPlugin,as as clearDrawCallbacks,U as clearUserComponents,T as color,An as computeUIRectLayout,wn as createMaskProcessor,nr as createRuntimeSceneConfig,Sr as createWebApp,yr as debug,F as defineComponent,ue as defineResource,Ce as defineSystem,k as defineTag,vr as error,_t as findEntityByName,js as flushPendingSystems,St as getAddressableType,Pt as getAddressableTypeByEditorType,Tt as getAllAssetExtensions,Rt as getAssetMimeType,vt as getAssetTypeEntry,O as getComponent,ct as getComponentAssetFields,ne as getComponentDefaults,Mt as getCustomExtensions,bt as getEditorType,mr as getLogger,t as getPlatform,n as getPlatformType,B as getUserComponent,At as getWeChatPackOptions,wr as info,Kt as initDrawAPI,Rs as initGLDebugAPI,fs as initGeometryAPI,Ye as initMaterialAPI,ys as initPostProcessAPI,Ts as initRendererAPI,Be as inputPlugin,zt as instantiatePrefab,fn as intersectRects,_n as invertMatrix4,D as isBuiltinComponent,It as isCustomExtension,ur as isEditor,Ct as isKnownAssetExtension,s as isPlatformInitialized,hr as isRuntime,We as isTextureRef,r as isWeChat,i as isWeb,ft as loadComponent,Vn as loadPhysicsModule,sr as loadRuntimeScene,ht as loadSceneData,dt as loadSceneWithAssets,Et as looksLikeAssetPath,o as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,gn as pointInWorldRect,Vt as prefabsPlugin,E as quat,L as registerComponent,lt as registerComponentAssetFields,is as registerDrawCallback,Dt as registerEmbeddedAssets,nt as registerMaterialCallback,Hs as sceneManagerPlugin,mn as screenToWorld,cr as setEditorMode,gr as setLogLevel,Qt as shutdownDrawAPI,Is as shutdownGLDebugAPI,ps as shutdownGeometryAPI,qe as shutdownMaterialAPI,ws as shutdownPostProcessAPI,Es as shutdownRendererAPI,jn as textInputPlugin,hn as textPlugin,Nn as transitionTo,zn as uiInteractionPlugin,Fn as uiLayoutPlugin,vn as uiMaskPlugin,br as uiPlugins,os as unregisterDrawCallback,pt as updateCameraAspectRatio,S as vec2,P as vec3,C as vec4,xr as warn,pn as worldRectToScreen,Ls as wrapSceneSystem};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/physics/index.d.ts b/desktop/public/sdk/esm/physics/index.d.ts
index 7f3b2b12d..387b0c13d 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -686,6 +686,8 @@ declare class App {
private lastTime_;
private fixedTimestep_;
private fixedAccumulator_;
+ private maxDeltaTime_;
+ private maxFixedSteps_;
private module_;
private pipeline_;
private spineInitPromise_?;
@@ -716,6 +718,8 @@ declare class App {
set physicsModule(m: unknown);
get world(): World;
setFixedTimestep(timestep: number): this;
+ setMaxDeltaTime(v: number): this;
+ setMaxFixedSteps(v: number): this;
onError(handler: (error: unknown, systemName: string) => void): this;
onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;
insertResource<T>(resource: ResourceDef<T>, value: T): this;
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index 025955b30..aa39035a0 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -761,6 +761,8 @@ declare class App {
private lastTime_;
private fixedTimestep_;
private fixedAccumulator_;
+ private maxDeltaTime_;
+ private maxFixedSteps_;
private module_;
private pipeline_;
private spineInitPromise_?;
@@ -791,6 +793,8 @@ declare class App {
set physicsModule(m: unknown);
get world(): World;
setFixedTimestep(timestep: number): this;
+ setMaxDeltaTime(v: number): this;
+ setMaxFixedSteps(v: number): this;
onError(handler: (error: unknown, systemName: string) => void): this;
onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;
insertResource<T>(resource: ResourceDef<T>, value: T): this;
diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.html
index b5b931a23..c79f71e4c 100644
--- a/desktop/src-tauri/src/preview_template.html
+++ b/desktop/src-tauri/src/preview_template.html
@@ -152,12 +152,35 @@
setupCanvas();
window.addEventListener('resize', () => setupCanvas());
+ step = 'apply runtime config';
+ if (config.maxDeltaTime !== undefined) sdk.RuntimeConfig.maxDeltaTime = config.maxDeltaTime;
+ if (config.maxFixedSteps !== undefined) sdk.RuntimeConfig.maxFixedSteps = config.maxFixedSteps;
+ if (config.textCanvasSize !== undefined) sdk.RuntimeConfig.textCanvasSize = config.textCanvasSize;
+ if (config.defaultFontFamily !== undefined) sdk.RuntimeConfig.defaultFontFamily = config.defaultFontFamily;
+ if (config.sceneTransitionDuration !== undefined) sdk.RuntimeConfig.sceneTransitionDuration = config.sceneTransitionDuration;
+ if (config.sceneTransitionColor) {
+ const hex = config.sceneTransitionColor.replace('#', '');
+ sdk.RuntimeConfig.sceneTransitionColor = {
+ r: parseInt(hex.substring(0,2), 16) / 255,
+ g: parseInt(hex.substring(2,4), 16) / 255,
+ b: parseInt(hex.substring(4,6), 16) / 255,
+ a: 1
+ };
+ }
+ if (config.canvasScaleMode !== undefined) {
+ const modeMap = { FixedWidth: 0, FixedHeight: 1, Expand: 2, Shrink: 3, Match: 4 };
+ sdk.RuntimeConfig.canvasScaleMode = modeMap[config.canvasScaleMode] ?? 1;
+ }
+ if (config.canvasMatchWidthOrHeight !== undefined) sdk.RuntimeConfig.canvasMatchWidthOrHeight = config.canvasMatchWidthOrHeight;
+
step = 'create app';
const previewPlugin = new sdk.PreviewPlugin('/.esengine/preview/scene.json', '/');
const app = sdk.createWebApp(Module, {
getViewportSize: getCanvasViewportSize
});
+ if (config.maxDeltaTime !== undefined) app.setMaxDeltaTime(config.maxDeltaTime);
+ if (config.maxFixedSteps !== undefined) app.setMaxFixedSteps(config.maxFixedSteps);
step = 'flushPendingSystems';
sdk.flushPendingSystems(app);
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index b2bdac84b..a7e0a15c1 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -523,11 +523,21 @@ export class Editor {
const resolution = config.designResolution ?? { width: DEFAULT_DESIGN_WIDTH, height: DEFAULT_DESIGN_HEIGHT };
setSettingsValue('project.designWidth', resolution.width);
setSettingsValue('project.designHeight', resolution.height);
+ setSettingsValue('build.atlasMaxSize', String(config.atlasMaxSize ?? 2048));
+ setSettingsValue('build.atlasPadding', config.atlasPadding ?? 2);
+ setSettingsValue('runtime.sceneTransitionDuration', config.sceneTransitionDuration ?? 0.3);
+ setSettingsValue('runtime.sceneTransitionColor', config.sceneTransitionColor ?? '#000000');
+ setSettingsValue('runtime.defaultFontFamily', config.defaultFontFamily ?? 'Arial');
+ setSettingsValue('runtime.canvasScaleMode', config.canvasScaleMode ?? 'FixedHeight');
+ setSettingsValue('runtime.canvasMatchWidthOrHeight', config.canvasMatchWidthOrHeight ?? 0.5);
+ setSettingsValue('runtime.maxDeltaTime', config.maxDeltaTime ?? 0.25);
+ setSettingsValue('runtime.maxFixedSteps', config.maxFixedSteps ?? 8);
+ setSettingsValue('runtime.textCanvasSize', String(config.textCanvasSize ?? 512));
}
const projectPath = this.projectPath_;
onSettingsChange((id, value) => {
- if (id.startsWith('project.') || id.startsWith('physics.')) {
+ if (id.startsWith('project.') || id.startsWith('physics.') || id.startsWith('build.') || id.startsWith('runtime.')) {
this.saveProjectField(projectPath);
if (id === 'project.spineVersion') {
this.spineVersionChangeHandler_?.(value as string);
@@ -566,6 +576,16 @@ export class Editor {
width: getSettingsValue<number>('project.designWidth') || DEFAULT_DESIGN_WIDTH,
height: getSettingsValue<number>('project.designHeight') || DEFAULT_DESIGN_HEIGHT,
};
+ config.atlasMaxSize = parseInt(getSettingsValue<string>('build.atlasMaxSize') ?? '2048', 10);
+ config.atlasPadding = getSettingsValue<number>('build.atlasPadding') ?? 2;
+ config.sceneTransitionDuration = getSettingsValue<number>('runtime.sceneTransitionDuration') ?? 0.3;
+ config.sceneTransitionColor = getSettingsValue<string>('runtime.sceneTransitionColor') ?? '#000000';
+ config.defaultFontFamily = getSettingsValue<string>('runtime.defaultFontFamily') ?? 'Arial';
+ config.canvasScaleMode = getSettingsValue<string>('runtime.canvasScaleMode') ?? 'FixedHeight';
+ config.canvasMatchWidthOrHeight = getSettingsValue<number>('runtime.canvasMatchWidthOrHeight') ?? 0.5;
+ config.maxDeltaTime = getSettingsValue<number>('runtime.maxDeltaTime') ?? 0.25;
+ config.maxFixedSteps = getSettingsValue<number>('runtime.maxFixedSteps') ?? 8;
+ config.textCanvasSize = parseInt(getSettingsValue<string>('runtime.textCanvasSize') ?? '512', 10);
config.modified = new Date().toISOString();
const fs = getEditorContext().fs;
if (fs) {
diff --git a/editor/src/PreviewManager.ts b/editor/src/PreviewManager.ts
index ea361993a..cff86ffe4 100644
--- a/editor/src/PreviewManager.ts
+++ b/editor/src/PreviewManager.ts
@@ -27,8 +27,8 @@ export class PreviewManager {
await scriptLoader.compile();
}
const compiledScript = scriptLoader?.getCompiledCode() ?? undefined;
- const { enablePhysics, physicsConfig, previewSpineVersion } = this.collectPreviewConfig(spineVersion);
- await this.previewService_.startPreview(scene, compiledScript, previewSpineVersion, enablePhysics, physicsConfig);
+ const { enablePhysics, physicsConfig, previewSpineVersion, runtimeConfig } = this.collectPreviewConfig(spineVersion);
+ await this.previewService_.startPreview(scene, compiledScript, previewSpineVersion, enablePhysics, physicsConfig, runtimeConfig);
} catch (err) {
console.error('Failed to start preview:', err);
}
@@ -45,8 +45,8 @@ export class PreviewManager {
): void {
if (!this.previewService_) return;
const compiledScript = scriptLoader?.getCompiledCode() ?? undefined;
- const { enablePhysics, physicsConfig, previewSpineVersion } = this.collectPreviewConfig(spineVersion);
- this.previewService_.updatePreviewFiles(scene, compiledScript, previewSpineVersion, enablePhysics, physicsConfig);
+ const { enablePhysics, physicsConfig, previewSpineVersion, runtimeConfig } = this.collectPreviewConfig(spineVersion);
+ this.previewService_.updatePreviewFiles(scene, compiledScript, previewSpineVersion, enablePhysics, physicsConfig, runtimeConfig);
}
private collectPreviewConfig(spineVersion: string) {
@@ -58,7 +58,17 @@ export class PreviewManager {
subStepCount: getSettingsValue<number>('physics.subStepCount') ?? 4,
} : undefined;
const previewSpineVersion = spineVersion === 'none' ? undefined : spineVersion;
- return { enablePhysics, physicsConfig, previewSpineVersion };
+ const runtimeConfig = {
+ sceneTransitionDuration: getSettingsValue<number>('runtime.sceneTransitionDuration') ?? 0.3,
+ sceneTransitionColor: getSettingsValue<string>('runtime.sceneTransitionColor') ?? '#000000',
+ defaultFontFamily: getSettingsValue<string>('runtime.defaultFontFamily') ?? 'Arial',
+ canvasScaleMode: getSettingsValue<string>('runtime.canvasScaleMode') ?? 'FixedHeight',
+ canvasMatchWidthOrHeight: getSettingsValue<number>('runtime.canvasMatchWidthOrHeight') ?? 0.5,
+ maxDeltaTime: getSettingsValue<number>('runtime.maxDeltaTime') ?? 0.25,
+ maxFixedSteps: getSettingsValue<number>('runtime.maxFixedSteps') ?? 8,
+ textCanvasSize: parseInt(getSettingsValue<string>('runtime.textCanvasSize') ?? '512', 10),
+ };
+ return { enablePhysics, physicsConfig, previewSpineVersion, runtimeConfig };
}
dispose(): void {
diff --git a/editor/src/builder/ArtifactBuilder.ts b/editor/src/builder/ArtifactBuilder.ts
index ec5bf20e2..a76016890 100644
--- a/editor/src/builder/ArtifactBuilder.ts
+++ b/editor/src/builder/ArtifactBuilder.ts
@@ -17,6 +17,7 @@ import { compileMaterials } from './MaterialCompiler';
import { convertPrefabAssetRefs, deserializePrefab } from '../prefab';
import { normalizePath, joinPath, isAbsolutePath, getParentDir } from '../utils/path';
import { getEsbuildWasmURL } from '../context/EditorContext';
+import { getSettingsValue } from '../settings';
// =============================================================================
// buildArtifact
@@ -70,6 +71,8 @@ export async function buildArtifact(
}
const packer = new TextureAtlasPacker(fs, projectDir, assetLibrary);
+ const atlasMaxSize = parseInt(getSettingsValue<string>('build.atlasMaxSize') ?? '2048', 10) || 2048;
+ const atlasPadding = getSettingsValue<number>('build.atlasPadding') ?? 2;
let atlasResult;
let atlasInputHash: string | undefined;
@@ -104,8 +107,9 @@ export async function buildArtifact(
cachedAtlas,
atlasInputHash,
cacheData?.atlasInputHash,
- 2048,
- [...assetPaths]
+ atlasMaxSize,
+ [...assetPaths],
+ atlasPadding
);
if (cachedAtlas && atlasInputHash === cacheData?.atlasInputHash) {
@@ -114,7 +118,7 @@ export async function buildArtifact(
progress.log('info', `Packed ${atlasResult.frameMap.size} textures into ${atlasResult.pages.length} atlas page(s)`);
}
} else {
- atlasResult = await packer.pack(imagePaths, sceneDataList, 2048, [...assetPaths]);
+ atlasResult = await packer.pack(imagePaths, sceneDataList, atlasMaxSize, [...assetPaths], atlasPadding);
if (atlasResult.pages.length > 0) {
progress.log('info', `Packed ${atlasResult.frameMap.size} textures into ${atlasResult.pages.length} atlas page(s)`);
diff --git a/editor/src/builder/BuildService.ts b/editor/src/builder/BuildService.ts
index cad2a5796..3b29f9dd2 100644
--- a/editor/src/builder/BuildService.ts
+++ b/editor/src/builder/BuildService.ts
@@ -29,6 +29,17 @@ export interface BuildResult {
cached?: boolean;
}
+export interface RuntimeBuildConfig {
+ sceneTransitionDuration?: number;
+ sceneTransitionColor?: string;
+ defaultFontFamily?: string;
+ canvasScaleMode?: string;
+ canvasMatchWidthOrHeight?: number;
+ maxDeltaTime?: number;
+ maxFixedSteps?: number;
+ textCanvasSize?: number;
+}
+
export interface BuildContext {
projectPath: string;
config: BuildConfig;
@@ -37,6 +48,7 @@ export interface BuildContext {
physicsGravity?: { x: number; y: number };
physicsFixedTimestep?: number;
physicsSubStepCount?: number;
+ runtimeConfig?: RuntimeBuildConfig;
progress?: BuildProgressReporter;
cache?: BuildCache;
}
@@ -88,6 +100,16 @@ export class BuildService {
},
physicsFixedTimestep: projectConfig?.physicsFixedTimestep ?? 1 / 60,
physicsSubStepCount: projectConfig?.physicsSubStepCount ?? 4,
+ runtimeConfig: {
+ sceneTransitionDuration: projectConfig?.sceneTransitionDuration,
+ sceneTransitionColor: projectConfig?.sceneTransitionColor,
+ defaultFontFamily: projectConfig?.defaultFontFamily,
+ canvasScaleMode: projectConfig?.canvasScaleMode,
+ canvasMatchWidthOrHeight: projectConfig?.canvasMatchWidthOrHeight,
+ maxDeltaTime: projectConfig?.maxDeltaTime,
+ maxFixedSteps: projectConfig?.maxFixedSteps,
+ textCanvasSize: projectConfig?.textCanvasSize,
+ },
progress,
cache: useCache ? this.cache_ : undefined,
};
diff --git a/editor/src/builder/PlayableEmitter.ts b/editor/src/builder/PlayableEmitter.ts
index 127b6fd1f..21ad593ce 100644
--- a/editor/src/builder/PlayableEmitter.ts
+++ b/editor/src/builder/PlayableEmitter.ts
@@ -360,6 +360,9 @@ ${imports}
? "document.getElementById('cta').style.display='block';"
: '';
+ const runtimeConfigCode = this.generateRuntimeConfigCode(context);
+ const runtimeAppConfigCode = this.generateRuntimeAppConfigCode(context);
+
return PLAYABLE_HTML_TEMPLATE
.replace('{{WASM_SDK}}', () => wasmSdk)
.replace('{{SPINE_SCRIPT}}', () => spineScript)
@@ -370,10 +373,45 @@ ${imports}
.replace('{{SCENE_NAME}}', () => sceneName)
.replace('{{PHYSICS_CONFIG}}', () => physicsConfig)
.replace('{{MANIFEST}}', () => manifestJson)
+ .replace('{{RUNTIME_CONFIG}}', () => runtimeConfigCode)
+ .replace('{{RUNTIME_APP_CONFIG}}', () => runtimeAppConfigCode)
.replace('{{CTA_STYLE}}', () => ctaStyle)
.replace('{{CTA_HTML}}', () => ctaHtml)
.replace('{{CTA_SCRIPT}}', () => ctaScript)
.replace('{{CTA_SHOW}}', () => ctaShow);
}
+ private generateRuntimeConfigCode(context: BuildContext): string {
+ const rc = context.runtimeConfig;
+ if (!rc) return '';
+ const lines: string[] = [];
+ if (rc.maxDeltaTime !== undefined) lines.push(`es.RuntimeConfig.maxDeltaTime=${rc.maxDeltaTime};`);
+ if (rc.maxFixedSteps !== undefined) lines.push(`es.RuntimeConfig.maxFixedSteps=${rc.maxFixedSteps};`);
+ if (rc.textCanvasSize !== undefined) lines.push(`es.RuntimeConfig.textCanvasSize=${rc.textCanvasSize};`);
+ if (rc.defaultFontFamily !== undefined) lines.push(`es.RuntimeConfig.defaultFontFamily=${JSON.stringify(rc.defaultFontFamily)};`);
+ if (rc.sceneTransitionDuration !== undefined) lines.push(`es.RuntimeConfig.sceneTransitionDuration=${rc.sceneTransitionDuration};`);
+ if (rc.sceneTransitionColor) {
+ const hex = rc.sceneTransitionColor.replace('#', '');
+ const r = parseInt(hex.substring(0, 2), 16) / 255;
+ const g = parseInt(hex.substring(2, 4), 16) / 255;
+ const b = parseInt(hex.substring(4, 6), 16) / 255;
+ lines.push(`es.RuntimeConfig.sceneTransitionColor={r:${r},g:${g},b:${b},a:1};`);
+ }
+ if (rc.canvasScaleMode !== undefined) {
+ const modeMap: Record<string, number> = { FixedWidth: 0, FixedHeight: 1, Expand: 2, Shrink: 3, Match: 4 };
+ lines.push(`es.RuntimeConfig.canvasScaleMode=${modeMap[rc.canvasScaleMode] ?? 1};`);
+ }
+ if (rc.canvasMatchWidthOrHeight !== undefined) lines.push(`es.RuntimeConfig.canvasMatchWidthOrHeight=${rc.canvasMatchWidthOrHeight};`);
+ return lines.join('\n ');
+ }
+
+ private generateRuntimeAppConfigCode(context: BuildContext): string {
+ const rc = context.runtimeConfig;
+ if (!rc) return '';
+ const lines: string[] = [];
+ if (rc.maxDeltaTime !== undefined) lines.push(`app.setMaxDeltaTime(${rc.maxDeltaTime});`);
+ if (rc.maxFixedSteps !== undefined) lines.push(`app.setMaxFixedSteps(${rc.maxFixedSteps});`);
+ return lines.join('\n ');
+ }
+
}
diff --git a/editor/src/builder/TextureAtlas.ts b/editor/src/builder/TextureAtlas.ts
index 38c17ea5c..0ebca64bf 100644
--- a/editor/src/builder/TextureAtlas.ts
+++ b/editor/src/builder/TextureAtlas.ts
@@ -46,23 +46,25 @@ interface RectWithId extends Rect {
// MaxRects Bin Packing
// =============================================================================
-const PADDING = 2;
+const DEFAULT_PADDING = 2;
class MaxRectsBin {
private width_: number;
private height_: number;
private freeRects_: Rect[];
+ private padding_: number;
readonly placed: RectWithId[] = [];
- constructor(width: number, height: number) {
+ constructor(width: number, height: number, padding: number = DEFAULT_PADDING) {
this.width_ = width;
this.height_ = height;
+ this.padding_ = padding;
this.freeRects_ = [{ x: 0, y: 0, width, height }];
}
insert(width: number, height: number, id: string): RectWithId | null {
- const paddedW = width + PADDING;
- const paddedH = height + PADDING;
+ const paddedW = width + this.padding_;
+ const paddedH = height + this.padding_;
let bestRect: Rect | null = null;
let bestShortSide = Infinity;
@@ -196,7 +198,8 @@ export class TextureAtlasPacker {
imagePaths: string[],
sceneDataList: Array<{ name: string; data: Record<string, unknown> }>,
maxSize: number = 2048,
- allAssetPaths?: string[]
+ allAssetPaths?: string[],
+ padding: number = DEFAULT_PADDING
): Promise<AtlasResult> {
const result: AtlasResult = { pages: [], frameMap: new Map() };
@@ -239,7 +242,7 @@ export class TextureAtlasPacker {
}
}
if (!placed) {
- const bin = new MaxRectsBin(maxSize, maxSize);
+ const bin = new MaxRectsBin(maxSize, maxSize, padding);
const rect = bin.insert(img.width, img.height, img.path);
if (rect) {
bins.push(bin);
@@ -301,13 +304,14 @@ export class TextureAtlasPacker {
currentInputHash: string,
cachedInputHash: string | undefined,
maxSize: number = 2048,
- allAssetPaths?: string[]
+ allAssetPaths?: string[],
+ padding: number = DEFAULT_PADDING
): Promise<AtlasResult> {
if (cached && cachedInputHash && currentInputHash === cachedInputHash) {
return cached;
}
- return this.pack(imagePaths, sceneDataList, maxSize, allAssetPaths);
+ return this.pack(imagePaths, sceneDataList, maxSize, allAssetPaths, padding);
}
rewriteSceneData(
diff --git a/editor/src/builder/WeChatEmitter.ts b/editor/src/builder/WeChatEmitter.ts
index a90f0fdd3..36d5a7fa0 100644
--- a/editor/src/builder/WeChatEmitter.ts
+++ b/editor/src/builder/WeChatEmitter.ts
@@ -5,7 +5,7 @@
import * as esbuild from 'esbuild-wasm/esm/browser';
import type { PlatformEmitter, BuildArtifact } from './PlatformEmitter';
-import type { BuildResult, BuildContext } from './BuildService';
+import type { BuildResult, BuildContext, RuntimeBuildConfig } from './BuildService';
import { BuildProgressReporter } from './BuildProgress';
import { getEditorContext } from '../context/EditorContext';
import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';
@@ -239,6 +239,7 @@ export class WeChatEmitter implements PlatformEmitter {
hasSpine: !!context.spineVersion,
hasPhysics: !!context.enablePhysics,
physicsConfig,
+ runtimeConfig: context.runtimeConfig,
});
await fs.writeFile(joinPath(outputDir, 'game.js'), gameJs);
diff --git a/editor/src/builder/templates.ts b/editor/src/builder/templates.ts
index c07fda39b..b95416715 100644
--- a/editor/src/builder/templates.ts
+++ b/editor/src/builder/templates.ts
@@ -75,7 +75,9 @@ function decodeBinary(dataUrl){
var es=window.esengine;
if(!es||!es.createWebApp){console.error('esengine not found');return}
+ {{RUNTIME_CONFIG}}
var app=es.createWebApp(Module);
+ {{RUNTIME_APP_CONFIG}}
if(typeof __PA__!=='undefined')es.registerEmbeddedAssets(app,__PA__);
es.flushPendingSystems(app);
@@ -146,10 +148,50 @@ export interface WeChatGameJsParams {
hasSpine: boolean;
hasPhysics: boolean;
physicsConfig: string;
+ runtimeConfig?: {
+ sceneTransitionDuration?: number;
+ sceneTransitionColor?: string;
+ defaultFontFamily?: string;
+ canvasScaleMode?: string;
+ canvasMatchWidthOrHeight?: number;
+ maxDeltaTime?: number;
+ maxFixedSteps?: number;
+ textCanvasSize?: number;
+ };
+}
+
+function generateRuntimeConfigBlock(rc?: WeChatGameJsParams['runtimeConfig']): string {
+ if (!rc) return '';
+ const lines: string[] = [];
+ if (rc.maxDeltaTime !== undefined) {
+ lines.push(` SDK.RuntimeConfig.maxDeltaTime = ${rc.maxDeltaTime};`);
+ lines.push(` app.setMaxDeltaTime(${rc.maxDeltaTime});`);
+ }
+ if (rc.maxFixedSteps !== undefined) {
+ lines.push(` SDK.RuntimeConfig.maxFixedSteps = ${rc.maxFixedSteps};`);
+ lines.push(` app.setMaxFixedSteps(${rc.maxFixedSteps});`);
+ }
+ if (rc.textCanvasSize !== undefined) lines.push(` SDK.RuntimeConfig.textCanvasSize = ${rc.textCanvasSize};`);
+ if (rc.defaultFontFamily !== undefined) lines.push(` SDK.RuntimeConfig.defaultFontFamily = ${JSON.stringify(rc.defaultFontFamily)};`);
+ if (rc.sceneTransitionDuration !== undefined) lines.push(` SDK.RuntimeConfig.sceneTransitionDuration = ${rc.sceneTransitionDuration};`);
+ if (rc.sceneTransitionColor) {
+ const hex = rc.sceneTransitionColor.replace('#', '');
+ const r = parseInt(hex.substring(0, 2), 16) / 255;
+ const g = parseInt(hex.substring(2, 4), 16) / 255;
+ const b = parseInt(hex.substring(4, 6), 16) / 255;
+ lines.push(` SDK.RuntimeConfig.sceneTransitionColor = {r:${r},g:${g},b:${b},a:1};`);
+ }
+ if (rc.canvasScaleMode !== undefined) {
+ const modeMap: Record<string, number> = { FixedWidth: 0, FixedHeight: 1, Expand: 2, Shrink: 3, Match: 4 };
+ lines.push(` SDK.RuntimeConfig.canvasScaleMode = ${modeMap[rc.canvasScaleMode] ?? 1};`);
+ }
+ if (rc.canvasMatchWidthOrHeight !== undefined) lines.push(` SDK.RuntimeConfig.canvasMatchWidthOrHeight = ${rc.canvasMatchWidthOrHeight};`);
+ return lines.join('\n');
}
export function generateWeChatGameJs(params: WeChatGameJsParams): string {
- const { userCode, firstSceneName, allSceneNames, hasSpine, hasPhysics, physicsConfig } = params;
+ const { userCode, firstSceneName, allSceneNames, hasSpine, hasPhysics, physicsConfig, runtimeConfig } = params;
+ const runtimeConfigBlock = generateRuntimeConfigBlock(runtimeConfig);
const spineInit = hasSpine ? `
async function initSpineModule() {
@@ -300,6 +342,8 @@ ${physicsInit}
}
});
+${runtimeConfigBlock}
+
${userCode}
SDK.flushPendingSystems(app);
diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.ts
index e79f796a0..8e0f668cf 100644
--- a/editor/src/panels/SceneViewPanel.ts
+++ b/editor/src/panels/SceneViewPanel.ts
@@ -1424,7 +1424,7 @@ export class SceneViewPanel {
private drawGrid(ctx: CanvasRenderingContext2D, w: number, h: number): void {
if (!getSettingsValue<boolean>('scene.showGrid')) return;
- const gridSize = 50;
+ const gridSize = getSettingsValue<number>('scene.gridSize') ?? 50;
const halfW = w / 2 / this.zoom_;
const halfH = h / 2 / this.zoom_;
diff --git a/editor/src/preview/PreviewService.ts b/editor/src/preview/PreviewService.ts
index 3b6d6e9fe..bb50b9e37 100644
--- a/editor/src/preview/PreviewService.ts
+++ b/editor/src/preview/PreviewService.ts
@@ -39,7 +39,7 @@ export class PreviewService {
this.previewDir_ = `${this.projectDir_}/.esengine/preview`;
}
- async startPreview(scene: SceneData, compiledScript?: string, spineVersion?: string, enablePhysics?: boolean, physicsConfig?: { gravityX: number; gravityY: number; fixedTimestep: number; subStepCount: number }): Promise<void> {
+ async startPreview(scene: SceneData, compiledScript?: string, spineVersion?: string, enablePhysics?: boolean, physicsConfig?: { gravityX: number; gravityY: number; fixedTimestep: number; subStepCount: number }, runtimeConfig?: Record<string, unknown>): Promise<void> {
const fs = this.getNativeFS();
const invoke = this.getTauriInvoke();
@@ -49,7 +49,7 @@ export class PreviewService {
}
console.log('PreviewService: Preparing files in', this.previewDir_);
- await this.preparePreviewFiles(fs, scene, compiledScript, spineVersion, enablePhysics, physicsConfig);
+ await this.preparePreviewFiles(fs, scene, compiledScript, spineVersion, enablePhysics, physicsConfig, runtimeConfig);
console.log('PreviewService: Files prepared');
const port = await invoke('start_preview_server', {
@@ -73,10 +73,11 @@ export class PreviewService {
spineVersion?: string,
enablePhysics?: boolean,
physicsConfig?: { gravityX: number; gravityY: number; fixedTimestep: number; subStepCount: number },
+ runtimeConfig?: Record<string, unknown>,
): Promise<void> {
const fs = this.getNativeFS();
if (!fs) return;
- await this.preparePreviewFiles(fs, scene, compiledScript, spineVersion, enablePhysics, physicsConfig);
+ await this.preparePreviewFiles(fs, scene, compiledScript, spineVersion, enablePhysics, physicsConfig, runtimeConfig);
await this.notifyReload();
}
@@ -87,6 +88,7 @@ export class PreviewService {
spineVersion?: string,
enablePhysics?: boolean,
physicsConfig?: { gravityX: number; gravityY: number; fixedTimestep: number; subStepCount: number },
+ runtimeConfig?: Record<string, unknown>,
): Promise<void> {
await this.ensureDirectory(fs, this.previewDir_);
@@ -110,6 +112,7 @@ export class PreviewService {
physicsGravityY: physicsConfig?.gravityY ?? -9.81,
physicsFixedTimestep: physicsConfig?.fixedTimestep ?? 1 / 60,
physicsSubStepCount: physicsConfig?.subStepCount ?? 4,
+ ...runtimeConfig,
}));
if (compiledScript) {
diff --git a/editor/src/settings/builtinSettings.ts b/editor/src/settings/builtinSettings.ts
index 3df050a67..cb38046c3 100644
--- a/editor/src/settings/builtinSettings.ts
+++ b/editor/src/settings/builtinSettings.ts
@@ -26,6 +26,18 @@ export function registerBuiltinSettings(): void {
order: 3,
});
+ registerSettingsSection({
+ id: 'build',
+ title: 'Build',
+ order: 4,
+ });
+
+ registerSettingsSection({
+ id: 'runtime',
+ title: 'Runtime',
+ order: 5,
+ });
+
registerSettingsItem({
id: 'project.name',
section: 'project',
@@ -219,4 +231,152 @@ export function registerBuiltinSettings(): void {
defaultValue: false,
order: 6,
});
+
+ registerSettingsItem({
+ id: 'scene.gridSize',
+ section: 'scene-view',
+ label: 'Grid Size',
+ type: 'number',
+ defaultValue: 50,
+ min: 5,
+ max: 500,
+ step: 5,
+ order: 7,
+ });
+
+ registerSettingsItem({
+ id: 'general.previewPort',
+ section: 'general',
+ label: 'Preview Port',
+ type: 'number',
+ defaultValue: 3456,
+ min: 1024,
+ max: 65535,
+ step: 1,
+ order: 1,
+ });
+
+ registerSettingsItem({
+ id: 'build.atlasMaxSize',
+ section: 'build',
+ label: 'Atlas Max Size',
+ type: 'select',
+ defaultValue: '2048',
+ order: 0,
+ options: [
+ { label: '512', value: '512' },
+ { label: '1024', value: '1024' },
+ { label: '2048', value: '2048' },
+ { label: '4096', value: '4096' },
+ ],
+ });
+
+ registerSettingsItem({
+ id: 'build.atlasPadding',
+ section: 'build',
+ label: 'Atlas Padding',
+ type: 'number',
+ defaultValue: 2,
+ min: 0,
+ max: 16,
+ step: 1,
+ order: 1,
+ });
+
+ registerSettingsItem({
+ id: 'runtime.sceneTransitionDuration',
+ section: 'runtime',
+ label: 'Scene Transition Duration',
+ type: 'number',
+ defaultValue: 0.3,
+ min: 0,
+ max: 5,
+ step: 0.1,
+ order: 0,
+ });
+
+ registerSettingsItem({
+ id: 'runtime.sceneTransitionColor',
+ section: 'runtime',
+ label: 'Scene Transition Color',
+ type: 'color',
+ defaultValue: '#000000',
+ order: 1,
+ });
+
+ registerSettingsItem({
+ id: 'runtime.defaultFontFamily',
+ section: 'runtime',
+ label: 'Default Font Family',
+ type: 'string',
+ defaultValue: 'Arial',
+ order: 2,
+ });
+
+ registerSettingsItem({
+ id: 'runtime.canvasScaleMode',
+ section: 'runtime',
+ label: 'Canvas Scale Mode',
+ type: 'select',
+ defaultValue: 'FixedHeight',
+ order: 3,
+ options: [
+ { label: 'Fixed Width', value: 'FixedWidth' },
+ { label: 'Fixed Height', value: 'FixedHeight' },
+ { label: 'Expand', value: 'Expand' },
+ { label: 'Shrink', value: 'Shrink' },
+ { label: 'Match', value: 'Match' },
+ ],
+ });
+
+ registerSettingsItem({
+ id: 'runtime.canvasMatchWidthOrHeight',
+ section: 'runtime',
+ label: 'Canvas Match W/H',
+ type: 'range',
+ defaultValue: 0.5,
+ min: 0,
+ max: 1,
+ step: 0.1,
+ order: 4,
+ });
+
+ registerSettingsItem({
+ id: 'runtime.maxDeltaTime',
+ section: 'runtime',
+ label: 'Max Delta Time',
+ type: 'number',
+ defaultValue: 0.25,
+ min: 0.01,
+ max: 1,
+ step: 0.01,
+ order: 5,
+ });
+
+ registerSettingsItem({
+ id: 'runtime.maxFixedSteps',
+ section: 'runtime',
+ label: 'Max Fixed Steps',
+ type: 'number',
+ defaultValue: 8,
+ min: 1,
+ max: 64,
+ step: 1,
+ order: 6,
+ });
+
+ registerSettingsItem({
+ id: 'runtime.textCanvasSize',
+ section: 'runtime',
+ label: 'Text Canvas Size',
+ type: 'select',
+ defaultValue: '512',
+ order: 7,
+ options: [
+ { label: '256', value: '256' },
+ { label: '512', value: '512' },
+ { label: '1024', value: '1024' },
+ { label: '2048', value: '2048' },
+ ],
+ });
}
diff --git a/editor/src/types/ProjectTypes.ts b/editor/src/types/ProjectTypes.ts
index b0700b673..a4a507e12 100644
--- a/editor/src/types/ProjectTypes.ts
+++ b/editor/src/types/ProjectTypes.ts
@@ -23,6 +23,16 @@ export interface ProjectConfig {
physicsFixedTimestep?: number;
physicsSubStepCount?: number;
designResolution?: { width: number; height: number };
+ atlasMaxSize?: number;
+ atlasPadding?: number;
+ sceneTransitionDuration?: number;
+ sceneTransitionColor?: string;
+ defaultFontFamily?: string;
+ canvasScaleMode?: string;
+ canvasMatchWidthOrHeight?: number;
+ maxDeltaTime?: number;
+ maxFixedSteps?: number;
+ textCanvasSize?: number;
}
// =============================================================================
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index d9552d5dd..166eb6b4e 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -62,6 +62,8 @@ export class App {
private lastTime_ = 0;
private fixedTimestep_ = 1 / 60;
private fixedAccumulator_ = 0;
+ private maxDeltaTime_ = 0.25;
+ private maxFixedSteps_ = 8;
private module_: ESEngineModule | null = null;
private pipeline_: RenderPipeline | null = null;
@@ -200,6 +202,16 @@ export class App {
return this;
}
+ setMaxDeltaTime(v: number): this {
+ this.maxDeltaTime_ = v;
+ return this;
+ }
+
+ setMaxFixedSteps(v: number): this {
+ this.maxFixedSteps_ = v;
+ return this;
+ }
+
onError(handler: (error: unknown, systemName: string) => void): this {
this.error_handler_ = handler;
return this;
@@ -270,7 +282,7 @@ export class App {
const deltaMs = currentTime - this.lastTime_;
this.lastTime_ = currentTime;
- const delta = Math.min(deltaMs / 1000, 0.25);
+ const delta = Math.min(deltaMs / 1000, this.maxDeltaTime_);
this.updateTime(delta);
this.world_.resetQueryPool();
@@ -280,14 +292,14 @@ export class App {
this.fixedAccumulator_ += delta;
let fixedSteps = 0;
- while (this.fixedAccumulator_ >= this.fixedTimestep_ && fixedSteps < 8) {
+ while (this.fixedAccumulator_ >= this.fixedTimestep_ && fixedSteps < this.maxFixedSteps_) {
this.fixedAccumulator_ -= this.fixedTimestep_;
this.runSchedule(Schedule.FixedPreUpdate);
this.runSchedule(Schedule.FixedUpdate);
this.runSchedule(Schedule.FixedPostUpdate);
fixedSteps++;
}
- if (fixedSteps >= 8) {
+ if (fixedSteps >= this.maxFixedSteps_) {
this.fixedAccumulator_ = 0;
}
diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.ts
index 5ffaae5a5..bd1d42d3d 100644
--- a/sdk/src/asset/AssetServer.ts
+++ b/sdk/src/asset/AssetServer.ts
@@ -4,7 +4,7 @@
*/
import type { Entity, TextureHandle, FontHandle } from '../types';
-import { DEFAULT_TEXT_CANVAS_SIZE } from '../defaults';
+import { RuntimeConfig } from '../defaults';
import type { ESEngineModule } from '../wasm';
import type { ShaderHandle } from '../material';
import { Material } from '../material';
@@ -131,7 +131,7 @@ export class AssetServer {
constructor(module: ESEngineModule) {
this.module_ = module;
- this.canvas_ = platformCreateCanvas(DEFAULT_TEXT_CANVAS_SIZE, DEFAULT_TEXT_CANVAS_SIZE) as HTMLCanvasElement;
+ this.canvas_ = platformCreateCanvas(RuntimeConfig.textCanvasSize, RuntimeConfig.textCanvasSize) as HTMLCanvasElement;
this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true })!;
const shaderLoader: ShaderLoader = {
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index e11e900fd..26134f97a 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -12,6 +12,8 @@ export {
DEFAULT_DESIGN_HEIGHT,
DEFAULT_PIXELS_PER_UNIT,
DEFAULT_TEXT_CANVAS_SIZE,
+ RuntimeConfig,
+ applyRuntimeConfig,
} from './defaults';
// =============================================================================
diff --git a/sdk/src/defaults.ts b/sdk/src/defaults.ts
index 57364133e..835e8b7f7 100644
--- a/sdk/src/defaults.ts
+++ b/sdk/src/defaults.ts
@@ -2,3 +2,27 @@ export const DEFAULT_DESIGN_WIDTH = 1920;
export const DEFAULT_DESIGN_HEIGHT = 1080;
export const DEFAULT_PIXELS_PER_UNIT = 100;
export const DEFAULT_TEXT_CANVAS_SIZE = 512;
+
+export const RuntimeConfig = {
+ sceneTransitionDuration: 0.3,
+ sceneTransitionColor: { r: 0, g: 0, b: 0, a: 1 } as { r: number; g: number; b: number; a: number },
+ defaultFontFamily: 'Arial',
+ canvasScaleMode: 1,
+ canvasMatchWidthOrHeight: 0.5,
+ maxDeltaTime: 0.25,
+ maxFixedSteps: 8,
+ textCanvasSize: 512,
+};
+
+export function applyRuntimeConfig(components: {
+ Text?: { _default: Record<string, unknown> };
+ TextInput?: { _default: Record<string, unknown> };
+ Canvas?: { _default: Record<string, unknown> };
+}): void {
+ if (components.Text) components.Text._default.fontFamily = RuntimeConfig.defaultFontFamily;
+ if (components.TextInput) components.TextInput._default.fontFamily = RuntimeConfig.defaultFontFamily;
+ if (components.Canvas) {
+ components.Canvas._default.scaleMode = RuntimeConfig.canvasScaleMode;
+ components.Canvas._default.matchWidthOrHeight = RuntimeConfig.canvasMatchWidthOrHeight;
+ }
+}
diff --git a/sdk/src/sceneManager.ts b/sdk/src/sceneManager.ts
index da67d550a..cc4d0a26d 100644
--- a/sdk/src/sceneManager.ts
+++ b/sdk/src/sceneManager.ts
@@ -17,6 +17,7 @@ import { Draw } from './draw';
import { defineResource } from './resource';
import { SceneOwner, Sprite } from './component';
import { Assets } from './asset/AssetPlugin';
+import { RuntimeConfig } from './defaults';
// =============================================================================
// Types
@@ -67,8 +68,6 @@ interface TransitionState {
const TRANSITION_CALLBACK_ID = '__scene_transition_overlay__';
const OVERLAY_SIZE = 20000;
-const DEFAULT_TRANSITION_DURATION = 0.3;
-const DEFAULT_TRANSITION_COLOR: Color = { r: 0, g: 0, b: 0, a: 1 };
// =============================================================================
// Scene Instance (internal)
@@ -210,8 +209,8 @@ export class SceneManagerState {
private startFadeTransition(targetScene: string, options: TransitionOptions): Promise<void> {
return new Promise(resolve => {
- const duration = options.duration ?? DEFAULT_TRANSITION_DURATION;
- const color = options.color ?? DEFAULT_TRANSITION_COLOR;
+ const duration = options.duration ?? RuntimeConfig.sceneTransitionDuration;
+ const color = options.color ?? { ...RuntimeConfig.sceneTransitionColor };
options.onStart?.();
diff --git a/sdk/src/ui/TextInputPlugin.ts b/sdk/src/ui/TextInputPlugin.ts
index b14ef2746..a3844e853 100644
--- a/sdk/src/ui/TextInputPlugin.ts
+++ b/sdk/src/ui/TextInputPlugin.ts
@@ -1,7 +1,7 @@
import type { App, Plugin } from '../app';
import type { Entity } from '../types';
import { INVALID_TEXTURE } from '../types';
-import { DEFAULT_TEXT_CANVAS_SIZE } from '../defaults';
+import { RuntimeConfig } from '../defaults';
import { defineSystem, Schedule } from '../system';
import { registerComponent, Sprite, type SpriteData } from '../component';
import { TextInput, type TextInputData } from './TextInput';
@@ -33,7 +33,7 @@ export class TextInputPlugin implements Plugin {
const world = app.world;
const textureCache = new Map<Entity, number>();
- const canvas = platformCreateCanvas(DEFAULT_TEXT_CANVAS_SIZE, 64);
+ const canvas = platformCreateCanvas(RuntimeConfig.textCanvasSize, 64);
const ctx = canvas.getContext('2d', { willReadFrequently: true })! as
CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
diff --git a/sdk/src/ui/TextRenderer.ts b/sdk/src/ui/TextRenderer.ts
index ac66f23da..c8d9893fd 100644
--- a/sdk/src/ui/TextRenderer.ts
+++ b/sdk/src/ui/TextRenderer.ts
@@ -4,7 +4,7 @@
*/
import type { Entity, Vec2 } from '../types';
-import { DEFAULT_TEXT_CANVAS_SIZE } from '../defaults';
+import { RuntimeConfig } from '../defaults';
import type { ESEngineModule, CppResourceManager } from '../wasm';
import { TextAlign, TextVerticalAlign, TextOverflow, type TextData } from './text';
import type { UIRectData } from './UIRect';
@@ -32,7 +32,7 @@ export class TextRenderer {
constructor(module: ESEngineModule) {
this.module = module;
- this.canvas = platformCreateCanvas(DEFAULT_TEXT_CANVAS_SIZE, DEFAULT_TEXT_CANVAS_SIZE);
+ this.canvas = platformCreateCanvas(RuntimeConfig.textCanvasSize, RuntimeConfig.textCanvasSize);
this.ctx = this.canvas.getContext('2d', { willReadFrequently: true })! as CanvasRenderingContext2D;
}