A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat: add scene management system with multi-scene, transitions, and render isolation
esenginea9302b202db9
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.jsindex f8c6b3ed9..380e926f5 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 m(e){return p.has(e.toLowerCase())}function y(){const e=[];for(const t of u)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function _(e){const t=g(e);return t?.wechatPackInclude??!1}let x=null;function w(){return x||(x=wx.getFileSystemManager()),x}function v(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(_(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return s.includes("no such file")||s.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function b(e){return new Promise((t,s)=>{w().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(v(e,t.errMsg)))}})})}function S(e,t="utf-8"){return new Promise((s,n)=>{w().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(v(e,t.errMsg)))}})})}function P(e){return new Promise(t=>{w().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function 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 U(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(U);const t={};for(const s in e)t[s]=U(e[s]);return t}let k=0;function D(e,t){const s=++k;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...U(t),...e}:U(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})};N("Name",ie);const ae=X("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),le=X("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ce=X("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ue=X("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),de={Static:0,Kinematic:1,Dynamic:2};let he=0;function pe(e,t){const s=++he;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function fe(e){return{_type:"res",_resource:e}}class ge{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_)}}class me{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.value_=this.get(e),t):(t=new ge(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const ye=pe({delta:0,elapsed:0,frameCount:0},"Time");function _e(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class xe{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>_e(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_),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.slice()}}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 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=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 ve{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 be;exports.Schedule=void 0,(be=exports.Schedule||(exports.Schedule={}))[be.Startup=0]="Startup",be[be.First=1]="First",be[be.PreUpdate=2]="PreUpdate",be[be.Update=3]="Update",be[be.PostUpdate=4]="PostUpdate",be[be.Last=5]="Last",be[be.FixedPreUpdate=10]="FixedPreUpdate",be[be.FixedUpdate=11]="FixedUpdate",be[be.FixedPostUpdate=12]="FixedPostUpdate";let Se=0;function Pe(e,t,s){const n=++Se;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=[])}class Ce{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ve&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new xe(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ve(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 Ee=pe(new Ae,"Input");class Me{constructor(e){this.target_=e??null}build(e){const s=new Ae;e.insertResource(Ee,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,Pe([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Re=new Me;function Ie(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=Fe(t[e]),o=Fe(r);s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r})}return n}function Fe(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Be(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 Ue(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}:Ue(e)}}return t}class ke{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)}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=Ie(t._name,t._default,n);if(e.length>0)throw new Error(Be(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,Ue(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=Ie(t._name,t._default,e);if(r.length>0)throw new Error(Be(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){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),s=this.queryCache_.get(t);if(s&&s.version===this.worldVersion_)return s.result;let n=null,r=1/0;for(const t of e)if(!H(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<r&&(r=s,n=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=n?n.keys():this.entities_;for(const t of i){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const De=pe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Le;function $e(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(Le=exports.BlendMode||(exports.BlendMode={}))[Le.Normal=0]="Normal",Le[Le.Additive=1]="Additive",Le[Le.Multiply=2]="Multiply",Le[Le.Screen=3]="Screen",Le[Le.PremultipliedAlpha=4]="PremultipliedAlpha";let We=null,ze=null,Oe=1;const He=new Map;function je(e){We=e,ze=e.getResourceManager(),Ze()}function Ne(){0!==qe&&We&&(We._free(qe),qe=0),He.clear(),Oe=1,Ge=!1,ze=null,We=null}function Ve(){if(!ze)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return ze}const Xe={createShader:(e,t)=>Ve().createShader(e,t),releaseShader(e){e>0&&Ve().releaseShader(e)},create(e){const t=Oe++,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 He.set(t,s),t},get:e=>He.get(e),setUniform(e,t,s){const n=He.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=He.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=He.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=He.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=He.get(e);s&&(s.depthTest=t)},getShader(e){const t=He.get(e);return t?.shader??0},release(e){He.delete(e)},isValid:e=>He.has(e),releaseAll(){He.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=He.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Oe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return He.set(s,n),s},toAssetData(e,t){const s=He.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=He.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Ge=!1,qe=0;const Ye=4096,Je=new Map;let Ke=null;function Qe(e){const t=(0===qe&&We&&(qe=We._malloc(Ye)),qe);if(0===t||!We)return{ptr:0,count:0};let s=0,n=0;const r=We.HEAPU8,o=We.HEAPU32,i=We.HEAPF32;for(const[a,l]of e){if(s+128>Ye)break;let e=Je.get(a);e||(Ke||(Ke=new TextEncoder),e=Ke.encode(a),Je.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 Ze(){if(!We||Ge)return;We.materialDataProvider=(e,t,s,n,r)=>{const o=He.get(e);if(!o)return We.HEAPU32[t>>2]=0,We.HEAPU32[s>>2]=0,We.HEAPU32[n>>2]=0,void(We.HEAPU32[r>>2]=0);We.HEAPU32[t>>2]=o.shader,We.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=Qe(o.uniforms);We.HEAPU32[n>>2]=i,We.HEAPU32[r>>2]=a},Ge=!0}const et={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class tt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r)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 st{constructor(e,t=""){this.cache_=new tt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Xe.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Xe.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:Xe.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 nt=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 rt(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)it(e,t,s)}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 ot(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=nt.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=nt.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)it(e,t,n)}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 it(e,t,s){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const n=V(s.type);n?e.insert(t,n,s.data):console.warn(`Unknown component type: ${s.type}`)}class at{constructor(e){this.textureCache_=new tt,this.shaderCache_=new tt,this.jsonCache_=new tt,this.textCache_=new tt,this.binaryCache_=new tt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new tt,this.prefabCache_=new tt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.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 st(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))}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(n))}}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(),Xe.releaseAll(),this.textureCache_.clearAll(),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 ot(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);return this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t))}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 Xe.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 Xe.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 lt=pe(null,"Assets");class ct{build(e){const t=e.wasmModule;t?e.insertResource(lt,new at(t)):console.warn("AssetPlugin: No WASM module available")}}const ut=new ct;async function dt(e,t,s){const{entities:n,rootId:r}=await ht(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 ot(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}}async function ht(e,t,s,n,r){const o=new Map;let i;if(void 0===n){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];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 ht(e,n.nestedPrefab.overrides,s,i,r);o.set(n.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),a.push(...t.entities);continue}const l=o.get(n.prefabEntityId),c=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:c?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};pt(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function pt(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 ft{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 dt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const gt=pe(null,"Prefabs");class mt{constructor(){this.name="PrefabsPlugin",this.dependencies=[lt]}build(e){const t=e.getResource(lt);e.insertResource(gt,new ft(e.world,t))}}const yt=new mt;let _t=null,xt=0,wt=0,vt=0;const bt=new Float32Array(256);function St(e){_t=e,xt=_t._malloc(64),wt=_t._malloc(64),vt=_t._malloc(1024)}function Pt(){_t&&(xt&&(_t._free(xt),xt=0),wt&&(_t._free(wt),wt=0),vt&&(_t._free(vt),vt=0)),_t=null}function Tt(){if(!_t)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return _t}const Ct={r:1,g:1,b:1,a:1},At={begin(e){const t=Tt();t.HEAPF32.set(e,xt/4),t.draw_begin(xt)},end(){Tt().draw_end()},line(e,t,s,n=1){Tt().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){Tt().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){Tt().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){Tt().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){Tt().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=Ct){Tt().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=Ct){Tt().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){Tt().draw_setLayer(e)},setDepth(e){Tt().draw_setDepth(e)},getDrawCallCount:()=>_t?_t.draw_getDrawCallCount():0,getPrimitiveCount:()=>_t?_t.draw_getPrimitiveCount():0,setBlendMode(e){Tt().draw_setBlendMode(e)},setDepthTest(e){Tt().draw_setDepthTest(e)},drawMesh(e,t,s){const n=Tt();n.HEAPF32.set(s,wt/4),n.draw_mesh(e,t,wt)},drawMeshWithMaterial(e,t,s){const n=Tt(),r=Xe.get(t);if(!r)return;if(At.setBlendMode(r.blendMode),At.setDepthTest(r.depthTest),0===r.uniforms.size)return void At.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,wt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Mt(t);if(!(n<0)){if($e(s))bt[o++]=10,bt[o++]=n,bt[o++]=s.slot??e++,bt[o++]=s.textureId;else if("number"==typeof s)bt[o++]=1,bt[o++]=n,bt[o++]=s;else if(Array.isArray(s)){bt[o++]=s.length,bt[o++]=n;for(let e=0;e<s.length;e++)bt[o++]=s[e]}else"w"in s?(bt[o++]=4,bt[o++]=n,bt[o++]=s.x,bt[o++]=s.y,bt[o++]=s.z,bt[o++]=s.w):"z"in s?(bt[o++]=3,bt[o++]=n,bt[o++]=s.x,bt[o++]=s.y,bt[o++]=s.z):(bt[o++]=2,bt[o++]=n,bt[o++]=s.x,bt[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(bt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),vt/4),n.draw_meshWithUniforms(e,r.shader,wt,vt,o)):n.draw_mesh(e,r.shader,wt)}},Et={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 Mt(e){return Et[e]??-1}var Rt;exports.DataType=void 0,(Rt=exports.DataType||(exports.DataType={}))[Rt.Float=1]="Float",Rt[Rt.Float2=2]="Float2",Rt[Rt.Float3=3]="Float3",Rt[Rt.Float4=4]="Float4",Rt[Rt.Int=5]="Int",Rt[Rt.Int2=6]="Int2",Rt[Rt.Int3=7]="Int3",Rt[Rt.Int4=8]="Int4";let It=null,Ft=0,Bt=0,Ut=0;function kt(e){It=e,Ft=It._malloc(262144),Bt=It._malloc(65536),Ut=It._malloc(256)}function Dt(){It&&(Ft&&It._free(Ft),Bt&&It._free(Bt),Ut&&It._free(Ut),Ft=0,Bt=0,Ut=0),It=null}function Lt(){if(!It)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return It}const $t={create(e){const t=Lt(),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,Ft/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,Ut,r).set(o),t.geometry_init(s,Ft,n,Ut,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,Bt,n).set(e.indices),t.geometry_setIndices16(s,Bt,n)}else{new Uint32Array(t.HEAPU8.buffer,Bt,n).set(e.indices),t.geometry_setIndices32(s,Bt,n)}}return s},updateVertices(e,t,s=0){const n=Lt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Ft/4),n.geometry_updateVertices(e,Ft,r,s)},release(e){e>0&&Lt().geometry_release(e)},isValid:e=>!(!It||e<=0)&&It.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return $t.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 $t.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 $t.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 Wt=null;function zt(e){Wt=e}function Ot(){Wt&&jt.isInitialized()&&jt.shutdown(),Wt=null}function Ht(){if(!Wt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Wt}const jt={init:(e,t)=>Ht().postprocess_init(e,t),shutdown(){Ht().postprocess_shutdown()},resize(e,t){Ht().postprocess_resize(e,t)},addPass:(e,t)=>Ht().postprocess_addPass(e,t),removePass(e){Ht().postprocess_removePass(e)},setEnabled(e,t){Ht().postprocess_setPassEnabled(e,t)},isEnabled:e=>Ht().postprocess_isPassEnabled(e),setUniform(e,t,s){Ht().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Ht().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Ht().postprocess_begin()},end(){Ht().postprocess_end()},getPassCount:()=>Ht().postprocess_getPassCount(),isInitialized:()=>!!Wt&&Wt.postprocess_isInitialized(),setBypass(e){Ht().postprocess_setBypass(e)},isBypassed:()=>!Wt||Wt.postprocess_isBypassed(),createBlur:()=>Xe.createShader(Nt,"#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:()=>Xe.createShader(Nt,"#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:()=>Xe.createShader(Nt,"#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:()=>Xe.createShader(Nt,"#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")},Nt="#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 Vt;exports.RenderStage=void 0,(Vt=exports.RenderStage||(exports.RenderStage={}))[Vt.Background=0]="Background",Vt[Vt.Opaque=1]="Opaque",Vt[Vt.Transparent=2]="Transparent",Vt[Vt.Overlay=3]="Overlay";let Xt=null,Gt=0;function qt(e){Xt=e,Gt=Xt._malloc(64)}function Yt(){Xt&&Gt&&(Xt._free(Gt),Gt=0),Xt=null}const Jt={init(e,t){Xt?.renderer_init(e,t)},resize(e,t){Xt?.renderer_resize(e,t)},begin(e,t){Xt&&Gt&&(Xt.HEAPF32.set(e,Gt/4),Xt.renderer_begin(Gt,t??0))},flush(){Xt?.renderer_flush()},end(){Xt?.renderer_end()},submitSprites(e){Xt&&Xt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Xt&&Xt.renderer_submitBitmapText(e._cpp)},submitSpine(e){Xt&&Xt.renderer_submitSpine?.(e._cpp)},setStage(e){Xt?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Xt?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Xt?.renderer_releaseTarget(e)},getTargetTexture:e=>Xt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Xt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Xt?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Xt?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Xt?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Xt?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Xt?Xt.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Xt?{drawCalls:Xt.renderer_getDrawCalls(),triangles:Xt.renderer_getTriangles(),sprites:Xt.renderer_getSprites(),text:Xt.renderer_getText(),spine:Xt.renderer_getSpine?.()??0,meshes:Xt.renderer_getMeshes(),culled:Xt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Kt=null;function Qt(e){Kt=e}function Zt(){Kt=null}const es={enable(){Kt?.gl_enableErrorCheck(!0)},disable(){Kt?.gl_enableErrorCheck(!1)},check:e=>Kt?.gl_checkErrors(e)??0,diagnose(){Kt?.renderer_diagnose()}},ts=new Map;function ss(e){ts.delete(e)}class ns{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(Jt.resize(n,r),jt.isInitialized()&&jt.getPassCount()>0&&jt.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Jt.setViewport(0,0,n,r),Jt.clearBuffers(3),Jt.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Jt.submitSprites(t),Jt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Jt.submitSpine(t),Jt.flush(),this.executeDrawCallbacks(s,o),Jt.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;Jt.setViewport(n.x,n.y,n.w,n.h),Jt.setScissor(n.x,n.y,n.w,n.h,!0),Jt.clearBuffers(r),Jt.setScissor(0,0,0,0,!1),Jt.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Jt.submitSprites(t),Jt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Jt.submitSpine(t),Jt.flush(),this.executeDrawCallbacks(s,o),Jt.end()}executeDrawCallbacks(e,t){const s=ts;if(s.size>0){At.begin(e);const n=[];for(const[e,r]of s.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}At.end();for(const e of n)ss(e)}}}class rs{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.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.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 ke,this.resources_=new me;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new rs}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}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Ce(this.world_,this.resources_),this.resources_.insert(ye,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1;const e=[Zt,Yt,Ot,Dt,Ne,Pt];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_){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;console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s)}}}updateTime(e){const t=this.resources_.get(ye);t.delta=e,t.elapsed+=e,t.frameCount++}}const os=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function is(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 as(e,t,s,n){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*s/(l.h*n);let u,d=0,h=0;if(r.projectionType===G.Orthographic){if(h=r.orthoSize,o){h=is(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=cs(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=ds(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const p=ps(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:new Float32Array(gs(u,p)),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const ls=new Float32Array(16);function cs(e,t,s,n,r,o){const i=ls;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 us=new Float32Array(16);function ds(e,t,s,n){const r=us;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 hs=new Float32Array(16);function ps(e,t,s){const n=hs;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const fs=new Float32Array(16);function gs(e,t){const s=fs;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var ms,ys,_s;exports.TextAlign=void 0,(ms=exports.TextAlign||(exports.TextAlign={}))[ms.Left=0]="Left",ms[ms.Center=1]="Center",ms[ms.Right=2]="Right",exports.TextVerticalAlign=void 0,(ys=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ys.Top=0]="Top",ys[ys.Middle=1]="Middle",ys[ys.Bottom=2]="Bottom",exports.TextOverflow=void 0,(_s=exports.TextOverflow||(exports.TextOverflow={}))[_s.Visible=0]="Visible",_s[_s.Clip=1]="Clip",_s[_s.Ellipsis=2]="Ellipsis";const xs=$("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}),ws=$("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 vs{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),m=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${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 bs(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Ss(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 Ps{build(e){N("Text",xs);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new vs(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Pe([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,xs));for(const e of r.keys())n.valid(e)&&n.has(e,xs)||r.delete(e);const e=n.getEntitiesWithComponents([xs]);for(const t of e){const e=n.get(t,xs),o=n.has(t,ws)?n.get(t,ws):null,i=r.get(t);if(i&&!Ss(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,bs(e,o))}}))}}const Ts=new Ps,Cs=$("UIMask",{enabled:!0});function As(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 Es(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,y]=g(d,p),[_,x]=g(h,f),w=Math.min(m,_),v=Math.max(m,_),b=Math.min(y,x),S=Math.max(y,x);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function Ms(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],m=e[13],y=e[14],_=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*m-h*g,C=d*y-p*g,A=d*_-f*g,E=h*y-p*m,M=h*_-f*m,R=p*_-f*y;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]=(m*P-y*S+_*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]=(y*v-g*P-_*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-m*v+_*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]=(m*w-g*b-y*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function Rs(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 Is(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 Fs(e,t,s,n,r,o,i){if(!e.has(t,ws)||!e.has(t,K))return null;const a=e.get(t,ws),l=e.get(t,K),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Es(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function Bs(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Cs]);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,Cs).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=Fs(t,s,r,o,i,a,l);e&&(n=As(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Fs(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 Us{build(e){if(N("UIMask",Cs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Bs(e.wasmModule,e.world))}}const ks=new Us,Ds=$("Interactable",{enabled:!0}),Ls=$("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var $s;exports.ButtonState=void 0,($s=exports.ButtonState||(exports.ButtonState={}))[$s.Normal=0]="Normal",$s[$s.Hovered=1]="Hovered",$s[$s.Pressed=2]="Pressed",$s[$s.Disabled=3]="Disabled";const Ws=$("Button",{state:exports.ButtonState.Normal,transition:null});class zs{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 Os=pe(new zs,"UIEvents"),Hs=W("ScreenSpace");function js(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 Ns(e,t,s,n,r,o){if(!e.has(t,ws))return;const i=e.get(t,ws),a=js(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)&&Ns(e,t,a.rect,a.centerX,a.centerY,!1)}class Vs{build(e){N("UIRect",ws);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Pe([fe(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),o=t.getEntitiesWithComponents([Hs,ws,J]);for(const e of o)Ns(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Xs=new Vs,Gs=new Float32Array(16),qs=new Float32Array(16);let Ys=!0,Js=1;class Ks{build(e){N("Interactable",Ds),N("Button",Ws);const t=e.world,s=new zs;e.insertResource(Os,s);let n=null,r=null;Js="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Pe([fe(Ee),fe(De)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([Ls]);for(const e of i){const s=t.get(e,Ls);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Js,l=o.screenH-e.mouseY*Js;!function(e){let t=!1;for(let s=0;s<16;s++)if(qs[s]!==e[s]){t=!0;break}t&&(qs.set(e),Ys=!0)}(o.viewProjection),Ys&&(Ms(o.viewProjection,Gs),Ys=!1);const c=Rs(a,l,Gs,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Ds,ws,K]);let d=null,h=-1/0;for(const e of u){t.has(e,Ls)||t.insert(e,Ls);if(!t.get(e,Ds).enabled)continue;const s=t.get(e,K),n=t.get(e,ws),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(Is(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,Ls)){t.get(n,Ls).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,Ls).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Ls);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,Ls)){const e=t.get(r,Ls);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,Pe([],()=>{const e=t.getEntitiesWithComponents([Ws]);for(const s of e){if(t.has(s,Ds)||t.insert(s,Ds,{enabled:!0}),!t.has(s,Ls))continue;const e=t.get(s,Ls),n=t.get(s,Ws),r=t.get(s,Ds),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 Qs=new Ks,Zs=$("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 en{build(e){N("TextInput",Zs);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;function f(){if(null===a||!s.valid(a))return;const t=s.get(a,Zs);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(Os).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,y()}function g(e){if(a===e)return;m();const t=s.get(e,Zs);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),y())}function m(){if(null!==a&&s.valid(a)&&s.has(a,Zs)){const e=s.get(a,Zs);e.focused=!1,e.dirty=!0}a=null,p.blur()}function y(){c=!0,u=0}function _(e,i,a,l){(r.width<a||r.height<l)&&(r.width=sn(Math.max(r.width,a)),r.height=sn(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=tn(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=tn(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,s=g+(e.length-1)*f,n=f}else t=g+o.measureText(e).width,s=(l-i.fontSize)/2,n=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,n)}o.restore();const m=o.getImageData(0,0,a,l),y=new Uint8Array(m.data.buffer),_=t.getResourceManager(),x=t._malloc(y.length);t.HEAPU8.set(y,x);const w=n.get(e);void 0!==w&&_.releaseTexture(w);const v=_.createTexture(a,l,x,y.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",()=>{l||null===a||f()}),p.addEventListener("compositionstart",()=>{l=!0}),p.addEventListener("compositionend",()=>{l=!1,f()}),p.addEventListener("keydown",t=>{if(null===a)return;if("Escape"===t.key)return void m();const n=s.get(a,Zs);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Os).emit(a,"submit"),void m()}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,y())}),p.addEventListener("blur",()=>{if(null!==a&&s.valid(a)&&s.has(a,Zs)){const e=s.get(a,Zs);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,Pe([fe(Os)],e=>{const t=s.getEntitiesWithComponents([Zs,Ds]);for(const e of t){if(!s.has(e,Ls))continue;if(s.get(e,Ls).justPressed)return void g(e)}if(null!==a){const e=s.getEntitiesWithComponents([Ds]);for(const t of e){if(s.has(t,Zs))continue;if(!s.has(t,Ls))continue;if(s.get(t,Ls).justPressed)return void m()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Pe([],()=>{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,Zs)))){s.get(a,Zs).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Zs)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([Zs,ws]);for(const e of i){const t=s.get(e,Zs);if(!t.dirty)continue;const n=s.get(e,ws),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}),_(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function tn(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 sn(e){let t=1;for(;t<e;)t*=2;return t}const nn=new en;async function rn(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 on=pe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),an=pe(null,"PhysicsAPI");function ln(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function cn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class un{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(on,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=rn(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,Pe([fe(ye)],a=>{const l=i.getEntitiesWithComponents([ae,J,K]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,ae),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=ln(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),dn(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===de.Kinematic){const e=ln(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=ln(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=cn(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(on,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(an,hn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function dn(e,t,s){const n=e.world;if(n.has(s,le)){const e=n.get(s,le);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,ce)){const e=n.get(s,ce);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 hn{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(hn.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 pn(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 fn(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 gn(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,m=a*p,y=l*h,_=l*p,x=c*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(y+x))*r,(g+b)*r,(m-v)*r,0,(g-b)*o,(1-(f+x))*o,(_+w)*o,0,(m+v)*i,(_-w)*i,(1-(f+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function mn(e,t,s,n,r,o,i,a){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]=pn(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 c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=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=fn(n),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=pn(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){new un("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,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=pn(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),h=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=Xe.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=Xe.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n),p=rt(e.world,s);if(function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const r=e.get(t,Q);r&&(r.texture=s[n.data.texture]||0,e.insert(t,Q,r))}}}(e.world,s,l,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if("BitmapText"!==n.type||!n.data.font||"string"!=typeof n.data.font)continue;const r=s[n.data.font]||0;if(!r)continue;const o=e.get(t,re);o&&(o.font=r,e.insert(t,re,o))}}}(e.world,s,d,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const r=s[n.data.material]||0;if(r)if("Sprite"===n.type){const s=e.get(t,Q);s&&(s.material=r,e.insert(t,Q,s))}else if("SpineAnimation"===n.type){const s=e.get(t,oe);s&&(s.material=r,e.insert(t,oe,s))}}}}(e.world,s,h,p),r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=n.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,c,p);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=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=gn(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],m=new Float32Array(s.HEAPF32.buffer,c,8*r),y=new Uint16Array(s.HEAPU8.buffer,u,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(m,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(y),t.renderer_submitTriangles(_,r,x,o,f,g,h),t._free(_),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource(lt);t&&t.setAddressableManifest(a)}}class yn{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 _n={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Jt.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Jt.getTargetTexture(s),width:e.width,height:e.height}},release(e){Jt.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Jt.releaseRenderTarget(e._handle),_n.create({width:t,height:s,depth:!0})),begin(e,t){Jt.begin(t,e._handle)},end(){Jt.end()},getDepthTexture:e=>Jt.getTargetDepthTexture(e._handle)};let xn=!1;var wn;exports.LogLevel=void 0,(wn=exports.LogLevel||(exports.LogLevel={}))[wn.Debug=0]="Debug",wn[wn.Info=1]="Info",wn[wn.Warn=2]="Warn",wn[wn.Error=3]="Error";class vn{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 bn{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new vn)}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 Sn=new bn;const Pn=[Ts,ks,Xs,Qs,nn];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=rs,exports.AssetPlugin=ct,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=at,exports.Assets=lt,exports.AsyncCache=tt,exports.BitmapText=re,exports.BodyType=de,exports.BoxCollider=le,exports.Button=Ws,exports.Camera=Z,exports.Canvas=ee,exports.CapsuleCollider=ue,exports.Children=ne,exports.CircleCollider=ce,exports.ClearFlags=q,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=ve,exports.DEFAULT_DESIGN_HEIGHT=R,exports.DEFAULT_DESIGN_WIDTH=M,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=I,exports.Draw=At,exports.EntityCommands=we,exports.GLDebug=es,exports.Geometry=$t,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Input=Ee,exports.InputPlugin=Me,exports.InputState=Ae,exports.Interactable=Ds,exports.LocalTransform=J,exports.Logger=bn,exports.Material=Xe,exports.MaterialLoader=st,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=hn,exports.PhysicsEvents=on,exports.PhysicsPlugin=un,exports.PostProcess=jt,exports.PrefabServer=ft,exports.Prefabs=gt,exports.PrefabsPlugin=mt,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.currentScene_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene(),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await s(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const r=new yn(this.baseUrl_);await r.prefetch(n);let o=null;const i=this.app_.spineInitPromise;if(i){e="init spine";o=(await i).controller.raw}e="loadRuntimeScene",await mn(this.app_,this.app_.wasmModule,n,r,o),e="ensureCamera",this.ensureCamera()}catch(t){const s=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${s}\n${n}`),new Error(`[PreviewPlugin:${e}] ${s}`)}}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=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,J,o);const i={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(r,Z,i)}}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.eventSource_.addEventListener("message",async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())}),this.eventSource_.addEventListener("error",e=>{console.error("[PreviewPlugin] EventSource error:",e)})}async reloadScene(){if(this.app_)try{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 yn(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await mn(this.app_,this.app_.wasmModule,t,n,r),this.ensureCamera(),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)=>{_e(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=xe,exports.RenderPipeline=ns,exports.RenderTexture=_n,exports.Renderer=Jt,exports.Res=fe,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=ae,exports.ScaleMode=Y,exports.ScreenSpace=Hs,exports.ShaderSources=et,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ce,exports.Text=xs,exports.TextInput=Zs,exports.TextInputPlugin=en,exports.TextPlugin=Ps,exports.TextRenderer=vs,exports.Time=ye,exports.UICameraInfo=De,exports.UIEventQueue=zs,exports.UIEvents=Os,exports.UIInteraction=Ls,exports.UIInteractionPlugin=Ks,exports.UILayoutPlugin=Vs,exports.UIMask=Cs,exports.UIMaskPlugin=Us,exports.UIRect=ws,exports.Velocity=te,exports.WebAssetProvider=yn,exports.World=ke,exports.WorldTransform=K,exports.addStartupSystem=function(e){Te().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Te().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Te().push({schedule:e,system:t})},exports.assetPlugin=ut,exports.clearDrawCallbacks=function(){ts.clear()},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=js,exports.createMaskProcessor=Bs,exports.createWebApp=function(e,t){return function(e,t){const s=rs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),St(e),je(e),kt(e),zt(e),qt(e),Qt(e);const r=new ns;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=as(e,n,t,r));const i=s.getResource(De);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(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}=i();l(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:s}=i();if(0===t||0===s)return;const c=e.registry_getCanvasEntity(n);if(c>=0){const e=n.getCanvas(c).backgroundColor;Jt.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;Jt.resize(t,s),jt.isInitialized()&&jt.getPassCount()>0&&!jt.isBypassed()&&jt.resize(t,s);const d=as(e,n,t,s);if(l(t,s,d),0===d.length)r.render({registry:{_cpp:n},viewProjection:os,width:t,height:s,elapsed:u});else{for(const e of d){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*s),l=Math.round(o.w*t),c=Math.round(o.h*s);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:u})}Jt.setViewport(0,0,t,s)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(ut),s.addPlugin(yt),s.addPlugin(Re),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Pn,...t})},exports.debug=function(e,t,s){Sn.debug(e,t,s)},exports.defineComponent=$,exports.defineResource=pe,exports.defineSystem=Pe,exports.defineTag=W,exports.error=function(e,t,s){Sn.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=nt.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?U(t._default):null},exports.getCustomExtensions=y,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return Sn},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=z,exports.getWeChatPackOptions=function(){return y().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Sn.info(e,t,s)},exports.initDrawAPI=St,exports.initGLDebugAPI=Qt,exports.initGeometryAPI=kt,exports.initMaterialAPI=je,exports.initPostProcessAPI=zt,exports.initRendererAPI=qt,exports.inputPlugin=Re,exports.instantiatePrefab=dt,exports.intersectRects=As,exports.invertMatrix4=Ms,exports.isBuiltinComponent=H,exports.isCustomExtension=_,exports.isEditor=function(){return xn},exports.isKnownAssetExtension=m,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!xn},exports.isTextureRef=$e,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=it,exports.loadPhysicsModule=rn,exports.loadRuntimeScene=mn,exports.loadSceneData=rt,exports.loadSceneWithAssets=ot,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&m(f(e)))},exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=n,exports.platformReadTextFile=r,exports.pointInWorldRect=Is,exports.prefabsPlugin=yt,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){nt.set(e,t)},exports.registerDrawCallback=function(e,t){ts.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(lt);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Ze,exports.screenToWorld=Rs,exports.setEditorMode=function(e){xn=e},exports.setLogLevel=function(e){Sn.setMinLevel(e)},exports.shutdownDrawAPI=Pt,exports.shutdownGLDebugAPI=Zt,exports.shutdownGeometryAPI=Dt,exports.shutdownMaterialAPI=Ne,exports.shutdownPostProcessAPI=Ot,exports.shutdownRendererAPI=Yt,exports.textInputPlugin=nn,exports.textPlugin=Ts,exports.uiInteractionPlugin=Qs,exports.uiLayoutPlugin=Xs,exports.uiMaskPlugin=ks,exports.uiPlugins=Pn,exports.unregisterDrawCallback=ss,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){Sn.warn(e,t,s)},exports.worldRectToScreen=Es,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=512,F=4294967295,B=4294967295;function U(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(U);const t={};for(const s in e)t[s]=U(e[s]);return t}let k=0;function D(e,t){const s=++k;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...U(t),...e}:U(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}}class _e{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_)}}class me{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.value_=this.get(e),t):(t=new _e(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const ye=fe({delta:0,elapsed:0,frameCount:0},"Time");function xe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class we{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_),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.slice()}}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 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=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 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;exports.Schedule=void 0,(Se=exports.Schedule||(exports.Schedule={}))[Se.Startup=0]="Startup",Se[Se.First=1]="First",Se[Se.PreUpdate=2]="PreUpdate",Se[Se.Update=3]="Update",Se[Se.PostUpdate=4]="PostUpdate",Se[Se.Last=5]="Last",Se[Se.FixedPreUpdate=10]="FixedPreUpdate",Se[Se.FixedUpdate=11]="FixedUpdate",Se[Se.FixedPostUpdate=12]="FixedPostUpdate";let Pe=0;function Te(e,t,s){const n=++Pe;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Ce(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Ae{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof be&&t[e].flush()}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 Ee{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 Me=fe(new Ee,"Input");class Re{constructor(e){this.target_=e??null}build(e){const s=new Ee;e.insertResource(Me,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,n){s.mouseX=t,s.mouseY=n,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,Te([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ie=new Re;function Fe(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]),o=Be(r);s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,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 ke(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}:ke(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)}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=Fe(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,ke(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=Fe(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){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),s=this.queryCache_.get(t);if(s&&s.version===this.worldVersion_)return s.result;let n=null,r=1/0;for(const t of e)if(!H(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<r&&(r=s,n=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=n?n.keys():this.entities_;for(const t of i){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const Le=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 $e;function We(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,($e=exports.BlendMode||(exports.BlendMode={}))[$e.Normal=0]="Normal",$e[$e.Additive=1]="Additive",$e[$e.Multiply=2]="Multiply",$e[$e.Screen=3]="Screen",$e[$e.PremultipliedAlpha=4]="PremultipliedAlpha";let ze=null,Oe=null,He=1;const je=new Map;function Ne(e){ze=e,Oe=e.getResourceManager(),et()}function Ve(){0!==Ye&&ze&&(ze._free(Ye),Ye=0),je.clear(),He=1,qe=!1,Oe=null,ze=null}function Xe(){if(!Oe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Oe}const Ge={createShader:(e,t)=>Xe().createShader(e,t),releaseShader(e){e>0&&Xe().releaseShader(e)},create(e){const t=He++,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 je.set(t,s),t},get:e=>je.get(e),setUniform(e,t,s){const n=je.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=je.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=je.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=je.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=je.get(e);s&&(s.depthTest=t)},getShader(e){const t=je.get(e);return t?.shader??0},release(e){je.delete(e)},isValid:e=>je.has(e),releaseAll(){je.clear()},createFromAsset(e,t){const 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=je.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=He++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return je.set(s,n),s},toAssetData(e,t){const s=je.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=je.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let qe=!1,Ye=0;const Je=4096,Ke=new Map;let Qe=null;function Ze(e){const t=(0===Ye&&ze&&(Ye=ze._malloc(Je)),Ye);if(0===t||!ze)return{ptr:0,count:0};let s=0,n=0;const r=ze.HEAPU8,o=ze.HEAPU32,i=ze.HEAPF32;for(const[a,l]of e){if(s+128>Je)break;let e=Ke.get(a);e||(Qe||(Qe=new TextEncoder),e=Qe.encode(a),Ke.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 et(){if(!ze||qe)return;ze.materialDataProvider=(e,t,s,n,r)=>{const o=je.get(e);if(!o)return ze.HEAPU32[t>>2]=0,ze.HEAPU32[s>>2]=0,ze.HEAPU32[n>>2]=0,void(ze.HEAPU32[r>>2]=0);ze.HEAPU32[t>>2]=o.shader,ze.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=Ze(o.uniforms);ze.HEAPU32[n>>2]=i,ze.HEAPU32[r>>2]=a},qe=!0}const tt={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 st{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)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 nt{constructor(e,t=""){this.cache_=new st,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&&(Ge.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ge.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:Ge.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 rt=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){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)at(e,t,s)}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 it(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=rt.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=rt.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)at(e,t,n)}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 at(e,t,s){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const n=V(s.type);n?e.insert(t,n,s.data):console.warn(`Unknown component type: ${s.type}`)}class lt{constructor(e){this.textureCache_=new st,this.shaderCache_=new st,this.jsonCache_=new st,this.textCache_=new st,this.binaryCache_=new st,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new st,this.prefabCache_=new st,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.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 nt(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))}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(n))}}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(),Ge.releaseAll(),this.textureCache_.clearAll(),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 it(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);return this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t))}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 Ge.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 Ge.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 ct=fe(null,"Assets");class ut{build(e){const t=e.wasmModule;t?e.insertResource(ct,new lt(t)):console.warn("AssetPlugin: No WASM module available")}}const dt=new ut;async function ht(e,t,s){const{entities:n,rootId:r}=await pt(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 it(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}}async function pt(e,t,s,n,r){const o=new Map;let i;if(void 0===n){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];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 pt(e,n.nestedPrefab.overrides,s,i,r);o.set(n.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),a.push(...t.entities);continue}const l=o.get(n.prefabEntityId),c=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:c?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};ft(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function ft(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 gt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return ht(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const _t=fe(null,"Prefabs");class mt{constructor(){this.name="PrefabsPlugin",this.dependencies=[ct]}build(e){const t=e.getResource(ct);e.insertResource(_t,new gt(e.world,t))}}const yt=new mt;let xt=null,wt=0,vt=0,bt=0;const St=new Float32Array(256);function Pt(e){xt=e,wt=xt._malloc(64),vt=xt._malloc(64),bt=xt._malloc(1024)}function Tt(){xt&&(wt&&(xt._free(wt),wt=0),vt&&(xt._free(vt),vt=0),bt&&(xt._free(bt),bt=0)),xt=null}function Ct(){if(!xt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return xt}const At={r:1,g:1,b:1,a:1},Et={begin(e){const t=Ct();t.HEAPF32.set(e,wt/4),t.draw_begin(wt)},end(){Ct().draw_end()},line(e,t,s,n=1){Ct().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){Ct().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){Ct().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){Ct().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){Ct().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=At){Ct().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=At){Ct().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){Ct().draw_setLayer(e)},setDepth(e){Ct().draw_setDepth(e)},getDrawCallCount:()=>xt?xt.draw_getDrawCallCount():0,getPrimitiveCount:()=>xt?xt.draw_getPrimitiveCount():0,setBlendMode(e){Ct().draw_setBlendMode(e)},setDepthTest(e){Ct().draw_setDepthTest(e)},drawMesh(e,t,s){const n=Ct();n.HEAPF32.set(s,vt/4),n.draw_mesh(e,t,vt)},drawMeshWithMaterial(e,t,s){const n=Ct(),r=Ge.get(t);if(!r)return;if(Et.setBlendMode(r.blendMode),Et.setDepthTest(r.depthTest),0===r.uniforms.size)return void Et.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,vt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Rt(t);if(!(n<0)){if(We(s))St[o++]=10,St[o++]=n,St[o++]=s.slot??e++,St[o++]=s.textureId;else if("number"==typeof s)St[o++]=1,St[o++]=n,St[o++]=s;else if(Array.isArray(s)){St[o++]=s.length,St[o++]=n;for(let e=0;e<s.length;e++)St[o++]=s[e]}else"w"in s?(St[o++]=4,St[o++]=n,St[o++]=s.x,St[o++]=s.y,St[o++]=s.z,St[o++]=s.w):"z"in s?(St[o++]=3,St[o++]=n,St[o++]=s.x,St[o++]=s.y,St[o++]=s.z):(St[o++]=2,St[o++]=n,St[o++]=s.x,St[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(St.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),bt/4),n.draw_meshWithUniforms(e,r.shader,vt,bt,o)):n.draw_mesh(e,r.shader,vt)}},Mt={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 Rt(e){return Mt[e]??-1}var It;exports.DataType=void 0,(It=exports.DataType||(exports.DataType={}))[It.Float=1]="Float",It[It.Float2=2]="Float2",It[It.Float3=3]="Float3",It[It.Float4=4]="Float4",It[It.Int=5]="Int",It[It.Int2=6]="Int2",It[It.Int3=7]="Int3",It[It.Int4=8]="Int4";let Ft=null,Bt=0,Ut=0,kt=0;function Dt(e){Ft=e,Bt=Ft._malloc(262144),Ut=Ft._malloc(65536),kt=Ft._malloc(256)}function Lt(){Ft&&(Bt&&Ft._free(Bt),Ut&&Ft._free(Ut),kt&&Ft._free(kt),Bt=0,Ut=0,kt=0),Ft=null}function $t(){if(!Ft)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ft}const Wt={create(e){const t=$t(),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,Bt/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,kt,r).set(o),t.geometry_init(s,Bt,n,kt,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,Ut,n).set(e.indices),t.geometry_setIndices16(s,Ut,n)}else{new Uint32Array(t.HEAPU8.buffer,Ut,n).set(e.indices),t.geometry_setIndices32(s,Ut,n)}}return s},updateVertices(e,t,s=0){const n=$t(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Bt/4),n.geometry_updateVertices(e,Bt,r,s)},release(e){e>0&&$t().geometry_release(e)},isValid:e=>!(!Ft||e<=0)&&Ft.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Wt.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 Wt.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 Wt.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 zt=null;function Ot(e){zt=e}function Ht(){zt&&Nt.isInitialized()&&Nt.shutdown(),zt=null}function jt(){if(!zt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return zt}const Nt={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:()=>!!zt&&zt.postprocess_isInitialized(),setBypass(e){jt().postprocess_setBypass(e)},isBypassed:()=>!zt||zt.postprocess_isBypassed(),createBlur:()=>Ge.createShader(Vt,"#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:()=>Ge.createShader(Vt,"#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:()=>Ge.createShader(Vt,"#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:()=>Ge.createShader(Vt,"#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")},Vt="#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 Xt;exports.RenderStage=void 0,(Xt=exports.RenderStage||(exports.RenderStage={}))[Xt.Background=0]="Background",Xt[Xt.Opaque=1]="Opaque",Xt[Xt.Transparent=2]="Transparent",Xt[Xt.Overlay=3]="Overlay";let Gt=null,qt=0;function Yt(e){Gt=e,qt=Gt._malloc(64)}function Jt(){Gt&&qt&&(Gt._free(qt),qt=0),Gt=null}const Kt={init(e,t){Gt?.renderer_init(e,t)},resize(e,t){Gt?.renderer_resize(e,t)},begin(e,t){Gt&&qt&&(Gt.HEAPF32.set(e,qt/4),Gt.renderer_begin(qt,t??0))},flush(){Gt?.renderer_flush()},end(){Gt?.renderer_end()},submitSprites(e){Gt&&Gt.renderer_submitSprites(e._cpp)},submitBitmapText(e){Gt&&Gt.renderer_submitBitmapText(e._cpp)},submitSpine(e){Gt&&Gt.renderer_submitSpine?.(e._cpp)},setStage(e){Gt?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Gt?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Gt?.renderer_releaseTarget(e)},getTargetTexture:e=>Gt?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Gt?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Gt?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Gt?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Gt?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Gt?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Gt?Gt.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Gt?{drawCalls:Gt.renderer_getDrawCalls(),triangles:Gt.renderer_getTriangles(),sprites:Gt.renderer_getSprites(),text:Gt.renderer_getText(),spine:Gt.renderer_getSpine?.()??0,meshes:Gt.renderer_getMeshes(),culled:Gt.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Qt=null;function Zt(e){Qt=e}function es(){Qt=null}const ts={enable(){Qt?.gl_enableErrorCheck(!0)},disable(){Qt?.gl_enableErrorCheck(!1)},check:e=>Qt?.gl_checkErrors(e)??0,diagnose(){Qt?.renderer_diagnose()}},ss=new Map;function ns(e,t,s){ss.set(e,{fn:t,scene:s??""})}function rs(e){ss.delete(e)}class os{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_||(Kt.resize(n,r),Nt.isInitialized()&&Nt.getPassCount()>0&&Nt.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Kt.setViewport(0,0,n,r),Kt.clearBuffers(3),Kt.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Kt.submitSprites(t),Kt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Kt.submitSpine(t),Kt.flush(),this.executeDrawCallbacks(s,o),Kt.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;Kt.setViewport(n.x,n.y,n.w,n.h),Kt.setScissor(n.x,n.y,n.w,n.h,!0),Kt.clearBuffers(r),Kt.setScissor(0,0,0,0,!1),Kt.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Kt.submitSprites(t),Kt.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Kt.submitSpine(t),Kt.flush(),this.executeDrawCallbacks(s,o),Kt.end()}executeDrawCallbacks(e,t){const s=ss;if(s.size>0){Et.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)}Et.end();for(const e of n)rs(e)}}}const is="__scene_transition_overlay__",as={r:0,g:0,b:0,a:1};class ls{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class cs{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),ns(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Nt.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Nt.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 us{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.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){"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??as;t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},ns(is,()=>{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;Et.setLayer(9999),Et.setDepth(9999),Et.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)})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,rs(is),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){return this.scenes_.get(e).status="running",this.activeScene_=e,this.contexts_.get(e)}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new ls(t);this.scenes_.set(e,s);const n=new cs(s,this.app_);this.contexts_.set(e,n);let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ct)?this.app_.getResource(ct):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(ct)&&(t.assetServer=this.app_.getResource(ct));const n=await it(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=hs(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}async loadAdditive(e){if(this.scenes_.has(e)){return this.scenes_.get(e).status="running",this.additiveScenes_.add(e),this.contexts_.get(e)}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new ls(t);this.scenes_.set(e,s);const n=new cs(s,this.app_);this.contexts_.set(e,n);let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ct)?this.app_.getResource(ct):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(ct)&&(t.assetServer=this.app_.getResource(ct));const n=await it(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=hs(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}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())rs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Nt.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{Nt.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 ds=fe(null,"SceneManager");function hs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(ds).getSceneStatus(t)&&s._fn(...n)}}}const ps={name:"SceneManager",build(e){const t=new us(e);e.insertResource(ds,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ds),s=t.getInitial();s&&t.load(s)}};e.addSystemToSchedule(exports.Schedule.Startup,s)}};class fs{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.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.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 me;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new fs}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}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(ds).register(e),this}setInitialScene(e){return this.getResource(ds).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ae(this.world_,this.resources_),this.resources_.insert(ye,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1;const e=[es,Jt,Ht,Lt,Ve,Tt];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_){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;console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s)}}}updateTime(e){const t=this.resources_.get(ye);t.delta=e,t.elapsed+=e,t.frameCount++}}const gs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function _s(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 ms(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,ae);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*s/(i.h*n);let u,d=0,h=0;if(r.projectionType===G.Orthographic){if(h=r.orthoSize,l){h=_s(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,a,l.scaleMode,l.matchWidthOrHeight)}d=h*a,u=xs(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=vs(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=Ss(o.position.x,o.position.y,o.position.z);c.push({entity:e,viewProjection:new Float32Array(Ts(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 ys=new Float32Array(16);function xs(e,t,s,n,r,o){const i=ys;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 ws=new Float32Array(16);function vs(e,t,s,n){const r=ws;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 bs=new Float32Array(16);function Ss(e,t,s){const n=bs;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 Ps=new Float32Array(16);function Ts(e,t){const s=Ps;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 Cs,As,Es;exports.TextAlign=void 0,(Cs=exports.TextAlign||(exports.TextAlign={}))[Cs.Left=0]="Left",Cs[Cs.Center=1]="Center",Cs[Cs.Right=2]="Right",exports.TextVerticalAlign=void 0,(As=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[As.Top=0]="Top",As[As.Middle=1]="Middle",As[As.Bottom=2]="Bottom",exports.TextOverflow=void 0,(Es=exports.TextOverflow||(exports.TextOverflow={}))[Es.Visible=0]="Visible",Es[Es.Clip=1]="Clip",Es[Es.Ellipsis=2]="Ellipsis";const Ms=$("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}),Rs=$("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 Is{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 Fs(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Bs(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 Us{build(e){N("Text",Ms);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Is(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Ms));for(const e of r.keys())n.valid(e)&&n.has(e,Ms)||r.delete(e);const e=n.getEntitiesWithComponents([Ms]);for(const t of e){const e=n.get(t,Ms),o=n.has(t,Rs)?n.get(t,Rs):null,i=r.get(t);if(i&&!Bs(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,Fs(e,o))}}))}}const ks=new Us,Ds=$("UIMask",{enabled:!0});function Ls(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 $s(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 Ws(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 zs(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 Os(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 Hs(e,t,s,n,r,o,i){if(!e.has(t,Rs)||!e.has(t,K))return null;const a=e.get(t,Rs),l=e.get(t,K),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return $s(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function js(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Ds]);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,Ds).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=Hs(t,s,r,o,i,a,l);e&&(n=Ls(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Hs(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 Ns{build(e){if(N("UIMask",Ds),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(js(e.wasmModule,e.world))}}const Vs=new Ns,Xs=$("Interactable",{enabled:!0}),Gs=$("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 Ys=$("Button",{state:exports.ButtonState.Normal,transition:null});class Js{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 Ks=fe(new Js,"UIEvents"),Qs=W("ScreenSpace");function Zs(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 en(e,t,s,n,r,o){if(!e.has(t,Rs))return;const i=e.get(t,Rs),a=Zs(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)&&en(e,t,a.rect,a.centerX,a.centerY,!1)}class tn{build(e){N("UIRect",Rs);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([ge(Le)],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([Qs,Rs,J]);for(const e of o)en(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const sn=new tn,nn=new Float32Array(16),rn=new Float32Array(16);let on=!0,an=1;class ln{build(e){N("Interactable",Xs),N("Button",Ys);const t=e.world,s=new Js;e.insertResource(Ks,s);let n=null,r=null;an="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([ge(Me),ge(Le)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([Gs]);for(const e of i){const s=t.get(e,Gs);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*an,l=o.screenH-e.mouseY*an;!function(e){let t=!1;for(let s=0;s<16;s++)if(rn[s]!==e[s]){t=!0;break}t&&(rn.set(e),on=!0)}(o.viewProjection),on&&(Ws(o.viewProjection,nn),on=!1);const c=zs(a,l,nn,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Xs,Rs,K]);let d=null,h=-1/0;for(const e of u){t.has(e,Gs)||t.insert(e,Gs);if(!t.get(e,Xs).enabled)continue;const s=t.get(e,K),n=t.get(e,Rs),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(Os(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,Gs)){t.get(n,Gs).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,Gs).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Gs);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,Gs)){const e=t.get(r,Gs);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,Te([],()=>{const e=t.getEntitiesWithComponents([Ys]);for(const s of e){if(t.has(s,Xs)||t.insert(s,Xs,{enabled:!0}),!t.has(s,Gs))continue;const e=t.get(s,Gs),n=t.get(s,Ys),r=t.get(s,Xs),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 cn=new ln,un=$("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 dn{build(e){N("TextInput",un);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;function f(){if(null===a||!s.valid(a))return;const t=s.get(a,un);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(Ks).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,m()}function g(e){if(a===e)return;_();const t=s.get(e,un);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),m())}function _(){if(null!==a&&s.valid(a)&&s.has(a,un)){const e=s.get(a,un);e.focused=!1,e.dirty=!0}a=null,p.blur()}function m(){c=!0,u=0}function y(e,i,a,l){(r.width<a||r.height<l)&&(r.width=pn(Math.max(r.width,a)),r.height=pn(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=hn(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=hn(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",()=>{l||null===a||f()}),p.addEventListener("compositionstart",()=>{l=!0}),p.addEventListener("compositionend",()=>{l=!1,f()}),p.addEventListener("keydown",t=>{if(null===a)return;if("Escape"===t.key)return void _();const n=s.get(a,un);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Ks).emit(a,"submit"),void _()}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,m())}),p.addEventListener("blur",()=>{if(null!==a&&s.valid(a)&&s.has(a,un)){const e=s.get(a,un);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([ge(Ks)],e=>{const t=s.getEntitiesWithComponents([un,Xs]);for(const e of t){if(!s.has(e,Gs))continue;if(s.get(e,Gs).justPressed)return void g(e)}if(null!==a){const e=s.getEntitiesWithComponents([Xs]);for(const t of e){if(s.has(t,un))continue;if(!s.has(t,Gs))continue;if(s.get(t,Gs).justPressed)return void _()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Te([],()=>{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,un)))){s.get(a,un).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,un)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([un,Rs]);for(const e of i){const t=s.get(e,un);if(!t.dirty)continue;const n=s.get(e,Rs),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}),y(e,t,r,o),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 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 pn(e){let t=1;for(;t<e;)t*=2;return t}const fn=new dn,gn={r:0,g:0,b:0},_n="__scene_transition_overlay__";function mn(e,t,s,n){return new Promise(r=>{const o=performance.now();ns(_n,()=>{const i=(performance.now()-o)/1e3,a=Math.min(i/e,1),l=t+(s-t)*a;Et.setLayer(9999),Et.setDepth(9999),Et.rect({x:0,y:0},{x:2e4,y:2e4},{r:n.r,g:n.g,b:n.b,a:l}),a>=1&&(rs(_n),r())})})}async function yn(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=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),wn=fe(null,"PhysicsAPI");function vn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function bn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Sn{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=yn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ee]);for(const s of t){const t=e.world.get(s,ee);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Te([ge(ye)],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=vn(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),Pn(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=vn(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=vn(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=bn(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(xn,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(wn,Tn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Pn(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 Tn{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(Tn.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 Cn(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 An(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 En(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 Mn(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]=Cn(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=An(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=Cn(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 Sn("",{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=Cn(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=Ge.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=Ge.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n),f=ot(e.world,s);if(l&&e.hasResource(ds))for(const t of f.values())e.world.insert(t,ae,{scene:l,persistent:!1});if(function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const r=e.get(t,Q);r&&(r.texture=s[n.data.texture]||0,e.insert(t,Q,r))}}}(e.world,s,c,f),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if("BitmapText"!==n.type||!n.data.font||"string"!=typeof n.data.font)continue;const r=s[n.data.font]||0;if(!r)continue;const o=e.get(t,re);o&&(o.font=r,e.insert(t,re,o))}}}(e.world,s,h,f),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const r=s[n.data.material]||0;if(r)if("Sprite"===n.type){const s=e.get(t,Q);s&&(s.material=r,e.insert(t,Q,s))}else if("SpineAnimation"===n.type){const s=e.get(t,oe);s&&(s.material=r,e.insert(t,oe,s))}}}}(e.world,s,p,f),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=En(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(ct);t&&t.setAddressableManifest(a)}}class Rn{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 In="__preview__";const Fn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Kt.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Kt.getTargetTexture(s),width:e.width,height:e.height}},release(e){Kt.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Kt.releaseRenderTarget(e._handle),Fn.create({width:t,height:s,depth:!0})),begin(e,t){Kt.begin(t,e._handle)},end(){Kt.end()},getDepthTexture:e=>Kt.getTargetDepthTexture(e._handle)};let Bn=!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 kn{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 Dn{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new kn)}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 Ln=new Dn;const $n=[ks,Vs,sn,cn,fn];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=fs,exports.AssetPlugin=ut,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=lt,exports.Assets=ct,exports.AsyncCache=st,exports.BitmapText=re,exports.BodyType=he,exports.BoxCollider=ce,exports.Button=Ys,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=be,exports.DEFAULT_DESIGN_HEIGHT=R,exports.DEFAULT_DESIGN_WIDTH=M,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=I,exports.Draw=Et,exports.EntityCommands=ve,exports.GLDebug=ts,exports.Geometry=Wt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Input=Me,exports.InputPlugin=Re,exports.InputState=Ee,exports.Interactable=Xs,exports.LocalTransform=J,exports.Logger=Dn,exports.Material=Ge,exports.MaterialLoader=nt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=Tn,exports.PhysicsEvents=xn,exports.PhysicsPlugin=Sn,exports.PostProcess=Nt,exports.PrefabServer=gt,exports.Prefabs=_t,exports.PrefabsPlugin=mt,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(ds);t.register({name:In,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(In),this.loadPromise_=t.load(In).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 Rn(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await Mn(this.app_,this.app_.wasmModule,t,n,r)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Z]);for(const n of s){if(e.get(n,Z).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([ee]);for(const r of n){const n=e.get(r,ee);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(ds).getScene(In),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)}}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.eventSource_.addEventListener("message",async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())}),this.eventSource_.addEventListener("error",e=>{console.error("[PreviewPlugin] EventSource error:",e)})}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(ds);await e.switchTo(In),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)=>{xe(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=we,exports.RenderPipeline=os,exports.RenderTexture=Fn,exports.Renderer=Kt,exports.Res=ge,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=le,exports.ScaleMode=Y,exports.SceneManager=ds,exports.SceneManagerState=us,exports.SceneOwner=ae,exports.ScreenSpace=Qs,exports.ShaderSources=tt,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ae,exports.Text=Ms,exports.TextInput=un,exports.TextInputPlugin=dn,exports.TextPlugin=Us,exports.TextRenderer=Is,exports.Time=ye,exports.UICameraInfo=Le,exports.UIEventQueue=Js,exports.UIEvents=Ks,exports.UIInteraction=Gs,exports.UIInteractionPlugin=ln,exports.UILayoutPlugin=tn,exports.UIMask=Ds,exports.UIMaskPlugin=Ns,exports.UIRect=Rs,exports.Velocity=te,exports.WebAssetProvider=Rn,exports.World=De,exports.WorldTransform=K,exports.addStartupSystem=function(e){Ce().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Ce().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Ce().push({schedule:e,system:t})},exports.assetPlugin=dt,exports.clearDrawCallbacks=function(){ss.clear()},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=Zs,exports.createMaskProcessor=js,exports.createWebApp=function(e,t){return function(e,t){const s=fs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Pt(e),Ne(e),Dt(e),Ot(e),Yt(e),Zt(e);const r=new os;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=ms(e,n,t,r));const i=s.getResource(Le);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(Le,{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;Kt.setClearColor(e.x,e.y,e.z,e.w)}const d=(a()-o)/1e3;let h;if(Kt.resize(t,c),Nt.isInitialized()&&Nt.getPassCount()>0&&!Nt.isBypassed()&&Nt.resize(t,c),s.hasResource(ds)){const e=s.getResource(ds).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=ms(e,n,t,c,s.world,h);if(l(t,c,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:gs,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})}Kt.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(dt),s.addPlugin(yt),s.addPlugin(Ie),s.addPlugin(ps),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:$n,...t})},exports.debug=function(e,t,s){Ln.debug(e,t,s)},exports.defineComponent=$,exports.defineResource=fe,exports.defineSystem=Te,exports.defineTag=W,exports.error=function(e,t,s){Ln.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=rt.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?U(t._default):null},exports.getCustomExtensions=m,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return Ln},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){Ln.info(e,t,s)},exports.initDrawAPI=Pt,exports.initGLDebugAPI=Zt,exports.initGeometryAPI=Dt,exports.initMaterialAPI=Ne,exports.initPostProcessAPI=Ot,exports.initRendererAPI=Yt,exports.inputPlugin=Ie,exports.instantiatePrefab=ht,exports.intersectRects=Ls,exports.invertMatrix4=Ws,exports.isBuiltinComponent=H,exports.isCustomExtension=y,exports.isEditor=function(){return Bn},exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Bn},exports.isTextureRef=We,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=at,exports.loadPhysicsModule=yn,exports.loadRuntimeScene=Mn,exports.loadSceneData=ot,exports.loadSceneWithAssets=it,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=Os,exports.prefabsPlugin=yt,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){rt.set(e,t)},exports.registerDrawCallback=ns,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ct);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=et,exports.sceneManagerPlugin=ps,exports.screenToWorld=zs,exports.setEditorMode=function(e){Bn=e},exports.setLogLevel=function(e){Ln.setMinLevel(e)},exports.shutdownDrawAPI=Tt,exports.shutdownGLDebugAPI=es,exports.shutdownGeometryAPI=Lt,exports.shutdownMaterialAPI=Ve,exports.shutdownPostProcessAPI=Ht,exports.shutdownRendererAPI=Jt,exports.textInputPlugin=fn,exports.textPlugin=ks,exports.transitionTo=async function(e,t,s){const n=e.getResource(ds),r=n.getActive();"fade"===s.type?await async function(e,t,s,n){const r=n.color??gn,o=n.duration/2;await mn(o,0,1,r),t&&await e.unload(t);await e.load(s),await mn(o,1,0,r)}(n,r,t,s):await async function(e,t,s,n){await e.loadAdditive(s);const r=n.color??gn;await mn(n.duration,1,0,r),t&&await e.unload(t)}(n,r,t,s)},exports.uiInteractionPlugin=cn,exports.uiLayoutPlugin=sn,exports.uiMaskPlugin=Vs,exports.uiPlugins=$n,exports.unregisterDrawCallback=rs,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){Ln.warn(e,t,s)},exports.worldRectToScreen=$s,exports.wrapSceneSystem=hs,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.mapdiff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.jsindex 9ea6162cc..8cf050a55 100644--- a/desktop/public/sdk/cjs/index.wechat.js+++ b/desktop/public/sdk/cjs/index.wechat.js@@ -1,2 +1,2 @@-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}function f(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const m=[{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"},_=new Map,y=new Set;for(const e of m)for(const t of e.extensions)_.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 _.get(w(e))}function b(e){return x(e)?.editorType??"unknown"}function v(e){return x(e)?.addressableType??null}function P(e){for(const t of m)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function S(e){return y.has(e.toLowerCase())}function C(){return y}function T(e){return"string"==typeof e&&(!!e.includes("/")&&S(w(e)))}function E(){const e=[];for(const t of m)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function A(){return E().map(e=>({type:"suffix",value:e}))}function M(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 B(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(R(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function U(e){return new Promise((t,n)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(B(e,t.errMsg)))}})})}function k(e,t="utf-8"){return new Promise((n,s)=>{F().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(B(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function z(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function D(e,t){return new Promise((n,s)=>{F().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function W(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function O(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}async function H(e){return O(await W(e))}let L=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return U(e)}async readTextFile(e){return k(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){const{pixelRatio:n}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX*n,s.clientY*n)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX*n,s.clientY*n)}),wx.onTouchEnd(t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)})}},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,n=0)=>({x:e,y:t,z:n}),Z=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),ee=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),te=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function ne(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(ne);const t={};for(const n in e)t[n]=ne(e[n]);return t}let se=0;function re(e,t){const n=++se;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...ne(t),...e}:ne(t)}}function oe(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function ie(e,t){const n=oe(),s=n.get(e);if(s)return s;const r=re(e,t);return n.set(e,r),ue(e,t,!1),r}function ae(e){const t=oe(),n=t.get(e);if(n)return n;const s=re(e,{});return t.set(e,s),ue(e,{},!0),s}function le(e){return oe().get(e)}function ce(){oe().clear()}function ue(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function de(e){return!0===e._builtin}const he=new Map;function fe(e,t){he.set(e,t)}function pe(e){return he.get(e)??le(e)}function me(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return he.set(e,n),n}const ge={Perspective:0,Orthographic:1},_e={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ye={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},we=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}}),xe=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}}),be=me("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}),ve=me("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:_e.ColorAndDepth}),Pe=me("Canvas",{designResolution:{x:N,y:X},pixelsPerUnit:100,scaleMode:ye.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Se=me("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ce=me("Parent",{entity:0}),Te=me("Children",{entities:[]}),Ee=me("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:J}),Ae=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}),Me={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};function Re(e){const t=pe(e);return t?ne(t._default):null}fe("Name",Me);const Ie=me("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Fe=me("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Be=me("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Ue=me("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ke={Static:0,Kinematic:1,Dynamic:2};let $e=0;function ze(e,t){const n=++$e;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function De(e){return{_type:"res",_resource:e}}function We(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_)}}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.value_=this.get(e),t):(t=new Oe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Le=ze({delta:0,elapsed:0,frameCount:0},"Time");function je(e){return{_type:"mut",_component:e}}function Ne(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Xe(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{Ne(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class Ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>Ne(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.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 s){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 n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a.slice()}}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,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function qe(){return{_type:"commands"}}class Ge{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=de(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Ye{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ge(this,null);return this.spawned_.push(e),e}entity(e){return new Ge(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Je;!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"}(Je||(Je={}));let Ke=0;function Qe(e,t,n){const s=++Ke;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Ze(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function et(e){Ze().push({schedule:Je.Update,system:e})}function tt(e){Ze().push({schedule:Je.Startup,system:e})}function nt(e,t){Ze().push({schedule:e,system:t})}class st{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ye&&t[e].flush()}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 Ye(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class rt{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 rt,"Input");class it{constructor(e){this.target_=e??null}build(e){const n=new rt;e.insertResource(ot,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Je.Last,Qe([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const at=new it;function lt(e,t,n){const s=[];for(const[e,r]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const n=ct(t[e]),o=ct(r);n!==o&&null!=r&&s.push({field:e,expected:n,actual:o,value:r})}return s}function ct(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ut(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}function dt(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:dt(e)}}return t}class ht{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 n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}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,n){return de(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return de(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return de(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(de(t)){if(!this.cppRegistry_)return null;const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.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.");de(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=lt(t._name,t._default,s);if(e.length>0)throw new Error(ut(t._name,e))}const r={...t._default,...s};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,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const r=lt(t._name,t._default,e);if(r.length>0)throw new Error(ut(t._name,r));s=e}const r=t.create(s);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),n=this.queryCache_.get(t);if(n&&n.version===this.worldVersion_)return n.result;let s=null,r=1/0;for(const t of e)if(!de(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<r&&(r=n,s=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=s?s.keys():this.entities_;for(const t of i){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const ft=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 pt;function mt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(pt||(pt={}));let gt=null,_t=null,yt=1;const wt=new Map;function xt(e){gt=e,_t=e.getResourceManager(),Rt()}function bt(){0!==Ct&>&&(gt._free(Ct),Ct=0),wt.clear(),yt=1,St=!1,_t=null,gt=null}function vt(){if(!_t)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return _t}const Pt={createShader:(e,t)=>vt().createShader(e,t),releaseShader(e){e>0&&vt().releaseShader(e)},create(e){const t=yt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??pt.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return wt.set(t,n),t},get:e=>wt.get(e),setUniform(e,t,n){const s=wt.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=wt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=wt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=wt.get(e);return t?.blendMode??pt.Normal},setDepthTest(e,t){const n=wt.get(e);n&&(n.depthTest=t)},getShader(e){const t=wt.get(e);return t?.shader??0},release(e){wt.delete(e)},isValid:e=>wt.has(e),releaseAll(){wt.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??pt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=wt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=yt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return wt.set(n,s),n},toAssetData(e,t){const n=wt.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=wt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let St=!1,Ct=0;const Tt=4096,Et=new Map;let At=null;function Mt(e){const t=(0===Ct&>&&(Ct=gt._malloc(Tt)),Ct);if(0===t||!gt)return{ptr:0,count:0};let n=0,s=0;const r=gt.HEAPU8,o=gt.HEAPU32,i=gt.HEAPF32;for(const[a,l]of e){if(n+128>Tt)break;let e=Et.get(a);e||(At||(At=new TextEncoder),e=At.encode(a),Et.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=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+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function Rt(){if(!gt||St)return;gt.materialDataProvider=(e,t,n,s,r)=>{const o=wt.get(e);if(!o)return gt.HEAPU32[t>>2]=0,gt.HEAPU32[n>>2]=0,gt.HEAPU32[s>>2]=0,void(gt.HEAPU32[r>>2]=0);gt.HEAPU32[t>>2]=o.shader,gt.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Mt(o.uniforms);gt.HEAPU32[s>>2]=i,gt.HEAPU32[r>>2]=a},St=!0}const It={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 Ft{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Bt{constructor(e,t=""){this.cache_=new Ft,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 c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:Pt.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const Ut=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function kt(e,t){Ut.set(e,t)}function $t(e){const t=Ut.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function zt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Me,{value:s.name}),!1!==s.visible)for(const n of s.components)Wt(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function Dt(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ut.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const s=await t.loadMaterial(e,n);u.set(e,s.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 s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ut.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=u.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Me,{value:n.name}),!1!==n.visible)for(const s of n.components)Wt(e,t,s)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Wt(e,t,n){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const s=pe(n.type);s?e.insert(t,s,n.data):console.warn(`Unknown component type: ${n.type}`)}function Ot(e,t){const n=e.getEntitiesWithComponents([ve]);for(const s of n){const n=e.get(s,ve);n&&(n.aspectRatio=t,e.insert(s,ve,n))}}function Ht(e,t){const n=e.getEntitiesWithComponents([Me]);for(const s of n){const n=e.get(s,Me);if(n&&n.value===t)return s}return null}class Lt{constructor(e){this.textureCache_=new Ft,this.shaderCache_=new Ft,this.jsonCache_=new Ft,this.textCache_=new Ft,this.binaryCache_=new Ft,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ft,this.prefabCache_=new Ft,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.module_=e,this.canvas_=d(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,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}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.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===x(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(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Dt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Pt.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return Pt.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const jt=ze(null,"Assets");class Nt{build(e){const t=e.wasmModule;t?e.insertResource(jt,new Lt(t)):console.warn("AssetPlugin: No WASM module available")}}const Xt=new Nt;class Vt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function qt(e,t){const n=e.getResource(jt);n&&n.registerEmbeddedAssets(t)}async function Gt(e,t,n){const{entities:s,rootId:r}=await Yt(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await Dt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function Yt(e,t,n,s,r){const o=new Map;let i;if(void 0===s){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Yt(e,s.nestedPrefab.overrides,n,i,r);o.set(s.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==s.parent?o.get(s.parent)??null:null),a.push(...t.entities);continue}const l=o.get(s.prefabEntityId),c=s.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:s.prefabEntityId,name:s.name,parent:c?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Jt(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function Jt(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Kt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Gt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Qt=ze(null,"Prefabs");class Zt{constructor(){this.name="PrefabsPlugin",this.dependencies=[jt]}build(e){const t=e.getResource(jt);e.insertResource(Qt,new Kt(e.world,t))}}const en=new Zt;let tn=null,nn=0,sn=0,rn=0;const on=new Float32Array(256);function an(e){tn=e,nn=tn._malloc(64),sn=tn._malloc(64),rn=tn._malloc(1024)}function ln(){tn&&(nn&&(tn._free(nn),nn=0),sn&&(tn._free(sn),sn=0),rn&&(tn._free(rn),rn=0)),tn=null}function cn(){if(!tn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return tn}const un={r:1,g:1,b:1,a:1},dn={begin(e){const t=cn();t.HEAPF32.set(e,nn/4),t.draw_begin(nn)},end(){cn().draw_end()},line(e,t,n,s=1){cn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){cn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){cn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){cn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){cn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=un){cn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=un){cn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){cn().draw_setLayer(e)},setDepth(e){cn().draw_setDepth(e)},getDrawCallCount:()=>tn?tn.draw_getDrawCallCount():0,getPrimitiveCount:()=>tn?tn.draw_getPrimitiveCount():0,setBlendMode(e){cn().draw_setBlendMode(e)},setDepthTest(e){cn().draw_setDepthTest(e)},drawMesh(e,t,n){const s=cn();s.HEAPF32.set(n,sn/4),s.draw_mesh(e,t,sn)},drawMeshWithMaterial(e,t,n){const s=cn(),r=Pt.get(t);if(!r)return;if(dn.setBlendMode(r.blendMode),dn.setDepthTest(r.depthTest),0===r.uniforms.size)return void dn.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,sn/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=fn(t);if(!(s<0)){if(mt(n))on[o++]=10,on[o++]=s,on[o++]=n.slot??e++,on[o++]=n.textureId;else if("number"==typeof n)on[o++]=1,on[o++]=s,on[o++]=n;else if(Array.isArray(n)){on[o++]=n.length,on[o++]=s;for(let e=0;e<n.length;e++)on[o++]=n[e]}else"w"in n?(on[o++]=4,on[o++]=s,on[o++]=n.x,on[o++]=n.y,on[o++]=n.z,on[o++]=n.w):"z"in n?(on[o++]=3,on[o++]=s,on[o++]=n.x,on[o++]=n.y,on[o++]=n.z):(on[o++]=2,on[o++]=s,on[o++]=n.x,on[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(on.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),rn/4),s.draw_meshWithUniforms(e,r.shader,sn,rn,o)):s.draw_mesh(e,r.shader,sn)}},hn={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 fn(e){return hn[e]??-1}var pn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(pn||(pn={}));let mn=null,gn=0,_n=0,yn=0;function wn(e){mn=e,gn=mn._malloc(262144),_n=mn._malloc(65536),yn=mn._malloc(256)}function xn(){mn&&(gn&&mn._free(gn),_n&&mn._free(_n),yn&&mn._free(yn),gn=0,_n=0,yn=0),mn=null}function bn(){if(!mn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return mn}const vn={create(e){const t=bn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,gn/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,yn,r).set(o),t.geometry_init(n,gn,s,yn,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,_n,s).set(e.indices),t.geometry_setIndices16(n,_n,s)}else{new Uint32Array(t.HEAPU8.buffer,_n,s).set(e.indices),t.geometry_setIndices32(n,_n,s)}}return n},updateVertices(e,t,n=0){const s=bn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,gn/4),s.geometry_updateVertices(e,gn,r,n)},release(e){e>0&&bn().geometry_release(e)},isValid:e=>!(!mn||e<=0)&&mn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return vn.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return vn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return vn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:pn.Float2},{name:"a_texCoord",type:pn.Float2}],indices:new Uint16Array(i)})}};let Pn=null;function Sn(e){Pn=e}function Cn(){Pn&&En.isInitialized()&&En.shutdown(),Pn=null}function Tn(){if(!Pn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Pn}const En={init:(e,t)=>Tn().postprocess_init(e,t),shutdown(){Tn().postprocess_shutdown()},resize(e,t){Tn().postprocess_resize(e,t)},addPass:(e,t)=>Tn().postprocess_addPass(e,t),removePass(e){Tn().postprocess_removePass(e)},setEnabled(e,t){Tn().postprocess_setPassEnabled(e,t)},isEnabled:e=>Tn().postprocess_isPassEnabled(e),setUniform(e,t,n){Tn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Tn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Tn().postprocess_begin()},end(){Tn().postprocess_end()},getPassCount:()=>Tn().postprocess_getPassCount(),isInitialized:()=>!!Pn&&Pn.postprocess_isInitialized(),setBypass(e){Tn().postprocess_setBypass(e)},isBypassed:()=>!Pn||Pn.postprocess_isBypassed(),createBlur:()=>Pt.createShader(An,"#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(An,"#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(An,"#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(An,"#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")},An="#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 Mn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Mn||(Mn={}));let Rn=null,In=0;function Fn(e){Rn=e,In=Rn._malloc(64)}function Bn(){Rn&&In&&(Rn._free(In),In=0),Rn=null}const Un={init(e,t){Rn?.renderer_init(e,t)},resize(e,t){Rn?.renderer_resize(e,t)},begin(e,t){Rn&&In&&(Rn.HEAPF32.set(e,In/4),Rn.renderer_begin(In,t??0))},flush(){Rn?.renderer_flush()},end(){Rn?.renderer_end()},submitSprites(e){Rn&&Rn.renderer_submitSprites(e._cpp)},submitBitmapText(e){Rn&&Rn.renderer_submitBitmapText(e._cpp)},submitSpine(e){Rn&&Rn.renderer_submitSpine?.(e._cpp)},setStage(e){Rn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Rn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Rn?.renderer_releaseTarget(e)},getTargetTexture:e=>Rn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Rn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Rn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Rn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Rn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Rn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Rn?Rn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Rn?{drawCalls:Rn.renderer_getDrawCalls(),triangles:Rn.renderer_getTriangles(),sprites:Rn.renderer_getSprites(),text:Rn.renderer_getText(),spine:Rn.renderer_getSpine?.()??0,meshes:Rn.renderer_getMeshes(),culled:Rn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let kn=null;function $n(e){kn=e}function zn(){kn=null}const Dn={enable(){kn?.gl_enableErrorCheck(!0)},disable(){kn?.gl_enableErrorCheck(!1)},check:e=>kn?.gl_checkErrors(e)??0,diagnose(){kn?.renderer_diagnose()}},Wn=new Map;function On(e,t){Wn.set(e,t)}function Hn(e){Wn.delete(e)}function Ln(){Wn.clear()}class jn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(Un.resize(s,r),En.isInitialized()&&En.getPassCount()>0&&En.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Un.setViewport(0,0,s,r),Un.clearBuffers(3),Un.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Un.submitSprites(t),Un.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Un.submitSpine(t),Un.flush(),this.executeDrawCallbacks(n,o),Un.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Un.setViewport(s.x,s.y,s.w,s.h),Un.setScissor(s.x,s.y,s.w,s.h,!0),Un.clearBuffers(r),Un.setScissor(0,0,0,0,!1),Un.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Un.submitSprites(t),Un.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Un.submitSpine(t),Un.flush(),this.executeDrawCallbacks(n,o),Un.end()}executeDrawCallbacks(e,t){const n=Wn;if(n.size>0){dn.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}dn.end();for(const e of s)Hn(e)}}}class Nn{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.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,.25);this.updateTime(n),this.world_.resetQueryPool(),this.runSchedule(Je.First),this.fixedAccumulator_+=n;let s=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&s<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Je.FixedPreUpdate),this.runSchedule(Je.FixedUpdate),this.runSchedule(Je.FixedPostUpdate),s++;s>=8&&(this.fixedAccumulator_=0),this.runSchedule(Je.PreUpdate),this.runSchedule(Je.Update),this.runSchedule(Je.PostUpdate),this.runSchedule(Je.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ht,this.resources_=new He;for(const e of Object.values(Je))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Nn}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this}addSystem(e){return this.addSystemToSchedule(Je.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Je.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}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new st(this.world_,this.resources_),this.resources_.insert(Le,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Je.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1;const e=[zn,Bn,Cn,xn,bt,ln];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const r=t.get(s);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,r=new Set,o=i=>{if(s.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}r.delete(i),s.add(i),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){let t=this.systems_.get(e);if(t&&this.runner_){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 n=e.system._name;console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n)}}}updateTime(e){const t=this.resources_.get(Le);t.delta=e,t.elapsed+=e,t.frameCount++}}function Xn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Vn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function qn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case ye.FixedWidth:return o;case ye.FixedHeight:return i;case ye.Expand:return Math.max(o,i);case ye.Shrink:return Math.min(o,i);case ye.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Gn(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(r.projectionType===ge.Orthographic){if(h=r.orthoSize,o){h=qn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=Jn(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Qn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=es(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:new Float32Array(ns(u,f)),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const Yn=new Float32Array(16);function Jn(e,t,n,s,r,o){const i=Yn;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const Kn=new Float32Array(16);function Qn(e,t,n,s){const r=Kn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const Zn=new Float32Array(16);function es(e,t,n){const s=Zn;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const ts=new Float32Array(16);function ns(e,t){const n=ts;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var ss,rs,os;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(ss||(ss={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(rs||(rs={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(os||(os={}));const is=ie("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:ss.Left,verticalAlign:rs.Top,wordWrap:!0,overflow:os.Visible,lineHeight:1.2}),as=ie("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=d(q,q),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===os.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(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),_=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${_}, ${y})`,r&&e.overflow===os.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case rs.Top:x=u;break;case rs.Middle:x=(p-w)/2;break;case rs.Bottom:x=p-w-u;break;default:x=u}else x=u;let b=x;for(const t of l){let s;switch(e.align){case ss.Left:s=u;break;case ss.Center:s=f/2;break;case ss.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}r&&e.overflow===os.Clip&&n.restore();const v=n.getImageData(0,0,f,p),P=new Uint8Array(v.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const T=S.createTexture(f,p,C,P.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 n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case ss.Left:return"left";case ss.Center:return"center";case ss.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function cs(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 us(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class ds{build(e){fe("Text",is);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ls(t),s=e.world,r=new Map;e.addSystemToSchedule(Je.PreUpdate,Qe([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,is));for(const e of r.keys())s.valid(e)&&s.has(e,is)||r.delete(e);const e=s.getEntitiesWithComponents([is]);for(const t of e){const e=s.get(t,is),o=s.has(t,as)?s.get(t,as):null,i=r.get(t);if(i&&!us(i,e,o))continue;s.has(t,be)||s.insert(t,be,{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=n.renderForEntity(t,e,o),l=s.get(t,be);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,be,l),r.set(t,cs(e,o))}}))}}const hs=new ds,fs=ie("UIMask",{enabled:!0});function ps(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function ms(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[g,_]=m(d,f),[y,w]=m(h,p),x=Math.min(g,y),b=Math.max(g,y),v=Math.min(_,w),P=Math.max(_,w);return{x:Math.round(x),y:Math.round(v),w:Math.round(b-x),h:Math.round(P-v)}}function gs(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],_=e[14],y=e[15],w=s*l-r*a,x=s*c-o*a,b=s*u-i*a,v=r*c-o*l,P=r*u-i*l,S=o*u-i*c,C=d*g-h*m,T=d*_-f*m,E=d*y-p*m,A=h*_-f*g,M=h*y-p*g,R=f*y-p*_;let I=w*R-x*M+b*A+v*E-P*T+S*C;return 0===I||(I=1/I,n[0]=(l*R-c*M+u*A)*I,n[1]=(o*M-r*R-i*A)*I,n[2]=(g*S-_*P+y*v)*I,n[3]=(f*P-h*S-p*v)*I,n[4]=(c*E-a*R-u*T)*I,n[5]=(s*R-o*E+i*T)*I,n[6]=(_*b-m*S-y*x)*I,n[7]=(d*S-f*b+p*x)*I,n[8]=(a*M-l*E+u*C)*I,n[9]=(r*E-s*M-i*C)*I,n[10]=(m*P-g*b+y*w)*I,n[11]=(h*b-d*P-p*w)*I,n[12]=(l*T-a*A-c*C)*I,n[13]=(s*A-r*T+o*C)*I,n[14]=(g*x-m*v-_*w)*I,n[15]=(d*v-h*x+f*w)*I),n}function _s(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function ys(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function ws(e,t,n,s,r,o,i){if(!e.has(t,as)||!e.has(t,xe))return null;const a=e.get(t,as),l=e.get(t,xe),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return ms(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function xs(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([fs]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,fs).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,Ce);){const e=t.get(s,Ce);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=ws(t,n,r,o,i,a,l);e&&(s=ps(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=ws(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class bs{build(e){if(fe("UIMask",fs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(xs(e.wasmModule,e.world))}}const vs=new bs,Ps=ie("Interactable",{enabled:!0}),Ss=ie("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Cs;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Cs||(Cs={}));const Ts=ie("Button",{state:Cs.Normal,transition:null});class Es{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(n=>n.entity===e&&n.type===t)}}const As=ze(new Es,"UIEvents"),Ms=ae("ScreenSpace");function Rs(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function Is(e,t,n,s,r,o){if(!e.has(t,as))return;const i=e.get(t,as),a=Rs(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,we);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,we,l),!e.has(t,Te))return;const c=e.get(t,Te);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Is(e,t,a.rect,a.centerX,a.centerY,!1)}class Fs{build(e){fe("UIRect",as);const t=e.world;e.addSystemToSchedule(Je.PreUpdate,Qe([De(ft)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([Ms,as,we]);for(const e of o)Is(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const Bs=new Fs,Us=new Float32Array(16),ks=new Float32Array(16);let $s=!0,zs=1;class Ds{build(e){fe("Interactable",Ps),fe("Button",Ts);const t=e.world,n=new Es;e.insertResource(As,n);let s=null,r=null;zs="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Je.PreUpdate,Qe([De(ot),De(ft)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Ss]);for(const e of i){const n=t.get(e,Ss);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*zs,l=o.screenH-e.mouseY*zs;!function(e){let t=!1;for(let n=0;n<16;n++)if(ks[n]!==e[n]){t=!0;break}t&&(ks.set(e),$s=!0)}(o.viewProjection),$s&&(gs(o.viewProjection,Us),$s=!1);const c=_s(a,l,Us,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([Ps,as,xe]);let d=null,h=-1/0;for(const e of u){t.has(e,Ss)||t.insert(e,Ss);if(!t.get(e,Ps).enabled)continue;const n=t.get(e,xe),s=t.get(e,as),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(ys(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,be)&&(n=t.get(e,be).layer),n>=h&&(h=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,Ss)){t.get(s,Ss).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,Ss).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Ss);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ss)){const e=t.get(r,Ss);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Je.Update,Qe([],()=>{const e=t.getEntitiesWithComponents([Ts]);for(const n of e){if(t.has(n,Ps)||t.insert(n,Ps,{enabled:!0}),!t.has(n,Ss))continue;const e=t.get(n,Ss),s=t.get(n,Ts),r=t.get(n,Ps),o=s.state;if(r.enabled?e.pressed?s.state=Cs.Pressed:e.hovered?s.state=Cs.Hovered:s.state=Cs.Normal:s.state=Cs.Disabled,o!==s.state&&s.transition&&t.has(n,be)){const e=t.get(n,be),r=s.transition;switch(s.state){case Cs.Normal:e.color={...r.normalColor};break;case Cs.Hovered:e.color={...r.hoveredColor};break;case Cs.Pressed:e.color={...r.pressedColor};break;case Cs.Disabled:e.color={...r.disabledColor}}t.insert(n,be,e)}}},{name:"ButtonSystem"}))}}const Ws=new Ds,Os=ie("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 Hs{build(e){fe("TextInput",Os);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(q,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const f=h;function p(){if(null===i||!n.valid(i))return;const t=n.get(i,Os);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(As).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,_()}function m(e){if(i===e)return;g();const t=n.get(e,Os);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),_())}function g(){if(null!==i&&n.valid(i)&&n.has(i,Os)){const e=n.get(i,Os);e.focused=!1,e.dirty=!0}i=null,f.blur()}function _(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=js(Math.max(r.width,a)),r.height=js(Math.max(r.height,c))),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,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=Ls(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=Ls(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const g=o.getImageData(0,0,a,c),_=new Uint8Array(g.data.buffer),y=t.getResourceManager(),w=t._malloc(_.length);t.HEAPU8.set(_,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const b=y.createTexture(a,c,w,_.length,1,!0);s.set(e,b),t._free(w);const v=n.get(e,be);v.texture=b,v.size.x=a,v.size.y=c,v.uvOffset.x=0,v.uvOffset.y=0,v.uvScale.x=1,v.uvScale.y=1,v.color={r:1,g:1,b:1,a:1},n.insert(e,be,v)}f.addEventListener("input",()=>{a||null===i||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void g();const s=n.get(i,Os);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(As).emit(i,"submit"),void g()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,_())}),f.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,Os)){const e=n.get(i,Os);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(Je.PreUpdate,Qe([De(As)],e=>{const t=n.getEntitiesWithComponents([Os,Ps]);for(const e of t){if(!n.has(e,Ss))continue;if(n.get(e,Ss).justPressed)return void m(e)}if(null!==i){const e=n.getEntitiesWithComponents([Ps]);for(const t of e){if(n.has(t,Os))continue;if(!n.has(t,Ss))continue;if(n.get(t,Ss).justPressed)return void g()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Je.PreUpdate,Qe([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,Os)))){n.get(i,Os).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Os)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Os,as]);for(const e of a){const t=n.get(e,Os);if(!t.dirty)continue;const s=n.get(e,as),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,be)||n.insert(e,be,{texture:Y,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}),y(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Ls(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function js(e){let t=1;for(;t<e;)t*=2;return t}const Ns=new Hs;async function Xs(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 Vs=ze({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),qs=ze(null,"PhysicsAPI");function Gs(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Ys(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Js{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Vs,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Xs(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([Pe]);for(const n of t){const t=e.world.get(n,Pe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(Je.PostUpdate,Qe([De(Le)],a=>{const l=i.getEntitiesWithComponents([Ie,we,xe]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,Ie),l=i.get(r,xe);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Gs(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Ks(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ke.Kinematic){const e=Gs(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,we);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,Ce)){const t=e.world.get(i,Ce);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,xe)){const n=e.world.get(t.entity,xe),s=Gs(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),h=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=Ys(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,we,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Vs,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(qs,Qs._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function Ks(e,t,n){const s=e.world;if(s.has(n,Fe)){const e=s.get(n,Fe);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,Be)){const e=s.get(n,Be);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,Ue)){const e=s.get(n,Ue);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Qs{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(Qs.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 Zs(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function er(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function tr(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,_=l*h,y=l*f,w=c*f,x=u*d,b=u*h,v=u*f;return new Float32Array([(1-(_+w))*r,(m+v)*r,(g-b)*r,0,(m-v)*o,(1-(p+w))*o,(y+x)*o,0,(g+b)*i,(y-x)*i,(1-(p+_))*i,0,e.position.x,e.position.y,e.position.z,1])}async function nr(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=Zs(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=await r.readText(a),u="binary"===x(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),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=er(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Zs(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new Js("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;const i=x(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Zs(e,c,!1),d=e.getResourceManager();s[r]=d.loadBitmapFont(t,u,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),h=await async function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Pt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=Pt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=zt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,be);r&&(r.texture=n[s.data.texture]||0,e.insert(t,be,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,Ee);o&&(o.font=r,e.insert(t,Ee,o))}}}(e.world,n,d,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,be);n&&(n.material=r,e.insert(t,be,n))}else if("SpineAnimation"===s.type){const n=e.get(t,Ae);n&&(n.material=r,e.insert(t,Ae,n))}}}}(e.world,n,h,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,Ae)?c.get(o,Ae):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,xe)){const e=tr(c.get(o,xe),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*r),_=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(_),t.renderer_submitTriangles(y,r,w,o,p,m,h),t._free(y),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,u,s)}if(a){const t=e.getResource(jt);t&&t.setAddressableManifest(a)}}class sr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===x(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){const t=x(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class rr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.currentScene_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene(),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new sr(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await nr(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([ve]);for(const s of n){if(e.get(s,ve).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([Pe]);for(const r of s){const s=e.get(r,Pe);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,we,o);const i={isActive:!0,projectionType:ge.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:_e.ColorAndDepth};e.insert(r,ve,i)}}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.eventSource_.addEventListener("message",async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())}),this.eventSource_.addEventListener("error",e=>{console.error("[PreviewPlugin] EventSource error:",e)})}async reloadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new sr(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await nr(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera(),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),n=Un.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Un.getTargetTexture(n),width:e.width,height:e.height}},release(e){Un.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Un.releaseRenderTarget(e._handle),or.create({width:t,height:n,depth:!0})),begin(e,t){Un.begin(t,e._handle)},end(){Un.end()},getDepthTexture:e=>Un.getTargetDepthTexture(e._handle)};let ir=!1;function ar(e){ir=e}function lr(){return ir}function cr(){return!ir}var ur;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(ur||(ur={}));class dr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${ur[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case ur.Debug:console.debug(t,n);break;case ur.Info:console.log(t,n);break;case ur.Warn:console.warn(t,n);break;case ur.Error:console.error(t,n)}}}class hr{constructor(){this.handlers_=[],this.minLevel_=ur.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,n){this.log(ur.Debug,e,t,n)}info(e,t,n){this.log(ur.Info,e,t,n)}warn(e,t,n){this.log(ur.Warn,e,t,n)}error(e,t,n){this.log(ur.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const fr=new hr;function pr(){return fr}function mr(e){fr.setMinLevel(e)}function gr(e,t,n){fr.debug(e,t,n)}function _r(e,t,n){fr.info(e,t,n)}function yr(e,t,n){fr.warn(e,t,n)}function wr(e,t,n){fr.error(e,t,n)}const xr=[hs,vs,Bs,Ws,Ns];function br(e,t){return function(e,t){const n=Nn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),an(e),xt(e),wn(e),Sn(e),Fn(e),$n(e);const r=new jn;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=Gn(e,s,t,r));const i=n.getResource(ft);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(ft,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;Un.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;Un.resize(t,n),En.isInitialized()&&En.getPassCount()>0&&!En.isBypassed()&&En.resize(t,n);const u=Gn(e,s,t,n);if(a(t,n,u),0===u.length)r.render({registry:{_cpp:s},viewProjection:Vn,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}Un.setViewport(0,0,t,n)}}};if(n.addSystemToSchedule(Je.First,l),n.addSystemToSchedule(Je.Last,c),n.addPlugin(Xt),n.addPlugin(en),n.addPlugin(at),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:xr,...t})}L||(L=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(n,s);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n[s++]=r:r<2048?(n[s++]=192|r>>6,n[s++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,n[s++]=240|r>>18,n[s++]=128|r>>12&63,n[s++]=128|r>>6&63,n[s++]=128|63&r):(n[s++]=224|r>>12,n[s++]=128|r>>6&63,n[s++]=128|63&r)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=j;export{Nn as App,Nt as AssetPlugin,Vt as AssetRefCounter,Lt as AssetServer,jt as Assets,Ft as AsyncCache,Ee as BitmapText,pt as BlendMode,ke as BodyType,Fe as BoxCollider,Ts as Button,Cs as ButtonState,ve as Camera,Pe as Canvas,Ue as CapsuleCollider,Te as Children,Be as CircleCollider,_e as ClearFlags,qe as Commands,Ye as CommandsInstance,X as DEFAULT_DESIGN_HEIGHT,N as DEFAULT_DESIGN_WIDTH,V as DEFAULT_PIXELS_PER_UNIT,q as DEFAULT_TEXT_CANVAS_SIZE,pn as DataType,dn as Draw,Ge as EntityCommands,Dn as GLDebug,vn as Geometry,G as INVALID_ENTITY,J as INVALID_FONT,Y as INVALID_TEXTURE,ot as Input,it as InputPlugin,rt as InputState,Ps as Interactable,we as LocalTransform,ur as LogLevel,hr as Logger,Pt as Material,Bt as MaterialLoader,je as Mut,Me as Name,Ce as Parent,Qs as Physics,Vs as PhysicsEvents,Js as PhysicsPlugin,En as PostProcess,Kt as PrefabServer,Qt as Prefabs,Zt as PrefabsPlugin,rr as PreviewPlugin,ge as ProjectionType,Xe as Query,Ve as QueryInstance,jn as RenderPipeline,Mn as RenderStage,or as RenderTexture,Un as Renderer,De as Res,We as ResMut,Ie as RigidBody,ye as ScaleMode,Je as Schedule,Ms as ScreenSpace,It as ShaderSources,Ae as SpineAnimation,be as Sprite,st as SystemRunner,is as Text,ss as TextAlign,Os as TextInput,Hs as TextInputPlugin,os as TextOverflow,ds as TextPlugin,ls as TextRenderer,rs as TextVerticalAlign,Le as Time,ft as UICameraInfo,Es as UIEventQueue,As as UIEvents,Ss as UIInteraction,Ds as UIInteractionPlugin,Fs as UILayoutPlugin,fs as UIMask,bs as UIMaskPlugin,as as UIRect,Se as Velocity,sr as WebAssetProvider,ht as World,xe as WorldTransform,tt as addStartupSystem,et as addSystem,nt as addSystemToSchedule,Xt as assetPlugin,Ln as clearDrawCallbacks,ce as clearUserComponents,ee as color,Rs as computeUIRectLayout,xs as createMaskProcessor,br as createWebApp,gr as debug,ie as defineComponent,ze as defineResource,Qe as defineSystem,ae as defineTag,wr as error,Ht as findEntityByName,Xn as flushPendingSystems,v as getAddressableType,P as getAddressableTypeByEditorType,C as getAllAssetExtensions,M as getAssetMimeType,x as getAssetTypeEntry,pe as getComponent,$t as getComponentAssetFields,Re as getComponentDefaults,E as getCustomExtensions,b as getEditorType,pr as getLogger,t as getPlatform,s as getPlatformType,le as getUserComponent,A as getWeChatPackOptions,_r as info,an as initDrawAPI,$n as initGLDebugAPI,wn as initGeometryAPI,xt as initMaterialAPI,Sn as initPostProcessAPI,Fn as initRendererAPI,at as inputPlugin,Gt as instantiatePrefab,ps as intersectRects,gs as invertMatrix4,de as isBuiltinComponent,R as isCustomExtension,lr as isEditor,S as isKnownAssetExtension,n as isPlatformInitialized,cr as isRuntime,mt as isTextureRef,r as isWeChat,o as isWeb,Wt as loadComponent,Xs as loadPhysicsModule,nr as loadRuntimeScene,zt as loadSceneData,Dt as loadSceneWithAssets,T as looksLikeAssetPath,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,ys as pointInWorldRect,en as prefabsPlugin,te as quat,fe as registerComponent,kt as registerComponentAssetFields,On as registerDrawCallback,qt as registerEmbeddedAssets,Rt as registerMaterialCallback,_s as screenToWorld,ar as setEditorMode,mr as setLogLevel,ln as shutdownDrawAPI,zn as shutdownGLDebugAPI,xn as shutdownGeometryAPI,bt as shutdownMaterialAPI,Cn as shutdownPostProcessAPI,Bn as shutdownRendererAPI,Ns as textInputPlugin,hs as textPlugin,Ws as uiInteractionPlugin,Bs as uiLayoutPlugin,vs as uiMaskPlugin,xr as uiPlugins,Hn as unregisterDrawCallback,Ot as updateCameraAspectRatio,K as vec2,Q as vec3,Z as vec4,yr as warn,ms as worldRectToScreen,$ as wxFileExists,z as wxFileExistsSync,O as wxGetImagePixels,W as wxLoadImage,H as wxLoadImagePixels,U as wxReadFile,k as wxReadTextFile,D as wxWriteFile};+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function 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 d(e,s){return t().createCanvas(e,s)}function h(){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 A(){const e=[];for(const t of _)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function E(){return A().map(e=>({type:"suffix",value:e}))}function M(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=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 de(e){return!0===e._builtin}const he=new Map;function fe(e,t){he.set(e,t)}function pe(e){return he.get(e)??ce(e)}function _e(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return he.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:[]}),Ae=_e("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:J}),Ee=_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}),Me={_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",Me);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 Oe(e){return{_type:"res_mut",_resource:e}}class Le{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_)}}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.value_=this.get(e),t):(t=new Le(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_),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 d 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(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(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];u=d}yield a.slice()}}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=de(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]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Je&&t[e].flush()}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);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 dt(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 ht(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}:ht(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)}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 de(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return de(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return de(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(de(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.");de(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(dt(t._name,e))}const r={...t._default,...n};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,ht(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(dt(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){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),s=this.queryCache_.get(t);if(s&&s.version===this.worldVersion_)return s.result;let n=null,r=1/0;for(const t of e)if(!de(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<r&&(r=s,n=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const i=this.queryPool_[this.queryPoolIdx_++];i.length=0;const o=n?n.keys():this.entities_;for(const t of o){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&i.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:i}),i}}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,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 At=4096,Et=new Map;let Mt=null;function Rt(e){const t=(0===Tt&&mt&&(Tt=mt._malloc(At)),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>At)break;let e=Et.get(a);e||(Mt||(Mt=new TextEncoder),e=Mt.encode(a),Et.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 d=0,h=[0,0,0,0];if("number"==typeof c)d=0,h[0]=c;else if(Array.isArray(c)){d=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)h[e]=c[e]}else"w"in c?(d=3,h=[c.x,c.y,c.z,c.w]):"z"in c?(d=2,h=[c.x,c.y,c.z,0]):"y"in c&&(d=1,h=[c.x,c.y,0,0]);i[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=h[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)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,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Me,{value:n.name}),!1!==n.visible)for(const s of n.components)Ot(e,t,s)}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 Wt(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,d=new Map,h=[];for(const e of r)h.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)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 o)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=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]=d.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,Me,{value:s.name}),!1!==s.visible)for(const n of s.components)Ot(e,t,n)}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){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const n=pe(s.type);n?e.insert(t,n,s.data):console.warn(`Unknown component type: ${s.type}`)}function Lt(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 Ht(e,t){const s=e.getEntitiesWithComponents([Me]);for(const n of s){const s=e.get(n,Me);if(s&&s.value===t)return n}return null}class jt{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.module_=e,this.canvas_=d(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))}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(n))}}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.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,d=u?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);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,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 Wt(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);return this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t))}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 Nt=ze(null,"Assets");class Xt{build(e){const t=e.wasmModule;t?e.insertResource(Nt,new jt(t)):console.warn("AssetPlugin: No WASM module available")}}const Vt=new Xt;class qt{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 Gt(e,t){const s=e.getResource(Nt);s&&s.registerEmbeddedAssets(t)}async function Yt(e,t,s){const{entities:n,rootId:r}=await Jt(t,s?.overrides??[],s,void 0,new Set),i={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await Wt(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}}async function Jt(e,t,s,n,r){const i=new Map;let o;if(void 0===n){o=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,o++)}const a=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Jt(e,n.nestedPrefab.overrides,s,o,r);i.set(n.prefabEntityId,t.rootId),o=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),a.push(...t.entities);continue}const c=i.get(n.prefabEntityId),l=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:l?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};Kt(u,t),a.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:c,nextId:o}}function Kt(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 Qt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Yt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Zt=ze(null,"Prefabs");class es{constructor(){this.name="PrefabsPlugin",this.dependencies=[Nt]}build(e){const t=e.getResource(Nt);e.insertResource(Zt,new Qt(e.world,t))}}const ts=new es;let ss=null,ns=0,rs=0,is=0;const os=new Float32Array(256);function as(e){ss=e,ns=ss._malloc(64),rs=ss._malloc(64),is=ss._malloc(1024)}function cs(){ss&&(ns&&(ss._free(ns),ns=0),rs&&(ss._free(rs),rs=0),is&&(ss._free(is),is=0)),ss=null}function ls(){if(!ss)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ss}const us={r:1,g:1,b:1,a:1},ds={begin(e){const t=ls();t.HEAPF32.set(e,ns/4),t.draw_begin(ns)},end(){ls().draw_end()},line(e,t,s,n=1){ls().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){ls().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){ls().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){ls().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){ls().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)},texture(e,t,s,n=us){ls().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=us){ls().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)},setLayer(e){ls().draw_setLayer(e)},setDepth(e){ls().draw_setDepth(e)},getDrawCallCount:()=>ss?ss.draw_getDrawCallCount():0,getPrimitiveCount:()=>ss?ss.draw_getPrimitiveCount():0,setBlendMode(e){ls().draw_setBlendMode(e)},setDepthTest(e){ls().draw_setDepthTest(e)},drawMesh(e,t,s){const n=ls();n.HEAPF32.set(s,rs/4),n.draw_mesh(e,t,rs)},drawMeshWithMaterial(e,t,s){const n=ls(),r=Pt.get(t);if(!r)return;if(ds.setBlendMode(r.blendMode),ds.setDepthTest(r.depthTest),0===r.uniforms.size)return void ds.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,rs/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=fs(t);if(!(n<0)){if(gt(s))os[i++]=10,os[i++]=n,os[i++]=s.slot??e++,os[i++]=s.textureId;else if("number"==typeof s)os[i++]=1,os[i++]=n,os[i++]=s;else if(Array.isArray(s)){os[i++]=s.length,os[i++]=n;for(let e=0;e<s.length;e++)os[i++]=s[e]}else"w"in s?(os[i++]=4,os[i++]=n,os[i++]=s.x,os[i++]=s.y,os[i++]=s.z,os[i++]=s.w):"z"in s?(os[i++]=3,os[i++]=n,os[i++]=s.x,os[i++]=s.y,os[i++]=s.z):(os[i++]=2,os[i++]=n,os[i++]=s.x,os[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(os.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}0!==i?(n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),is/4),n.draw_meshWithUniforms(e,r.shader,rs,is,i)):n.draw_mesh(e,r.shader,rs)}},hs={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 fs(e){return hs[e]??-1}var ps;!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"}(ps||(ps={}));let _s=null,gs=0,ms=0,ys=0;function ws(e){_s=e,gs=_s._malloc(262144),ms=_s._malloc(65536),ys=_s._malloc(256)}function xs(){_s&&(gs&&_s._free(gs),ms&&_s._free(ms),ys&&_s._free(ys),gs=0,ms=0,ys=0),_s=null}function vs(){if(!_s)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return _s}const bs={create(e){const t=vs(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,gs/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ys,r).set(i),t.geometry_init(s,gs,n,ys,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,ms,n).set(e.indices),t.geometry_setIndices16(s,ms,n)}else{new Uint32Array(t.HEAPU8.buffer,ms,n).set(e.indices),t.geometry_setIndices32(s,ms,n)}}return s},updateVertices(e,t,s=0){const n=vs(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,gs/4),n.geometry_updateVertices(e,gs,r,s)},release(e){e>0&&vs().geometry_release(e)},isValid:e=>!(!_s||e<=0)&&_s.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return bs.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:ps.Float2},{name:"a_texCoord",type:ps.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 bs.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:ps.Float2},{name:"a_texCoord",type:ps.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 bs.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:ps.Float2},{name:"a_texCoord",type:ps.Float2}],indices:new Uint16Array(o)})}};let Ss=null;function Ps(e){Ss=e}function Cs(){Ss&&As.isInitialized()&&As.shutdown(),Ss=null}function Ts(){if(!Ss)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ss}const As={init:(e,t)=>Ts().postprocess_init(e,t),shutdown(){Ts().postprocess_shutdown()},resize(e,t){Ts().postprocess_resize(e,t)},addPass:(e,t)=>Ts().postprocess_addPass(e,t),removePass(e){Ts().postprocess_removePass(e)},setEnabled(e,t){Ts().postprocess_setPassEnabled(e,t)},isEnabled:e=>Ts().postprocess_isPassEnabled(e),setUniform(e,t,s){Ts().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){Ts().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){Ts().postprocess_begin()},end(){Ts().postprocess_end()},getPassCount:()=>Ts().postprocess_getPassCount(),isInitialized:()=>!!Ss&&Ss.postprocess_isInitialized(),setBypass(e){Ts().postprocess_setBypass(e)},isBypassed:()=>!Ss||Ss.postprocess_isBypassed(),createBlur:()=>Pt.createShader(Es,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Pt.createShader(Es,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Pt.createShader(Es,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Pt.createShader(Es,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Es="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Ms;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ms||(Ms={}));let Rs=null,Is=0;function Fs(e){Rs=e,Is=Rs._malloc(64)}function ks(){Rs&&Is&&(Rs._free(Is),Is=0),Rs=null}const Bs={init(e,t){Rs?.renderer_init(e,t)},resize(e,t){Rs?.renderer_resize(e,t)},begin(e,t){Rs&&Is&&(Rs.HEAPF32.set(e,Is/4),Rs.renderer_begin(Is,t??0))},flush(){Rs?.renderer_flush()},end(){Rs?.renderer_end()},submitSprites(e){Rs&&Rs.renderer_submitSprites(e._cpp)},submitBitmapText(e){Rs&&Rs.renderer_submitBitmapText(e._cpp)},submitSpine(e){Rs&&Rs.renderer_submitSpine?.(e._cpp)},setStage(e){Rs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Rs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Rs?.renderer_releaseTarget(e)},getTargetTexture:e=>Rs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Rs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Rs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Rs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Rs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Rs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Rs?Rs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Rs?{drawCalls:Rs.renderer_getDrawCalls(),triangles:Rs.renderer_getTriangles(),sprites:Rs.renderer_getSprites(),text:Rs.renderer_getText(),spine:Rs.renderer_getSpine?.()??0,meshes:Rs.renderer_getMeshes(),culled:Rs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Us=null;function $s(e){Us=e}function Ds(){Us=null}const zs={enable(){Us?.gl_enableErrorCheck(!0)},disable(){Us?.gl_enableErrorCheck(!1)},check:e=>Us?.gl_checkErrors(e)??0,diagnose(){Us?.renderer_diagnose()}},Ws=new Map;function Os(e,t,s){Ws.set(e,{fn:t,scene:s??""})}function Ls(e){Ws.delete(e)}function Hs(){Ws.clear()}class js{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_||(Bs.resize(n,r),As.isInitialized()&&As.getPassCount()>0&&As.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Bs.setViewport(0,0,n,r),Bs.clearBuffers(3),Bs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Bs.submitSprites(t),Bs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Bs.submitSpine(t),Bs.flush(),this.executeDrawCallbacks(s,i),Bs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Bs.setViewport(n.x,n.y,n.w,n.h),Bs.setScissor(n.x,n.y,n.w,n.h,!0),Bs.clearBuffers(r),Bs.setScissor(0,0,0,0,!1),Bs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Bs.submitSprites(t),Bs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Bs.submitSpine(t),Bs.flush(),this.executeDrawCallbacks(s,i),Bs.end()}executeDrawCallbacks(e,t){const s=Ws;if(s.size>0){ds.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)}ds.end();for(const e of n)Ls(e)}}}const Ns="__scene_transition_overlay__",Xs={r:0,g:0,b:0,a:1};class Vs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class qs{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),Os(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=As.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){As.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 Gs{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.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){"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??Xs;t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Os(Ns,()=>{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;ds.setLayer(9999),ds.setDepth(9999),ds.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)})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Ls(Ns),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){return this.scenes_.get(e).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 Vs(t);this.scenes_.set(e,s);const n=new qs(s,this.app_);this.contexts_.set(e,n);let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Nt)?this.app_.getResource(Nt):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(Nt)&&(t.assetServer=this.app_.getResource(Nt));const n=await Wt(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=Js(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n}async loadAdditive(e){if(this.scenes_.has(e)){return this.scenes_.get(e).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 Vs(t);this.scenes_.set(e,s);const n=new qs(s,this.app_);this.contexts_.set(e,n);let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Nt)?this.app_.getResource(Nt):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(Nt)&&(t.assetServer=this.app_.getResource(Nt));const n=await Wt(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=Js(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n}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())Ls(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{As.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{As.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 Ys=ze(null,"SceneManager");function Js(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Ys).getSceneStatus(t)&&s._fn(...n)}}}const Ks={name:"SceneManager",build(e){const t=new Gs(e);e.insertResource(Ys,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ys),s=t.getInitial();s&&t.load(s)}};e.addSystemToSchedule(Ke.Startup,s)}};class Qs{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.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,.25);this.updateTime(s),this.world_.resetQueryPool(),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 Qs}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}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(Ys).register(e),this}setInitialScene(e){return this.getResource(Ys).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_=h(),this.mainLoop())}quit(){this.running_=!1;const e=[Ds,ks,Cs,xs,bt,cs];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_){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;console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s)}}}updateTime(e){const t=this.resources_.get(je);t.delta=e,t.elapsed+=e,t.frameCount++}}function Zs(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 en=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function tn(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 sn(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,d=0,h=0;if(r.projectionType===ge.Orthographic){if(h=r.orthoSize,c){h=tn(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}d=h*a,u=rn(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=an(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=ln(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(dn(u,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const nn=new Float32Array(16);function rn(e,t,s,n,r,i){const o=nn;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 on=new Float32Array(16);function an(e,t,s,n){const r=on;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 cn=new Float32Array(16);function ln(e,t,s){const n=cn;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 un=new Float32Array(16);function dn(e,t){const s=un;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 hn,fn,pn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(hn||(hn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(fn||(fn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(pn||(pn={}));const _n=oe("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:hn.Left,verticalAlign:fn.Top,wordWrap:!0,overflow:pn.Visible,lineHeight:1.2}),gn=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 mn{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(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),d=Math.ceil(this.measureWidth(c)),h=Math.ceil(c.length*l),f=r?Math.ceil(i):d+2*u,p=r?Math.ceil(o):h+2*u;if(r&&e.overflow===pn.Ellipsis&&h>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===pn.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 fn.Top:x=u;break;case fn.Middle:x=(p-w)/2;break;case fn.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 hn.Left:n=u;break;case hn.Center:n=f/2;break;case hn.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=l}r&&e.overflow===pn.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 hn.Left:return"left";case hn.Center:return"center";case hn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function yn(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 wn(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 xn{build(e){fe("Text",_n);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new mn(t),n=e.world,r=new Map;e.addSystemToSchedule(Ke.PreUpdate,Ze([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,_n));for(const e of r.keys())n.valid(e)&&n.has(e,_n)||r.delete(e);const e=n.getEntitiesWithComponents([_n]);for(const t of e){const e=n.get(t,_n),i=n.has(t,gn)?n.get(t,gn):null,o=r.get(t);if(o&&!wn(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,yn(e,i))}}))}}const vn=new xn,bn=oe("UIMask",{enabled:!0});function Sn(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,c,l,u){const d=e-s*r,h=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]=_(d,f),[y,w]=_(h,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 Cn(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],d=e[8],h=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=d*g-h*_,T=d*m-f*_,A=d*y-p*_,E=h*m-f*g,M=h*y-p*g,R=f*y-p*m;let I=w*R-x*M+v*E+b*A-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*R-l*M+u*E)*I,s[1]=(i*M-r*R-o*E)*I,s[2]=(g*P-m*S+y*b)*I,s[3]=(f*S-h*P-p*b)*I,s[4]=(l*A-a*R-u*T)*I,s[5]=(n*R-i*A+o*T)*I,s[6]=(m*v-_*P-y*x)*I,s[7]=(d*P-f*v+p*x)*I,s[8]=(a*M-c*A+u*C)*I,s[9]=(r*A-n*M-o*C)*I,s[10]=(_*S-g*v+y*w)*I,s[11]=(h*v-d*S-p*w)*I,s[12]=(c*T-a*E-l*C)*I,s[13]=(n*E-r*T+i*C)*I,s[14]=(g*x-_*b-m*w)*I,s[15]=(d*b-h*x+f*w)*I),s}function Tn(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],d=s[3]*a+s[7]*c+s[15];return{x:l/d,y:u/d}}function An(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 En(e,t,s,n,r,i,o){if(!e.has(t,gn)||!e.has(t,xe))return null;const a=e.get(t,gn),c=e.get(t,xe),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return Pn(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,s,n,r,i,o)}function Mn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([bn]);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,bn).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 d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(l.has(s)){const e=En(t,s,r,i,o,a,c);e&&(n=Sn(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=En(t,e,r,i,o,a,c);s&&d(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class Rn{build(e){if(fe("UIMask",bn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Mn(e.wasmModule,e.world))}}const In=new Rn,Fn=oe("Interactable",{enabled:!0}),kn=oe("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Bn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Bn||(Bn={}));const Un=oe("Button",{state:Bn.Normal,transition:null});class $n{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 Dn=ze(new $n,"UIEvents"),zn=ae("ScreenSpace");function Wn(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,d=i.bottom+t.y*a;let h,f,p,_;if(c===l&&u===d){const e=c+s.x,t=u+s.y,n=.5*r.x,i=.5*r.y;h=e-n,f=t-i,p=e+n,_=t+i}else h=c+s.x,f=u+s.y,p=l+n.x,_=d+n.y;return{centerX:.5*(h+p),centerY:.5*(f+_),width:p-h,height:_-f,rect:{left:h,bottom:f,right:p,top:_}}}function On(e,t,s,n,r,i){if(!e.has(t,gn))return;const o=e.get(t,gn),a=Wn(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)&&On(e,t,a.rect,a.centerX,a.centerY,!1)}class Ln{build(e){fe("UIRect",gn);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([zn,gn,we]);for(const e of i)On(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Hn=new Ln,jn=new Float32Array(16),Nn=new Float32Array(16);let Xn=!0,Vn=1;class qn{build(e){fe("Interactable",Fn),fe("Button",Un);const t=e.world,s=new $n;e.insertResource(Dn,s);let n=null,r=null;Vn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Ke.PreUpdate,Ze([We(ot),We(pt)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([kn]);for(const e of o){const s=t.get(e,kn);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*Vn,c=i.screenH-e.mouseY*Vn;!function(e){let t=!1;for(let s=0;s<16;s++)if(Nn[s]!==e[s]){t=!0;break}t&&(Nn.set(e),Xn=!0)}(i.viewProjection),Xn&&(Cn(i.viewProjection,jn),Xn=!1);const l=Tn(a,c,jn,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([Fn,gn,xe]);let d=null,h=-1/0;for(const e of u){t.has(e,kn)||t.insert(e,kn);if(!t.get(e,Fn).enabled)continue;const s=t.get(e,xe),n=t.get(e,gn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(An(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>=h&&(h=s,d=e)}}if(n!==d){if(null!==n&&t.valid(n)&&t.has(n,kn)){t.get(n,kn).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,kn).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,kn);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,kn)){const e=t.get(r,kn);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([Un]);for(const s of e){if(t.has(s,Fn)||t.insert(s,Fn,{enabled:!0}),!t.has(s,kn))continue;const e=t.get(s,kn),n=t.get(s,Un),r=t.get(s,Fn),i=n.state;if(r.enabled?e.pressed?n.state=Bn.Pressed:e.hovered?n.state=Bn.Hovered:n.state=Bn.Normal:n.state=Bn.Disabled,i!==n.state&&n.transition&&t.has(s,ve)){const e=t.get(s,ve),r=n.transition;switch(n.state){case Bn.Normal:e.color={...r.normalColor};break;case Bn.Hovered:e.color={...r.hoveredColor};break;case Bn.Pressed:e.color={...r.pressedColor};break;case Bn.Disabled:e.color={...r.disabledColor}}t.insert(s,ve,e)}}},{name:"ButtonSystem"}))}}const Gn=new qn,Yn=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 Jn{build(e){fe("TextInput",Yn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=d(q,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,u=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const f=h;function p(){if(null===o||!s.valid(o))return;const t=s.get(o,Yn);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(Dn).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,m()}function _(e){if(o===e)return;g();const t=s.get(e,Yn);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),m())}function g(){if(null!==o&&s.valid(o)&&s.has(o,Yn)){const e=s.get(o,Yn);e.focused=!1,e.dirty=!0}o=null,f.blur()}function m(){c=!0,l=0}function y(e,o,a,l){(r.width<a||r.height<l)&&(r.width=Qn(Math.max(r.width,a)),r.height=Qn(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 d=0===o.value.length,h=d?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=d?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=Kn(i,h,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(h,_,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=Kn(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",()=>{a||null===o||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===o)return;if("Escape"===t.key)return void g();const n=s.get(o,Yn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Dn).emit(o,"submit"),void g()}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,m())}),f.addEventListener("blur",()=>{if(null!==o&&s.valid(o)&&s.has(o,Yn)){const e=s.get(o,Yn);e.focused=!1,e.dirty=!0}o=null}),e.addSystemToSchedule(Ke.PreUpdate,Ze([We(Dn)],e=>{const t=s.getEntitiesWithComponents([Yn,Fn]);for(const e of t){if(!s.has(e,kn))continue;if(s.get(e,kn).justPressed)return void _(e)}if(null!==o){const e=s.getEntitiesWithComponents([Fn]);for(const t of e){if(s.has(t,Yn))continue;if(!s.has(t,kn))continue;if(s.get(t,kn).justPressed)return void g()}}},{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,Yn)))){s.get(o,Yn).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Yn)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Yn,gn]);for(const e of a){const t=s.get(e,Yn);if(!t.dirty)continue;const n=s.get(e,gn),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}),y(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Kn(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 Qn(e){let t=1;for(;t<e;)t*=2;return t}const Zn=new Jn,er={r:0,g:0,b:0},tr="__scene_transition_overlay__";async function sr(e,t,s){const n=e.getResource(Ys),r=n.getActive();"fade"===s.type?await async function(e,t,s,n){const r=n.color??er,i=n.duration/2;await nr(i,0,1,r),t&&await e.unload(t);await e.load(s),await nr(i,1,0,r)}(n,r,t,s):await async function(e,t,s,n){await e.loadAdditive(s);const r=n.color??er;await nr(n.duration,1,0,r),t&&await e.unload(t)}(n,r,t,s)}function nr(e,t,s,n){return new Promise(r=>{const i=performance.now();Os(tr,()=>{const o=(performance.now()-i)/1e3,a=Math.min(o/e,1),c=t+(s-t)*a;ds.setLayer(9999),ds.setDepth(9999),ds.rect({x:0,y:0},{x:2e4,y:2e4},{r:n.r,g:n.g,b:n.b,a:c}),a>=1&&(Ls(tr),r())})})}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 d=a,h=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);d=(r*o-i*u)/(0!==s.scale.x?s.scale.x:1),h=(r*u+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}u.position.x=d,u.position.y=h;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,dr._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 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 hr(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,d=a+a,h=c+c,f=l+l,p=a*d,_=a*h,g=a*f,m=c*h,y=c*f,w=l*f,x=u*d,v=u*h,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]=hr(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={},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 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 d,h;if(u){const e=await r.readBinary(o);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const f=s.loadSkeleton(d,h,n,n.length,u);if(t._free(d),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=hr(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,d,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 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,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=hr(e,l,!1),d=e.getResourceManager();n[r]=d.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),p=zt(e.world,s);if(c&&e.hasResource(Ys))for(const t of p.values())e.world.insert(t,Re,{scene:c,persistent:!1});if(function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components)if("Sprite"===n.type&&n.data.texture&&"string"==typeof n.data.texture){const r=e.get(t,ve);r&&(r.texture=s[n.data.texture]||0,e.insert(t,ve,r))}}}(e.world,s,l,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if("BitmapText"!==n.type||!n.data.font||"string"!=typeof n.data.font)continue;const r=s[n.data.font]||0;if(!r)continue;const i=e.get(t,Ae);i&&(i.font=r,e.insert(t,Ae,i))}}}(e.world,s,h,p),function(e,t,s,n){for(const r of t.entities){const t=n.get(r.id);if(void 0!==t)for(const n of r.components){if(!n.data||"string"!=typeof n.data.material||!n.data.material)continue;const r=s[n.data.material]||0;if(r)if("Sprite"===n.type){const s=e.get(t,ve);s&&(s.material=r,e.insert(t,ve,s))}else if("SpineAnimation"===n.type){const s=e.get(t,Ee);s&&(s.material=r,e.insert(t,Ee,s))}}}}(e.world,s,f,p),r&&d){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}(d,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,Ee)?l.get(i,Ee):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(o,c*d);let h=0;if(l.has(i,xe)){const e=pr(l.get(i,xe),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>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),d=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,u,d,f);const p=s.HEAPU32[d>>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,_,h),t._free(y),t._free(w),s._free(l),s._free(u),s._free(d),s._free(f)}h&&t._free(h)}})}(e,t,r,d,n)}if(a){const t=e.getResource(Nt);t&&t.setAddressableManifest(a)}}class gr{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 mr="__preview__";class yr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Ys);t.register({name:mr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(mr),this.loadPromise_=t.load(mr).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 gr(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)}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(Ys).getScene(mr),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)}}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.eventSource_.addEventListener("message",async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())}),this.eventSource_.addEventListener("error",e=>{console.error("[PreviewPlugin] EventSource error:",e)})}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Ys);await e.switchTo(mr),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 wr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Bs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Bs.getTargetTexture(s),width:e.width,height:e.height}},release(e){Bs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Bs.releaseRenderTarget(e._handle),wr.create({width:t,height:s,depth:!0})),begin(e,t){Bs.begin(t,e._handle)},end(){Bs.end()},getDepthTexture:e=>Bs.getTargetDepthTexture(e._handle)};let xr=!1;function vr(e){xr=e}function br(){return xr}function Sr(){return!xr}var Pr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Pr||(Pr={}));class Cr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Pr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Pr.Debug:console.debug(t,s);break;case Pr.Info:console.log(t,s);break;case Pr.Warn:console.warn(t,s);break;case Pr.Error:console.error(t,s)}}}class Tr{constructor(){this.handlers_=[],this.minLevel_=Pr.Info,this.addHandler(new Cr)}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(Pr.Debug,e,t,s)}info(e,t,s){this.log(Pr.Info,e,t,s)}warn(e,t,s){this.log(Pr.Warn,e,t,s)}error(e,t,s){this.log(Pr.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 Tr;function Er(){return Ar}function Mr(e){Ar.setMinLevel(e)}function Rr(e,t,s){Ar.debug(e,t,s)}function Ir(e,t,s){Ar.info(e,t,s)}function Fr(e,t,s){Ar.warn(e,t,s)}function kr(e,t,s){Ar.error(e,t,s)}const Br=[vn,In,Hn,Gn,Zn];function Ur(e,t){return function(e,t){const s=Qs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),as(e),vt(e),ws(e),Ps(e),Fs(e),$s(e);const r=new js;s.pipeline_=r;let i=h();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=sn(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;Bs.setClearColor(e.x,e.y,e.z,e.w)}const u=(h()-i)/1e3;let d;if(Bs.resize(t,c),As.isInitialized()&&As.getPassCount()>0&&!As.isBypassed()&&As.resize(t,c),s.hasResource(Ys)){const e=s.getResource(Ys).getActiveScenes();e.length>0&&(d=new Set(e))}r.setActiveScenes(d??null);const f=sn(e,n,t,c,s.world,d);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:en,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})}Bs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Ke.First,c),s.addSystemToSchedule(Ke.Last,l),s.addPlugin(Vt),s.addPlugin(ts),s.addPlugin(ct),s.addPlugin(Ks),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Br,...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{Qs as App,Xt as AssetPlugin,qt as AssetRefCounter,jt as AssetServer,Nt as Assets,kt as AsyncCache,Ae as BitmapText,_t as BlendMode,$e as BodyType,ke as BoxCollider,Un as Button,Bn 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,ps as DataType,ds as Draw,Ye as EntityCommands,zs as GLDebug,bs as Geometry,G as INVALID_ENTITY,J as INVALID_FONT,Y as INVALID_TEXTURE,ot as Input,at as InputPlugin,it as InputState,Fn as Interactable,we as LocalTransform,Pr as LogLevel,Tr as Logger,Pt as Material,Bt as MaterialLoader,Ne as Mut,Me as Name,Ce as Parent,dr as Physics,ir as PhysicsEvents,lr as PhysicsPlugin,As as PostProcess,Qt as PrefabServer,Zt as Prefabs,es as PrefabsPlugin,yr as PreviewPlugin,ge as ProjectionType,Ve as Query,qe as QueryInstance,js as RenderPipeline,Ms as RenderStage,wr as RenderTexture,Bs as Renderer,We as Res,Oe as ResMut,Fe as RigidBody,ye as ScaleMode,Ys as SceneManager,Gs as SceneManagerState,Re as SceneOwner,Ke as Schedule,zn as ScreenSpace,Ft as ShaderSources,Ee as SpineAnimation,ve as Sprite,rt as SystemRunner,_n as Text,hn as TextAlign,Yn as TextInput,Jn as TextInputPlugin,pn as TextOverflow,xn as TextPlugin,mn as TextRenderer,fn as TextVerticalAlign,je as Time,pt as UICameraInfo,$n as UIEventQueue,Dn as UIEvents,kn as UIInteraction,qn as UIInteractionPlugin,Ln as UILayoutPlugin,bn as UIMask,Rn as UIMaskPlugin,gn as UIRect,Pe as Velocity,gr as WebAssetProvider,ft as World,xe as WorldTransform,st as addStartupSystem,tt as addSystem,nt as addSystemToSchedule,Vt as assetPlugin,Hs as clearDrawCallbacks,le as clearUserComponents,ee as color,Wn as computeUIRectLayout,Mn as createMaskProcessor,Ur as createWebApp,Rr as debug,oe as defineComponent,ze as defineResource,Ze as defineSystem,ae as defineTag,kr as error,Ht as findEntityByName,Zs as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,C as getAllAssetExtensions,M as getAssetMimeType,x as getAssetTypeEntry,pe as getComponent,Dt as getComponentAssetFields,Ie as getComponentDefaults,A as getCustomExtensions,v as getEditorType,Er as getLogger,t as getPlatform,n as getPlatformType,ce as getUserComponent,E as getWeChatPackOptions,Ir as info,as as initDrawAPI,$s as initGLDebugAPI,ws as initGeometryAPI,vt as initMaterialAPI,Ps as initPostProcessAPI,Fs as initRendererAPI,ct as inputPlugin,Yt as instantiatePrefab,Sn as intersectRects,Cn as invertMatrix4,de as isBuiltinComponent,R as isCustomExtension,br as isEditor,P as isKnownAssetExtension,s as isPlatformInitialized,Sr as isRuntime,gt as isTextureRef,r as isWeChat,i as isWeb,Ot as loadComponent,rr as loadPhysicsModule,_r as loadRuntimeScene,zt as loadSceneData,Wt as loadSceneWithAssets,T as looksLikeAssetPath,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,An as pointInWorldRect,ts as prefabsPlugin,te as quat,fe as registerComponent,$t as registerComponentAssetFields,Os as registerDrawCallback,Gt as registerEmbeddedAssets,It as registerMaterialCallback,Ks as sceneManagerPlugin,Tn as screenToWorld,vr as setEditorMode,Mr as setLogLevel,cs as shutdownDrawAPI,Ds as shutdownGLDebugAPI,xs as shutdownGeometryAPI,bt as shutdownMaterialAPI,Cs as shutdownPostProcessAPI,ks as shutdownRendererAPI,Zn as textInputPlugin,vn as textPlugin,sr as transitionTo,Gn as uiInteractionPlugin,Hn as uiLayoutPlugin,In as uiMaskPlugin,Br as uiPlugins,Ls as unregisterDrawCallback,Lt as updateCameraAspectRatio,K as vec2,Q as vec3,Z as vec4,Fr as warn,Pn as worldRectToScreen,Js 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.mapdiff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.tsindex 831ba85a6..f93869a47 100644--- a/desktop/public/sdk/esm/esengine.d.ts+++ b/desktop/public/sdk/esm/esengine.d.ts@@ -219,6 +219,10 @@ interface BitmapTextData {interface NameData {value: string;}+interface SceneOwnerData {+ scene: string;+ persistent: boolean;+}declare const LocalTransform$1: BuiltinComponentDef<LocalTransformData>;declare const WorldTransform$1: BuiltinComponentDef<WorldTransformData>;declare const Sprite$1: BuiltinComponentDef<SpriteData>;@@ -230,6 +234,7 @@ declare const Children$1: BuiltinComponentDef<ChildrenData>;declare const BitmapText$1: BuiltinComponentDef<BitmapTextData>;declare const SpineAnimation$1: BuiltinComponentDef<SpineAnimationData>;declare const Name: ComponentDef<NameData>;+declare const SceneOwner: ComponentDef<SceneOwnerData>;type ComponentData<C> = C extends BuiltinComponentDef<infer T> ? T : C extends ComponentDef<infer T> ? T : never;declare function getComponentDefaults(typeName: string): Record<string, unknown> | null;@@ -833,470 +838,99 @@ declare class RenderPipeline {private maskProcessor_;private lastWidth_;private lastHeight_;+ private activeScenes_;get spineRenderer(): SpineRendererFn | null;setSpineRenderer(fn: SpineRendererFn | null): void;get maskProcessor(): MaskProcessorFn | null;setMaskProcessor(fn: MaskProcessorFn | null): void;+ setActiveScenes(scenes: Set<string> | null): void;render(params: RenderParams): void;renderCamera(params: CameraRenderParams): void;private executeDrawCallbacks;}/**- * @file app.ts- * @brief Application builder and web platform integration+ * @file blend.ts+ * @brief Blend mode definitions for rendering*/--interface Plugin {- name?: string;- dependencies?: ResourceDef<any>[];- build(app: App): void;-}-declare class App {- private readonly world_;- private readonly resources_;- private readonly systems_;- private runner_;- private running_;- private lastTime_;- private fixedTimestep_;- private fixedAccumulator_;- private module_;- private pipeline_;- private spineInitPromise_?;- private physicsInitPromise_?;- private physicsModule_?;- private readonly installed_plugins_;- private error_handler_;- private constructor();- static new(): App;- addPlugin(plugin: Plugin): this;- addSystemToSchedule(schedule: Schedule, system: SystemDef, options?: {- runBefore?: string[];- runAfter?: string[];- }): this;- addSystem(system: SystemDef): this;- addStartupSystem(system: SystemDef): this;- connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;- get wasmModule(): ESEngineModule | null;- get pipeline(): RenderPipeline | null;- setSpineRenderer(fn: SpineRendererFn | null): void;- get spineInitPromise(): Promise<unknown> | undefined;- set spineInitPromise(p: Promise<unknown> | undefined);- get physicsInitPromise(): Promise<unknown> | undefined;- set physicsInitPromise(p: Promise<unknown> | undefined);- get physicsModule(): unknown;- set physicsModule(m: unknown);- get world(): World;- setFixedTimestep(timestep: number): this;- onError(handler: (error: unknown, systemName: string) => void): this;- insertResource<T>(resource: ResourceDef<T>, value: T): this;- getResource<T>(resource: ResourceDef<T>): T;- hasResource<T>(resource: ResourceDef<T>): boolean;- run(): void;- private mainLoop;- quit(): void;- private sortSystems;- private runSchedule;- private updateTime;-}-interface WebAppOptions {- getViewportSize?: () => {- width: number;- height: number;- };- glContextHandle?: number;- plugins?: Plugin[];+declare enum BlendMode {+ Normal = 0,+ Additive = 1,+ Multiply = 2,+ Screen = 3,+ PremultipliedAlpha = 4}-declare function flushPendingSystems(app: App): void;-declare class InputState {- keysDown: Set<string>;- keysPressed: Set<string>;- keysReleased: Set<string>;- mouseX: number;- mouseY: number;- mouseButtons: Set<number>;- mouseButtonsPressed: Set<number>;- mouseButtonsReleased: Set<number>;- scrollDeltaX: number;- scrollDeltaY: number;- isKeyDown(key: string): boolean;- isKeyPressed(key: string): boolean;- isKeyReleased(key: string): boolean;- getMousePosition(): {- x: number;- y: number;- };- isMouseButtonDown(button: number): boolean;- isMouseButtonPressed(button: number): boolean;- isMouseButtonReleased(button: number): boolean;- getScrollDelta(): {- x: number;- y: number;- };-}-declare const Input: ResourceDef<InputState>;-declare class InputPlugin implements Plugin {- private target_;- constructor(target?: unknown);- build(app: App): void;-}-declare const inputPlugin: InputPlugin;+/**+ * @file material.ts+ * @brief Material and Shader API for custom rendering+ * @details Provides shader creation and material management for custom visual effects.+ */-declare enum TextAlign {- Left = 0,- Center = 1,- Right = 2-}-declare enum TextVerticalAlign {- Top = 0,- Middle = 1,- Bottom = 2-}-declare enum TextOverflow {- Visible = 0,- Clip = 1,- Ellipsis = 2+type ShaderHandle = number;+type MaterialHandle = number;+interface TextureRef {+ __textureRef: true;+ textureId: number;+ slot?: number;}-interface TextData {- content: string;- fontFamily: string;- fontSize: number;- color: Color;- align: TextAlign;- verticalAlign: TextVerticalAlign;- wordWrap: boolean;- overflow: TextOverflow;- lineHeight: number;+type UniformValue = number | Vec2 | Vec3 | Vec4 | number[] | TextureRef;+declare function isTextureRef(v: UniformValue): v is TextureRef;+interface MaterialOptions {+ shader: ShaderHandle;+ uniforms?: Record<string, UniformValue>;+ blendMode?: BlendMode;+ depthTest?: boolean;}-declare const Text: ComponentDef<TextData>;--interface UIRectData {- anchorMin: Vec2;- anchorMax: Vec2;- offsetMin: Vec2;- offsetMax: Vec2;- size: Vec2;- pivot: Vec2;+interface MaterialAssetData {+ version: string;+ type: 'material';+ shader: string;+ blendMode: number;+ depthTest: boolean;+ properties: Record<string, unknown>;}-declare const UIRect: ComponentDef<UIRectData>;--/**- * @file TextRenderer.ts- * @brief Renders text to GPU textures using Canvas 2D API- */--interface TextRenderResult {- textureHandle: number;- width: number;- height: number;+interface MaterialData {+ shader: ShaderHandle;+ uniforms: Map<string, UniformValue>;+ blendMode: BlendMode;+ depthTest: boolean;+ dirty_: boolean;+ cachedBuffer_: Float32Array | null;+ cachedIdx_: number;}-declare class TextRenderer {- private canvas;- private ctx;- private module;- private cache;- constructor(module: ESEngineModule);+declare function initMaterialAPI(wasmModule: ESEngineModule): void;+declare function shutdownMaterialAPI(): void;+declare const Material: {/**- * Renders text to a texture and returns the handle+ * Creates a shader from vertex and fragment source code.+ * @param vertexSrc GLSL vertex shader source+ * @param fragmentSrc GLSL fragment shader source+ * @returns Shader handle, or 0 on failure*/- renderText(text: TextData, uiRect?: UIRectData | null): TextRenderResult;- private truncateWithEllipsis;+ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle;/**- * Renders text for an entity and caches the result+ * Releases a shader.+ * @param shader Shader handle to release*/- renderForEntity(entity: Entity, text: TextData, uiRect?: UIRectData | null): TextRenderResult;+ releaseShader(shader: ShaderHandle): void;/**- * Gets cached render result for entity+ * Creates a material with a shader and optional settings.+ * @param options Material creation options+ * @returns Material handle*/- getCached(entity: Entity): TextRenderResult | undefined;+ create(options: MaterialOptions): MaterialHandle;/**- * Releases texture for entity+ * Gets material data by handle.+ * @param material Material handle+ * @returns Material data or undefined*/- release(entity: Entity): void;- cleanupOrphaned(isAlive: (entity: Entity) => boolean): void;+ get(material: MaterialHandle): MaterialData | undefined;/**- * Releases all cached textures- */- releaseAll(): void;- private wrapText;- private measureWidth;- private mapAlign;- private nextPowerOf2;-}--/**- * @file TextPlugin.ts- * @brief Plugin that automatically syncs Text components to Sprite textures- */--declare class TextPlugin implements Plugin {- build(app: App): void;-}-declare const textPlugin: TextPlugin;--interface UIMaskData {- enabled: boolean;-}-declare const UIMask: ComponentDef<UIMaskData>;--declare function createMaskProcessor(wasm: ESEngineModule, world: World): MaskProcessorFn;-declare class UIMaskPlugin implements Plugin {- build(app: App): void;-}-declare const uiMaskPlugin: UIMaskPlugin;--interface ScreenRect {- x: number;- y: number;- w: number;- h: number;-}-declare function intersectRects(a: ScreenRect, b: ScreenRect): ScreenRect;-declare function worldRectToScreen(worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number, vp: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): ScreenRect;-declare function invertMatrix4(m: Float32Array, result?: Float32Array): Float32Array;-declare function screenToWorld(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): {- x: number;- y: number;-};-declare function pointInWorldRect(px: number, py: number, worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number): boolean;--interface InteractableData {- enabled: boolean;-}-declare const Interactable: ComponentDef<InteractableData>;--interface UIInteractionData {- hovered: boolean;- pressed: boolean;- justPressed: boolean;- justReleased: boolean;-}-declare const UIInteraction: ComponentDef<UIInteractionData>;--declare enum ButtonState {- Normal = 0,- Hovered = 1,- Pressed = 2,- Disabled = 3-}-interface ButtonTransition {- normalColor: Color;- hoveredColor: Color;- pressedColor: Color;- disabledColor: Color;-}-interface ButtonData {- state: ButtonState;- transition: ButtonTransition | null;-}-declare const Button: ComponentDef<ButtonData>;--type UIEventType = 'click' | 'press' | 'release' | 'hover_enter' | 'hover_exit' | 'submit' | 'change';-interface UIEvent {- entity: Entity;- type: UIEventType;-}-declare class UIEventQueue {- private events_;- emit(entity: Entity, type: UIEventType): void;- drain(): UIEvent[];- query(type: UIEventType): UIEvent[];- hasEvent(entity: Entity, type: UIEventType): boolean;-}-declare const UIEvents: ResourceDef<UIEventQueue>;--interface UICameraData {- viewProjection: Float32Array;- vpX: number;- vpY: number;- vpW: number;- vpH: number;- screenW: number;- screenH: number;- worldLeft: number;- worldBottom: number;- worldRight: number;- worldTop: number;- valid: boolean;-}-declare const UICameraInfo: ResourceDef<UICameraData>;--declare const ScreenSpace: ComponentDef<{}>;--interface LayoutRect {- left: number;- bottom: number;- right: number;- top: number;-}-interface LayoutResult {- centerX: number;- centerY: number;- width: number;- height: number;- rect: LayoutRect;-}-declare function computeUIRectLayout(anchorMin: {- x: number;- y: number;-}, anchorMax: {- x: number;- y: number;-}, offsetMin: {- x: number;- y: number;-}, offsetMax: {- x: number;- y: number;-}, size: {- x: number;- y: number;-}, parentRect: LayoutRect): LayoutResult;--declare class UILayoutPlugin implements Plugin {- build(app: App): void;-}-declare const uiLayoutPlugin: UILayoutPlugin;--declare class UIInteractionPlugin implements Plugin {- build(app: App): void;-}-declare const uiInteractionPlugin: UIInteractionPlugin;--interface TextInputData {- value: string;- placeholder: string;- placeholderColor: Color;- fontFamily: string;- fontSize: number;- color: Color;- backgroundColor: Color;- padding: number;- maxLength: number;- multiline: boolean;- password: boolean;- readOnly: boolean;- focused: boolean;- cursorPos: number;- dirty: boolean;-}-declare const TextInput: ComponentDef<TextInputData>;--declare class TextInputPlugin implements Plugin {- build(app: App): void;-}-declare const textInputPlugin: TextInputPlugin;--type AssetContentType = 'json' | 'text' | 'binary' | 'image' | 'audio';-type AddressableAssetType = 'texture' | 'material' | 'spine' | 'bitmap-font' | 'prefab' | 'json' | 'text' | 'binary' | 'audio';-type EditorAssetType = 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton' | 'bitmap-font' | 'prefab' | 'json' | 'audio' | 'scene' | 'unknown';-interface AssetTypeEntry {- extensions: string[];- contentType: AssetContentType;- editorType: EditorAssetType;- addressableType: AddressableAssetType | null;- wechatPackInclude: boolean;- hasTransitiveDeps: boolean;-}-declare function getAssetTypeEntry(extensionOrPath: string): AssetTypeEntry | undefined;-declare function getEditorType(path: string): EditorAssetType;-declare function getAddressableType(path: string): AddressableAssetType | null;-declare function getAddressableTypeByEditorType(editorType: string): AddressableAssetType | null;-declare function isKnownAssetExtension(ext: string): boolean;-declare function getAllAssetExtensions(): Set<string>;-declare function looksLikeAssetPath(value: unknown): value is string;-declare function getCustomExtensions(): string[];-declare function getWeChatPackOptions(): Array<{- type: string;- value: string;-}>;-declare function getAssetMimeType(ext: string): string | undefined;-declare function isCustomExtension(path: string): boolean;--/**- * @file blend.ts- * @brief Blend mode definitions for rendering- */-declare enum BlendMode {- Normal = 0,- Additive = 1,- Multiply = 2,- Screen = 3,- PremultipliedAlpha = 4-}--/**- * @file material.ts- * @brief Material and Shader API for custom rendering- * @details Provides shader creation and material management for custom visual effects.- */--type ShaderHandle = number;-type MaterialHandle = number;-interface TextureRef {- __textureRef: true;- textureId: number;- slot?: number;-}-type UniformValue = number | Vec2 | Vec3 | Vec4 | number[] | TextureRef;-declare function isTextureRef(v: UniformValue): v is TextureRef;-interface MaterialOptions {- shader: ShaderHandle;- uniforms?: Record<string, UniformValue>;- blendMode?: BlendMode;- depthTest?: boolean;-}-interface MaterialAssetData {- version: string;- type: 'material';- shader: string;- blendMode: number;- depthTest: boolean;- properties: Record<string, unknown>;-}-interface MaterialData {- shader: ShaderHandle;- uniforms: Map<string, UniformValue>;- blendMode: BlendMode;- depthTest: boolean;- dirty_: boolean;- cachedBuffer_: Float32Array | null;- cachedIdx_: number;-}-declare function initMaterialAPI(wasmModule: ESEngineModule): void;-declare function shutdownMaterialAPI(): void;-declare const Material: {- /**- * Creates a shader from vertex and fragment source code.- * @param vertexSrc GLSL vertex shader source- * @param fragmentSrc GLSL fragment shader source- * @returns Shader handle, or 0 on failure- */- createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle;- /**- * Releases a shader.- * @param shader Shader handle to release- */- releaseShader(shader: ShaderHandle): void;- /**- * Creates a material with a shader and optional settings.- * @param options Material creation options- * @returns Material handle- */- create(options: MaterialOptions): MaterialHandle;- /**- * Gets material data by handle.- * @param material Material handle- * @returns Material data or undefined- */- get(material: MaterialHandle): MaterialData | undefined;- /**- * Sets a uniform value on a material.- * @param material Material handle- * @param name Uniform name- * @param value Uniform value+ * Sets a uniform value on a material.+ * @param material Material handle+ * @param name Uniform name+ * @param value Uniform value*/setUniform(material: MaterialHandle, name: string, value: UniformValue): void;/**@@ -1407,67 +1041,8 @@ declare class MaterialLoader {private resolveShaderPath;}-/**- * @file scene.ts- * @brief Scene loading utilities- */--interface SceneEntityData {- id: number;- name: string;- parent: number | null;- children: number[];- components: SceneComponentData[];- visible?: boolean;-}-interface SceneComponentData {- type: string;- data: Record<string, unknown>;-}-interface SliceBorder$1 {- left: number;- right: number;- top: number;- bottom: number;-}-interface TextureMetadata {- version: string;- type: 'texture';- sliceBorder: SliceBorder$1;-}-interface SceneData {- version: string;- name: string;- entities: SceneEntityData[];- textureMetadata?: Record<string, TextureMetadata>;-}-interface SceneLoadOptions {- assetServer?: AssetServer;- assetBaseUrl?: string;-}-type AssetFieldType = 'texture' | 'material' | 'font';-interface AssetFieldDescriptor {- field: string;- type: AssetFieldType;-}-interface SpineFieldDescriptor {- skeletonField: string;- atlasField: string;-}-interface ComponentAssetFields {- fields?: AssetFieldDescriptor[];- spine?: SpineFieldDescriptor;-}-declare function registerComponentAssetFields(componentType: string, config: ComponentAssetFields): void;-declare function getComponentAssetFields(componentType: string): string[];-declare function loadSceneData(world: World, sceneData: SceneData): Map<number, Entity>;-declare function loadSceneWithAssets(world: World, sceneData: SceneData, options?: SceneLoadOptions): Promise<Map<number, Entity>>;-declare function loadComponent(world: World, entity: Entity, compData: SceneComponentData): void;-declare function updateCameraAspectRatio(world: World, aspectRatio: number): void;-declare function findEntityByName(world: World, name: string): Entity | null;--interface PrefabData {- version: string;+interface PrefabData {+ version: string;name: string;rootEntityId: number;entities: PrefabEntityData[];@@ -1624,176 +1199,692 @@ declare class SpineModuleController {removeAllListeners(entity: Entity): void;}-/**- * @file AssetServer.ts- * @brief Asset loading and caching system- */--interface TextureInfo {- handle: TextureHandle;- width: number;- height: number;+type AssetContentType = 'json' | 'text' | 'binary' | 'image' | 'audio';+type AddressableAssetType = 'texture' | 'material' | 'spine' | 'bitmap-font' | 'prefab' | 'json' | 'text' | 'binary' | 'audio';+type EditorAssetType = 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton' | 'bitmap-font' | 'prefab' | 'json' | 'audio' | 'scene' | 'unknown';+interface AssetTypeEntry {+ extensions: string[];+ contentType: AssetContentType;+ editorType: EditorAssetType;+ addressableType: AddressableAssetType | null;+ wechatPackInclude: boolean;+ hasTransitiveDeps: boolean;+}+declare function getAssetTypeEntry(extensionOrPath: string): AssetTypeEntry | undefined;+declare function getEditorType(path: string): EditorAssetType;+declare function getAddressableType(path: string): AddressableAssetType | null;+declare function getAddressableTypeByEditorType(editorType: string): AddressableAssetType | null;+declare function isKnownAssetExtension(ext: string): boolean;+declare function getAllAssetExtensions(): Set<string>;+declare function looksLikeAssetPath(value: unknown): value is string;+declare function getCustomExtensions(): string[];+declare function getWeChatPackOptions(): Array<{+ type: string;+ value: string;+}>;+declare function getAssetMimeType(ext: string): string | undefined;+declare function isCustomExtension(path: string): boolean;++/**+ * @file AssetServer.ts+ * @brief Asset loading and caching system+ */++interface TextureInfo {+ handle: TextureHandle;+ width: number;+ height: number;+}+interface SliceBorder$1 {+ left: number;+ right: number;+ top: number;+ bottom: number;+}+interface SpineLoadResult {+ success: boolean;+ error?: string;+}+interface SpineDescriptor {+ skeleton: string;+ atlas: string;+ baseUrl?: string;+}+interface FileLoadOptions {+ baseUrl?: string;+ noCache?: boolean;+}++interface AddressableResultMap {+ texture: TextureInfo;+ material: LoadedMaterial;+ spine: SpineLoadResult;+ 'bitmap-font': FontHandle;+ prefab: PrefabData;+ json: unknown;+ text: string;+ binary: ArrayBuffer;+ audio: ArrayBuffer;+}+interface AssetBundle {+ textures: Map<string, TextureInfo>;+ materials: Map<string, LoadedMaterial>;+ spine: Map<string, SpineLoadResult>;+ fonts: Map<string, FontHandle>;+ prefabs: Map<string, PrefabData>;+ json: Map<string, unknown>;+ text: Map<string, string>;+ binary: Map<string, ArrayBuffer>;+}+interface AddressableManifestAsset {+ path: string;+ address?: string;+ type: AddressableAssetType;+ size: number;+ labels: string[];+ metadata?: {+ atlas?: string;+ atlasPage?: number;+ atlasFrame?: {+ x: number;+ y: number;+ width: number;+ height: number;+ };+ };+}+interface AddressableManifestGroup {+ bundleMode: string;+ labels: string[];+ assets: Record<string, AddressableManifestAsset>;+}+interface AddressableManifest {+ version: '2.0';+ groups: Record<string, AddressableManifestGroup>;+}+declare class AssetServer {+ baseUrl?: string;+ private module_;+ private textureCache_;+ private shaderCache_;+ private jsonCache_;+ private textCache_;+ private binaryCache_;+ private loadedSpines_;+ private virtualFSPaths_;+ private materialLoader_;+ private canvas_;+ private ctx_;+ private fontCache_;+ private prefabCache_;+ private embedded_;+ private embeddedOnly_;+ private addressableManifest_;+ private addressIndex_;+ private labelIndex_;+ private groupAssets_;+ private spineController_;+ private spineSkeletons_;+ constructor(module: ESEngineModule);+ registerEmbeddedAssets(assets: Record<string, string>): void;+ setEmbeddedOnly(value: boolean): void;+ /**+ * Load texture with vertical flip (for Sprite/UI).+ * OpenGL UV origin is bottom-left, so standard images need flipping.+ */+ loadTexture(source: string): Promise<TextureInfo>;+ /**+ * Load texture without flip (for Spine).+ * Spine runtime handles UV coordinates internally.+ */+ loadTextureRaw(source: string): Promise<TextureInfo>;+ getTexture(source: string): TextureInfo | undefined;+ hasTexture(source: string): boolean;+ releaseTexture(source: string): void;+ releaseAll(): void;+ private cleanupVirtualFS;+ setTextureMetadata(handle: TextureHandle, border: SliceBorder$1): void;+ setTextureMetadataByPath(source: string, border: SliceBorder$1): boolean;+ setSpineController(controller: SpineModuleController): void;+ getSpineSkeletonHandle(skeletonPath: string, atlasPath: string): number | undefined;+ loadSpine(skeletonPath: string, atlasPath: string, baseUrl?: string): Promise<SpineLoadResult>;+ isSpineLoaded(skeletonPath: string, atlasPath: string): boolean;+ loadBitmapFont(fontPath: string, baseUrl?: string): Promise<FontHandle>;+ getFont(fontPath: string): FontHandle | undefined;+ releaseFont(fontPath: string): void;+ private loadBmfontAsset;+ private loadFntFile;+ loadPrefab(path: string, baseUrl?: string): Promise<PrefabData>;+ loadMaterial(path: string, baseUrl?: string): Promise<LoadedMaterial>;+ getMaterial(path: string, baseUrl?: string): LoadedMaterial | undefined;+ hasMaterial(path: string, baseUrl?: string): boolean;+ loadShader(path: string): Promise<ShaderHandle>;+ loadJson<T = unknown>(path: string, options?: FileLoadOptions): Promise<T>;+ loadText(path: string, options?: FileLoadOptions): Promise<string>;+ loadBinary(path: string, options?: FileLoadOptions): Promise<ArrayBuffer>;+ loadScene(world: World, sceneData: SceneData): Promise<Map<number, Entity>>;+ loadAll(manifest: AddressableManifest): Promise<AssetBundle>;+ setAddressableManifest(manifest: AddressableManifest): void;+ resolveAddress(address: string): AddressableManifestAsset | undefined;+ load<T extends AddressableAssetType = AddressableAssetType>(address: string): Promise<AddressableResultMap[T]>;+ loadByLabel(label: string): Promise<AssetBundle>;+ loadGroup(groupName: string): Promise<AssetBundle>;+ private loadAddressableAsset;+ private loadAddressableAssets;+ private textureCacheKey;+ private loadTextureWithFlip;+ private loadTextureInternal;+ private loadImage;+ private createTextureFromImage;+ private getWebGL2Context;+ private createTextureWebGL2;+ private createTextureFallback;+ private unpremultiplyAlpha;+ private loadShaderInternal;+ private parseEsShader;+ private decodeDataUrlText;+ private decodeDataUrlBinary;+ private isLocalPath;+ private toLocalPath;+ private fetchJson;+ private fetchText;+ private fetchBinary;+ private writeToVirtualFS;+ private ensureVirtualDir;+ private resolveUrl;+ private nextPowerOf2;+ private parseAtlasTextures;+}++/**+ * @file scene.ts+ * @brief Scene loading utilities+ */++interface SceneEntityData {+ id: number;+ name: string;+ parent: number | null;+ children: number[];+ components: SceneComponentData[];+ visible?: boolean;+}+interface SceneComponentData {+ type: string;+ data: Record<string, unknown>;+}+interface SliceBorder {+ left: number;+ right: number;+ top: number;+ bottom: number;+}+interface TextureMetadata {+ version: string;+ type: 'texture';+ sliceBorder: SliceBorder;+}+interface SceneData {+ version: string;+ name: string;+ entities: SceneEntityData[];+ textureMetadata?: Record<string, TextureMetadata>;+}+interface SceneLoadOptions {+ assetServer?: AssetServer;+ assetBaseUrl?: string;+}+type AssetFieldType = 'texture' | 'material' | 'font';+interface AssetFieldDescriptor {+ field: string;+ type: AssetFieldType;+}+interface SpineFieldDescriptor {+ skeletonField: string;+ atlasField: string;+}+interface ComponentAssetFields {+ fields?: AssetFieldDescriptor[];+ spine?: SpineFieldDescriptor;+}+declare function registerComponentAssetFields(componentType: string, config: ComponentAssetFields): void;+declare function getComponentAssetFields(componentType: string): string[];+declare function loadSceneData(world: World, sceneData: SceneData): Map<number, Entity>;+declare function loadSceneWithAssets(world: World, sceneData: SceneData, options?: SceneLoadOptions): Promise<Map<number, Entity>>;+declare function loadComponent(world: World, entity: Entity, compData: SceneComponentData): void;+declare function updateCameraAspectRatio(world: World, aspectRatio: number): void;+declare function findEntityByName(world: World, name: string): Entity | null;++/**+ * @file customDraw.ts+ * @brief Custom draw callback registration for the render pipeline+ */+type DrawCallback = (elapsed: number) => void;+declare function registerDrawCallback(id: string, fn: DrawCallback, scene?: string): void;+declare function unregisterDrawCallback(id: string): void;+declare function clearDrawCallbacks(): void;++type SceneStatus = 'loading' | 'running' | 'paused' | 'sleeping' | 'unloading';+interface SceneConfig {+ name: string;+ path?: string;+ data?: SceneData;+ systems?: Array<{+ schedule: Schedule;+ system: SystemDef;+ }>;+ setup?: (ctx: SceneContext) => void | Promise<void>;+ cleanup?: (ctx: SceneContext) => void;+}+interface SceneContext {+ readonly name: string;+ readonly entities: ReadonlySet<Entity>;+ spawn(): Entity;+ despawn(entity: Entity): void;+ registerDrawCallback(id: string, fn: DrawCallback): void;+ addPostProcessPass(name: string, shader: ShaderHandle): number;+ removePostProcessPass(name: string): void;+ setPersistent(entity: Entity, persistent: boolean): void;+}+interface TransitionOptions {+ keepPersistent?: boolean;+ transition?: 'none' | 'fade';+ duration?: number;+ color?: Color;+ onStart?: () => void;+ onComplete?: () => void;+}+declare class SceneManagerState {+ private readonly app_;+ private readonly configs_;+ private readonly scenes_;+ private readonly contexts_;+ private readonly additiveScenes_;+ private readonly pausedScenes_;+ private readonly sleepingScenes_;+ private readonly loadOrder_;+ private activeScene_;+ private initialScene_;+ private transition_;+ constructor(app: App);+ register(config: SceneConfig): void;+ setInitial(name: string): void;+ getInitial(): string | null;+ isTransitioning(): boolean;+ switchTo(name: string, options?: TransitionOptions): Promise<void>;+ private startFadeTransition;+ updateTransition(dt: number): void;+ load(name: string): Promise<SceneContext>;+ loadAdditive(name: string): Promise<SceneContext>;+ unload(name: string, options?: TransitionOptions): Promise<void>;+ pause(name: string): void;+ resume(name: string): void;+ sleep(name: string): void;+ wake(name: string): void;+ private setPostProcessPassesEnabled;+ isPaused(name: string): boolean;+ isSleeping(name: string): boolean;+ isLoaded(name: string): boolean;+ isActive(name: string): boolean;+ getActive(): string | null;+ getActiveScenes(): string[];+ getLoaded(): string[];+ getLoadOrder(): string[];+ bringToTop(name: string): void;+ getScene(name: string): SceneContext | null;+ getSceneStatus(name: string): SceneStatus | null;+}+declare const SceneManager: ResourceDef<SceneManagerState>;+declare function wrapSceneSystem(app: App, sceneName: string, system: SystemDef): SystemDef;++/**+ * @file app.ts+ * @brief Application builder and web platform integration+ */++interface Plugin {+ name?: string;+ dependencies?: ResourceDef<any>[];+ build(app: App): void;+}+declare class App {+ private readonly world_;+ private readonly resources_;+ private readonly systems_;+ private runner_;+ private running_;+ private lastTime_;+ private fixedTimestep_;+ private fixedAccumulator_;+ private module_;+ private pipeline_;+ private spineInitPromise_?;+ private physicsInitPromise_?;+ private physicsModule_?;+ private readonly installed_plugins_;+ private error_handler_;+ private constructor();+ static new(): App;+ addPlugin(plugin: Plugin): this;+ addSystemToSchedule(schedule: Schedule, system: SystemDef, options?: {+ runBefore?: string[];+ runAfter?: string[];+ }): this;+ addSystem(system: SystemDef): this;+ addStartupSystem(system: SystemDef): this;+ connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;+ get wasmModule(): ESEngineModule | null;+ get pipeline(): RenderPipeline | null;+ setSpineRenderer(fn: SpineRendererFn | null): void;+ get spineInitPromise(): Promise<unknown> | undefined;+ set spineInitPromise(p: Promise<unknown> | undefined);+ get physicsInitPromise(): Promise<unknown> | undefined;+ set physicsInitPromise(p: Promise<unknown> | undefined);+ get physicsModule(): unknown;+ set physicsModule(m: unknown);+ get world(): World;+ setFixedTimestep(timestep: number): this;+ onError(handler: (error: unknown, systemName: string) => void): this;+ insertResource<T>(resource: ResourceDef<T>, value: T): this;+ getResource<T>(resource: ResourceDef<T>): T;+ hasResource<T>(resource: ResourceDef<T>): boolean;+ registerScene(config: SceneConfig): this;+ setInitialScene(name: string): this;+ run(): void;+ private mainLoop;+ quit(): void;+ private sortSystems;+ private runSchedule;+ private updateTime;+}+interface WebAppOptions {+ getViewportSize?: () => {+ width: number;+ height: number;+ };+ glContextHandle?: number;+ plugins?: Plugin[];+}+declare function flushPendingSystems(app: App): void;++declare class InputState {+ keysDown: Set<string>;+ keysPressed: Set<string>;+ keysReleased: Set<string>;+ mouseX: number;+ mouseY: number;+ mouseButtons: Set<number>;+ mouseButtonsPressed: Set<number>;+ mouseButtonsReleased: Set<number>;+ scrollDeltaX: number;+ scrollDeltaY: number;+ isKeyDown(key: string): boolean;+ isKeyPressed(key: string): boolean;+ isKeyReleased(key: string): boolean;+ getMousePosition(): {+ x: number;+ y: number;+ };+ isMouseButtonDown(button: number): boolean;+ isMouseButtonPressed(button: number): boolean;+ isMouseButtonReleased(button: number): boolean;+ getScrollDelta(): {+ x: number;+ y: number;+ };+}+declare const Input: ResourceDef<InputState>;+declare class InputPlugin implements Plugin {+ private target_;+ constructor(target?: unknown);+ build(app: App): void;+}+declare const inputPlugin: InputPlugin;++declare enum TextAlign {+ Left = 0,+ Center = 1,+ Right = 2+}+declare enum TextVerticalAlign {+ Top = 0,+ Middle = 1,+ Bottom = 2+}+declare enum TextOverflow {+ Visible = 0,+ Clip = 1,+ Ellipsis = 2+}+interface TextData {+ content: string;+ fontFamily: string;+ fontSize: number;+ color: Color;+ align: TextAlign;+ verticalAlign: TextVerticalAlign;+ wordWrap: boolean;+ overflow: TextOverflow;+ lineHeight: number;+}+declare const Text: ComponentDef<TextData>;++interface UIRectData {+ anchorMin: Vec2;+ anchorMax: Vec2;+ offsetMin: Vec2;+ offsetMax: Vec2;+ size: Vec2;+ pivot: Vec2;+}+declare const UIRect: ComponentDef<UIRectData>;++/**+ * @file TextRenderer.ts+ * @brief Renders text to GPU textures using Canvas 2D API+ */++interface TextRenderResult {+ textureHandle: number;+ width: number;+ height: number;+}+declare class TextRenderer {+ private canvas;+ private ctx;+ private module;+ private cache;+ constructor(module: ESEngineModule);+ /**+ * Renders text to a texture and returns the handle+ */+ renderText(text: TextData, uiRect?: UIRectData | null): TextRenderResult;+ private truncateWithEllipsis;+ /**+ * Renders text for an entity and caches the result+ */+ renderForEntity(entity: Entity, text: TextData, uiRect?: UIRectData | null): TextRenderResult;+ /**+ * Gets cached render result for entity+ */+ getCached(entity: Entity): TextRenderResult | undefined;+ /**+ * Releases texture for entity+ */+ release(entity: Entity): void;+ cleanupOrphaned(isAlive: (entity: Entity) => boolean): void;+ /**+ * Releases all cached textures+ */+ releaseAll(): void;+ private wrapText;+ private measureWidth;+ private mapAlign;+ private nextPowerOf2;+}++/**+ * @file TextPlugin.ts+ * @brief Plugin that automatically syncs Text components to Sprite textures+ */++declare class TextPlugin implements Plugin {+ build(app: App): void;+}+declare const textPlugin: TextPlugin;++interface UIMaskData {+ enabled: boolean;+}+declare const UIMask: ComponentDef<UIMaskData>;++declare function createMaskProcessor(wasm: ESEngineModule, world: World): MaskProcessorFn;+declare class UIMaskPlugin implements Plugin {+ build(app: App): void;+}+declare const uiMaskPlugin: UIMaskPlugin;++interface ScreenRect {+ x: number;+ y: number;+ w: number;+ h: number;+}+declare function intersectRects(a: ScreenRect, b: ScreenRect): ScreenRect;+declare function worldRectToScreen(worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number, vp: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): ScreenRect;+declare function invertMatrix4(m: Float32Array, result?: Float32Array): Float32Array;+declare function screenToWorld(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): {+ x: number;+ y: number;+};+declare function pointInWorldRect(px: number, py: number, worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number): boolean;++interface InteractableData {+ enabled: boolean;+}+declare const Interactable: ComponentDef<InteractableData>;++interface UIInteractionData {+ hovered: boolean;+ pressed: boolean;+ justPressed: boolean;+ justReleased: boolean;+}+declare const UIInteraction: ComponentDef<UIInteractionData>;++declare enum ButtonState {+ Normal = 0,+ Hovered = 1,+ Pressed = 2,+ Disabled = 3+}+interface ButtonTransition {+ normalColor: Color;+ hoveredColor: Color;+ pressedColor: Color;+ disabledColor: Color;+}+interface ButtonData {+ state: ButtonState;+ transition: ButtonTransition | null;+}+declare const Button: ComponentDef<ButtonData>;++type UIEventType = 'click' | 'press' | 'release' | 'hover_enter' | 'hover_exit' | 'submit' | 'change';+interface UIEvent {+ entity: Entity;+ type: UIEventType;+}+declare class UIEventQueue {+ private events_;+ emit(entity: Entity, type: UIEventType): void;+ drain(): UIEvent[];+ query(type: UIEventType): UIEvent[];+ hasEvent(entity: Entity, type: UIEventType): boolean;+}+declare const UIEvents: ResourceDef<UIEventQueue>;++interface UICameraData {+ viewProjection: Float32Array;+ vpX: number;+ vpY: number;+ vpW: number;+ vpH: number;+ screenW: number;+ screenH: number;+ worldLeft: number;+ worldBottom: number;+ worldRight: number;+ worldTop: number;+ valid: boolean;}-interface SliceBorder {+declare const UICameraInfo: ResourceDef<UICameraData>;++declare const ScreenSpace: ComponentDef<{}>;++interface LayoutRect {left: number;+ bottom: number;right: number;top: number;- bottom: number;-}-interface SpineLoadResult {- success: boolean;- error?: string;-}-interface SpineDescriptor {- skeleton: string;- atlas: string;- baseUrl?: string;}-interface FileLoadOptions {- baseUrl?: string;- noCache?: boolean;+interface LayoutResult {+ centerX: number;+ centerY: number;+ width: number;+ height: number;+ rect: LayoutRect;}+declare function computeUIRectLayout(anchorMin: {+ x: number;+ y: number;+}, anchorMax: {+ x: number;+ y: number;+}, offsetMin: {+ x: number;+ y: number;+}, offsetMax: {+ x: number;+ y: number;+}, size: {+ x: number;+ y: number;+}, parentRect: LayoutRect): LayoutResult;-interface AddressableResultMap {- texture: TextureInfo;- material: LoadedMaterial;- spine: SpineLoadResult;- 'bitmap-font': FontHandle;- prefab: PrefabData;- json: unknown;- text: string;- binary: ArrayBuffer;- audio: ArrayBuffer;-}-interface AssetBundle {- textures: Map<string, TextureInfo>;- materials: Map<string, LoadedMaterial>;- spine: Map<string, SpineLoadResult>;- fonts: Map<string, FontHandle>;- prefabs: Map<string, PrefabData>;- json: Map<string, unknown>;- text: Map<string, string>;- binary: Map<string, ArrayBuffer>;-}-interface AddressableManifestAsset {- path: string;- address?: string;- type: AddressableAssetType;- size: number;- labels: string[];- metadata?: {- atlas?: string;- atlasPage?: number;- atlasFrame?: {- x: number;- y: number;- width: number;- height: number;- };- };+declare class UILayoutPlugin implements Plugin {+ build(app: App): void;}-interface AddressableManifestGroup {- bundleMode: string;- labels: string[];- assets: Record<string, AddressableManifestAsset>;+declare const uiLayoutPlugin: UILayoutPlugin;++declare class UIInteractionPlugin implements Plugin {+ build(app: App): void;}-interface AddressableManifest {- version: '2.0';- groups: Record<string, AddressableManifestGroup>;+declare const uiInteractionPlugin: UIInteractionPlugin;++interface TextInputData {+ value: string;+ placeholder: string;+ placeholderColor: Color;+ fontFamily: string;+ fontSize: number;+ color: Color;+ backgroundColor: Color;+ padding: number;+ maxLength: number;+ multiline: boolean;+ password: boolean;+ readOnly: boolean;+ focused: boolean;+ cursorPos: number;+ dirty: boolean;}-declare class AssetServer {- baseUrl?: string;- private module_;- private textureCache_;- private shaderCache_;- private jsonCache_;- private textCache_;- private binaryCache_;- private loadedSpines_;- private virtualFSPaths_;- private materialLoader_;- private canvas_;- private ctx_;- private fontCache_;- private prefabCache_;- private embedded_;- private embeddedOnly_;- private addressableManifest_;- private addressIndex_;- private labelIndex_;- private groupAssets_;- private spineController_;- private spineSkeletons_;- constructor(module: ESEngineModule);- registerEmbeddedAssets(assets: Record<string, string>): void;- setEmbeddedOnly(value: boolean): void;- /**- * Load texture with vertical flip (for Sprite/UI).- * OpenGL UV origin is bottom-left, so standard images need flipping.- */- loadTexture(source: string): Promise<TextureInfo>;- /**- * Load texture without flip (for Spine).- * Spine runtime handles UV coordinates internally.- */- loadTextureRaw(source: string): Promise<TextureInfo>;- getTexture(source: string): TextureInfo | undefined;- hasTexture(source: string): boolean;- releaseTexture(source: string): void;- releaseAll(): void;- private cleanupVirtualFS;- setTextureMetadata(handle: TextureHandle, border: SliceBorder): void;- setTextureMetadataByPath(source: string, border: SliceBorder): boolean;- setSpineController(controller: SpineModuleController): void;- getSpineSkeletonHandle(skeletonPath: string, atlasPath: string): number | undefined;- loadSpine(skeletonPath: string, atlasPath: string, baseUrl?: string): Promise<SpineLoadResult>;- isSpineLoaded(skeletonPath: string, atlasPath: string): boolean;- loadBitmapFont(fontPath: string, baseUrl?: string): Promise<FontHandle>;- getFont(fontPath: string): FontHandle | undefined;- releaseFont(fontPath: string): void;- private loadBmfontAsset;- private loadFntFile;- loadPrefab(path: string, baseUrl?: string): Promise<PrefabData>;- loadMaterial(path: string, baseUrl?: string): Promise<LoadedMaterial>;- getMaterial(path: string, baseUrl?: string): LoadedMaterial | undefined;- hasMaterial(path: string, baseUrl?: string): boolean;- loadShader(path: string): Promise<ShaderHandle>;- loadJson<T = unknown>(path: string, options?: FileLoadOptions): Promise<T>;- loadText(path: string, options?: FileLoadOptions): Promise<string>;- loadBinary(path: string, options?: FileLoadOptions): Promise<ArrayBuffer>;- loadScene(world: World, sceneData: SceneData): Promise<Map<number, Entity>>;- loadAll(manifest: AddressableManifest): Promise<AssetBundle>;- setAddressableManifest(manifest: AddressableManifest): void;- resolveAddress(address: string): AddressableManifestAsset | undefined;- load<T extends AddressableAssetType = AddressableAssetType>(address: string): Promise<AddressableResultMap[T]>;- loadByLabel(label: string): Promise<AssetBundle>;- loadGroup(groupName: string): Promise<AssetBundle>;- private loadAddressableAsset;- private loadAddressableAssets;- private textureCacheKey;- private loadTextureWithFlip;- private loadTextureInternal;- private loadImage;- private createTextureFromImage;- private getWebGL2Context;- private createTextureWebGL2;- private createTextureFallback;- private unpremultiplyAlpha;- private loadShaderInternal;- private parseEsShader;- private decodeDataUrlText;- private decodeDataUrlBinary;- private isLocalPath;- private toLocalPath;- private fetchJson;- private fetchText;- private fetchBinary;- private writeToVirtualFS;- private ensureVirtualDir;- private resolveUrl;- private nextPowerOf2;- private parseAtlasTextures;+declare const TextInput: ComponentDef<TextInputData>;++declare class TextInputPlugin implements Plugin {+ build(app: App): void;}+declare const textInputPlugin: TextInputPlugin;declare class AsyncCache<T> {private cache_;@@ -1858,6 +1949,30 @@ declare class AssetRefCounter {declare function registerEmbeddedAssets(app: App, assets: Record<string, string>): void;+/**+ * @file scenePlugin.ts+ * @brief Plugin that provides scene management capabilities+ */++declare const sceneManagerPlugin: Plugin;++/**+ * @file sceneTransition.ts+ * @brief Scene transition animations (fade, crossfade)+ */++interface TransitionConfig {+ duration: number;+ type: 'fade' | 'crossfade';+ color?: {+ r: number;+ g: number;+ b: number;+ a: number;+ };+}+declare function transitionTo(app: App, targetScene: string, config: TransitionConfig): Promise<void>;+declare class PrefabServer {private readonly world_;private readonly assetServer_;@@ -1946,7 +2061,7 @@ declare function loadRuntimeScene(app: App, module: ESEngineModule, sceneData: Sgravity?: Vec2;fixedTimestep?: number;subStepCount?: number;-}, manifest?: AddressableManifest | null): Promise<void>;+}, manifest?: AddressableManifest | null, sceneName?: string): Promise<void>;/*** @file PreviewPlugin.ts@@ -1959,14 +2074,13 @@ declare class PreviewPlugin implements Plugin {private app_;private loadPromise_;private eventSource_;- private currentScene_;constructor(sceneUrl: string, baseUrl?: string);build(app: App): void;/*** @brief Wait for scene loading to complete*/waitForReady(): Promise<void>;- private loadScene;+ private loadRuntimeData;private ensureCamera;private setupHotReload;private reloadScene;@@ -2492,15 +2606,6 @@ declare const RenderTexture: {getDepthTexture(rt: RenderTextureHandle): number;};-/**- * @file customDraw.ts- * @brief Custom draw callback registration for the render pipeline- */-type DrawCallback = (elapsed: number) => void;-declare function registerDrawCallback(id: string, fn: DrawCallback): void;-declare function unregisterDrawCallback(id: string): void;-declare function clearDrawCallbacks(): void;-declare function setEditorMode(active: boolean): void;declare function isEditor(): boolean;declare function isRuntime(): boolean;@@ -2615,5 +2720,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, 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, 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, screenToWorld, setEditorMode, setLogLevel, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textInputPlugin, textPlugin, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, worldRectToScreen };-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, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ScreenRect, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemOptions, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };+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, 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, 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.jsindex b36c1cf39..e58e48a2f 100644--- a/desktop/public/sdk/esm/esengine.js+++ b/desktop/public/sdk/esm/esengine.js@@ -1,2 +1,2 @@-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},i=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},d=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",o),n.addEventListener("mousedown",i),n.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",u),n.addEventListener("wheel",d),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",i),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("wheel",d)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,m=1080,_=100,g=512,y=0,w=4294967295,x=4294967295,v=(e=0,t=0)=>({x:e,y:t}),b=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),P=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),S=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),C=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function T(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(T);const t={};for(const n in e)t[n]=T(e[n]);return t}let E=0;function M(e,t){const n=++E;return{_id:Symbol(`Component_${n}_${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 n=A(),s=n.get(e);if(s)return s;const r=M(e,t);return n.set(e,r),k(e,t,!1),r}function I(e){const t=A(),n=t.get(e);if(n)return n;const s=M(e,{});return t.set(e,s),k(e,{},!0),s}function F(e){return A().get(e)}function B(){A().clear()}function k(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function U(e){return!0===e._builtin}const $=new Map;function z(e,t){$.set(e,t)}function D(e){return $.get(e)??F(e)}function L(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return $.set(e,n),n}const H={Perspective:0,Orthographic:1},O={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},W={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},j=L("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=L("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=L("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=L("Camera",{projectionType:H.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:O.ColorAndDepth}),Y=L("Canvas",{designResolution:{x:p,y:m},pixelsPerUnit:100,scaleMode:W.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),q=L("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),G=L("Parent",{entity:0}),J=L("Children",{entities:[]}),K=L("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:x}),Q=L("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})};function ee(e){const t=D(e);return t?T(t._default):null}z("Name",Z);const te=L("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ne=L("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),se=L("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),re=L("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 ie=0;function ae(e,t){const n=++ie;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function le(e){return{_type:"res",_resource:e}}function ce(e){return{_type:"res_mut",_resource:e}}class ue{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_)}}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.value_=this.get(e),t):(t=new ue(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const he=ae({delta:0,elapsed:0,frameCount:0},"Time");function fe(e){return{_type:"mut",_component:e}}function pe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function me(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{pe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class _e{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>pe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.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 s){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 n=0;n<t.length;n++)if(this.world_.has(d,t[n])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,n[e]);if(o){for(let t=0;t<c;t++)l[t].data=a[e[t]+1];u=d}yield a.slice()}}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,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function 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 n;return n=U(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class we{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,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var xe;!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"}(xe||(xe={}));let ve=0;function be(e,t,n){const s=++ve;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Pe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Se(e){Pe().push({schedule:xe.Update,system:e})}function Ce(e){Pe().push({schedule:xe.Startup,system:e})}function Te(e,t){Pe().push({schedule:e,system:t})}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 n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof we&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new _e(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new we(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 Ae=ae(new Me,"Input");class Re{constructor(e){this.target_=e??null}build(e){const n=new Me;e.insertResource(Ae,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(xe.Last,be([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ie=new Re;function Fe(e,t,n){const s=[];for(const[e,r]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const n=Be(t[e]),o=Be(r);n!==o&&null!=r&&s.push({field:e,expected:n,actual:o,value:r})}return s}function Be(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ke(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}function Ue(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:Ue(e)}}return t}class $e{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;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 n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}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,n){return U(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}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 n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.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 n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=Fe(t._name,t._default,s);if(e.length>0)throw new Error(ke(t._name,e))}const r={...t._default,...s};return this.cppRegistry_&&this.getBuiltinMethods(t._cppName).add(e,Ue(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,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const r=Fe(t._name,t._default,e);if(r.length>0)throw new Error(ke(t._name,r));s=e}const r=t.create(s);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),n=this.queryCache_.get(t);if(n&&n.version===this.worldVersion_)return n.result;let s=null,r=1/0;for(const t of e)if(!U(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<r&&(r=n,s=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const o=this.queryPool_[this.queryPoolIdx_++];o.length=0;const i=s?s.keys():this.entities_;for(const t of i){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&o.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:o}),o}}const ze=ae({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 De;function Le(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"}(De||(De={}));let He=null,Oe=null,We=1;const je=new Map;function Ne(e){He=e,Oe=e.getResourceManager(),et()}function Ve(){0!==Ge&&He&&(He._free(Ge),Ge=0),je.clear(),We=1,qe=!1,Oe=null,He=null}function Xe(){if(!Oe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Oe}const Ye={createShader:(e,t)=>Xe().createShader(e,t),releaseShader(e){e>0&&Xe().releaseShader(e)},create(e){const t=We++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??De.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return je.set(t,n),t},get:e=>je.get(e),setUniform(e,t,n){const s=je.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=je.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=je.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=je.get(e);return t?.blendMode??De.Normal},setDepthTest(e,t){const n=je.get(e);n&&(n.depthTest=t)},getShader(e){const t=je.get(e);return t?.shader??0},release(e){je.delete(e)},isValid:e=>je.has(e),releaseAll(){je.clear()},createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??De.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=je.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=We++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return je.set(n,s),n},toAssetData(e,t){const n=je.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=je.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let qe=!1,Ge=0;const Je=4096,Ke=new Map;let Qe=null;function Ze(e){const t=(0===Ge&&He&&(Ge=He._malloc(Je)),Ge);if(0===t||!He)return{ptr:0,count:0};let n=0,s=0;const r=He.HEAPU8,o=He.HEAPU32,i=He.HEAPF32;for(const[a,l]of e){if(n+128>Je)break;let e=Ke.get(a);e||(Qe||(Qe=new TextEncoder),e=Qe.encode(a),Ke.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=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+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function et(){if(!He||qe)return;He.materialDataProvider=(e,t,n,s,r)=>{const o=je.get(e);if(!o)return He.HEAPU32[t>>2]=0,He.HEAPU32[n>>2]=0,He.HEAPU32[s>>2]=0,void(He.HEAPU32[r>>2]=0);He.HEAPU32[t>>2]=o.shader,He.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Ze(o.uniforms);He.HEAPU32[s>>2]=i,He.HEAPU32[r>>2]=a},qe=!0}const tt={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,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class st{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&&(Ye.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ye.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:Ye.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const rt=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){rt.set(e,t)}function it(e){const t=rt.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function at(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Z,{value:s.name}),!1!==s.visible)for(const n of s.components)ct(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function lt(e,t,n){const s=new Map,r=n?.assetServer,o=n?.assetBaseUrl,i=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],l=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=rt.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;l.has(t)||(l.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const c=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);c.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),c.set(e,0)}})());for(const e of o)h.push((async()=>{try{const s=await t.loadMaterial(e,n);u.set(e,s.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 s=await t.loadBitmapFont(e,n);d.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=rt.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=c.get(t)??0;break;case"material":n[e.field]=u.get(t)??0;break;case"font":n[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Z,{value:n.name}),!1!==n.visible)for(const s of n.components)ct(e,t,s)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function ct(e,t,n){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const s=D(n.type);s?e.insert(t,s,n.data):console.warn(`Unknown component type: ${n.type}`)}function ut(e,t){const n=e.getEntitiesWithComponents([X]);for(const s of n){const n=e.get(s,X);n&&(n.aspectRatio=t,e.insert(s,X,n))}}function dt(e,t){const n=e.getEntitiesWithComponents([Z]);for(const s of n){const n=e.get(s,Z);if(n&&n.value===t)return s}return null}const ht=[{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}],ft={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"},pt=new Map,mt=new Set;for(const e of ht)for(const t of e.extensions)pt.set(t,e),mt.add(t);function _t(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function gt(e){return pt.get(_t(e))}function yt(e){return gt(e)?.editorType??"unknown"}function wt(e){return gt(e)?.addressableType??null}function xt(e){for(const t of ht)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function vt(e){return mt.has(e.toLowerCase())}function bt(){return mt}function Pt(e){return"string"==typeof e&&(!!e.includes("/")&&vt(_t(e)))}function St(){const e=[];for(const t of ht)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function Ct(){return St().map(e=>({type:"suffix",value:e}))}function Tt(e){return ft[e.toLowerCase()]}function Et(e){const t=gt(e);return t?.wechatPackInclude??!1}class Mt{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.module_=e,this.canvas_=d(g,g),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new st(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}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(),Ye.releaseAll(),this.textureCache_.clearAll(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===gt(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(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=l.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=gt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return lt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Ye.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return Ye.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const At=ae(null,"Assets");class Rt{build(e){const t=e.wasmModule;t?e.insertResource(At,new Mt(t)):console.warn("AssetPlugin: No WASM module available")}}const It=new Rt;class Ft{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Bt(e,t){const n=e.getResource(At);n&&n.registerEmbeddedAssets(t)}async function kt(e,t,n){const{entities:s,rootId:r}=await Ut(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await lt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function Ut(e,t,n,s,r){const o=new Map;let i;if(void 0===s){i=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),i=Math.max(i,t.prefabEntityId+1))}else{i=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,i++)}const a=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Ut(e,s.nestedPrefab.overrides,n,i,r);o.set(s.prefabEntityId,t.rootId),i=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==s.parent?o.get(s.parent)??null:null),a.push(...t.entities);continue}const l=o.get(s.prefabEntityId),c=s.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:s.prefabEntityId,name:s.name,parent:c?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};$t(u,t),a.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:l,nextId:i}}function $t(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class zt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return kt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Dt=ae(null,"Prefabs");class Lt{constructor(){this.name="PrefabsPlugin",this.dependencies=[At]}build(e){const t=e.getResource(At);e.insertResource(Dt,new zt(e.world,t))}}const Ht=new Lt;let Ot=null,Wt=0,jt=0,Nt=0;const Vt=new Float32Array(256);function Xt(e){Ot=e,Wt=Ot._malloc(64),jt=Ot._malloc(64),Nt=Ot._malloc(1024)}function Yt(){Ot&&(Wt&&(Ot._free(Wt),Wt=0),jt&&(Ot._free(jt),jt=0),Nt&&(Ot._free(Nt),Nt=0)),Ot=null}function qt(){if(!Ot)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ot}const Gt={r:1,g:1,b:1,a:1},Jt={begin(e){const t=qt();t.HEAPF32.set(e,Wt/4),t.draw_begin(Wt)},end(){qt().draw_end()},line(e,t,n,s=1){qt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){qt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){qt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){qt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){qt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Gt){qt().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=Gt){qt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){qt().draw_setLayer(e)},setDepth(e){qt().draw_setDepth(e)},getDrawCallCount:()=>Ot?Ot.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ot?Ot.draw_getPrimitiveCount():0,setBlendMode(e){qt().draw_setBlendMode(e)},setDepthTest(e){qt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=qt();s.HEAPF32.set(n,jt/4),s.draw_mesh(e,t,jt)},drawMeshWithMaterial(e,t,n){const s=qt(),r=Ye.get(t);if(!r)return;if(Jt.setBlendMode(r.blendMode),Jt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Jt.drawMesh(e,r.shader,n);let o;if(s.HEAPF32.set(n,jt/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,n]of r.uniforms){const s=Qt(t);if(!(s<0)){if(Le(n))Vt[o++]=10,Vt[o++]=s,Vt[o++]=n.slot??e++,Vt[o++]=n.textureId;else if("number"==typeof n)Vt[o++]=1,Vt[o++]=s,Vt[o++]=n;else if(Array.isArray(n)){Vt[o++]=n.length,Vt[o++]=s;for(let e=0;e<n.length;e++)Vt[o++]=n[e]}else"w"in n?(Vt[o++]=4,Vt[o++]=s,Vt[o++]=n.x,Vt[o++]=n.y,Vt[o++]=n.z,Vt[o++]=n.w):"z"in n?(Vt[o++]=3,Vt[o++]=s,Vt[o++]=n.x,Vt[o++]=n.y,Vt[o++]=n.z):(Vt[o++]=2,Vt[o++]=s,Vt[o++]=n.x,Vt[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(Vt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}0!==o?(s.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Nt/4),s.draw_meshWithUniforms(e,r.shader,jt,Nt,o)):s.draw_mesh(e,r.shader,jt)}},Kt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function Qt(e){return Kt[e]??-1}var Zt;!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"}(Zt||(Zt={}));let en=null,tn=0,nn=0,sn=0;function rn(e){en=e,tn=en._malloc(262144),nn=en._malloc(65536),sn=en._malloc(256)}function on(){en&&(tn&&en._free(tn),nn&&en._free(nn),sn&&en._free(sn),tn=0,nn=0,sn=0),en=null}function an(){if(!en)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return en}const ln={create(e){const t=an(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,tn/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,sn,r).set(o),t.geometry_init(n,tn,s,sn,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,nn,s).set(e.indices),t.geometry_setIndices16(n,nn,s)}else{new Uint32Array(t.HEAPU8.buffer,nn,s).set(e.indices),t.geometry_setIndices32(n,nn,s)}}return n},updateVertices(e,t,n=0){const s=an(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,tn/4),s.geometry_updateVertices(e,tn,r,n)},release(e){e>0&&an().geometry_release(e)},isValid:e=>!(!en||e<=0)&&en.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return ln.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:Zt.Float2},{name:"a_texCoord",type:Zt.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return ln.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Zt.Float2},{name:"a_texCoord",type:Zt.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return ln.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Zt.Float2},{name:"a_texCoord",type:Zt.Float2}],indices:new Uint16Array(i)})}};let cn=null;function un(e){cn=e}function dn(){cn&&fn.isInitialized()&&fn.shutdown(),cn=null}function hn(){if(!cn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return cn}const fn={init:(e,t)=>hn().postprocess_init(e,t),shutdown(){hn().postprocess_shutdown()},resize(e,t){hn().postprocess_resize(e,t)},addPass:(e,t)=>hn().postprocess_addPass(e,t),removePass(e){hn().postprocess_removePass(e)},setEnabled(e,t){hn().postprocess_setPassEnabled(e,t)},isEnabled:e=>hn().postprocess_isPassEnabled(e),setUniform(e,t,n){hn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){hn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){hn().postprocess_begin()},end(){hn().postprocess_end()},getPassCount:()=>hn().postprocess_getPassCount(),isInitialized:()=>!!cn&&cn.postprocess_isInitialized(),setBypass(e){hn().postprocess_setBypass(e)},isBypassed:()=>!cn||cn.postprocess_isBypassed(),createBlur:()=>Ye.createShader(pn,"#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:()=>Ye.createShader(pn,"#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:()=>Ye.createShader(pn,"#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:()=>Ye.createShader(pn,"#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")},pn="#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 mn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(mn||(mn={}));let _n=null,gn=0;function yn(e){_n=e,gn=_n._malloc(64)}function wn(){_n&&gn&&(_n._free(gn),gn=0),_n=null}const xn={init(e,t){_n?.renderer_init(e,t)},resize(e,t){_n?.renderer_resize(e,t)},begin(e,t){_n&&gn&&(_n.HEAPF32.set(e,gn/4),_n.renderer_begin(gn,t??0))},flush(){_n?.renderer_flush()},end(){_n?.renderer_end()},submitSprites(e){_n&&_n.renderer_submitSprites(e._cpp)},submitBitmapText(e){_n&&_n.renderer_submitBitmapText(e._cpp)},submitSpine(e){_n&&_n.renderer_submitSpine?.(e._cpp)},setStage(e){_n?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>_n?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){_n?.renderer_releaseTarget(e)},getTargetTexture:e=>_n?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>_n?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){_n?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){_n?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){_n?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){_n?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>_n?_n.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>_n?{drawCalls:_n.renderer_getDrawCalls(),triangles:_n.renderer_getTriangles(),sprites:_n.renderer_getSprites(),text:_n.renderer_getText(),spine:_n.renderer_getSpine?.()??0,meshes:_n.renderer_getMeshes(),culled:_n.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let vn=null;function bn(e){vn=e}function Pn(){vn=null}const Sn={enable(){vn?.gl_enableErrorCheck(!0)},disable(){vn?.gl_enableErrorCheck(!1)},check:e=>vn?.gl_checkErrors(e)??0,diagnose(){vn?.renderer_diagnose()}},Cn=new Map;function Tn(e,t){Cn.set(e,t)}function En(e){Cn.delete(e)}function Mn(){Cn.clear()}class An{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(xn.resize(s,r),fn.isInitialized()&&fn.getPassCount()>0&&fn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),xn.setViewport(0,0,s,r),xn.clearBuffers(3),xn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),xn.submitSprites(t),xn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):xn.submitSpine(t),xn.flush(),this.executeDrawCallbacks(n,o),xn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;xn.setViewport(s.x,s.y,s.w,s.h),xn.setScissor(s.x,s.y,s.w,s.h,!0),xn.clearBuffers(r),xn.setScissor(0,0,0,0,!1),xn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),xn.submitSprites(t),xn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):xn.submitSpine(t),xn.flush(),this.executeDrawCallbacks(n,o),xn.end()}executeDrawCallbacks(e,t){const n=Cn;if(n.size>0){Jt.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Jt.end();for(const e of s)En(e)}}}class Rn{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.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,.25);this.updateTime(n),this.world_.resetQueryPool(),this.runSchedule(xe.First),this.fixedAccumulator_+=n;let s=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&s<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(xe.FixedPreUpdate),this.runSchedule(xe.FixedUpdate),this.runSchedule(xe.FixedPostUpdate),s++;s>=8&&(this.fixedAccumulator_=0),this.runSchedule(xe.PreUpdate),this.runSchedule(xe.Update),this.runSchedule(xe.PostUpdate),this.runSchedule(xe.Last),requestAnimationFrame(this.mainLoop)},this.world_=new $e,this.resources_=new de;for(const e of Object.values(xe))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Rn}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this}addSystem(e){return this.addSystemToSchedule(xe.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(xe.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}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Ee(this.world_,this.resources_),this.resources_.insert(he,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(xe.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1;const e=[Pn,wn,dn,on,Ve,Yt];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const r=t.get(s);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,r=new Set,o=i=>{if(s.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}r.delete(i),s.add(i),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){let t=this.systems_.get(e);if(t&&this.runner_){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 n=e.system._name;console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n)}}}updateTime(e){const t=this.resources_.get(he);t.delta=e,t.elapsed+=e,t.frameCount++}}function In(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Fn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Bn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case W.FixedWidth:return o;case W.FixedHeight:return i;case W.Expand:return Math.max(o,i);case W.Shrink:return Math.min(o,i);case W.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function kn(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(r.projectionType===H.Orthographic){if(h=r.orthoSize,o){h=Bn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=$n(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Dn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=Hn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:new Float32Array(Wn(u,f)),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const Un=new Float32Array(16);function $n(e,t,n,s,r,o){const i=Un;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const zn=new Float32Array(16);function Dn(e,t,n,s){const r=zn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const Ln=new Float32Array(16);function Hn(e,t,n){const s=Ln;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const On=new Float32Array(16);function Wn(e,t){const n=On;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var jn,Nn,Vn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(jn||(jn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Nn||(Nn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Vn||(Vn={}));const Xn=R("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:jn.Left,verticalAlign:Nn.Top,wordWrap:!0,overflow:Vn.Visible,lineHeight:1.2}),Yn=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 qn{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(g,g),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===Vn.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(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,r&&e.overflow===Vn.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case Nn.Top:x=u;break;case Nn.Middle:x=(p-w)/2;break;case Nn.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of l){let s;switch(e.align){case jn.Left:s=u;break;case jn.Center:s=f/2;break;case jn.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}r&&e.overflow===Vn.Clip&&n.restore();const b=n.getImageData(0,0,f,p),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const T=S.createTexture(f,p,C,P.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 n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case jn.Left:return"left";case jn.Center:return"center";case jn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function Gn(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 Jn(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class Kn{build(e){z("Text",Xn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new qn(t),s=e.world,r=new Map;e.addSystemToSchedule(xe.PreUpdate,be([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Xn));for(const e of r.keys())s.valid(e)&&s.has(e,Xn)||r.delete(e);const e=s.getEntitiesWithComponents([Xn]);for(const t of e){const e=s.get(t,Xn),o=s.has(t,Yn)?s.get(t,Yn):null,i=r.get(t);if(i&&!Jn(i,e,o))continue;s.has(t,V)||s.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=n.renderForEntity(t,e,o),l=s.get(t,V);l.texture=a.textureHandle,l.size.x=a.width,l.size.y=a.height,l.uvOffset.x=0,l.uvOffset.y=0,l.uvScale.x=1,l.uvScale.y=1,s.insert(t,V,l),r.set(t,Gn(e,o))}}))}}const Qn=new Kn,Zn=R("UIMask",{enabled:!0});function es(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function ts(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[_,g]=m(d,f),[y,w]=m(h,p),x=Math.min(_,y),v=Math.max(_,y),b=Math.min(g,w),P=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(P-b)}}function ns(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=e[14],y=e[15],w=s*l-r*a,x=s*c-o*a,v=s*u-i*a,b=r*c-o*l,P=r*u-i*l,S=o*u-i*c,C=d*_-h*m,T=d*g-f*m,E=d*y-p*m,M=h*g-f*_,A=h*y-p*_,R=f*y-p*g;let I=w*R-x*A+v*M+b*E-P*T+S*C;return 0===I||(I=1/I,n[0]=(l*R-c*A+u*M)*I,n[1]=(o*A-r*R-i*M)*I,n[2]=(_*S-g*P+y*b)*I,n[3]=(f*P-h*S-p*b)*I,n[4]=(c*E-a*R-u*T)*I,n[5]=(s*R-o*E+i*T)*I,n[6]=(g*v-m*S-y*x)*I,n[7]=(d*S-f*v+p*x)*I,n[8]=(a*A-l*E+u*C)*I,n[9]=(r*E-s*A-i*C)*I,n[10]=(m*P-_*v+y*w)*I,n[11]=(h*v-d*P-p*w)*I,n[12]=(l*T-a*M-c*C)*I,n[13]=(s*M-r*T+o*C)*I,n[14]=(_*x-m*b-g*w)*I,n[15]=(d*b-h*x+f*w)*I),n}function ss(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function rs(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function os(e,t,n,s,r,o,i){if(!e.has(t,Yn)||!e.has(t,N))return null;const a=e.get(t,Yn),l=e.get(t,N),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return ts(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function is(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Zn]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Zn).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,G);){const e=t.get(s,G);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=os(t,n,r,o,i,a,l);e&&(s=es(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=os(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class as{build(e){if(z("UIMask",Zn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(is(e.wasmModule,e.world))}}const ls=new as,cs=R("Interactable",{enabled:!0}),us=R("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var ds;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(ds||(ds={}));const hs=R("Button",{state:ds.Normal,transition:null});class fs{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(n=>n.entity===e&&n.type===t)}}const ps=ae(new fs,"UIEvents"),ms=I("ScreenSpace");function _s(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function gs(e,t,n,s,r,o){if(!e.has(t,Yn))return;const i=e.get(t,Yn),a=_s(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,j);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,j,l),!e.has(t,J))return;const c=e.get(t,J);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&gs(e,t,a.rect,a.centerX,a.centerY,!1)}class ys{build(e){z("UIRect",Yn);const t=e.world;e.addSystemToSchedule(xe.PreUpdate,be([le(ze)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([ms,Yn,j]);for(const e of o)gs(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const ws=new ys,xs=new Float32Array(16),vs=new Float32Array(16);let bs=!0,Ps=1;class Ss{build(e){z("Interactable",cs),z("Button",hs);const t=e.world,n=new fs;e.insertResource(ps,n);let s=null,r=null;Ps="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(xe.PreUpdate,be([le(Ae),le(ze)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([us]);for(const e of i){const n=t.get(e,us);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a=e.mouseX*Ps,l=o.screenH-e.mouseY*Ps;!function(e){let t=!1;for(let n=0;n<16;n++)if(vs[n]!==e[n]){t=!0;break}t&&(vs.set(e),bs=!0)}(o.viewProjection),bs&&(ns(o.viewProjection,xs),bs=!1);const c=ss(a,l,xs,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([cs,Yn,N]);let d=null,h=-1/0;for(const e of u){t.has(e,us)||t.insert(e,us);if(!t.get(e,cs).enabled)continue;const n=t.get(e,N),s=t.get(e,Yn),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(rs(c.x,c.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,V)&&(n=t.get(e,V).layer),n>=h&&(h=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,us)){t.get(s,us).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,us).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,us);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,us)){const e=t.get(r,us);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(xe.Update,be([],()=>{const e=t.getEntitiesWithComponents([hs]);for(const n of e){if(t.has(n,cs)||t.insert(n,cs,{enabled:!0}),!t.has(n,us))continue;const e=t.get(n,us),s=t.get(n,hs),r=t.get(n,cs),o=s.state;if(r.enabled?e.pressed?s.state=ds.Pressed:e.hovered?s.state=ds.Hovered:s.state=ds.Normal:s.state=ds.Disabled,o!==s.state&&s.transition&&t.has(n,V)){const e=t.get(n,V),r=s.transition;switch(s.state){case ds.Normal:e.color={...r.normalColor};break;case ds.Hovered:e.color={...r.hoveredColor};break;case ds.Pressed:e.color={...r.pressedColor};break;case ds.Disabled:e.color={...r.disabledColor}}t.insert(n,V,e)}}},{name:"ButtonSystem"}))}}const Cs=new Ss,Ts=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 Es{build(e){z("TextInput",Ts);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(g,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!h)return;const f=h;function p(){if(null===i||!n.valid(i))return;const t=n.get(i,Ts);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(ps).emit(i,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,y()}function m(e){if(i===e)return;_();const t=n.get(e,Ts);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),y())}function _(){if(null!==i&&n.valid(i)&&n.has(i,Ts)){const e=n.get(i,Ts);e.focused=!1,e.dirty=!0}i=null,f.blur()}function y(){l=!0,c=0}function x(e,i,a,c){(r.width<a||r.height<c)&&(r.width=As(Math.max(r.width,a)),r.height=As(Math.max(r.height,c))),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,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=Ms(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=Ms(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const _=o.getImageData(0,0,a,c),g=new Uint8Array(_.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,c,w,g.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,V);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,V,b)}f.addEventListener("input",()=>{a||null===i||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void _();const s=n.get(i,Ts);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(ps).emit(i,"submit"),void _()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,y())}),f.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,Ts)){const e=n.get(i,Ts);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(xe.PreUpdate,be([le(ps)],e=>{const t=n.getEntitiesWithComponents([Ts,cs]);for(const e of t){if(!n.has(e,us))continue;if(n.get(e,us).justPressed)return void m(e)}if(null!==i){const e=n.getEntitiesWithComponents([cs]);for(const t of e){if(n.has(t,Ts))continue;if(!n.has(t,us))continue;if(n.get(t,us).justPressed)return void _()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(xe.PreUpdate,be([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,Ts)))){n.get(i,Ts).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Ts)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Ts,Yn]);for(const e of a){const t=n.get(e,Ts);if(!t.dirty)continue;const s=n.get(e,Yn),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,V)||n.insert(e,V,{texture:w,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}),x(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Ms(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function As(e){let t=1;for(;t<e;)t*=2;return t}const Rs=new Es;async function Is(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 Fs=ae({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Bs=ae(null,"PhysicsAPI");function ks(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Us(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class $s{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Fs,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Is(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([Y]);for(const n of t){const t=e.world.get(n,Y);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(xe.PostUpdate,be([le(he)],a=>{const l=i.getEntitiesWithComponents([te,j,N]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,te),l=i.get(r,N);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=ks(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),zs(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===oe.Kinematic){const e=ks(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,j);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,G)){const t=e.world.get(i,G);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,N)){const n=e.world.get(t.entity,N),s=ks(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),h=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=Us(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,j,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Fs,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Bs,Ds._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function zs(e,t,n){const s=e.world;if(s.has(n,ne)){const e=s.get(n,ne);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,se)){const e=s.get(n,se);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,re)){const e=s.get(n,re);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Ds{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(Ds.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 Ls(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Hs(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Os(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,_=a*f,g=l*h,y=l*f,w=c*f,x=u*d,v=u*h,b=u*f;return new Float32Array([(1-(g+w))*r,(m+b)*r,(_-v)*r,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*i,(y-x)*i,(1-(p+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Ws(e,t,n,s,r,o,i,a){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=Ls(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,l);let c={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),c=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=await r.readText(a),u="binary"===gt(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),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=Hs(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Ls(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,n,s)),o){new $s("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;const i=gt(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=o?`${o}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Ls(e,c,!1),d=e.getResourceManager();s[r]=d.loadBitmapFont(t,u,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),h=await async function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Ye.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=Ye.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),f=at(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,V);r&&(r.texture=n[s.data.texture]||0,e.insert(t,V,r))}}}(e.world,n,l,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,K);o&&(o.font=r,e.insert(t,K,o))}}}(e.world,n,d,f),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,V);n&&(n.material=r,e.insert(t,V,n))}else if("SpineAnimation"===s.type){const n=e.get(t,Q);n&&(n.material=r,e.insert(t,Q,n))}}}}(e.world,n,h,f),r&&u){const s=function(e,t,n,s){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,n,c,f);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,Q)?c.get(o,Q):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,N)){const e=Os(c.get(o,N),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],_=new Float32Array(n.HEAPF32.buffer,c,8*r),g=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,r,w,o,p,m,h),t._free(y),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,u,s)}if(a){const t=e.getResource(At);t&&t.setAddressableManifest(a)}}class js{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===gt(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of s){const t=gt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class Ns{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.currentScene_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene(),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(!this.app_)return;let e="fetch scene";try{const t=await i(this.sceneUrl_);if(!t.ok)throw new Error(`Failed to fetch scene: ${t.status}`);e="parse scene JSON";const n=await t.json();e="prefetch assets";const s=new js(this.baseUrl_);await s.prefetch(n);let r=null;const o=this.app_.spineInitPromise;if(o){e="init spine";r=(await o).controller.raw}e="loadRuntimeScene",await Ws(this.app_,this.app_.wasmModule,n,s,r),e="ensureCamera",this.ensureCamera()}catch(t){const n=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:"";throw console.error(`[PreviewPlugin] Failed at step "${e}": ${n}\n${s}`),new Error(`[PreviewPlugin:${e}] ${n}`)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([X]);for(const s of n){if(e.get(s,X).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([Y]);for(const r of s){const s=e.get(r,Y);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,j,o);const i={isActive:!0,projectionType:H.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:O.ColorAndDepth};e.insert(r,X,i)}}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.eventSource_.addEventListener("message",async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())}),this.eventSource_.addEventListener("error",e=>{console.error("[PreviewPlugin] EventSource error:",e)})}async reloadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new js(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await Ws(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera(),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 Vs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=xn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:xn.getTargetTexture(n),width:e.width,height:e.height}},release(e){xn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(xn.releaseRenderTarget(e._handle),Vs.create({width:t,height:n,depth:!0})),begin(e,t){xn.begin(t,e._handle)},end(){xn.end()},getDepthTexture:e=>xn.getTargetDepthTexture(e._handle)};let Xs=!1;function Ys(e){Xs=e}function qs(){return Xs}function Gs(){return!Xs}var Js;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Js||(Js={}));class Ks{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Js[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Js.Debug:console.debug(t,n);break;case Js.Info:console.log(t,n);break;case Js.Warn:console.warn(t,n);break;case Js.Error:console.error(t,n)}}}class Qs{constructor(){this.handlers_=[],this.minLevel_=Js.Info,this.addHandler(new Ks)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(Js.Debug,e,t,n)}info(e,t,n){this.log(Js.Info,e,t,n)}warn(e,t,n){this.log(Js.Warn,e,t,n)}error(e,t,n){this.log(Js.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Zs=new Qs;function er(){return Zs}function tr(e){Zs.setMinLevel(e)}function nr(e,t,n){Zs.debug(e,t,n)}function sr(e,t,n){Zs.info(e,t,n)}function rr(e,t,n){Zs.warn(e,t,n)}function or(e,t,n){Zs.error(e,t,n)}const ir=[Qn,ls,ws,Cs,Rs];function ar(e,t){return function(e,t){const n=Rn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Xt(e),Ne(e),rn(e),un(e),yn(e),bn(e);const r=new An;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,o){o||(o=kn(e,s,t,r));const i=n.getResource(ze);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(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});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;xn.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;xn.resize(t,n),fn.isInitialized()&&fn.getPassCount()>0&&!fn.isBypassed()&&fn.resize(t,n);const u=kn(e,s,t,n);if(a(t,n,u),0===u.length)r.render({registry:{_cpp:s},viewProjection:Fn,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}xn.setViewport(0,0,t,n)}}};if(n.addSystemToSchedule(xe.First,l),n.addSystemToSchedule(xe.Last,c),n.addPlugin(It),n.addPlugin(Ht),n.addPlugin(Ie),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:ir,...t})}e=f;export{Rn as App,Rt as AssetPlugin,Ft as AssetRefCounter,Mt as AssetServer,At as Assets,nt as AsyncCache,K as BitmapText,De as BlendMode,oe as BodyType,ne as BoxCollider,hs as Button,ds as ButtonState,X as Camera,Y as Canvas,re as CapsuleCollider,J as Children,se as CircleCollider,O as ClearFlags,ge as Commands,we as CommandsInstance,m as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,_ as DEFAULT_PIXELS_PER_UNIT,g as DEFAULT_TEXT_CANVAS_SIZE,Zt as DataType,Jt as Draw,ye as EntityCommands,Sn as GLDebug,ln as Geometry,y as INVALID_ENTITY,x as INVALID_FONT,w as INVALID_TEXTURE,Ae as Input,Re as InputPlugin,Me as InputState,cs as Interactable,j as LocalTransform,Js as LogLevel,Qs as Logger,Ye as Material,st as MaterialLoader,fe as Mut,Z as Name,G as Parent,Ds as Physics,Fs as PhysicsEvents,$s as PhysicsPlugin,fn as PostProcess,zt as PrefabServer,Dt as Prefabs,Lt as PrefabsPlugin,Ns as PreviewPlugin,H as ProjectionType,me as Query,_e as QueryInstance,An as RenderPipeline,mn as RenderStage,Vs as RenderTexture,xn as Renderer,le as Res,ce as ResMut,te as RigidBody,W as ScaleMode,xe as Schedule,ms as ScreenSpace,tt as ShaderSources,Q as SpineAnimation,V as Sprite,Ee as SystemRunner,Xn as Text,jn as TextAlign,Ts as TextInput,Es as TextInputPlugin,Vn as TextOverflow,Kn as TextPlugin,qn as TextRenderer,Nn as TextVerticalAlign,he as Time,ze as UICameraInfo,fs as UIEventQueue,ps as UIEvents,us as UIInteraction,Ss as UIInteractionPlugin,ys as UILayoutPlugin,Zn as UIMask,as as UIMaskPlugin,Yn as UIRect,q as Velocity,js as WebAssetProvider,$e as World,N as WorldTransform,Ce as addStartupSystem,Se as addSystem,Te as addSystemToSchedule,It as assetPlugin,Mn as clearDrawCallbacks,B as clearUserComponents,S as color,_s as computeUIRectLayout,is as createMaskProcessor,ar as createWebApp,nr as debug,R as defineComponent,ae as defineResource,be as defineSystem,I as defineTag,or as error,dt as findEntityByName,In as flushPendingSystems,wt as getAddressableType,xt as getAddressableTypeByEditorType,bt as getAllAssetExtensions,Tt as getAssetMimeType,gt as getAssetTypeEntry,D as getComponent,it as getComponentAssetFields,ee as getComponentDefaults,St as getCustomExtensions,yt as getEditorType,er as getLogger,t as getPlatform,s as getPlatformType,F as getUserComponent,Ct as getWeChatPackOptions,sr as info,Xt as initDrawAPI,bn as initGLDebugAPI,rn as initGeometryAPI,Ne as initMaterialAPI,un as initPostProcessAPI,yn as initRendererAPI,Ie as inputPlugin,kt as instantiatePrefab,es as intersectRects,ns as invertMatrix4,U as isBuiltinComponent,Et as isCustomExtension,qs as isEditor,vt as isKnownAssetExtension,n as isPlatformInitialized,Gs as isRuntime,Le as isTextureRef,r as isWeChat,o as isWeb,ct as loadComponent,Is as loadPhysicsModule,Ws as loadRuntimeScene,at as loadSceneData,lt as loadSceneWithAssets,Pt as looksLikeAssetPath,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,rs as pointInWorldRect,Ht as prefabsPlugin,C as quat,z as registerComponent,ot as registerComponentAssetFields,Tn as registerDrawCallback,Bt as registerEmbeddedAssets,et as registerMaterialCallback,ss as screenToWorld,Ys as setEditorMode,tr as setLogLevel,Yt as shutdownDrawAPI,Pn as shutdownGLDebugAPI,on as shutdownGeometryAPI,Ve as shutdownMaterialAPI,dn as shutdownPostProcessAPI,wn as shutdownRendererAPI,Rs as textInputPlugin,Qn as textPlugin,Cs as uiInteractionPlugin,ws as uiLayoutPlugin,ls as uiMaskPlugin,ir as uiPlugins,En as unregisterDrawCallback,ut as updateCameraAspectRatio,v as vec2,b as vec3,P as vec4,rr as warn,ts as worldRectToScreen};+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),i=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},o=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},h=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",i),n.addEventListener("mousedown",o),n.addEventListener("mouseup",a),n.addEventListener("touchstart",c),n.addEventListener("touchmove",l),n.addEventListener("touchend",u),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",i),n.removeEventListener("mousedown",o),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",c),n.removeEventListener("touchmove",l),n.removeEventListener("touchend",u),n.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,n=0)=>({x:e,y:t,z:n}),S=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),P=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),C=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function T(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(T);const t={};for(const n in e)t[n]=T(e[n]);return t}let E=0;function M(e,t){const n=++E;return{_id:Symbol(`Component_${n}_${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 n=A(),s=n.get(e);if(s)return s;const r=M(e,t);return n.set(e,r),B(e,t,!1),r}function I(e){const t=A(),n=t.get(e);if(n)return n;const s=M(e,{});return t.set(e,s),B(e,{},!0),s}function F(e){return A().get(e)}function k(){A().clear()}function B(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function U(e){return!0===e._builtin}const $=new Map;function z(e,t){$.set(e,t)}function D(e){return $.get(e)??F(e)}function L(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return $.set(e,n),n}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=L("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=L("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=L("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=L("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=L("Canvas",{designResolution:{x:p,y:_},pixelsPerUnit:100,scaleMode:W.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),q=L("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),G=L("Parent",{entity:0}),J=L("Children",{entities:[]}),K=L("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:x}),Q=L("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}z("Name",Z);const ne=L("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),se=L("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),re=L("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ie=L("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 n=++ae;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_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_)}}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.value_=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=[],n=[]){const s=[];return e.forEach((e,t)=>{_e(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class 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_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.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 s){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 n=0;n<t.length;n++)if(this.world_.has(h,t[n])){e=!0;break}if(e)continue}a[0]=h;for(let e=0;e<r;e++)a[e+1]=this.world_.get(h,n[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];u=h}yield a.slice()}}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,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function 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 n;return n=U(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class 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,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var 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,n){const s=++be;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}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 n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof xe&&t[e].flush()}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 n=new Ae;e.insertResource(Re,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(ve.Last,Se([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Fe=new Ie;function ke(e,t,n){const s=[];for(const[e,r]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const n=Be(t[e]),i=Be(r);n!==i&&null!=r&&s.push({field:e,expected:n,actual:i,value:r})}return s}function Be(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ue(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}function $e(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:$e(e)}}return t}class ze{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;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 n of t)this.tsStorage_.get(n)?.delete(e);this.entityComponents_.delete(e)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(this.iterationDepth_=0)}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,n){return U(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}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 n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.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 n=this.cppRegistry_;return t={add:n[`add${e}`].bind(n),get:n[`get${e}`].bind(n),has:n[`has${e}`].bind(n),remove:n[`remove${e}`].bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=ke(t._name,t._default,s);if(e.length>0)throw new Error(Ue(t._name,e))}const r={...t._default,...s};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,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const r=ke(t._name,t._default,e);if(r.length>0)throw new Error(Ue(t._name,r));s=e}const r=t.create(s);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0,this.queryCache_.clear()}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();const t=e.map(e=>e._name).sort().join(","),n=this.queryCache_.get(t);if(n&&n.version===this.worldVersion_)return n.result;let s=null,r=1/0;for(const t of e)if(!U(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<r&&(r=n,s=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const i=this.queryPool_[this.queryPoolIdx_++];i.length=0;const o=s?s.keys():this.entities_;for(const t of o){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&i.push(t)}return this.queryCache_.set(t,{version:this.worldVersion_,result:i}),i}}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 Le;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"}(Le||(Le={}));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,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++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Le.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return Ne.set(t,n),t},get:e=>Ne.get(e),setUniform(e,t,n){const s=Ne.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=Ne.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ne.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=Ne.get(e);return t?.blendMode??Le.Normal},setDepthTest(e,t){const n=Ne.get(e);n&&(n.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 n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Le.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ne.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=je++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ne.set(n,s),n},toAssetData(e,t){const n=Ne.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=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 n=0,s=0;const r=He.HEAPU8,i=He.HEAPU32,o=He.HEAPF32;for(const[a,c]of e){if(n+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+n>>2]=l,n+=4,r.set(e,t+n),n+=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+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function tt(){if(!He||Ge)return;He.materialDataProvider=(e,t,n,s,r)=>{const i=Ne.get(e);if(!i)return He.HEAPU32[t>>2]=0,He.HEAPU32[n>>2]=0,He.HEAPU32[s>>2]=0,void(He.HEAPU32[r>>2]=0);He.HEAPU32[t>>2]=i.shader,He.HEAPU32[n>>2]=i.blendMode;const{ptr:o,count:a}=et(i.uniforms);He.HEAPU32[s>>2]=o,He.HEAPU32[r>>2]=a},Ge=!0}const nt={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 st{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const s=t(),r=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{i.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class rt{constructor(e,t=""){this.cache_=new st,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 n=await c(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),i=await this.shaderLoader_.load(r);return{handle:qe.createFromAsset(s,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const 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 n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function ct(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Z,{value:s.name}),!1!==s.visible)for(const n of s.components)ut(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function lt(e,t,n){const s=new Map,r=n?.assetServer,i=n?.assetBaseUrl,o=new Map;r&&await async function(e,t,n,s){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],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 n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const 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:n?`${n}/${e}`:`/${e}`,i=await t.loadTexture(r);l.set(e,i.handle),s.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 s=await t.loadMaterial(e,n);u.set(e,s.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 s=await t.loadBitmapFont(e,n);h.set(e,s)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),h.set(e,0)}})());for(const e of a)d.push((async()=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=it.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":n[e.field]=l.get(t)??0;break;case"material":n[e.field]=u.get(t)??0;break;case"font":n[e.field]=h.get(t)??0}}}}(t,r,i,o);for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Z,{value:n.name}),!1!==n.visible)for(const s of n.components)ut(e,t,s)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function ut(e,t,n){if("UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const s=D(n.type);s?e.insert(t,s,n.data):console.warn(`Unknown component type: ${n.type}`)}function ht(e,t){const n=e.getEntitiesWithComponents([X]);for(const s of n){const n=e.get(s,X);n&&(n.aspectRatio=t,e.insert(s,X,n))}}function dt(e,t){const n=e.getEntitiesWithComponents([Z]);for(const s of n){const n=e.get(s,Z);if(n&&n.value===t)return s}return null}const ft=[{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}],pt={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"},_t=new Map,gt=new Set;for(const e of ft)for(const t of e.extensions)_t.set(t,e),gt.add(t);function mt(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function yt(e){return _t.get(mt(e))}function wt(e){return yt(e)?.editorType??"unknown"}function xt(e){return yt(e)?.addressableType??null}function vt(e){for(const t of ft)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function bt(e){return gt.has(e.toLowerCase())}function St(){return gt}function Pt(e){return"string"==typeof e&&(!!e.includes("/")&&bt(mt(e)))}function Ct(){const e=[];for(const t of ft)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function Tt(){return Ct().map(e=>({type:"suffix",value:e}))}function Et(e){return pt[e.toLowerCase()]}function Mt(e){const t=yt(e);return t?.wechatPackInclude??!1}class At{constructor(e){this.textureCache_=new st,this.shaderCache_=new st,this.jsonCache_=new st,this.textCache_=new st,this.binaryCache_=new st,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new st,this.prefabCache_=new st,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.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,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}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.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),c=[];for(const e of a){const t=o?`${o}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),c.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,n),u="binary"===yt(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(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,i,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),r=c.find(e=>e.name===n);if(r){const n=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,r.info.width,r.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=yt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${s}`:s,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return lt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const r=s.metadata?.atlas;r&&n.push(this.loadSpine(s.path,r).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,n,a,i.length,1,s);return this.module_._free(a),{handle:c,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return qe.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await l(t))throw new Error(`Shader file not found: ${e}`);const s=await c(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(s);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return qe.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await c(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return c(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Rt=ce(null,"Assets");class It{build(e){const t=e.wasmModule;t?e.insertResource(Rt,new At(t)):console.warn("AssetPlugin: No WASM module available")}}const Ft=new It;class kt{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Bt(e,t){const n=e.getResource(Rt);n&&n.registerEmbeddedAssets(t)}async function Ut(e,t,n){const{entities:s,rootId:r}=await $t(t,n?.overrides??[],n,void 0,new Set),i={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await lt(e,i,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=o.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:o}}async function $t(e,t,n,s,r){const i=new Map;let o;if(void 0===s){o=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=s;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,o++)}const a=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(r?.has(s.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${s.nestedPrefab.prefabPath}`);continue}r?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await $t(e,s.nestedPrefab.overrides,n,o,r);i.set(s.prefabEntityId,t.rootId),o=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?i.get(s.parent)??null:null),a.push(...t.entities);continue}const c=i.get(s.prefabEntityId),l=s.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:l?null:null!==s.parent?i.get(s.parent)??null:null,children:s.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};zt(u,t),a.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:a,rootId:c,nextId:o}}function zt(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Dt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,r=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Ut(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Lt=ce(null,"Prefabs");class Ot{constructor(){this.name="PrefabsPlugin",this.dependencies=[Rt]}build(e){const t=e.getResource(Rt);e.insertResource(Lt,new Dt(e.world,t))}}const Ht=new Ot;let Wt=null,jt=0,Nt=0,Vt=0;const Xt=new Float32Array(256);function Yt(e){Wt=e,jt=Wt._malloc(64),Nt=Wt._malloc(64),Vt=Wt._malloc(1024)}function qt(){Wt&&(jt&&(Wt._free(jt),jt=0),Nt&&(Wt._free(Nt),Nt=0),Vt&&(Wt._free(Vt),Vt=0)),Wt=null}function Gt(){if(!Wt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Wt}const Jt={r:1,g:1,b:1,a:1},Kt={begin(e){const t=Gt();t.HEAPF32.set(e,jt/4),t.draw_begin(jt)},end(){Gt().draw_end()},line(e,t,n,s=1){Gt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){Gt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){Gt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){Gt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){Gt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Jt){Gt().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=Jt){Gt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){Gt().draw_setLayer(e)},setDepth(e){Gt().draw_setDepth(e)},getDrawCallCount:()=>Wt?Wt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Wt?Wt.draw_getPrimitiveCount():0,setBlendMode(e){Gt().draw_setBlendMode(e)},setDepthTest(e){Gt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=Gt();s.HEAPF32.set(n,Nt/4),s.draw_mesh(e,t,Nt)},drawMeshWithMaterial(e,t,n){const s=Gt(),r=qe.get(t);if(!r)return;if(Kt.setBlendMode(r.blendMode),Kt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Kt.drawMesh(e,r.shader,n);let i;if(s.HEAPF32.set(n,Nt/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,n]of r.uniforms){const s=Zt(t);if(!(s<0)){if(Oe(n))Xt[i++]=10,Xt[i++]=s,Xt[i++]=n.slot??e++,Xt[i++]=n.textureId;else if("number"==typeof n)Xt[i++]=1,Xt[i++]=s,Xt[i++]=n;else if(Array.isArray(n)){Xt[i++]=n.length,Xt[i++]=s;for(let e=0;e<n.length;e++)Xt[i++]=n[e]}else"w"in n?(Xt[i++]=4,Xt[i++]=s,Xt[i++]=n.x,Xt[i++]=n.y,Xt[i++]=n.z,Xt[i++]=n.w):"z"in n?(Xt[i++]=3,Xt[i++]=s,Xt[i++]=n.x,Xt[i++]=n.y,Xt[i++]=n.z):(Xt[i++]=2,Xt[i++]=s,Xt[i++]=n.x,Xt[i++]=n.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<i)&&(r.cachedBuffer_=new Float32Array(i)),r.cachedBuffer_.set(Xt.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}0!==i?(s.HEAPF32.set(r.cachedBuffer_.subarray(0,i),Vt/4),s.draw_meshWithUniforms(e,r.shader,Nt,Vt,i)):s.draw_mesh(e,r.shader,Nt)}},Qt={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 Zt(e){return Qt[e]??-1}var en;!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"}(en||(en={}));let tn=null,nn=0,sn=0,rn=0;function on(e){tn=e,nn=tn._malloc(262144),sn=tn._malloc(65536),rn=tn._malloc(256)}function an(){tn&&(nn&&tn._free(nn),sn&&tn._free(sn),rn&&tn._free(rn),nn=0,sn=0,rn=0),tn=null}function cn(){if(!tn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return tn}const ln={create(e){const t=cn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,nn/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,rn,r).set(i),t.geometry_init(n,nn,s,rn,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,sn,s).set(e.indices),t.geometry_setIndices16(n,sn,s)}else{new Uint32Array(t.HEAPU8.buffer,sn,s).set(e.indices),t.geometry_setIndices32(n,sn,s)}}return n},updateVertices(e,t,n=0){const s=cn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,nn/4),s.geometry_updateVertices(e,nn,r,n)},release(e){e>0&&cn().geometry_release(e)},isValid:e=>!(!tn||e<=0)&&tn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return ln.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:en.Float2},{name:"a_texCoord",type:en.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;n.push(i,o,a,c)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return ln.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:en.Float2},{name:"a_texCoord",type:en.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(r-n);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return ln.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:en.Float2},{name:"a_texCoord",type:en.Float2}],indices:new Uint16Array(o)})}};let un=null;function hn(e){un=e}function dn(){un&&pn.isInitialized()&&pn.shutdown(),un=null}function fn(){if(!un)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return un}const pn={init:(e,t)=>fn().postprocess_init(e,t),shutdown(){fn().postprocess_shutdown()},resize(e,t){fn().postprocess_resize(e,t)},addPass:(e,t)=>fn().postprocess_addPass(e,t),removePass(e){fn().postprocess_removePass(e)},setEnabled(e,t){fn().postprocess_setPassEnabled(e,t)},isEnabled:e=>fn().postprocess_isPassEnabled(e),setUniform(e,t,n){fn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){fn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){fn().postprocess_begin()},end(){fn().postprocess_end()},getPassCount:()=>fn().postprocess_getPassCount(),isInitialized:()=>!!un&&un.postprocess_isInitialized(),setBypass(e){fn().postprocess_setBypass(e)},isBypassed:()=>!un||un.postprocess_isBypassed(),createBlur:()=>qe.createShader(_n,"#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(_n,"#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(_n,"#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(_n,"#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")},_n="#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 gn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(gn||(gn={}));let mn=null,yn=0;function wn(e){mn=e,yn=mn._malloc(64)}function xn(){mn&&yn&&(mn._free(yn),yn=0),mn=null}const vn={init(e,t){mn?.renderer_init(e,t)},resize(e,t){mn?.renderer_resize(e,t)},begin(e,t){mn&&yn&&(mn.HEAPF32.set(e,yn/4),mn.renderer_begin(yn,t??0))},flush(){mn?.renderer_flush()},end(){mn?.renderer_end()},submitSprites(e){mn&&mn.renderer_submitSprites(e._cpp)},submitBitmapText(e){mn&&mn.renderer_submitBitmapText(e._cpp)},submitSpine(e){mn&&mn.renderer_submitSpine?.(e._cpp)},setStage(e){mn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>mn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){mn?.renderer_releaseTarget(e)},getTargetTexture:e=>mn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>mn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){mn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){mn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){mn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){mn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>mn?mn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>mn?{drawCalls:mn.renderer_getDrawCalls(),triangles:mn.renderer_getTriangles(),sprites:mn.renderer_getSprites(),text:mn.renderer_getText(),spine:mn.renderer_getSpine?.()??0,meshes:mn.renderer_getMeshes(),culled:mn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let bn=null;function Sn(e){bn=e}function Pn(){bn=null}const Cn={enable(){bn?.gl_enableErrorCheck(!0)},disable(){bn?.gl_enableErrorCheck(!1)},check:e=>bn?.gl_checkErrors(e)??0,diagnose(){bn?.renderer_diagnose()}},Tn=new Map;function En(e,t,n){Tn.set(e,{fn:t,scene:n??""})}function Mn(e){Tn.delete(e)}function An(){Tn.clear()}class Rn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:i}=e;s===this.lastWidth_&&r===this.lastHeight_||(vn.resize(s,r),pn.isInitialized()&&pn.getPassCount()>0&&pn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),vn.setViewport(0,0,s,r),vn.clearBuffers(3),vn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),vn.submitSprites(t),vn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):vn.submitSpine(t),vn.flush(),this.executeDrawCallbacks(n,i),vn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:i}=e;vn.setViewport(s.x,s.y,s.w,s.h),vn.setScissor(s.x,s.y,s.w,s.h,!0),vn.clearBuffers(r),vn.setScissor(0,0,0,0,!1),vn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),vn.submitSprites(t),vn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):vn.submitSpine(t),vn.flush(),this.executeDrawCallbacks(n,i),vn.end()}executeDrawCallbacks(e,t){const n=Tn;if(n.size>0){Kt.begin(e);const s=[];for(const[e,r]of n.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Kt.end();for(const e of s)Mn(e)}}}const In="__scene_transition_overlay__",Fn={r:0,g:0,b:0,a:1};class kn{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Bn{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),En(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=pn.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){pn.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 n=this.app_.world.get(e,ee);n.persistent=t,this.app_.world.insert(e,ee,n)}}}class Un{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.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){"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??.3,r=t.color??Fn;t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:r,targetScene:e,options:t,resolve:n},En(In,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;Kt.setLayer(9999),Kt.setDepth(9999),Kt.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{n&&n!==e&&await this.unload(n,t),await this.load(e)})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Mn(In),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){return this.scenes_.get(e).status="running",this.activeScene_=e,this.contexts_.get(e)}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new kn(t);this.scenes_.set(e,n);const s=new Bn(n,this.app_);this.contexts_.set(e,s);let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Rt)?this.app_.getResource(Rt):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(Rt)&&(t.assetServer=this.app_.getResource(Rt));const s=await lt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,ee,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=zn(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s}async loadAdditive(e){if(this.scenes_.has(e)){return this.scenes_.get(e).status="running",this.additiveScenes_.add(e),this.contexts_.get(e)}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new kn(t);this.scenes_.set(e,n);const s=new Bn(n,this.app_);this.contexts_.set(e,s);let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Rt)?this.app_.getResource(Rt):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(Rt)&&(t.assetServer=this.app_.getResource(Rt));const s=await lt(this.app_.world,r,t);for(const t of s.values())n.entities.add(t),this.app_.world.insert(t,ee,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:n,system:s}of t.systems){const t=zn(this.app_,e,s);this.app_.addSystemToSchedule(n,t)}return t.setup&&await t.setup(s),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const r=t?.keepPersistent??!0;for(const e of n.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,ee)){if(this.app_.world.get(e,ee).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Mn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{pn.removePass(e)}catch{}n.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=null)}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(t&&"running"===t.status){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,V)){const n=this.app_.world.get(e,V);t.savedAlphas.set(e,n.color.a),n.color={...n.color,a:0},this.app_.world.insert(e,V,n)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,V)){const n=this.app_.world.get(e,V),s=t.savedAlphas.get(e)??1;n.color={...n.color,a:s},this.app_.world.insert(e,V,n)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{pn.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const $n=ce(null,"SceneManager");function zn(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource($n).getSceneStatus(t)&&n._fn(...s)}}}const Dn={name:"SceneManager",build(e){const t=new Un(e);e.insertResource($n,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource($n),n=t.getInitial();n&&t.load(n)}};e.addSystemToSchedule(ve.Startup,n)}};class Ln{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.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,.25);this.updateTime(n),this.world_.resetQueryPool(),this.runSchedule(ve.First),this.fixedAccumulator_+=n;let s=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&s<8;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ve.FixedPreUpdate),this.runSchedule(ve.FixedUpdate),this.runSchedule(ve.FixedPostUpdate),s++;s>=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 ze,this.resources_=new de;for(const e of Object.values(ve))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ln}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this}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}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($n).register(e),this}setInitialScene(e){return this.getResource($n).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;const e=[Pn,xn,dn,an,Xe,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 n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const r=t.get(s);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,r=new Set,i=o=>{if(s.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&i(n)}r.delete(o),s.add(o),n.push(a)};for(let t=0;t<e.length;t++)i(t);return n}runSchedule(e){let t=this.systems_.get(e);if(t&&this.runner_){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 n=e.system._name;console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n)}}}updateTime(e){const t=this.resources_.get(fe);t.delta=e,t.elapsed+=e,t.frameCount++}}function On(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Hn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Wn(e,t,n,s,r){const i=e*t/n,o=e;switch(s){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 jn(e,t,n,s,r,i){if(0===n||0===s)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,ee);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const c=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(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*n/(o.h*s);let u,h=0,d=0;if(r.projectionType===O.Orthographic){if(d=r.orthoSize,c){d=Wn(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}h=d*a,u=Vn(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Yn(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=Gn(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(Kn(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 Nn=new Float32Array(16);function Vn(e,t,n,s,r,i){const o=Nn;o.fill(0);const a=t-e,c=s-n,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(s+n)/c,o[14]=-(i+r)/l,o[15]=1,o}const Xn=new Float32Array(16);function Yn(e,t,n,s){const r=Xn;r.fill(0);const i=1/Math.tan(e/2),o=n-s;return r[0]=i/t,r[5]=i,r[10]=(s+n)/o,r[11]=-1,r[14]=2*s*n/o,r}const qn=new Float32Array(16);function Gn(e,t,n){const s=qn;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}const Jn=new Float32Array(16);function Kn(e,t){const n=Jn;for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}var Qn,Zn,es;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Qn||(Qn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Zn||(Zn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(es||(es={}));const ts=R("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Qn.Left,verticalAlign:Zn.Top,wordWrap:!0,overflow:es.Visible,lineHeight:1.2}),ns=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 ss{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 n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let 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===es.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(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const _=Math.round(255*e.color.r),g=Math.round(255*e.color.g),m=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${_}, ${g}, ${m}, ${y})`,r&&e.overflow===es.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case Zn.Top:x=u;break;case Zn.Middle:x=(p-w)/2;break;case Zn.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of c){let s;switch(e.align){case Qn.Left:s=u;break;case Qn.Center:s=f/2;break;case Qn.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=l}r&&e.overflow===es.Clip&&n.restore();const b=n.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 n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case Qn.Left:return"left";case Qn.Center:return"center";case Qn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function rs(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 is(e,t,n){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(n?n.size.x:0)||e.containerHeight!==(n?n.size.y:0)}class os{build(e){z("Text",ts);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ss(t),s=e.world,r=new Map;e.addSystemToSchedule(ve.PreUpdate,Se([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,ts));for(const e of r.keys())s.valid(e)&&s.has(e,ts)||r.delete(e);const e=s.getEntitiesWithComponents([ts]);for(const t of e){const e=s.get(t,ts),i=s.has(t,ns)?s.get(t,ns):null,o=r.get(t);if(o&&!is(o,e,i))continue;s.has(t,V)||s.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=n.renderForEntity(t,e,i),c=s.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,s.insert(t,V,c),r.set(t,rs(e,i))}}))}}const as=new os,cs=R("UIMask",{enabled:!0});function ls(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,i-s)}}function us(e,t,n,s,r,i,o,a,c,l,u){const h=e-n*r,d=e+n*(1-r),f=t-s*i,p=t+s*(1-i);function _(e,t){const n=o[0]*e+o[4]*t+o[12],s=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(n/r)+.5)*l,c+(.5*(s/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 hs(e,t){const n=t??new Float32Array(16),s=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=s*c-r*a,x=s*l-i*a,v=s*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,n[0]=(c*R-l*A+u*M)*I,n[1]=(i*A-r*R-o*M)*I,n[2]=(g*P-m*S+y*b)*I,n[3]=(f*S-d*P-p*b)*I,n[4]=(l*E-a*R-u*T)*I,n[5]=(s*R-i*E+o*T)*I,n[6]=(m*v-_*P-y*x)*I,n[7]=(h*P-f*v+p*x)*I,n[8]=(a*A-c*E+u*C)*I,n[9]=(r*E-s*A-o*C)*I,n[10]=(_*S-g*v+y*w)*I,n[11]=(d*v-h*S-p*w)*I,n[12]=(c*T-a*M-l*C)*I,n[13]=(s*M-r*T+i*C)*I,n[14]=(g*x-_*b-m*w)*I,n[15]=(h*b-d*x+f*w)*I),n}function ds(e,t,n,s,r,i,o){const a=(e-s)/i*2-1,c=(t-r)/o*2-1,l=n[0]*a+n[4]*c+n[12],u=n[1]*a+n[5]*c+n[13],h=n[3]*a+n[7]*c+n[15];return{x:l/h,y:u/h}}function fs(e,t,n,s,r,i,o,a){return e>=n-r*o&&e<=n+r*(1-o)&&t>=s-i*a&&t<=s+i*(1-a)}function ps(e,t,n,s,r,i,o){if(!e.has(t,ns)||!e.has(t,N))return null;const a=e.get(t,ns),c=e.get(t,N),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return us(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,n,s,r,i,o)}function _s(e,t){return(n,s,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([cs]);if(0!==c.length)try{!function(e,t,n,s,r,i,o,a,c){const l=new Set;for(const e of s){t.get(e,cs).enabled&&l.add(e)}const u=[];for(const e of s){if(!l.has(e))continue;let n=!0,s=e;for(;t.has(s,G);){const e=t.get(s,G);if(l.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(l.has(n)){const e=ps(t,n,r,i,o,a,c);e&&(s=ls(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=ps(t,e,r,i,o,a,c);n&&h(e,n)}}(e,t,n,c,s,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class gs{build(e){if(z("UIMask",cs),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(_s(e.wasmModule,e.world))}}const ms=new gs,ys=R("Interactable",{enabled:!0}),ws=R("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var xs;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(xs||(xs={}));const vs=R("Button",{state:xs.Normal,transition:null});class bs{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(n=>n.entity===e&&n.type===t)}}const Ss=ce(new bs,"UIEvents"),Ps=I("ScreenSpace");function Cs(e,t,n,s,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+n.x,t=u+n.y,s=.5*r.x,i=.5*r.y;d=e-s,f=t-i,p=e+s,_=t+i}else d=c+n.x,f=u+n.y,p=l+s.x,_=h+s.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function Ts(e,t,n,s,r,i){if(!e.has(t,ns))return;const o=e.get(t,ns),a=Cs(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,n);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const c=e.get(t,j);if(i?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-s,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)&&Ts(e,t,a.rect,a.centerX,a.centerY,!1)}class Es{build(e){z("UIRect",ns);const t=e.world;e.addSystemToSchedule(ve.PreUpdate,Se([le(De)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),i=t.getEntitiesWithComponents([Ps,ns,j]);for(const e of i)Ts(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const Ms=new Es,As=new Float32Array(16),Rs=new Float32Array(16);let Is=!0,Fs=1;class ks{build(e){z("Interactable",ys),z("Button",vs);const t=e.world,n=new bs;e.insertResource(Ss,n);let s=null,r=null;Fs="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(ve.PreUpdate,Se([le(Re),le(De)],(e,i)=>{n.drain();const o=t.getEntitiesWithComponents([ws]);for(const e of o){const n=t.get(e,ws);n.justPressed=!1,n.justReleased=!1}if(!i.valid)return;const a=e.mouseX*Fs,c=i.screenH-e.mouseY*Fs;!function(e){let t=!1;for(let n=0;n<16;n++)if(Rs[n]!==e[n]){t=!0;break}t&&(Rs.set(e),Is=!0)}(i.viewProjection),Is&&(hs(i.viewProjection,As),Is=!1);const l=ds(a,c,As,i.vpX,i.vpY,i.vpW,i.vpH),u=t.getEntitiesWithComponents([ys,ns,N]);let h=null,d=-1/0;for(const e of u){t.has(e,ws)||t.insert(e,ws);if(!t.get(e,ys).enabled)continue;const n=t.get(e,N),s=t.get(e,ns),r=s.size.x*n.scale.x,i=s.size.y*n.scale.y;if(fs(l.x,l.y,n.position.x,n.position.y,r,i,s.pivot.x,s.pivot.y)){let n=0;t.has(e,V)&&(n=t.get(e,V).layer),n>=d&&(d=n,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,ws)){t.get(s,ws).hovered=!1,n.emit(s,"hover_exit")}if(null!==h){t.get(h,ws).hovered=!0,n.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,ws);e.pressed=!0,e.justPressed=!0,r=h,n.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,ws)){const e=t.get(r,ws);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(ve.Update,Se([],()=>{const e=t.getEntitiesWithComponents([vs]);for(const n of e){if(t.has(n,ys)||t.insert(n,ys,{enabled:!0}),!t.has(n,ws))continue;const e=t.get(n,ws),s=t.get(n,vs),r=t.get(n,ys),i=s.state;if(r.enabled?e.pressed?s.state=xs.Pressed:e.hovered?s.state=xs.Hovered:s.state=xs.Normal:s.state=xs.Disabled,i!==s.state&&s.transition&&t.has(n,V)){const e=t.get(n,V),r=s.transition;switch(s.state){case xs.Normal:e.color={...r.normalColor};break;case xs.Hovered:e.color={...r.hoveredColor};break;case xs.Pressed:e.color={...r.pressedColor};break;case xs.Disabled:e.color={...r.disabledColor}}t.insert(n,V,e)}}},{name:"ButtonSystem"}))}}const Bs=new ks,Us=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 $s{build(e){z("TextInput",Us);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=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;function p(){if(null===o||!n.valid(o))return;const t=n.get(o,Us);if(t.readOnly)return;let s=f.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),f.value=s),s!==t.value){t.value=s;e.getResource(Ss).emit(o,"change")}t.cursorPos=f.selectionStart??s.length,t.dirty=!0,y()}function _(e){if(o===e)return;g();const t=n.get(e,Us);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),y())}function g(){if(null!==o&&n.valid(o)&&n.has(o,Us)){const e=n.get(o,Us);e.focused=!1,e.dirty=!0}o=null,f.blur()}function y(){c=!0,l=0}function x(e,o,a,l){(r.width<a||r.height<l)&&(r.width=Ds(Math.max(r.width,a)),r.height=Ds(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=zs(i,d,a-2*_);let t=_;for(const n of e)i.fillText(n,_,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,n,s;if(o.multiline){const e=zs(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,n=_+(e.length-1)*p,s=p}else t=_+i.measureText(e).width,n=(l-o.fontSize)/2,s=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,n,2,s)}i.restore();const 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=s.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,m.length,1,!0);s.set(e,v),t._free(w);const b=n.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},n.insert(e,V,b)}f.addEventListener("input",()=>{a||null===o||p()}),f.addEventListener("compositionstart",()=>{a=!0}),f.addEventListener("compositionend",()=>{a=!1,p()}),f.addEventListener("keydown",t=>{if(null===o)return;if("Escape"===t.key)return void g();const s=n.get(o,Us);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Ss).emit(o,"submit"),void g()}let r=s.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,s.cursorPos-1):"ArrowRight"===t.key?r=Math.min(s.value.length,s.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=s.value.length),r!==s.cursorPos&&(s.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,s.dirty=!0,y())}),f.addEventListener("blur",()=>{if(null!==o&&n.valid(o)&&n.has(o,Us)){const e=n.get(o,Us);e.focused=!1,e.dirty=!0}o=null}),e.addSystemToSchedule(ve.PreUpdate,Se([le(Ss)],e=>{const t=n.getEntitiesWithComponents([Us,ys]);for(const e of t){if(!n.has(e,ws))continue;if(n.get(e,ws).justPressed)return void _(e)}if(null!==o){const e=n.getEntitiesWithComponents([ys]);for(const t of e){if(n.has(t,Us))continue;if(!n.has(t,ws))continue;if(n.get(t,ws).justPressed)return void g()}}},{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&&n.valid(o)&&n.has(o,Us)))){n.get(o,Us).dirty=!0}const i=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Us)||(i.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Us,ns]);for(const e of a){const t=n.get(e,Us);if(!t.dirty)continue;const s=n.get(e,ns),r=Math.ceil(s.size.x),i=Math.ceil(s.size.y);r<=0||i<=0||(n.has(e,V)||n.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}),x(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function zs(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const i of t){const t=s+i;e.measureText(t).width>n&&s?(r.push(s),s=i):s=t}s&&r.push(s)}return r.length>0?r:[""]}function Ds(e){let t=1;for(;t<e;)t*=2;return t}const Ls=new $s,Os={r:0,g:0,b:0},Hs="__scene_transition_overlay__";async function Ws(e,t,n){const s=e.getResource($n),r=s.getActive();"fade"===n.type?await async function(e,t,n,s){const r=s.color??Os,i=s.duration/2;await js(i,0,1,r),t&&await e.unload(t);await e.load(n),await js(i,1,0,r)}(s,r,t,n):await async function(e,t,n,s){await e.loadAdditive(n);const r=s.color??Os;await js(s.duration,1,0,r),t&&await e.unload(t)}(s,r,t,n)}function js(e,t,n,s){return new Promise(r=>{const i=performance.now();En(Hs,()=>{const o=(performance.now()-i)/1e3,a=Math.min(o/e,1),c=t+(n-t)*a;Kt.setLayer(9999),Kt.setDepth(9999),Kt.rect({x:0,y:0},{x:2e4,y:2e4},{r:s.r,g:s.g,b:s.b,a:c}),a>=1&&(Mn(Hs),r())})})}async function Ns(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 Vs=ce({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Xs=ce(null,"PhysicsAPI");function Ys(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function qs(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Gs{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Vs,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Ns(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([Y]);for(const n of t){const t=e.world.get(n,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([ne,j,N]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,ne),c=o.get(r,N);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=Ys(c.rotation);s._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),Js(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===oe.Kinematic){const e=Ys(c.rotation);s._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<s;r++){const s=i+4*r,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,c=t.HEAPF32[s+2]*n,l=t.HEAPF32[s+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 n=e.world.get(t.entity,N),s=Ys(n.rotation),r=a-n.position.x,i=c-n.position.y,o=Math.cos(-s),u=Math.sin(-s);h=(r*o-i*u)/(0!==n.scale.x?n.scale.x:1),d=(r*u+i*o)/(0!==n.scale.y?n.scale.y:1),f=l-s}}u.position.x=h,u.position.y=d;const p=qs(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,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;i.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<c;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;l.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Vs,{collisionEnters:s,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Xs,Ks._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(()=>{}),e.physicsInitPromise=s}}function Js(e,t,n){const s=e.world;if(s.has(n,se)){const e=s.get(n,se);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,re)){const e=s.get(n,re);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,ie)){const e=s.get(n,ie);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Ks{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(Ks.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 Qs(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),i}function Zs(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function er(e,t,n,s){const r=e.scale.x*t*(n?-1:1),i=e.scale.y*t*(s?-1:1),o=e.scale.z,a=e.rotation.x,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,n,s,r,i,o,a,c){const l=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=Qs(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,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,n,s,r){const i={};for(const o of s.entities)for(const s of o.components){if("SpineAnimation"!==s.type||!s.data)continue;const o=s.data.skeletonPath,a=s.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const s=await r.readText(a),u="binary"===yt(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),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,u);if(t._free(h),f<0)continue;i[o]=f;const p=Zs(s),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),o=Qs(e,i,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,h,n,s)),i){new Gs("",{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,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,i;const o=yt(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await n.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${o}`:o;t=await n.readText(c),i=c.substring(0,c.lastIndexOf("/"))}else t=await n.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const c=i?`${i}/${a[1]}`:a[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(c):await n.loadPixels(c),u=Qs(e,l,!1),h=e.getResourceManager();s[r]=h.loadBitmapFont(t,u,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=qe.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=qe.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s),p=ct(e.world,n);if(c&&e.hasResource($n))for(const t of p.values())e.world.insert(t,ee,{scene:c,persistent:!1});if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,V);r&&(r.texture=n[s.data.texture]||0,e.insert(t,V,r))}}}(e.world,n,l,p),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const i=e.get(t,K);i&&(i.font=r,e.insert(t,K,i))}}}(e.world,n,d,p),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,V);n&&(n.material=r,e.insert(t,V,n))}else if("SpineAnimation"===s.type){const n=e.get(t,Q);n&&(n.material=r,e.insert(t,Q,n))}}}}(e.world,n,f,p),r&&h){const s=function(e,t,n,s){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=n[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=s.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,n,u,p);!function(e,t,n,s,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&&s.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=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(o,e),i=s.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=n._malloc(a),u=n._malloc(c),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,l,u,h,f);const p=n.HEAPU32[h>>2],_=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,l,8*r),m=new Uint16Array(n.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),n._free(l),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,r,h,s)}if(a){const t=e.getResource(Rt);t&&t.setAddressableManifest(a)}}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,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&("binary"===yt(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of s){const t=yt(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||i.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}i.length>0&&await Promise.all(i)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const sr="__preview__";class rr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource($n);t.register({name:sr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(sr),this.loadPromise_=t.load(sr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new nr(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.spineInitPromise;if(r){s=(await r).controller.raw}await tr(this.app_,this.app_.wasmModule,t,n,s)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([X]);for(const s of n){if(e.get(s,X).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([Y]);for(const r of s){const s=e.get(r,Y);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=this.app_.getResource($n).getScene(sr),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:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:H.ColorAndDepth};e.insert(i,X,a)}}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.eventSource_.addEventListener("message",async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())}),this.eventSource_.addEventListener("error",e=>{console.error("[PreviewPlugin] EventSource error:",e)})}async reloadScene(){if(this.app_)try{const e=this.app_.getResource($n);await e.switchTo(sr),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 ir={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=vn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:vn.getTargetTexture(n),width:e.width,height:e.height}},release(e){vn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(vn.releaseRenderTarget(e._handle),ir.create({width:t,height:n,depth:!0})),begin(e,t){vn.begin(t,e._handle)},end(){vn.end()},getDepthTexture:e=>vn.getTargetDepthTexture(e._handle)};let or=!1;function ar(e){or=e}function cr(){return or}function lr(){return!or}var ur;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(ur||(ur={}));class hr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${ur[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case ur.Debug:console.debug(t,n);break;case ur.Info:console.log(t,n);break;case ur.Warn:console.warn(t,n);break;case ur.Error:console.error(t,n)}}}class dr{constructor(){this.handlers_=[],this.minLevel_=ur.Info,this.addHandler(new hr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(ur.Debug,e,t,n)}info(e,t,n){this.log(ur.Info,e,t,n)}warn(e,t,n){this.log(ur.Warn,e,t,n)}error(e,t,n){this.log(ur.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const fr=new dr;function pr(){return fr}function _r(e){fr.setMinLevel(e)}function gr(e,t,n){fr.debug(e,t,n)}function mr(e,t,n){fr.info(e,t,n)}function yr(e,t,n){fr.warn(e,t,n)}function wr(e,t,n){fr.error(e,t,n)}const xr=[as,ms,Ms,Bs,Ls];function vr(e,t){return function(e,t){const n=Ln.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Yt(e),Ve(e),on(e),hn(e),wn(e),Sn(e);const r=new Rn;n.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=jn(e,s,t,r));const o=n.getResource(De);if(i.length>0){const e=i[0],n=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(n.x*t),o.vpY=Math.round((1-n.y-n.h)*r),o.vpW=Math.round(n.w*t),o.vpH=Math.round(n.h*r),o.screenW=t,o.screenH=r,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}n.insertResource(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(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;vn.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-i)/1e3;let h;if(vn.resize(t,c),pn.isInitialized()&&pn.getPassCount()>0&&!pn.isBypassed()&&pn.resize(t,c),n.hasResource($n)){const e=n.getResource($n).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=jn(e,s,t,c,n.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:s},viewProjection:Hn,width:t,height:c,elapsed:u});else{for(const e of f){const n=e.viewportRect,i=Math.round(n.x*t),o=Math.round((1-n.y-n.h)*c),a=Math.round(n.w*t),l=Math.round(n.h*c);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:l},clearFlags:e.clearFlags,elapsed:u})}vn.setViewport(0,0,t,c)}}};if(n.addSystemToSchedule(ve.First,c),n.addSystemToSchedule(ve.Last,l),n.addPlugin(Ft),n.addPlugin(Ht),n.addPlugin(Fe),n.addPlugin(Dn),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:xr,...t})}e=f;export{Ln as App,It as AssetPlugin,kt as AssetRefCounter,At as AssetServer,Rt as Assets,st as AsyncCache,K as BitmapText,Le as BlendMode,oe as BodyType,se as BoxCollider,vs as Button,xs 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,en as DataType,Kt as Draw,we as EntityCommands,Cn as GLDebug,ln as Geometry,y as INVALID_ENTITY,x as INVALID_FONT,w as INVALID_TEXTURE,Re as Input,Ie as InputPlugin,Ae as InputState,ys as Interactable,j as LocalTransform,ur as LogLevel,dr as Logger,qe as Material,rt as MaterialLoader,pe as Mut,Z as Name,G as Parent,Ks as Physics,Vs as PhysicsEvents,Gs as PhysicsPlugin,pn as PostProcess,Dt as PrefabServer,Lt as Prefabs,Ot as PrefabsPlugin,rr as PreviewPlugin,O as ProjectionType,ge as Query,me as QueryInstance,Rn as RenderPipeline,gn as RenderStage,ir as RenderTexture,vn as Renderer,le as Res,ue as ResMut,ne as RigidBody,W as ScaleMode,$n as SceneManager,Un as SceneManagerState,ee as SceneOwner,ve as Schedule,Ps as ScreenSpace,nt as ShaderSources,Q as SpineAnimation,V as Sprite,Me as SystemRunner,ts as Text,Qn as TextAlign,Us as TextInput,$s as TextInputPlugin,es as TextOverflow,os as TextPlugin,ss as TextRenderer,Zn as TextVerticalAlign,fe as Time,De as UICameraInfo,bs as UIEventQueue,Ss as UIEvents,ws as UIInteraction,ks as UIInteractionPlugin,Es as UILayoutPlugin,cs as UIMask,gs as UIMaskPlugin,ns as UIRect,q as Velocity,nr as WebAssetProvider,ze as World,N as WorldTransform,Te as addStartupSystem,Ce as addSystem,Ee as addSystemToSchedule,Ft as assetPlugin,An as clearDrawCallbacks,k as clearUserComponents,P as color,Cs as computeUIRectLayout,_s as createMaskProcessor,vr as createWebApp,gr as debug,R as defineComponent,ce as defineResource,Se as defineSystem,I as defineTag,wr as error,dt as findEntityByName,On as flushPendingSystems,xt as getAddressableType,vt as getAddressableTypeByEditorType,St as getAllAssetExtensions,Et as getAssetMimeType,yt as getAssetTypeEntry,D as getComponent,at as getComponentAssetFields,te as getComponentDefaults,Ct as getCustomExtensions,wt as getEditorType,pr as getLogger,t as getPlatform,s as getPlatformType,F as getUserComponent,Tt as getWeChatPackOptions,mr as info,Yt as initDrawAPI,Sn as initGLDebugAPI,on as initGeometryAPI,Ve as initMaterialAPI,hn as initPostProcessAPI,wn as initRendererAPI,Fe as inputPlugin,Ut as instantiatePrefab,ls as intersectRects,hs as invertMatrix4,U as isBuiltinComponent,Mt as isCustomExtension,cr as isEditor,bt as isKnownAssetExtension,n as isPlatformInitialized,lr as isRuntime,Oe as isTextureRef,r as isWeChat,i as isWeb,ut as loadComponent,Ns as loadPhysicsModule,tr as loadRuntimeScene,ct as loadSceneData,lt as loadSceneWithAssets,Pt as looksLikeAssetPath,o as platformFetch,l as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,fs as pointInWorldRect,Ht as prefabsPlugin,C as quat,z as registerComponent,ot as registerComponentAssetFields,En as registerDrawCallback,Bt as registerEmbeddedAssets,tt as registerMaterialCallback,Dn as sceneManagerPlugin,ds as screenToWorld,ar as setEditorMode,_r as setLogLevel,qt as shutdownDrawAPI,Pn as shutdownGLDebugAPI,an as shutdownGeometryAPI,Xe as shutdownMaterialAPI,dn as shutdownPostProcessAPI,xn as shutdownRendererAPI,Ls as textInputPlugin,as as textPlugin,Ws as transitionTo,Bs as uiInteractionPlugin,Ms as uiLayoutPlugin,ms as uiMaskPlugin,xr as uiPlugins,Mn as unregisterDrawCallback,ht as updateCameraAspectRatio,v as vec2,b as vec3,S as vec4,yr as warn,us as worldRectToScreen,zn as wrapSceneSystem};//# sourceMappingURL=index.js.mapdiff --git a/desktop/public/sdk/esm/physics/index.d.ts b/desktop/public/sdk/esm/physics/index.d.tsindex d2139d60a..9c6f07502 100644--- a/desktop/public/sdk/esm/physics/index.d.ts+++ b/desktop/public/sdk/esm/physics/index.d.ts@@ -584,15 +584,88 @@ declare class RenderPipeline {private maskProcessor_;private lastWidth_;private lastHeight_;+ private activeScenes_;get spineRenderer(): SpineRendererFn | null;setSpineRenderer(fn: SpineRendererFn | null): void;get maskProcessor(): MaskProcessorFn | null;setMaskProcessor(fn: MaskProcessorFn | null): void;+ setActiveScenes(scenes: Set<string> | null): void;render(params: RenderParams): void;renderCamera(params: CameraRenderParams): void;private executeDrawCallbacks;}+/**+ * @file material.ts+ * @brief Material and Shader API for custom rendering+ * @details Provides shader creation and material management for custom visual effects.+ */++type ShaderHandle = number;++/**+ * @file scene.ts+ * @brief Scene loading utilities+ */++interface SceneEntityData {+ id: number;+ name: string;+ parent: number | null;+ children: number[];+ components: SceneComponentData[];+ visible?: boolean;+}+interface SceneComponentData {+ type: string;+ data: Record<string, unknown>;+}+interface SliceBorder {+ left: number;+ right: number;+ top: number;+ bottom: number;+}+interface TextureMetadata {+ version: string;+ type: 'texture';+ sliceBorder: SliceBorder;+}+interface SceneData {+ version: string;+ name: string;+ entities: SceneEntityData[];+ textureMetadata?: Record<string, TextureMetadata>;+}++/**+ * @file customDraw.ts+ * @brief Custom draw callback registration for the render pipeline+ */+type DrawCallback = (elapsed: number) => void;++interface SceneConfig {+ name: string;+ path?: string;+ data?: SceneData;+ systems?: Array<{+ schedule: Schedule;+ system: SystemDef;+ }>;+ setup?: (ctx: SceneContext) => void | Promise<void>;+ cleanup?: (ctx: SceneContext) => void;+}+interface SceneContext {+ readonly name: string;+ readonly entities: ReadonlySet<Entity>;+ spawn(): Entity;+ despawn(entity: Entity): void;+ registerDrawCallback(id: string, fn: DrawCallback): void;+ addPostProcessPass(name: string, shader: ShaderHandle): number;+ removePostProcessPass(name: string): void;+ setPersistent(entity: Entity, persistent: boolean): void;+}+/*** @file app.ts* @brief Application builder and web platform integration@@ -644,6 +717,8 @@ declare class App {insertResource<T>(resource: ResourceDef<T>, value: T): this;getResource<T>(resource: ResourceDef<T>): T;hasResource<T>(resource: ResourceDef<T>): boolean;+ registerScene(config: SceneConfig): this;+ setInitialScene(name: string): this;run(): void;private mainLoop;quit(): void;diff --git a/desktop/public/sdk/esm/physics/index.js b/desktop/public/sdk/esm/physics/index.jsindex c080d4387..d30f2ab31 100644--- a/desktop/public/sdk/esm/physics/index.js+++ b/desktop/public/sdk/esm/physics/index.js@@ -1,2 +1,2 @@-const e=new Map;function t(t,s){const i={_id:Symbol(`Builtin_${t}`),_name:t,_cppName:t,_builtin:!0,_default:s};return e.set(t,i),i}const s=t("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),i=t("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});t("Sprite",{texture:4294967295,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}),t("Camera",{projectionType:1,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:3});const n=t("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}});t("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}});const o=t("Parent",{entity:0});t("Children",{entities:[]}),t("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295}),t("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});const r={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};var a,l;a="Name",l=r,e.set(a,l);let c=0;function u(e,t){const s=++c;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}const y=u({delta:0,elapsed:0,frameCount:0},"Time");var p;!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"}(p||(p={}));let _=0;async function m(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()}async function d(e,t){await t.loadDynamicLibrary(new Uint8Array(e),{loadAsync:!0,allowUndefined:!0});const s=t.cwrap.bind(t);return{_physics_init:s("physics_init",null,["number","number","number","number"]),_physics_shutdown:s("physics_shutdown",null,[]),_physics_createBody:s("physics_createBody",null,["number","number","number","number","number","number","number","number","number","number"]),_physics_destroyBody:s("physics_destroyBody",null,["number"]),_physics_hasBody:s("physics_hasBody","number",["number"]),_physics_addBoxShape:s("physics_addBoxShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_addCircleShape:s("physics_addCircleShape",null,["number","number","number","number","number","number","number","number"]),_physics_addCapsuleShape:s("physics_addCapsuleShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_step:s("physics_step",null,["number"]),_physics_setBodyTransform:s("physics_setBodyTransform",null,["number","number","number","number"]),_physics_getDynamicBodyCount:s("physics_getDynamicBodyCount","number",[]),_physics_getDynamicBodyTransforms:s("physics_getDynamicBodyTransforms","number",[]),_physics_collectEvents:s("physics_collectEvents",null,[]),_physics_getCollisionEnterCount:s("physics_getCollisionEnterCount","number",[]),_physics_getCollisionEnterBuffer:s("physics_getCollisionEnterBuffer","number",[]),_physics_getCollisionExitCount:s("physics_getCollisionExitCount","number",[]),_physics_getCollisionExitBuffer:s("physics_getCollisionExitBuffer","number",[]),_physics_getSensorEnterCount:s("physics_getSensorEnterCount","number",[]),_physics_getSensorEnterBuffer:s("physics_getSensorEnterBuffer","number",[]),_physics_getSensorExitCount:s("physics_getSensorExitCount","number",[]),_physics_getSensorExitBuffer:s("physics_getSensorExitBuffer","number",[]),_physics_applyForce:s("physics_applyForce",null,["number","number","number"]),_physics_applyImpulse:s("physics_applyImpulse",null,["number","number","number"]),_physics_setLinearVelocity:s("physics_setLinearVelocity",null,["number","number","number"]),_physics_getLinearVelocity:s("physics_getLinearVelocity","number",["number"]),_physics_setGravity:s("physics_setGravity",null,["number","number"]),_physics_getGravity:s("physics_getGravity","number",[]),_physics_setAngularVelocity:s("physics_setAngularVelocity",null,["number","number"]),_physics_getAngularVelocity:s("physics_getAngularVelocity","number",["number"]),_physics_applyTorque:s("physics_applyTorque",null,["number","number"]),_physics_applyAngularImpulse:s("physics_applyAngularImpulse",null,["number","number"]),_physics_updateBodyProperties:s("physics_updateBodyProperties",null,["number","number","number","number","number","number","number"]),get HEAPF32(){return t.HEAPF32},get HEAPU8(){return t.HEAPU8},get HEAPU32(){return t.HEAPU32},_malloc:t._malloc.bind(t),_free:t._free.bind(t)}}const h=t("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),f=t("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),g=t("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),b=t("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),x={Static:0,Kinematic:1,Dynamic:2},E=u({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),S=u(null,"PhysicsAPI");function P(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function C(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class v{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(E,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,r=new Map,a=m(this.wasmUrl_,this.factory_).then(a=>{a._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const l=function(e){const t=e.world.getEntitiesWithComponents([n]);for(const s of t){const t=e.world.get(s,n);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),c=1/l,u=e.world;var m;e.addSystemToSchedule(p.PostUpdate,function(e,t,s){const i=++_;return{_id:Symbol(`System_${i}_${s?.name}`),_params:e,_fn:t,_name:s?.name??`System_${i}`}}([(m=y,{_type:"res",_resource:m})],n=>{const y=u.getEntitiesWithComponents([h,s,i]),p=new Set;for(const s of y){p.add(s);const n=u.get(s,h),o=u.get(s,i);if(t.has(s)){const e=r.get(s);!e||e.bodyType===n.bodyType&&e.gravityScale===n.gravityScale&&e.linearDamping===n.linearDamping&&e.angularDamping===n.angularDamping&&e.fixedRotation===n.fixedRotation&&e.bullet===n.bullet||(a._physics_updateBodyProperties(s,n.bodyType,n.gravityScale,n.linearDamping,n.angularDamping,n.fixedRotation?1:0,n.bullet?1:0),e.bodyType=n.bodyType,e.gravityScale=n.gravityScale,e.linearDamping=n.linearDamping,e.angularDamping=n.angularDamping,e.fixedRotation=n.fixedRotation,e.bullet=n.bullet)}else{if(!n.enabled)continue;const i=P(o.rotation);a._physics_createBody(s,n.bodyType,o.position.x*c,o.position.y*c,i,n.gravityScale,n.linearDamping,n.angularDamping,n.fixedRotation?1:0,n.bullet?1:0),A(e,a,s),t.add(s),r.set(s,{bodyType:n.bodyType,gravityScale:n.gravityScale,linearDamping:n.linearDamping,angularDamping:n.angularDamping,fixedRotation:n.fixedRotation,bullet:n.bullet})}if(n.bodyType===x.Kinematic){const e=P(o.rotation);a._physics_setBodyTransform(s,o.position.x*c,o.position.y*c,e)}}for(const e of t)p.has(e)||(a._physics_destroyBody(e),t.delete(e),r.delete(e));a._physics_step(n.delta),function(e,t,n){const r=t._physics_getDynamicBodyCount();if(0===r)return;const a=t._physics_getDynamicBodyTransforms(),l=a>>2;for(let a=0;a<r;a++){const r=l+4*a,c=t.HEAPU32[r],u=t.HEAPF32[r+1]*n,y=t.HEAPF32[r+2]*n,p=t.HEAPF32[r+3];if(!e.world.valid(c))continue;const _=e.world.get(c,s);if(!_)continue;let m=u,d=y,h=p;if(e.world.has(c,o)){const t=e.world.get(c,o);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,i)){const s=e.world.get(t.entity,i),n=P(s.rotation),o=u-s.position.x,r=y-s.position.y,a=Math.cos(-n),l=Math.sin(-n);m=(o*a-r*l)/(0!==s.scale.x?s.scale.x:1),d=(o*l+r*a)/(0!==s.scale.y?s.scale.y:1),h=p-n}}_.position.x=m,_.position.y=d;const f=C(h);_.rotation.w=f.w,_.rotation.x=f.x,_.rotation.y=f.y,_.rotation.z=f.z,e.world.insert(c,s,_)}}(e,a,l),function(e,t,s){t._physics_collectEvents();const i=[],n=t._physics_getCollisionEnterCount();if(n>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<n;o++){const n=e+6*o;i.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1],normalX:t.HEAPF32[n+2],normalY:t.HEAPF32[n+3],contactX:t.HEAPF32[n+4]*s,contactY:t.HEAPF32[n+5]*s})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<r;s++){const i=e+2*s;o.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const i=e+2*s;a.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const i=e+2*s;c.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}e.insertResource(E,{collisionEnters:i,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,a,l)},{name:"PhysicsSystem"})),e.physicsModule=a,e.insertResource(S,B._fromModule(a)),e.setFixedTimestep(this.config_.fixedTimestep)});a.catch(()=>{}),e.physicsInitPromise=a}}function A(e,t,s){const i=e.world;if(i.has(s,f)){const e=i.get(s,f);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(i.has(s,g)){const e=i.get(s,g);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(i.has(s,b)){const e=i.get(s,b);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 B{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(B.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)}}export{x as BodyType,f as BoxCollider,b as CapsuleCollider,g as CircleCollider,B as Physics,S as PhysicsAPI,E as PhysicsEvents,v as PhysicsPlugin,h as RigidBody,m as loadPhysicsModule,d as loadPhysicsSideModule};+function e(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(e);const n={};for(const i in t)n[i]=e(t[i]);return n}let t=0;const n=new Map;function i(e,t){const i={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return n.set(e,i),i}const s=i("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),o=i("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});i("Sprite",{texture:4294967295,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}),i("Camera",{projectionType:1,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:3});const r=i("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}});i("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}});const a=i("Parent",{entity:0});i("Children",{entities:[]}),i("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295}),i("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});const l={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};var c,u;!function(n,i){const s="undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map),o=s.get(n);if(o)return o;const r=function(n,i){const s=++t;return{_id:Symbol(`Component_${s}_${n}`),_name:n,_default:i,_builtin:!1,create:t=>t?{...e(i),...t}:e(i)}}(n,i);s.set(n,r),function(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}(n,i,!1)}("SceneOwner",{scene:"",persistent:!1}),c="Name",u=l,n.set(c,u);let y=0;function p(e,t){const n=++y;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}const _=p({delta:0,elapsed:0,frameCount:0},"Time");var m;!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"}(m||(m={}));let d=0;async function h(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()}async function f(e,t){await t.loadDynamicLibrary(new Uint8Array(e),{loadAsync:!0,allowUndefined:!0});const n=t.cwrap.bind(t);return{_physics_init:n("physics_init",null,["number","number","number","number"]),_physics_shutdown:n("physics_shutdown",null,[]),_physics_createBody:n("physics_createBody",null,["number","number","number","number","number","number","number","number","number","number"]),_physics_destroyBody:n("physics_destroyBody",null,["number"]),_physics_hasBody:n("physics_hasBody","number",["number"]),_physics_addBoxShape:n("physics_addBoxShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_addCircleShape:n("physics_addCircleShape",null,["number","number","number","number","number","number","number","number"]),_physics_addCapsuleShape:n("physics_addCapsuleShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_step:n("physics_step",null,["number"]),_physics_setBodyTransform:n("physics_setBodyTransform",null,["number","number","number","number"]),_physics_getDynamicBodyCount:n("physics_getDynamicBodyCount","number",[]),_physics_getDynamicBodyTransforms:n("physics_getDynamicBodyTransforms","number",[]),_physics_collectEvents:n("physics_collectEvents",null,[]),_physics_getCollisionEnterCount:n("physics_getCollisionEnterCount","number",[]),_physics_getCollisionEnterBuffer:n("physics_getCollisionEnterBuffer","number",[]),_physics_getCollisionExitCount:n("physics_getCollisionExitCount","number",[]),_physics_getCollisionExitBuffer:n("physics_getCollisionExitBuffer","number",[]),_physics_getSensorEnterCount:n("physics_getSensorEnterCount","number",[]),_physics_getSensorEnterBuffer:n("physics_getSensorEnterBuffer","number",[]),_physics_getSensorExitCount:n("physics_getSensorExitCount","number",[]),_physics_getSensorExitBuffer:n("physics_getSensorExitBuffer","number",[]),_physics_applyForce:n("physics_applyForce",null,["number","number","number"]),_physics_applyImpulse:n("physics_applyImpulse",null,["number","number","number"]),_physics_setLinearVelocity:n("physics_setLinearVelocity",null,["number","number","number"]),_physics_getLinearVelocity:n("physics_getLinearVelocity","number",["number"]),_physics_setGravity:n("physics_setGravity",null,["number","number"]),_physics_getGravity:n("physics_getGravity","number",[]),_physics_setAngularVelocity:n("physics_setAngularVelocity",null,["number","number"]),_physics_getAngularVelocity:n("physics_getAngularVelocity","number",["number"]),_physics_applyTorque:n("physics_applyTorque",null,["number","number"]),_physics_applyAngularImpulse:n("physics_applyAngularImpulse",null,["number","number"]),_physics_updateBodyProperties:n("physics_updateBodyProperties",null,["number","number","number","number","number","number","number"]),get HEAPF32(){return t.HEAPF32},get HEAPU8(){return t.HEAPU8},get HEAPU32(){return t.HEAPU32},_malloc:t._malloc.bind(t),_free:t._free.bind(t)}}const g=i("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),b=i("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),x=i("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),E=i("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),S={Static:0,Kinematic:1,Dynamic:2},P=p({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),w=p(null,"PhysicsAPI");function C(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function A(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class v{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(P,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,i=h(this.wasmUrl_,this.factory_).then(i=>{i._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const l=function(e){const t=e.world.getEntitiesWithComponents([r]);for(const n of t){const t=e.world.get(n,r);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),c=1/l,u=e.world;var y;e.addSystemToSchedule(m.PostUpdate,function(e,t,n){const i=++d;return{_id:Symbol(`System_${i}_${n?.name}`),_params:e,_fn:t,_name:n?.name??`System_${i}`}}([(y=_,{_type:"res",_resource:y})],r=>{const y=u.getEntitiesWithComponents([g,s,o]),p=new Set;for(const s of y){p.add(s);const r=u.get(s,g),a=u.get(s,o);if(t.has(s)){const e=n.get(s);!e||e.bodyType===r.bodyType&&e.gravityScale===r.gravityScale&&e.linearDamping===r.linearDamping&&e.angularDamping===r.angularDamping&&e.fixedRotation===r.fixedRotation&&e.bullet===r.bullet||(i._physics_updateBodyProperties(s,r.bodyType,r.gravityScale,r.linearDamping,r.angularDamping,r.fixedRotation?1:0,r.bullet?1:0),e.bodyType=r.bodyType,e.gravityScale=r.gravityScale,e.linearDamping=r.linearDamping,e.angularDamping=r.angularDamping,e.fixedRotation=r.fixedRotation,e.bullet=r.bullet)}else{if(!r.enabled)continue;const o=C(a.rotation);i._physics_createBody(s,r.bodyType,a.position.x*c,a.position.y*c,o,r.gravityScale,r.linearDamping,r.angularDamping,r.fixedRotation?1:0,r.bullet?1:0),B(e,i,s),t.add(s),n.set(s,{bodyType:r.bodyType,gravityScale:r.gravityScale,linearDamping:r.linearDamping,angularDamping:r.angularDamping,fixedRotation:r.fixedRotation,bullet:r.bullet})}if(r.bodyType===S.Kinematic){const e=C(a.rotation);i._physics_setBodyTransform(s,a.position.x*c,a.position.y*c,e)}}for(const e of t)p.has(e)||(i._physics_destroyBody(e),t.delete(e),n.delete(e));i._physics_step(r.delta),function(e,t,n){const i=t._physics_getDynamicBodyCount();if(0===i)return;const r=t._physics_getDynamicBodyTransforms(),l=r>>2;for(let r=0;r<i;r++){const i=l+4*r,c=t.HEAPU32[i],u=t.HEAPF32[i+1]*n,y=t.HEAPF32[i+2]*n,p=t.HEAPF32[i+3];if(!e.world.valid(c))continue;const _=e.world.get(c,s);if(!_)continue;let m=u,d=y,h=p;if(e.world.has(c,a)){const t=e.world.get(c,a);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,o)){const n=e.world.get(t.entity,o),i=C(n.rotation),s=u-n.position.x,r=y-n.position.y,a=Math.cos(-i),l=Math.sin(-i);m=(s*a-r*l)/(0!==n.scale.x?n.scale.x:1),d=(s*l+r*a)/(0!==n.scale.y?n.scale.y:1),h=p-i}}_.position.x=m,_.position.y=d;const f=A(h);_.rotation.w=f.w,_.rotation.x=f.x,_.rotation.y=f.y,_.rotation.z=f.z,e.world.insert(c,s,_)}}(e,i,l),function(e,t,n){t._physics_collectEvents();const i=[],s=t._physics_getCollisionEnterCount();if(s>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<s;o++){const s=e+6*o;i.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1],normalX:t.HEAPF32[s+2],normalY:t.HEAPF32[s+3],contactX:t.HEAPF32[s+4]*n,contactY:t.HEAPF32[s+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const i=e+2*n;o.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const i=e+2*n;a.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const i=e+2*n;c.push({sensorEntity:t.HEAPU32[i],visitorEntity:t.HEAPU32[i+1]})}}e.insertResource(P,{collisionEnters:i,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,i,l)},{name:"PhysicsSystem"})),e.physicsModule=i,e.insertResource(w,U._fromModule(i)),e.setFixedTimestep(this.config_.fixedTimestep)});i.catch(()=>{}),e.physicsInitPromise=i}}function B(e,t,n){const i=e.world;if(i.has(n,b)){const e=i.get(n,b);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(i.has(n,x)){const e=i.get(n,x);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(i.has(n,E)){const e=i.get(n,E);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class U{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(U.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)}}export{S as BodyType,b as BoxCollider,E as CapsuleCollider,x as CircleCollider,U as Physics,w as PhysicsAPI,P as PhysicsEvents,v as PhysicsPlugin,g as RigidBody,h as loadPhysicsModule,f as loadPhysicsSideModule};//# sourceMappingURL=index.js.mapdiff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.tsindex 111692d2d..d7a01eb0f 100644--- a/desktop/public/sdk/esm/spine/index.d.ts+++ b/desktop/public/sdk/esm/spine/index.d.ts@@ -539,73 +539,24 @@ declare class RenderPipeline {private maskProcessor_;private lastWidth_;private lastHeight_;+ private activeScenes_;get spineRenderer(): SpineRendererFn | null;setSpineRenderer(fn: SpineRendererFn | null): void;get maskProcessor(): MaskProcessorFn | null;setMaskProcessor(fn: MaskProcessorFn | null): void;+ setActiveScenes(scenes: Set<string> | null): void;render(params: RenderParams): void;renderCamera(params: CameraRenderParams): void;private executeDrawCallbacks;}/**- * @file app.ts- * @brief Application builder and web platform integration+ * @file material.ts+ * @brief Material and Shader API for custom rendering+ * @details Provides shader creation and material management for custom visual effects.*/-interface Plugin {- name?: string;- dependencies?: ResourceDef<any>[];- build(app: App): void;-}-declare class App {- private readonly world_;- private readonly resources_;- private readonly systems_;- private runner_;- private running_;- private lastTime_;- private fixedTimestep_;- private fixedAccumulator_;- private module_;- private pipeline_;- private spineInitPromise_?;- private physicsInitPromise_?;- private physicsModule_?;- private readonly installed_plugins_;- private error_handler_;- private constructor();- static new(): App;- addPlugin(plugin: Plugin): this;- addSystemToSchedule(schedule: Schedule, system: SystemDef, options?: {- runBefore?: string[];- runAfter?: string[];- }): this;- addSystem(system: SystemDef): this;- addStartupSystem(system: SystemDef): this;- connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;- get wasmModule(): ESEngineModule | null;- get pipeline(): RenderPipeline | null;- setSpineRenderer(fn: SpineRendererFn | null): void;- get spineInitPromise(): Promise<unknown> | undefined;- set spineInitPromise(p: Promise<unknown> | undefined);- get physicsInitPromise(): Promise<unknown> | undefined;- set physicsInitPromise(p: Promise<unknown> | undefined);- get physicsModule(): unknown;- set physicsModule(m: unknown);- get world(): World;- setFixedTimestep(timestep: number): this;- onError(handler: (error: unknown, systemName: string) => void): this;- insertResource<T>(resource: ResourceDef<T>, value: T): this;- getResource<T>(resource: ResourceDef<T>): T;- hasResource<T>(resource: ResourceDef<T>): boolean;- run(): void;- private mainLoop;- quit(): void;- private sortSystems;- private runSchedule;- private updateTime;-}+type ShaderHandle = number;/*** @file SpineModuleLoader.ts@@ -727,6 +678,130 @@ declare class SpineModuleController {removeAllListeners(entity: Entity): void;}+/**+ * @file scene.ts+ * @brief Scene loading utilities+ */++interface SceneEntityData {+ id: number;+ name: string;+ parent: number | null;+ children: number[];+ components: SceneComponentData[];+ visible?: boolean;+}+interface SceneComponentData {+ type: string;+ data: Record<string, unknown>;+}+interface SliceBorder {+ left: number;+ right: number;+ top: number;+ bottom: number;+}+interface TextureMetadata {+ version: string;+ type: 'texture';+ sliceBorder: SliceBorder;+}+interface SceneData {+ version: string;+ name: string;+ entities: SceneEntityData[];+ textureMetadata?: Record<string, TextureMetadata>;+}++/**+ * @file customDraw.ts+ * @brief Custom draw callback registration for the render pipeline+ */+type DrawCallback = (elapsed: number) => void;++interface SceneConfig {+ name: string;+ path?: string;+ data?: SceneData;+ systems?: Array<{+ schedule: Schedule;+ system: SystemDef;+ }>;+ setup?: (ctx: SceneContext) => void | Promise<void>;+ cleanup?: (ctx: SceneContext) => void;+}+interface SceneContext {+ readonly name: string;+ readonly entities: ReadonlySet<Entity>;+ spawn(): Entity;+ despawn(entity: Entity): void;+ registerDrawCallback(id: string, fn: DrawCallback): void;+ addPostProcessPass(name: string, shader: ShaderHandle): number;+ removePostProcessPass(name: string): void;+ setPersistent(entity: Entity, persistent: boolean): void;+}++/**+ * @file app.ts+ * @brief Application builder and web platform integration+ */++interface Plugin {+ name?: string;+ dependencies?: ResourceDef<any>[];+ build(app: App): void;+}+declare class App {+ private readonly world_;+ private readonly resources_;+ private readonly systems_;+ private runner_;+ private running_;+ private lastTime_;+ private fixedTimestep_;+ private fixedAccumulator_;+ private module_;+ private pipeline_;+ private spineInitPromise_?;+ private physicsInitPromise_?;+ private physicsModule_?;+ private readonly installed_plugins_;+ private error_handler_;+ private constructor();+ static new(): App;+ addPlugin(plugin: Plugin): this;+ addSystemToSchedule(schedule: Schedule, system: SystemDef, options?: {+ runBefore?: string[];+ runAfter?: string[];+ }): this;+ addSystem(system: SystemDef): this;+ addStartupSystem(system: SystemDef): this;+ connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;+ get wasmModule(): ESEngineModule | null;+ get pipeline(): RenderPipeline | null;+ setSpineRenderer(fn: SpineRendererFn | null): void;+ get spineInitPromise(): Promise<unknown> | undefined;+ set spineInitPromise(p: Promise<unknown> | undefined);+ get physicsInitPromise(): Promise<unknown> | undefined;+ set physicsInitPromise(p: Promise<unknown> | undefined);+ get physicsModule(): unknown;+ set physicsModule(m: unknown);+ get world(): World;+ setFixedTimestep(timestep: number): this;+ onError(handler: (error: unknown, systemName: string) => void): this;+ insertResource<T>(resource: ResourceDef<T>, value: T): this;+ getResource<T>(resource: ResourceDef<T>): T;+ hasResource<T>(resource: ResourceDef<T>): boolean;+ registerScene(config: SceneConfig): this;+ setInitialScene(name: string): this;+ run(): void;+ private mainLoop;+ quit(): void;+ private sortSystems;+ private runSchedule;+ private updateTime;+}+declare const SpineResource: ResourceDef<SpineModuleController | null>;declare class SpinePlugin implements Plugin {private wasmUrl_;diff --git a/desktop/public/sdk/esm/spine/index.js b/desktop/public/sdk/esm/spine/index.jsindex 496a662ef..cd9501b4f 100644--- a/desktop/public/sdk/esm/spine/index.js+++ b/desktop/public/sdk/esm/spine/index.js@@ -1,2 +1,2 @@-let e=0;function t(t,n){const a=++e;return{_id:Symbol(`Resource_${a}_${n??""}`),_name:n??`Resource_${a}`,_default:t}}t({delta:0,elapsed:0,frameCount:0},"Time");const n=new Map;function a(e,t){const a={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return n.set(e,a),a}a("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});const r=a("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});a("Sprite",{texture:4294967295,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}),a("Camera",{projectionType:1,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:3}),a("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),a("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),a("Parent",{entity:0}),a("Children",{entities:[]}),a("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295});const s=a("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}),i={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};var o,l,u;o="Name",l=i,n.set(o,l),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"}(u||(u={}));const c=t(null,"Assets");function p(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"])}}async function h(e,t){if(!t)throw new Error("SpineModuleLoader: factory parameter is required. Pass the Spine WASM factory function explicitly via loadSpineModule(url, factory).");const n=await t();return{raw:n,api:p(n)}}class m{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let a,r;if("string"==typeof e){const t=(new TextEncoder).encode(e);r=t.length,a=this.raw_._malloc(r+1),this.raw_.HEAPU8.set(t,a),this.raw_.HEAPU8[a+r]=0}else r=e.length,a=this.raw_._malloc(r),this.raw_.HEAPU8.set(e,a);const s=this.api_.loadSkeleton(a,r,t,t.length,n);return this.raw_._free(a),s}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,a,r){this.api_.setAtlasPageTexture(e,t,n,a,r)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,a=0){return!!this.api_.playAnimation(e,t,n,a)}addAnimation(e,t,n=!0,a=0,r=0){return!!this.api_.addAnimation(e,t,n,a,r)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch{return[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch{return[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),a=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,a))return this.raw_._free(n),this.raw_._free(a),null;const r=this.raw_.HEAPF32[n>>2],s=this.raw_.HEAPF32[a>>2];return this.raw_._free(n),this.raw_._free(a),{x:r,y:s}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,a=t>>2,r={x:n[a],y:n[a+1],width:n[a+2],height:n[a+3]};return this.raw_._free(t),r}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],a=this.raw_._malloc(8),r=a,s=a+4;for(let a=0;a<t;a++){const t=this.api_.getMeshBatchVertexCount(e,a),i=this.api_.getMeshBatchIndexCount(e,a);if(t<=0||i<=0)continue;const o=8*t*4,l=2*i,u=this.raw_._malloc(o),c=this.raw_._malloc(l);this.api_.getMeshBatchData(e,a,u,c,r,s);const p=new Float32Array(this.raw_.HEAPF32.buffer,u,8*t),h=new Uint16Array(this.raw_.HEAPU8.buffer,c,i);n.push({vertices:new Float32Array(p),indices:new Uint16Array(h),textureId:this.raw_.HEAPU32[r>>2],blendMode:this.raw_.HEAPU32[s>>2]}),this.raw_._free(u),this.raw_._free(c)}return this.raw_._free(a),n}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const a=this.listeners_.get(e);a.has(t)||a.set(t,new Set),a.get(t).add(n)}off(e,t,n){const a=this.listeners_.get(e);if(!a)return;const r=a.get(t);r&&r.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}const _=t(null,"SpineController"),d=new Float32Array(16);function g(e,t,n,a){const r=e.scale.x*t*(n?-1:1),s=e.scale.y*t*(a?-1:1),i=e.scale.z,o=e.rotation.x,l=e.rotation.y,u=e.rotation.z,c=e.rotation.w,p=o+o,h=l+l,m=u+u,_=o*p,g=o*h,b=o*m,f=l*h,w=l*m,y=u*m,S=c*p,A=c*h,P=c*m;return d[0]=(1-(f+y))*r,d[1]=(g+P)*r,d[2]=(b-A)*r,d[3]=0,d[4]=(g-P)*s,d[5]=(1-(_+y))*s,d[6]=(w+S)*s,d[7]=0,d[8]=(b+A)*i,d[9]=(w-S)*i,d[10]=(1-(_+f))*i,d[11]=0,d[12]=e.position.x,d[13]=e.position.y,d[14]=e.position.z,d[15]=1,d}class b{constructor(e,t){this.wasmUrl_=e,this.factory_=t}build(e){const t=e.wasmModule,n=h(this.wasmUrl_,this.factory_).then(({raw:n,api:a})=>{const i=new m(n,a);e.insertResource(_,i),e.hasResource(c)&&e.getResource(c).setSpineController(i);const o=new Map,l=new Map,p=new Map,h={_id:Symbol("SpineAutoSystem"),_name:"SpineAutoSystem",_params:[],_fn:()=>{const t=e.world,n=e.hasResource(c)?e.getResource(c):null;if(!n)return;const a=t.getEntitiesWithComponents([s]),r=new Set;for(const e of a){r.add(e);const a=t.get(e,s),u=`${a.skeletonPath}:${a.atlasPath}`;if(!o.has(e)||l.get(e)!==u){o.has(e)&&(i.destroyInstance(o.get(e)),o.delete(e),l.delete(e),p.delete(e));const t=n.getSpineSkeletonHandle(a.skeletonPath,a.atlasPath);if(void 0===t)continue;const r=i.createInstance(t);if(r<0)continue;o.set(e,r),l.set(e,u),a.skin&&i.setSkin(r,a.skin),a.animation&&i.play(r,a.animation,a.loop),p.set(e,{animation:a.animation,skin:a.skin,loop:a.loop});continue}const c=p.get(e);if(!c)continue;const h=o.get(e);c.skin!==a.skin&&(i.setSkin(h,a.skin),c.skin=a.skin),c.animation===a.animation&&c.loop===a.loop||(a.animation&&i.play(h,a.animation,a.loop),c.animation=a.animation,c.loop=a.loop)}for(const[e,t]of o)r.has(e)||(i.destroyInstance(t),o.delete(e),l.delete(e),p.delete(e))}};if(e.addSystemToSchedule(u.PreUpdate,h),!e.pipeline?.spineRenderer){let n=0;e.setSpineRenderer((a,l)=>{let u=l-n;n=l,(u<=0||u>.5)&&(u=1/60);const c=e.world;for(const[e,n]of o){const a=c.has(e,s)?c.get(e,s):null,o=!1!==a?.playing,l=a?.timeScale??1;let p;if(o&&i.update(n,u*l),c.has(e,r)){p=g(c.get(e,r),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1)}const h=a?.color;M(t,i,n,p,h)}})}return{controller:i,coreModule:t}});e.insertResource(_,null),n.catch(()=>{}),e.spineInitPromise=n}}let f=new Float32Array(0),w=0,y=0,S=0,A=0,P=0,x=null;function k(e,t,n,a){if(t&&n>=a)return[t,n];t&&e._free(t);const r=2*a;return[e._malloc(r),r]}function M(e,t,n,a,r){x&&x!==e&&x&&(w&&(x._free(w),w=0,y=0),S&&(x._free(S),S=0,A=0),P&&(x._free(P),P=0),x=null),x=e;const s=t.extractMeshBatches(n);a&&(P||(P=e._malloc(64)),e.HEAPF32.set(a,P>>2));const i=r&&(1!==r.r||1!==r.g||1!==r.b||1!==r.a);for(const t of s){let n=t.vertices;if(i){const e=t.blendMode>=4;f.length<n.length&&(f=new Float32Array(2*n.length)),f.set(n);const a=f.subarray(0,n.length);for(let t=0;t<a.length;t+=8)e?(a[t+4]*=r.r*r.a,a[t+5]*=r.g*r.a,a[t+6]*=r.b*r.a):(a[t+4]*=r.r,a[t+5]*=r.g,a[t+6]*=r.b),a[t+7]*=r.a;n=a}const s=n.byteLength,o=t.indices.byteLength;[w,y]=k(e,w,y,s),[S,A]=k(e,S,A,o),e.HEAPF32.set(n,w>>2),new Uint16Array(e.HEAPU8.buffer,S,t.indices.length).set(t.indices),e.renderer_submitTriangles(w,n.length/8,S,t.indices.length,t.textureId,t.blendMode,a?P:0)}}export{m as SpineModuleController,b as SpinePlugin,_ as SpineResource,h as loadSpineModule,M as submitSpineMeshesToCore,p as wrapSpineModule};+let e=0;function t(t,n){const i=++e;return{_id:Symbol(`Resource_${i}_${n??""}`),_name:n??`Resource_${i}`,_default:t}}t({delta:0,elapsed:0,frameCount:0},"Time");function n(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(n);const t={};for(const i in e)t[i]=n(e[i]);return t}let i=0;const r=new Map;function s(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return r.set(e,n),n}s("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});const a=s("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}});s("Sprite",{texture:4294967295,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}),s("Camera",{projectionType:1,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:3}),s("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),s("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),s("Parent",{entity:0}),s("Children",{entities:[]}),s("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295});const o=s("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}),l={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})};var u,c,p;!function(e,t){const r="undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map),s=r.get(e);if(s)return s;const a=function(e,t){const r=++i;return{_id:Symbol(`Component_${r}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...n(t),...e}:n(t)}}(e,t);r.set(e,a),function(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}(e,t,!1)}("SceneOwner",{scene:"",persistent:!1}),u="Name",c=l,r.set(u,c),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"}(p||(p={}));const _=t(null,"Assets");function m(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"])}}async function h(e,t){if(!t)throw new Error("SpineModuleLoader: factory parameter is required. Pass the Spine WASM factory function explicitly via loadSpineModule(url, factory).");const n=await t();return{raw:n,api:m(n)}}class d{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let i,r;if("string"==typeof e){const t=(new TextEncoder).encode(e);r=t.length,i=this.raw_._malloc(r+1),this.raw_.HEAPU8.set(t,i),this.raw_.HEAPU8[i+r]=0}else r=e.length,i=this.raw_._malloc(r),this.raw_.HEAPU8.set(e,i);const s=this.api_.loadSkeleton(i,r,t,t.length,n);return this.raw_._free(i),s}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,i,r){this.api_.setAtlasPageTexture(e,t,n,i,r)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,i=0){return!!this.api_.playAnimation(e,t,n,i)}addAnimation(e,t,n=!0,i=0,r=0){return!!this.api_.addAnimation(e,t,n,i,r)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch{return[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch{return[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),i=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,i))return this.raw_._free(n),this.raw_._free(i),null;const r=this.raw_.HEAPF32[n>>2],s=this.raw_.HEAPF32[i>>2];return this.raw_._free(n),this.raw_._free(i),{x:r,y:s}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,i=t>>2,r={x:n[i],y:n[i+1],width:n[i+2],height:n[i+3]};return this.raw_._free(t),r}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],i=this.raw_._malloc(8),r=i,s=i+4;for(let i=0;i<t;i++){const t=this.api_.getMeshBatchVertexCount(e,i),a=this.api_.getMeshBatchIndexCount(e,i);if(t<=0||a<=0)continue;const o=8*t*4,l=2*a,u=this.raw_._malloc(o),c=this.raw_._malloc(l);this.api_.getMeshBatchData(e,i,u,c,r,s);const p=new Float32Array(this.raw_.HEAPF32.buffer,u,8*t),_=new Uint16Array(this.raw_.HEAPU8.buffer,c,a);n.push({vertices:new Float32Array(p),indices:new Uint16Array(_),textureId:this.raw_.HEAPU32[r>>2],blendMode:this.raw_.HEAPU32[s>>2]}),this.raw_._free(u),this.raw_._free(c)}return this.raw_._free(i),n}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const i=this.listeners_.get(e);i.has(t)||i.set(t,new Set),i.get(t).add(n)}off(e,t,n){const i=this.listeners_.get(e);if(!i)return;const r=i.get(t);r&&r.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}const g=t(null,"SpineController"),f=new Float32Array(16);function b(e,t,n,i){const r=e.scale.x*t*(n?-1:1),s=e.scale.y*t*(i?-1:1),a=e.scale.z,o=e.rotation.x,l=e.rotation.y,u=e.rotation.z,c=e.rotation.w,p=o+o,_=l+l,m=u+u,h=o*p,d=o*_,g=o*m,b=l*_,w=l*m,y=u*m,S=c*p,A=c*_,P=c*m;return f[0]=(1-(b+y))*r,f[1]=(d+P)*r,f[2]=(g-A)*r,f[3]=0,f[4]=(d-P)*s,f[5]=(1-(h+y))*s,f[6]=(w+S)*s,f[7]=0,f[8]=(g+A)*a,f[9]=(w-S)*a,f[10]=(1-(h+b))*a,f[11]=0,f[12]=e.position.x,f[13]=e.position.y,f[14]=e.position.z,f[15]=1,f}class w{constructor(e,t){this.wasmUrl_=e,this.factory_=t}build(e){const t=e.wasmModule,n=h(this.wasmUrl_,this.factory_).then(({raw:n,api:i})=>{const r=new d(n,i);e.insertResource(g,r),e.hasResource(_)&&e.getResource(_).setSpineController(r);const s=new Map,l=new Map,u=new Map,c={_id:Symbol("SpineAutoSystem"),_name:"SpineAutoSystem",_params:[],_fn:()=>{const t=e.world,n=e.hasResource(_)?e.getResource(_):null;if(!n)return;const i=t.getEntitiesWithComponents([o]),a=new Set;for(const e of i){a.add(e);const i=t.get(e,o),c=`${i.skeletonPath}:${i.atlasPath}`;if(!s.has(e)||l.get(e)!==c){s.has(e)&&(r.destroyInstance(s.get(e)),s.delete(e),l.delete(e),u.delete(e));const t=n.getSpineSkeletonHandle(i.skeletonPath,i.atlasPath);if(void 0===t)continue;const a=r.createInstance(t);if(a<0)continue;s.set(e,a),l.set(e,c),i.skin&&r.setSkin(a,i.skin),i.animation&&r.play(a,i.animation,i.loop),u.set(e,{animation:i.animation,skin:i.skin,loop:i.loop});continue}const p=u.get(e);if(!p)continue;const _=s.get(e);p.skin!==i.skin&&(r.setSkin(_,i.skin),p.skin=i.skin),p.animation===i.animation&&p.loop===i.loop||(i.animation&&r.play(_,i.animation,i.loop),p.animation=i.animation,p.loop=i.loop)}for(const[e,t]of s)a.has(e)||(r.destroyInstance(t),s.delete(e),l.delete(e),u.delete(e))}};if(e.addSystemToSchedule(p.PreUpdate,c),!e.pipeline?.spineRenderer){let n=0;e.setSpineRenderer((i,l)=>{let u=l-n;n=l,(u<=0||u>.5)&&(u=1/60);const c=e.world;for(const[e,n]of s){const i=c.has(e,o)?c.get(e,o):null,s=!1!==i?.playing,l=i?.timeScale??1;let p;if(s&&r.update(n,u*l),c.has(e,a)){p=b(c.get(e,a),i?.skeletonScale??1,i?.flipX??!1,i?.flipY??!1)}const _=i?.color;U(t,r,n,p,_)}})}return{controller:r,coreModule:t}});e.insertResource(g,null),n.catch(()=>{}),e.spineInitPromise=n}}let y=new Float32Array(0),S=0,A=0,P=0,x=0,k=0,M=null;function B(e,t,n,i){if(t&&n>=i)return[t,n];t&&e._free(t);const r=2*i;return[e._malloc(r),r]}function U(e,t,n,i,r){M&&M!==e&&M&&(S&&(M._free(S),S=0,A=0),P&&(M._free(P),P=0,x=0),k&&(M._free(k),k=0),M=null),M=e;const s=t.extractMeshBatches(n);i&&(k||(k=e._malloc(64)),e.HEAPF32.set(i,k>>2));const a=r&&(1!==r.r||1!==r.g||1!==r.b||1!==r.a);for(const t of s){let n=t.vertices;if(a){const e=t.blendMode>=4;y.length<n.length&&(y=new Float32Array(2*n.length)),y.set(n);const i=y.subarray(0,n.length);for(let t=0;t<i.length;t+=8)e?(i[t+4]*=r.r*r.a,i[t+5]*=r.g*r.a,i[t+6]*=r.b*r.a):(i[t+4]*=r.r,i[t+5]*=r.g,i[t+6]*=r.b),i[t+7]*=r.a;n=i}const s=n.byteLength,o=t.indices.byteLength;[S,A]=B(e,S,A,s),[P,x]=B(e,P,x,o),e.HEAPF32.set(n,S>>2),new Uint16Array(e.HEAPU8.buffer,P,t.indices.length).set(t.indices),e.renderer_submitTriangles(S,n.length/8,P,t.indices.length,t.textureId,t.blendMode,i?k:0)}}export{d as SpineModuleController,w as SpinePlugin,g as SpineResource,h as loadSpineModule,U as submitSpineMeshesToCore,m as wrapSpineModule};//# sourceMappingURL=index.js.mapdiff --git a/sdk/src/app.ts b/sdk/src/app.tsindex acf997591..924c37aee 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -18,10 +18,14 @@ import { initPostProcessAPI, shutdownPostProcessAPI } from './postprocess';import { initRendererAPI, shutdownRendererAPI } from './renderer';import { initGLDebugAPI, shutdownGLDebugAPI } from './glDebug';import { platformNow } from './platform';-import { ProjectionType, ScaleMode } from './component';+import { ProjectionType, ScaleMode, SceneOwner } from './component';+import type { Entity } from './types';import { RenderPipeline, type SpineRendererFn } from './renderPipeline';import { Renderer } from './renderer';import { PostProcess } from './postprocess';+import type { SceneConfig } from './sceneManager';+import { SceneManager } from './sceneManager';+import { sceneManagerPlugin } from './scenePlugin';// =============================================================================// Plugin Interface@@ -215,6 +219,20 @@ export class App {return this.resources_.has(resource);}+ // =========================================================================+ // Scene Management+ // =========================================================================++ registerScene(config: SceneConfig): this {+ this.getResource(SceneManager).register(config);+ return this;+ }++ setInitialScene(name: string): this {+ this.getResource(SceneManager).setInitial(name);+ return this;+ }+// =========================================================================// Run// =========================================================================@@ -497,7 +515,17 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): APostProcess.resize(width, height);}- const cameras = collectCameras(module, cppRegistry, width, height);+ let activeScenes: Set<string> | undefined;+ if (app.hasResource(SceneManager)) {+ const mgr = app.getResource(SceneManager);+ const running = mgr.getActiveScenes();+ if (running.length > 0) {+ activeScenes = new Set(running);+ }+ }++ pipeline.setActiveScenes(activeScenes ?? null);+ const cameras = collectCameras(module, cppRegistry, width, height, app.world, activeScenes);syncUICameraInfo(width, height, cameras);@@ -533,6 +561,7 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): Aapp.addPlugin(assetPlugin);app.addPlugin(prefabsPlugin);app.addPlugin(inputPlugin);+ app.addPlugin(sceneManagerPlugin);if (options?.plugins) {for (const plugin of options.plugins) {app.addPlugin(plugin);@@ -605,15 +634,31 @@ interface CameraInfo {cameraY: number;}-function collectCameras(module: ESEngineModule, registry: CppRegistry, width: number, height: number): CameraInfo[] {+function collectCameras(+ module: ESEngineModule,+ registry: CppRegistry,+ width: number,+ height: number,+ world?: World,+ activeScenes?: Set<string>,+): CameraInfo[] {if (width === 0 || height === 0) return [];const cameraEntities = module.registry_getCameraEntities(registry);if (cameraEntities.length === 0) return [];+ const filtered = activeScenes && world+ ? cameraEntities.filter((e: number) => {+ const owner = world.tryGet(e as Entity, SceneOwner);+ if (!owner || owner.scene === '') return true;+ return activeScenes.has(owner.scene);+ })+ : cameraEntities;+ if (filtered.length === 0) return [];+const canvas = findCanvasData(module, registry);const cameras: CameraInfo[] = [];- for (const e of cameraEntities) {+ for (const e of filtered) {const camera = registry.getCamera(e);const transform = registry.getLocalTransform(e);diff --git a/sdk/src/component.ts b/sdk/src/component.tsindex f8327d712..8e78f43c3 100644--- a/sdk/src/component.ts+++ b/sdk/src/component.ts@@ -271,6 +271,11 @@ export interface NameData {value: string;}+export interface SceneOwnerData {+ scene: string;+ persistent: boolean;+}+// =============================================================================// Builtin Component Instances// =============================================================================@@ -373,6 +378,11 @@ export const Name: ComponentDef<NameData> = {}};+export const SceneOwner = defineComponent<SceneOwnerData>('SceneOwner', {+ scene: '',+ persistent: false,+});+export type {RigidBodyData, BoxColliderData, CircleColliderData, CapsuleColliderData,};diff --git a/sdk/src/core.ts b/sdk/src/core.tsindex e77418f1a..e11e900fd 100644--- a/sdk/src/core.ts+++ b/sdk/src/core.ts@@ -65,6 +65,7 @@ export {BitmapText,SpineAnimation,Name,+ SceneOwner,ProjectionType,ClearFlags,ScaleMode,@@ -83,6 +84,7 @@ export {type CircleColliderData,type CapsuleColliderData,type NameData,+ type SceneOwnerData,} from './component';export {@@ -299,6 +301,27 @@ export {type SceneLoadOptions,} from './scene';+// =============================================================================+// Scene Manager+// =============================================================================++export {+ SceneManager,+ SceneManagerState,+ wrapSceneSystem,+ type SceneConfig,+ type SceneContext,+ type SceneStatus,+ type TransitionOptions,+} from './sceneManager';++export { sceneManagerPlugin } from './scenePlugin';++export {+ transitionTo,+ type TransitionConfig,+} from './sceneTransition';+// =============================================================================// Prefab// =============================================================================@@ -320,7 +343,9 @@ export { Prefabs, PrefabServer, PrefabsPlugin, prefabsPlugin } from './prefabSerexport {loadRuntimeScene,+ createRuntimeSceneConfig,type RuntimeAssetProvider,+ type RuntimeSceneOptions,} from './runtimeLoader';// =============================================================================diff --git a/sdk/src/customDraw.ts b/sdk/src/customDraw.tsindex 960df436c..5680fd84f 100644--- a/sdk/src/customDraw.ts+++ b/sdk/src/customDraw.ts@@ -5,10 +5,10 @@export type DrawCallback = (elapsed: number) => void;-const callbacks = new Map<string, DrawCallback>();+const callbacks = new Map<string, { fn: DrawCallback; scene: string }>();-export function registerDrawCallback(id: string, fn: DrawCallback): void {- callbacks.set(id, fn);+export function registerDrawCallback(id: string, fn: DrawCallback, scene?: string): void {+ callbacks.set(id, { fn, scene: scene ?? '' });}export function unregisterDrawCallback(id: string): void {@@ -19,6 +19,14 @@ export function clearDrawCallbacks(): void {callbacks.clear();}-export function getDrawCallbacks(): ReadonlyMap<string, DrawCallback> {+export function clearSceneDrawCallbacks(sceneName: string): void {+ for (const [id, entry] of callbacks) {+ if (entry.scene === sceneName) {+ callbacks.delete(id);+ }+ }+}++export function getDrawCallbacks(): ReadonlyMap<string, { fn: DrawCallback; scene: string }> {return callbacks;}diff --git a/sdk/src/preview/PreviewPlugin.ts b/sdk/src/preview/PreviewPlugin.tsindex 3139745c9..b010e02ac 100644--- a/sdk/src/preview/PreviewPlugin.ts+++ b/sdk/src/preview/PreviewPlugin.ts@@ -9,8 +9,11 @@ import { loadRuntimeScene } from '../runtimeLoader';import { LocalTransform, Camera, Canvas, ProjectionType, ClearFlags, type LocalTransformData, type CameraData, type CanvasData } from '../component';import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT, DEFAULT_PIXELS_PER_UNIT } from '../defaults';import { platformFetch } from '../platform';+import { SceneManager } from '../sceneManager';import { WebAssetProvider } from './WebAssetProvider';+const PREVIEW_SCENE = '__preview__';+// =============================================================================// PreviewPlugin// =============================================================================@@ -21,7 +24,6 @@ export class PreviewPlugin implements Plugin {private app_: App | null = null;private loadPromise_: Promise<void> | null = null;private eventSource_: EventSource | null = null;- private currentScene_: SceneData | null = null;constructor(sceneUrl: string, baseUrl?: string) {this.sceneUrl_ = sceneUrl;@@ -31,7 +33,17 @@ export class PreviewPlugin implements Plugin {build(app: App): void {this.app_ = app;- this.loadPromise_ = this.loadScene();+ const manager = app.getResource(SceneManager);+ manager.register({+ name: PREVIEW_SCENE,+ setup: async () => {+ await this.loadRuntimeData();+ this.ensureCamera();+ },+ });+ manager.setInitial(PREVIEW_SCENE);++ this.loadPromise_ = manager.load(PREVIEW_SCENE).then(() => {});this.setupHotReload();}@@ -44,41 +56,29 @@ export class PreviewPlugin implements Plugin {}}- private async loadScene(): Promise<void> {+ private async loadRuntimeData(): Promise<void> {if (!this.app_) return;- let step = 'fetch scene';- try {- const response = await platformFetch(this.sceneUrl_);- if (!response.ok) {- throw new Error(`Failed to fetch scene: ${response.status}`);- }- step = 'parse scene JSON';- const sceneData = await response.json<SceneData>();-- step = 'prefetch assets';- const provider = new WebAssetProvider(this.baseUrl_);- await provider.prefetch(sceneData);-- let spineModule = null;- const spinePromise = this.app_.spineInitPromise;- if (spinePromise) {- step = 'init spine';- const result = await spinePromise as { controller: { raw: any }; coreModule: unknown };- spineModule = result.controller.raw;- }+ const response = await platformFetch(this.sceneUrl_);+ if (!response.ok) {+ throw new Error(`Failed to fetch scene: ${response.status}`);+ }+ const sceneData = await response.json<SceneData>();- step = 'loadRuntimeScene';- await loadRuntimeScene(this.app_, this.app_.wasmModule!, sceneData, provider, spineModule);+ const provider = new WebAssetProvider(this.baseUrl_);+ await provider.prefetch(sceneData);- step = 'ensureCamera';- this.ensureCamera();- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- const stack = err instanceof Error ? err.stack : '';- console.error(`[PreviewPlugin] Failed at step "${step}": ${msg}\n${stack}`);- throw new Error(`[PreviewPlugin:${step}] ${msg}`);+ let spineModule = null;+ const spinePromise = this.app_.spineInitPromise;+ if (spinePromise) {+ const result = await spinePromise as { controller: { raw: any }; coreModule: unknown };+ spineModule = result.controller.raw;}++ await loadRuntimeScene(+ this.app_, this.app_.wasmModule!, sceneData, provider, spineModule,+ null, undefined, null, PREVIEW_SCENE,+ );}private ensureCamera(): void {@@ -113,7 +113,9 @@ export class PreviewPlugin implements Plugin {}}- const cameraEntity = world.spawn();+ const manager = this.app_.getResource(SceneManager);+ const sceneCtx = manager.getScene(PREVIEW_SCENE);+ const cameraEntity = sceneCtx ? sceneCtx.spawn() : world.spawn();const transformData: LocalTransformData = {position: { x: 0, y: 0, z: 10 },@@ -164,25 +166,8 @@ export class PreviewPlugin implements Plugin {if (!this.app_) return;try {- const response = await platformFetch(this.sceneUrl_);- if (!response.ok) {- throw new Error(`Failed to fetch scene: ${response.status}`);- }- const sceneData = await response.json<SceneData>();-- const provider = new WebAssetProvider(this.baseUrl_);- await provider.prefetch(sceneData);-- let spineModule = null;- const spinePromise = this.app_.spineInitPromise;- if (spinePromise) {- const result = await spinePromise as { controller: { raw: any }; coreModule: unknown };- spineModule = result.controller.raw;- }-- await loadRuntimeScene(this.app_, this.app_.wasmModule!, sceneData, provider, spineModule);-- this.ensureCamera();+ const manager = this.app_.getResource(SceneManager);+ await manager.switchTo(PREVIEW_SCENE);console.log('[PreviewPlugin] Scene reloaded successfully');} catch (err) {const msg = err instanceof Error ? err.message : String(err);diff --git a/sdk/src/renderPipeline.ts b/sdk/src/renderPipeline.tsindex 198b80cc5..a4d4714b2 100644--- a/sdk/src/renderPipeline.ts+++ b/sdk/src/renderPipeline.ts@@ -39,6 +39,7 @@ export class RenderPipeline {private maskProcessor_: MaskProcessorFn | null = null;private lastWidth_ = 0;private lastHeight_ = 0;+ private activeScenes_: Set<string> | null = null;get spineRenderer(): SpineRendererFn | null {return this.spineRenderer_;@@ -56,6 +57,10 @@ export class RenderPipeline {this.maskProcessor_ = fn;}+ setActiveScenes(scenes: Set<string> | null): void {+ this.activeScenes_ = scenes;+ }+render(params: RenderParams): void {const { registry, viewProjection, width, height, elapsed } = params;@@ -119,9 +124,10 @@ export class RenderPipeline {if (cbs.size > 0) {Draw.begin(viewProjection);const failed: string[] = [];- for (const [id, fn] of cbs.entries()) {+ for (const [id, entry] of cbs.entries()) {+ if (entry.scene && this.activeScenes_ && !this.activeScenes_.has(entry.scene)) continue;try {- fn(elapsed);+ entry.fn(elapsed);} catch (e) {console.error(`[CustomDraw] callback '${id}' error:`, e);failed.push(id);diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex 2c50a6440..dd7ecff6f 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -3,7 +3,7 @@* @brief Runtime scene loader for builder targets (WeChat, Playable, etc.)*/-import { Sprite, SpineAnimation, BitmapText, WorldTransform, type SpineAnimationData, type WorldTransformData } from './component';+import { Sprite, SpineAnimation, BitmapText, WorldTransform, SceneOwner, type SpineAnimationData, type WorldTransformData } from './component';import { Material } from './material';import { loadSceneData, type SceneData } from './scene';import type { ESEngineModule } from './wasm';@@ -15,6 +15,7 @@ import type { Entity, Vec2 } from './types';import type { AddressableManifest } from './asset/AssetServer';import { Assets } from './asset/AssetPlugin';import { getAssetTypeEntry } from './assetTypes';+import { SceneManager, type SceneConfig } from './sceneManager';// =============================================================================// Public Interface@@ -479,6 +480,7 @@ export async function loadRuntimeScene(physicsModule?: PhysicsWasmModule | null,physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number },manifest?: AddressableManifest | null,+ sceneName?: string,): Promise<void> {const textureCache = await loadTextures(module, sceneData, provider);applyTextureMetadata(module, sceneData, textureCache);@@ -504,6 +506,12 @@ export async function loadRuntimeScene(const materialCache = await loadMaterials(sceneData, provider);const entityMap = loadSceneData(app.world, sceneData);+ if (sceneName && app.hasResource(SceneManager)) {+ for (const entity of entityMap.values()) {+ app.world.insert(entity, SceneOwner, { scene: sceneName, persistent: false });+ }+ }+updateSpriteTextures(app.world, sceneData, textureCache, entityMap);updateBitmapTextFonts(app.world, sceneData, fontCache, entityMap);updateMaterials(app.world, sceneData, materialCache, entityMap);@@ -520,3 +528,37 @@ export async function loadRuntimeScene(}}}++export interface RuntimeSceneOptions {+ app: App;+ module: ESEngineModule;+ provider: RuntimeAssetProvider;+ spineModule?: SpineWasmModule | null;+ physicsModule?: PhysicsWasmModule | null;+ physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number };+ manifest?: AddressableManifest | null;+}++export function createRuntimeSceneConfig(+ name: string,+ sceneData: SceneData,+ options: RuntimeSceneOptions,+): SceneConfig {+ return {+ name,+ data: sceneData,+ async setup() {+ await loadRuntimeScene(+ options.app,+ options.module,+ sceneData,+ options.provider,+ options.spineModule,+ options.physicsModule,+ options.physicsConfig,+ options.manifest,+ name,+ );+ },+ };+}diff --git a/sdk/src/sceneManager.ts b/sdk/src/sceneManager.tsnew file mode 100644index 000000000..de50374a5--- /dev/null+++ b/sdk/src/sceneManager.ts@@ -0,0 +1,599 @@+/**+ * @file sceneManager.ts+ * @brief Scene management system for loading, switching, and unloading scenes+ */++import type { App } from './app';+import type { Entity, Color } from './types';+import type { SceneData, SceneLoadOptions } from './scene';+import type { SystemDef } from './system';+import type { ShaderHandle } from './material';+import type { DrawCallback } from './customDraw';+import { Schedule } from './system';+import { loadSceneWithAssets } from './scene';+import { registerDrawCallback, unregisterDrawCallback } from './customDraw';+import { PostProcess } from './postprocess';+import { Draw } from './draw';+import { defineResource } from './resource';+import { SceneOwner, Sprite } from './component';+import { Assets } from './asset/AssetPlugin';++// =============================================================================+// Types+// =============================================================================++export type SceneStatus = 'loading' | 'running' | 'paused' | 'sleeping' | 'unloading';++export interface SceneConfig {+ name: string;+ path?: string;+ data?: SceneData;+ systems?: Array<{ schedule: Schedule; system: SystemDef }>;+ setup?: (ctx: SceneContext) => void | Promise<void>;+ cleanup?: (ctx: SceneContext) => void;+}++export interface SceneContext {+ readonly name: string;+ readonly entities: ReadonlySet<Entity>;+ spawn(): Entity;+ despawn(entity: Entity): void;+ registerDrawCallback(id: string, fn: DrawCallback): void;+ addPostProcessPass(name: string, shader: ShaderHandle): number;+ removePostProcessPass(name: string): void;+ setPersistent(entity: Entity, persistent: boolean): void;+}++export interface TransitionOptions {+ keepPersistent?: boolean;+ transition?: 'none' | 'fade';+ duration?: number;+ color?: Color;+ onStart?: () => void;+ onComplete?: () => void;+}++type TransitionPhase = 'fade-out' | 'fade-in';++interface TransitionState {+ phase: TransitionPhase;+ elapsed: number;+ duration: number;+ color: Color;+ targetScene: string;+ options: TransitionOptions;+ resolve: () => void;+}++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)+// =============================================================================++class SceneInstance {+ readonly config: SceneConfig;+ readonly entities = new Set<Entity>();+ readonly drawCallbacks = new Map<string, DrawCallback>();+ readonly postProcessPasses: string[] = [];+ readonly savedAlphas = new Map<Entity, number>();+ status: SceneStatus = 'loading';++ constructor(config: SceneConfig) {+ this.config = config;+ }+}++// =============================================================================+// Scene Context Implementation+// =============================================================================++class SceneContextImpl implements SceneContext {+ private readonly instance_: SceneInstance;+ private readonly app_: App;++ constructor(instance: SceneInstance, app: App) {+ this.instance_ = instance;+ this.app_ = app;+ }++ get name(): string {+ return this.instance_.config.name;+ }++ get entities(): ReadonlySet<Entity> {+ return this.instance_.entities;+ }++ spawn(): Entity {+ const entity = this.app_.world.spawn();+ this.instance_.entities.add(entity);+ this.app_.world.insert(entity, SceneOwner, {+ scene: this.instance_.config.name,+ persistent: false,+ });+ return entity;+ }++ despawn(entity: Entity): void {+ this.instance_.entities.delete(entity);+ this.app_.world.despawn(entity);+ }++ registerDrawCallback(id: string, fn: DrawCallback): void {+ this.instance_.drawCallbacks.set(id, fn);+ registerDrawCallback(id, fn, this.instance_.config.name);+ }++ addPostProcessPass(name: string, shader: ShaderHandle): number {+ const index = PostProcess.addPass(name, shader);+ this.instance_.postProcessPasses.push(name);+ return index;+ }++ removePostProcessPass(name: string): void {+ PostProcess.removePass(name);+ const idx = this.instance_.postProcessPasses.indexOf(name);+ if (idx !== -1) {+ this.instance_.postProcessPasses.splice(idx, 1);+ }+ }++ setPersistent(entity: Entity, persistent: boolean): void {+ if (this.app_.world.has(entity, SceneOwner)) {+ const data = this.app_.world.get(entity, SceneOwner);+ data.persistent = persistent;+ this.app_.world.insert(entity, SceneOwner, data);+ }+ }+}++// =============================================================================+// Scene Manager State+// =============================================================================++export class SceneManagerState {+ private readonly app_: App;+ private readonly configs_ = new Map<string, SceneConfig>();+ private readonly scenes_ = new Map<string, SceneInstance>();+ private readonly contexts_ = new Map<string, SceneContextImpl>();+ private readonly additiveScenes_ = new Set<string>();+ private readonly pausedScenes_ = new Set<string>();+ private readonly sleepingScenes_ = new Set<string>();+ private readonly loadOrder_: string[] = [];+ private activeScene_: string | null = null;+ private initialScene_: string | null = null;+ private transition_: TransitionState | null = null;++ constructor(app: App) {+ this.app_ = app;+ }++ register(config: SceneConfig): void {+ this.configs_.set(config.name, config);+ }++ setInitial(name: string): void {+ this.initialScene_ = name;+ }++ getInitial(): string | null {+ return this.initialScene_;+ }++ isTransitioning(): boolean {+ return this.transition_ !== null;+ }++ async switchTo(name: string, options?: TransitionOptions): Promise<void> {+ const transition = options?.transition ?? 'none';++ if (transition === 'fade') {+ await this.startFadeTransition(name, options ?? {});+ return;+ }++ if (this.activeScene_ && this.activeScene_ !== name) {+ await this.unload(this.activeScene_, options);+ }+ await this.load(name);+ }++ 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;++ options.onStart?.();++ this.transition_ = {+ phase: 'fade-out',+ elapsed: 0,+ duration,+ color,+ targetScene,+ options,+ resolve,+ };++ registerDrawCallback(TRANSITION_CALLBACK_ID, () => {+ if (!this.transition_) return;+ const halfDuration = this.transition_.duration / 2;+ const t = Math.min(this.transition_.elapsed / halfDuration, 1);+ const alpha = this.transition_.phase === 'fade-out' ? t : 1 - t;+ Draw.setLayer(9999);+ Draw.setDepth(9999);+ Draw.rect(+ { x: 0, y: 0 },+ { x: OVERLAY_SIZE, y: OVERLAY_SIZE },+ { r: color.r, g: color.g, b: color.b, a: alpha },+ );+ });+ });+ }++ updateTransition(dt: number): void {+ if (!this.transition_) return;++ this.transition_.elapsed += dt;+ const halfDuration = this.transition_.duration / 2;++ if (this.transition_.phase === 'fade-out' && this.transition_.elapsed >= halfDuration) {+ this.transition_.phase = 'fade-in';+ this.transition_.elapsed = 0;++ const { targetScene, options } = this.transition_;+ const oldScene = this.activeScene_;++ const doSwitch = async () => {+ if (oldScene && oldScene !== targetScene) {+ await this.unload(oldScene, options);+ }+ await this.load(targetScene);+ };+ doSwitch();+ }++ if (this.transition_.phase === 'fade-in' && this.transition_.elapsed >= halfDuration) {+ const { resolve, options } = this.transition_;+ this.transition_ = null;+ unregisterDrawCallback(TRANSITION_CALLBACK_ID);+ options.onComplete?.();+ resolve();+ }+ }++ async load(name: string): Promise<SceneContext> {+ if (this.scenes_.has(name)) {+ const existing = this.scenes_.get(name)!;+ existing.status = 'running';+ this.activeScene_ = name;+ return this.contexts_.get(name)!;+ }++ const config = this.configs_.get(name);+ if (!config) {+ throw new Error(`Scene "${name}" is not registered`);+ }++ const instance = new SceneInstance(config);+ this.scenes_.set(name, instance);++ const ctx = new SceneContextImpl(instance, this.app_);+ this.contexts_.set(name, ctx);++ let sceneData = config.data;+ if (!sceneData && config.path) {+ const assetServer = this.app_.hasResource(Assets)+ ? this.app_.getResource(Assets)+ : null;+ if (assetServer) {+ sceneData = await assetServer.loadJson<SceneData>(config.path);+ } else {+ const response = await fetch(config.path);+ sceneData = await response.json() as SceneData;+ }+ }++ if (sceneData) {+ const loadOptions: SceneLoadOptions = {};+ if (this.app_.hasResource(Assets)) {+ loadOptions.assetServer = this.app_.getResource(Assets);+ }+ const entityMap = await loadSceneWithAssets(+ this.app_.world, sceneData, loadOptions+ );++ for (const entity of entityMap.values()) {+ instance.entities.add(entity);+ this.app_.world.insert(entity, SceneOwner, {+ scene: name,+ persistent: false,+ });+ }+ }++ if (config.systems) {+ for (const { schedule, system } of config.systems) {+ const wrapped = wrapSceneSystem(this.app_, name, system);+ this.app_.addSystemToSchedule(schedule, wrapped);+ }+ }++ if (config.setup) {+ await config.setup(ctx);+ }++ instance.status = 'running';+ this.activeScene_ = name;+ this.loadOrder_.push(name);+ return ctx;+ }++ async loadAdditive(name: string): Promise<SceneContext> {+ if (this.scenes_.has(name)) {+ const existing = this.scenes_.get(name)!;+ existing.status = 'running';+ this.additiveScenes_.add(name);+ return this.contexts_.get(name)!;+ }++ const config = this.configs_.get(name);+ if (!config) {+ throw new Error(`Scene "${name}" is not registered`);+ }++ const instance = new SceneInstance(config);+ this.scenes_.set(name, instance);++ const ctx = new SceneContextImpl(instance, this.app_);+ this.contexts_.set(name, ctx);++ let sceneData = config.data;+ if (!sceneData && config.path) {+ const assetServer = this.app_.hasResource(Assets)+ ? this.app_.getResource(Assets)+ : null;+ if (assetServer) {+ sceneData = await assetServer.loadJson<SceneData>(config.path);+ } else {+ const response = await fetch(config.path);+ sceneData = await response.json() as SceneData;+ }+ }++ if (sceneData) {+ const loadOptions: SceneLoadOptions = {};+ if (this.app_.hasResource(Assets)) {+ loadOptions.assetServer = this.app_.getResource(Assets);+ }+ const entityMap = await loadSceneWithAssets(+ this.app_.world, sceneData, loadOptions+ );++ for (const entity of entityMap.values()) {+ instance.entities.add(entity);+ this.app_.world.insert(entity, SceneOwner, {+ scene: name,+ persistent: false,+ });+ }+ }++ if (config.systems) {+ for (const { schedule, system } of config.systems) {+ const wrapped = wrapSceneSystem(this.app_, name, system);+ this.app_.addSystemToSchedule(schedule, wrapped);+ }+ }++ if (config.setup) {+ await config.setup(ctx);+ }++ instance.status = 'running';+ this.additiveScenes_.add(name);+ this.loadOrder_.push(name);+ return ctx;+ }++ async unload(name: string, options?: TransitionOptions): Promise<void> {+ const instance = this.scenes_.get(name);+ if (!instance) return;++ const ctx = this.contexts_.get(name)!;+ instance.status = 'unloading';++ if (instance.config.cleanup) {+ instance.config.cleanup(ctx);+ }++ const keepPersistent = options?.keepPersistent ?? true;+ for (const entity of instance.entities) {+ if (keepPersistent && this.app_.world.valid(entity) &&+ this.app_.world.has(entity, SceneOwner)) {+ const data = this.app_.world.get(entity, SceneOwner);+ if (data.persistent) continue;+ }+ if (this.app_.world.valid(entity)) {+ this.app_.world.despawn(entity);+ }+ }+ instance.entities.clear();++ for (const id of instance.drawCallbacks.keys()) {+ unregisterDrawCallback(id);+ }+ instance.drawCallbacks.clear();++ for (const passName of instance.postProcessPasses) {+ try {+ PostProcess.removePass(passName);+ } catch {+ // pass may already be removed+ }+ }+ instance.postProcessPasses.length = 0;++ this.scenes_.delete(name);+ this.contexts_.delete(name);+ this.additiveScenes_.delete(name);+ this.pausedScenes_.delete(name);+ this.sleepingScenes_.delete(name);++ const orderIdx = this.loadOrder_.indexOf(name);+ if (orderIdx !== -1) {+ this.loadOrder_.splice(orderIdx, 1);+ }++ if (this.activeScene_ === name) {+ this.activeScene_ = null;+ }+ }++ pause(name: string): void {+ const instance = this.scenes_.get(name);+ if (!instance || instance.status !== 'running') return;+ instance.status = 'paused';+ this.pausedScenes_.add(name);+ this.setPostProcessPassesEnabled(instance, false);+ }++ resume(name: string): void {+ const instance = this.scenes_.get(name);+ if (!instance || instance.status !== 'paused') return;+ instance.status = 'running';+ this.pausedScenes_.delete(name);+ this.setPostProcessPassesEnabled(instance, true);+ }++ sleep(name: string): void {+ const instance = this.scenes_.get(name);+ if (!instance || instance.status !== 'running') return;+ instance.status = 'sleeping';+ this.sleepingScenes_.add(name);+ this.setPostProcessPassesEnabled(instance, false);+ instance.savedAlphas.clear();++ for (const entity of instance.entities) {+ if (this.app_.world.valid(entity) && this.app_.world.has(entity, Sprite)) {+ const sprite = this.app_.world.get(entity, Sprite);+ instance.savedAlphas.set(entity, sprite.color.a);+ sprite.color = { ...sprite.color, a: 0 };+ this.app_.world.insert(entity, Sprite, sprite);+ }+ }+ }++ wake(name: string): void {+ const instance = this.scenes_.get(name);+ if (!instance || instance.status !== 'sleeping') return;+ instance.status = 'running';+ this.sleepingScenes_.delete(name);+ this.setPostProcessPassesEnabled(instance, true);++ for (const entity of instance.entities) {+ if (this.app_.world.valid(entity) && this.app_.world.has(entity, Sprite)) {+ const sprite = this.app_.world.get(entity, Sprite);+ const savedAlpha = instance.savedAlphas.get(entity) ?? 1;+ sprite.color = { ...sprite.color, a: savedAlpha };+ this.app_.world.insert(entity, Sprite, sprite);+ }+ }+ instance.savedAlphas.clear();+ }++ private setPostProcessPassesEnabled(instance: SceneInstance, enabled: boolean): void {+ for (const passName of instance.postProcessPasses) {+ try {+ PostProcess.setEnabled(passName, enabled);+ } catch {+ // pass may have been removed externally+ }+ }+ }++ isPaused(name: string): boolean {+ return this.pausedScenes_.has(name);+ }++ isSleeping(name: string): boolean {+ return this.sleepingScenes_.has(name);+ }++ isLoaded(name: string): boolean {+ return this.scenes_.has(name);+ }++ isActive(name: string): boolean {+ return this.activeScene_ === name;+ }++ getActive(): string | null {+ return this.activeScene_;+ }++ getActiveScenes(): string[] {+ const result: string[] = [];+ for (const [name, instance] of this.scenes_) {+ if (instance.status === 'running') {+ result.push(name);+ }+ }+ return result;+ }++ getLoaded(): string[] {+ return Array.from(this.scenes_.keys());+ }++ getLoadOrder(): string[] {+ return [...this.loadOrder_];+ }++ bringToTop(name: string): void {+ const idx = this.loadOrder_.indexOf(name);+ if (idx === -1) return;+ this.loadOrder_.splice(idx, 1);+ this.loadOrder_.push(name);+ }++ getScene(name: string): SceneContext | null {+ return this.contexts_.get(name) ?? null;+ }++ getSceneStatus(name: string): SceneStatus | null {+ return this.scenes_.get(name)?.status ?? null;+ }+}++// =============================================================================+// Scene Manager Resource+// =============================================================================++export const SceneManager = defineResource<SceneManagerState>(+ null!,+ 'SceneManager'+);++// =============================================================================+// Scene System Wrapper+// =============================================================================++export function wrapSceneSystem(app: App, sceneName: string, system: SystemDef): SystemDef {+ return {+ _id: Symbol(`SceneScoped_${system._name}_${sceneName}`),+ _name: `${system._name}@${sceneName}`,+ _params: system._params,+ _fn: (...args: never[]) => {+ const manager = app.getResource(SceneManager);+ const status = manager.getSceneStatus(sceneName);+ if (status === 'running') {+ (system._fn as Function)(...args);+ }+ },+ };+}diff --git a/sdk/src/scenePlugin.ts b/sdk/src/scenePlugin.tsnew file mode 100644index 000000000..136f3f20c--- /dev/null+++ b/sdk/src/scenePlugin.ts@@ -0,0 +1,43 @@+/**+ * @file scenePlugin.ts+ * @brief Plugin that provides scene management capabilities+ */++import type { App, Plugin } from './app';+import { SceneManager, SceneManagerState } from './sceneManager';+import { defineSystem, Schedule } from './system';+import { Res, ResMut, Time } from './resource';+import type { SystemDef } from './system';++const sceneTransitionSystem = defineSystem(+ [ResMut(SceneManager), Res(Time)],+ (scenesRes, time) => {+ const mgr = scenesRes.get();+ mgr.updateTransition(time.delta);+ },+ { name: 'SceneTransitionSystem' }+);++export const sceneManagerPlugin: Plugin = {+ name: 'SceneManager',+ build(app: App): void {+ const state = new SceneManagerState(app);+ app.insertResource(SceneManager, state);++ const initSystem: SystemDef = {+ _id: Symbol('SceneInitSystem'),+ _name: 'SceneInitSystem',+ _params: [],+ _fn: () => {+ const manager = app.getResource(SceneManager);+ const initial = manager.getInitial();+ if (initial) {+ manager.load(initial);+ }+ },+ };++ app.addSystemToSchedule(Schedule.Startup, initSystem);+ app.addSystemToSchedule(Schedule.Last, sceneTransitionSystem);+ },+};diff --git a/sdk/src/sceneTransition.ts b/sdk/src/sceneTransition.tsnew file mode 100644index 000000000..cdee798ba--- /dev/null+++ b/sdk/src/sceneTransition.ts@@ -0,0 +1,27 @@+/**+ * @file sceneTransition.ts+ * @brief Convenience wrapper for scene transitions+ */++import type { App } from './app';+import type { Color } from './types';+import { SceneManager } from './sceneManager';++export interface TransitionConfig {+ duration: number;+ type: 'fade';+ color?: Color;+}++export async function transitionTo(+ app: App,+ targetScene: string,+ config: TransitionConfig,+): Promise<void> {+ const manager = app.getResource(SceneManager);+ await manager.switchTo(targetScene, {+ transition: config.type,+ duration: config.duration,+ color: config.color,+ });+}